1 /* SPDX-License-Identifier: GPL-2.0-or-later */
3 /***************************************************************************
4 * Copyright (C) 2004, 2005 by Dominic Rath *
5 * Dominic.Rath@gmx.de *
7 * Copyright (C) 2007,2008 Øyvind Harboe *
8 * oyvind.harboe@zylin.com *
9 ***************************************************************************/
15 #include "configuration.h"
17 #include "replacements.h"
19 static size_t num_config_files;
20 static char **config_file_names;
22 static size_t num_script_dirs;
23 static char **script_search_dirs;
25 void add_script_search_dir(const char *dir)
28 script_search_dirs = realloc(script_search_dirs, (num_script_dirs + 1) * sizeof(char *));
30 script_search_dirs[num_script_dirs-1] = strdup(dir);
31 script_search_dirs[num_script_dirs] = NULL;
33 LOG_DEBUG("adding %s", dir);
36 void add_config_command(const char *cfg)
39 config_file_names = realloc(config_file_names, (num_config_files + 1) * sizeof(char *));
41 config_file_names[num_config_files-1] = strdup(cfg);
42 config_file_names[num_config_files] = NULL;
45 void free_config(void)
47 while (num_config_files)
48 free(config_file_names[--num_config_files]);
50 free(config_file_names);
51 config_file_names = NULL;
53 while (num_script_dirs)
54 free(script_search_dirs[--num_script_dirs]);
56 free(script_search_dirs);
57 script_search_dirs = NULL;
60 /* return full path or NULL according to search rules */
61 char *find_file(const char *file)
64 char **search_dirs = script_search_dirs;
66 char const *mode = "r";
69 /* Check absolute and relative to current working dir first.
70 * This keeps full_path reporting belowing working. */
71 full_path = alloc_printf("%s", file);
72 fp = fopen(full_path, mode);
82 full_path = alloc_printf("%s/%s", dir, file);
83 fp = fopen(full_path, mode);
88 LOG_DEBUG("found %s", full_path);
97 FILE *open_file_from_path(const char *file, const char *mode)
100 return fopen(file, mode);
102 char *full_path = find_file(file);
106 fp = fopen(full_path, mode);
112 int parse_config_file(struct command_context *cmd_ctx)
117 if (!config_file_names) {
118 command_run_line(cmd_ctx, "script openocd.cfg");
122 cfg = config_file_names;
125 retval = command_run_line(cmd_ctx, *cfg);
126 if (retval != ERROR_OK)
138 char *get_home_dir(const char *append_path)
141 char homepath[MAX_PATH];
144 char *home = getenv("HOME");
149 home = getenv("USERPROFILE");
152 char *drive = getenv("HOMEDRIVE");
153 char *path = getenv("HOMEPATH");
155 snprintf(homepath, MAX_PATH, "%s/%s", drive, path);
160 struct passwd *pwd = getpwuid(getuid());
173 home_path = alloc_printf("%s/%s", home, append_path);
175 home_path = alloc_printf("%s", home);