Fix initialization of configdir

Windows code leaked memory (result of _fullpath()).

POSIX code passed a null buffer to getcwd(), which is not portable,
and failed to check for errors.
This commit is contained in:
Markus Armbruster 2008-02-04 07:39:42 +01:00
parent b76e5a5eed
commit 91eefc3f3a

View file

@ -66,7 +66,7 @@ struct keymatch configkeys[] = {
}; };
static struct keymatch *keylookup(char *key, struct keymatch tbl[]); static struct keymatch *keylookup(char *key, struct keymatch tbl[]);
static void set_paths(char *); static int set_paths(char *);
/* /*
* read in empire configuration * read in empire configuration
@ -150,7 +150,8 @@ emp_config(char *file)
done: done:
WORLD_X &= ~1; /* force even */ WORLD_X &= ~1; /* force even */
set_paths(file); if (set_paths(file) < 0)
return -1;
return -errors; return -errors;
} }
@ -170,43 +171,39 @@ keylookup(char *command, struct keymatch *tbl)
return NULL; return NULL;
} }
static void static int
set_paths(char *econfig) set_paths(char *econfig)
{ {
char *slash; char *p, *slash;
char *cwd = getcwd(NULL, 0);
#ifdef _WIN32 #ifdef _WIN32
/* normalize path separator to '\\', for easier searching: */ p = _fullpath(NULL, econfig, 0);
econfig = _fullpath(NULL, econfig, 0); slash = strrchr(p, '\\');
slash = strrchr(econfig, '\\');
configdir = malloc(slash - econfig + 1);
memcpy(configdir, econfig, slash - econfig);
configdir[slash - econfig] = 0;
#else #else
if ((slash = strrchr(econfig, '/'))) { char buf[1024];
configdir = malloc(slash - econfig + 1); char *cwd;
memcpy(configdir, econfig, slash - econfig);
configdir[slash - econfig] = 0;
} else
configdir = strdup(cwd);
if (configdir[0] != '/') { cwd = getcwd(buf, sizeof(buf));
char *tmp = configdir; p = fnameat(econfig, cwd);
size_t len = strlen(cwd); if (p[0] != '/') {
fprintf(stderr, "Can't get current working directory (%s)\n",
configdir = malloc(len + 1 + strlen(tmp) + 1); strerror(errno));
sprintf(configdir, "%s/%s", cwd, tmp); return -1;
free(tmp);
} }
if (p == econfig)
p = strdup(p);
slash = strrchr(p, '/');
#endif /* !_WIN32 */ #endif /* !_WIN32 */
*slash = 0;
configdir = realloc(p, slash + 1 - configdir);
infodir = fnameat(infodir_conf, configdir); infodir = fnameat(infodir_conf, configdir);
gamedir = fnameat(gamedir_conf, configdir); gamedir = fnameat(gamedir_conf, configdir);
builtindir = fnameat(builtindir_conf, configdir); builtindir = fnameat(builtindir_conf, configdir);
schedulefil = fnameat("schedule", configdir); schedulefil = fnameat("schedule", configdir);
free(cwd); return 0;
} }
void void