Signed-off-by: Max Schillinger <max@mxsr.de>
---
* Prevent out-of-bounds access.
* Rename 'dir' parameter to 'filepath'.
include/util.h | 2 ++
src/main.c | 11 ++---------
src/util.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 51 insertions(+), 9 deletions(-)
diff --git a/include/util.h b/include/util.h
index 42127c4..b29cc3e 100644
--- a/include/util.h
+++ b/include/util.h
@@ -28,6 +28,8 @@ char *xstrdup(const char *s);
char *gen_name(int *id, const char *fmt);
+const char *relpath(const char *dir);
+
void errline(struct location loc);
#endif
diff --git a/src/main.c b/src/main.c
index 313e462..62d2667 100644
--- a/src/main.c
+++ b/src/main.c
@@ -70,7 +70,6 @@ main(int argc, char *argv[])
{
const char *output = NULL, *typedefs = NULL;
const char *target = DEFAULT_TARGET;
- const char *modpath = NULL;
const char *mainsym = "main";
bool is_test = false;
struct unit unit = {0};
@@ -91,7 +90,6 @@ main(int argc, char *argv[])
usage(argv[0]);
return EXIT_SUCCESS;
case 'M':
- modpath = optarg;
break;
case 'm':
mainsym = optarg;
@@ -144,13 +142,8 @@ main(int argc, char *argv[])
memcpy((char **)sources + 1, argv + optind, sizeof(char **) * nsources);
sources[0] = "<unknown>";
- if (modpath) {
- size_t modlen = strlen(modpath);
- for (size_t i = 1; i <= nsources; i++) {
- if (strncmp(sources[i], modpath, modlen) == 0) {
- sources[i] += modlen;
- }
- }
+ for (size_t i = 1; i <= nsources; i++) {
+ sources[i] = relpath(sources[i]);
}
for (size_t i = 0; i < nsources; ++i) {
diff --git a/src/util.c b/src/util.c
index c3691bb..8c13f4e 100644
--- a/src/util.c
+++ b/src/util.c
@@ -1,3 +1,4 @@
+#include <limits.h>
#include <sys/stat.h>
#include <stdarg.h>
#include <stdbool.h>
@@ -113,6 +114,52 @@ gen_name(int *id, const char *fmt)
return str;
}
+const char *
+relpath(const char *filepath)
+{
+ if (filepath[0] != '/') {
+ return filepath;
+ }
+ char cwd[PATH_MAX];
+ if (getcwd(cwd, sizeof(cwd)) == NULL) {
+ return filepath;
+ }
+ size_t cwdlen = strlen(cwd);
+ if (strncmp(filepath, cwd, cwdlen) == 0) {
+ return (strlen(filepath) > cwdlen) ? filepath + cwdlen + 1 : filepath;
+ }
+ int common_prefix = -1;
+ for (int i = 0; filepath[i] != '\0' && filepath[i] == cwd[i]; i++) {
+ if (filepath[i] == '/') {
+ common_prefix = i;
+ }
+ }
+ if (common_prefix == -1) {
+ return filepath;
+ }
+ int dirs_up = 1;
+ for (int i = common_prefix + 1; cwd[i] != '\0'; i++) {
+ if (cwd[i] == '/') {
+ dirs_up++;
+ }
+ }
+ const char *unique_part = filepath + common_prefix + 1;
+ if (*unique_part == '\0') {
+ return filepath;
+ }
+ char dir_up[] = "../";
+ size_t l_dir_up = strlen(dir_up);
+ size_t l_relpath = dirs_up * l_dir_up + strlen(unique_part) + 1;
+ char *relfilepath = xcalloc(1, l_relpath);
+ int i = 0;
+ for (int d = 0; d < dirs_up; d++) {
+ strcpy(relfilepath + i, dir_up);
+ i += l_dir_up;
+ }
+ strcpy(relfilepath + i, unique_part);
+ return relfilepath;
+}
+
void
errline(struct location loc)
{
--
2.43.0