Clean up -MT/-MQ code

Remove unreachable argument presence check (handled by `getopt`)
Merge allocation paths into a single `realloc` call
Avoid searching for string lengths multiple times
Tiny (compatible) change: no space between last dependent and colon if
`-MT` or `-MQ` is specified
This commit is contained in:
ISSOtm
2021-11-06 13:21:19 +01:00
parent 47442941b6
commit b06e3b239d

View File

@@ -288,33 +288,23 @@ int main(int argc, char *argv[])
generatePhonyDeps = true; generatePhonyDeps = true;
break; break;
char *newTarget;
case 'Q': case 'Q':
case 'T': case 'T':
if (musl_optind == argc) newTarget = musl_optarg;
errx(1, "-M%c takes a target file name argument", depType);
ep = musl_optarg;
if (depType == 'Q') if (depType == 'Q')
ep = make_escape(ep); newTarget = make_escape(newTarget);
size_t newTargetLen = strlen(newTarget) + 1; // Plus the space
targetFileNameLen += strlen(ep) + 1; targetFileName = realloc(targetFileName,
if (!targetFileName) { targetFileNameLen + newTargetLen + 1);
/* On first alloc, make an empty str */
targetFileName = malloc(targetFileNameLen + 1);
if (targetFileName)
*targetFileName = '\0';
} else {
targetFileName = realloc(targetFileName,
targetFileNameLen + 1);
}
if (targetFileName == NULL) if (targetFileName == NULL)
err(1, "Cannot append new file to target file list"); err(1, "Cannot append new file to target file list");
strcat(targetFileName, ep); memcpy(&targetFileName[targetFileNameLen], newTarget, newTargetLen);
if (depType == 'Q') if (depType == 'Q')
free(ep); free(newTarget);
char *ptr = targetFileName + strlen(targetFileName); targetFileNameLen += newTargetLen;
targetFileName[targetFileNameLen - 1] = ' ';
*ptr++ = ' ';
*ptr = '\0';
break; break;
} }
break; break;
@@ -328,6 +318,8 @@ int main(int argc, char *argv[])
if (targetFileName == NULL) if (targetFileName == NULL)
targetFileName = objectName; targetFileName = objectName;
else
targetFileName[targetFileNameLen - 1] = '\0'; // Overwrite the last space
if (argc == musl_optind) { if (argc == musl_optind) {
fputs("FATAL: No input files\n", stderr); fputs("FATAL: No input files\n", stderr);
@@ -344,7 +336,7 @@ int main(int argc, char *argv[])
if (dependfile) { if (dependfile) {
if (!targetFileName) if (!targetFileName)
errx(1, "Dependency files can only be created if a target file is specified with either -o, -MQ or -MT\n"); errx(1, "Dependency files can only be created if a target file is specified with either -o, -MQ or -MT");
fprintf(dependfile, "%s: %s\n", targetFileName, mainFileName); fprintf(dependfile, "%s: %s\n", targetFileName, mainFileName);
} }