-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathargs.c
421 lines (381 loc) · 13.1 KB
/
args.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//
// args.c
// stuff
//
// Created by Michael Trent on 5/31/19.
//
#include "stuff/args.h"
#include "stuff/errors.h"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/errno.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
enum expand_result {
EXPAND_ERROR = -1,
EXPAND_COMPLETE = 0,
EXPAND_CONTINUE = 1,
};
/*
* struct string_list is a poor-man's alternative to std::vector<string>,
* "managing" a list of strings. a zeroed structure represents a valid empty
* string list; i.e., "struct string_list strings = {0};". if non-NULL, the
* strs member must point to malloced, reallocable memory; each string in the
* strs array must also be individually malloced. the strs array is expected
* to be only large enough to hold nstr string pointers, it is not generally
* null terminated.
*
* it should become its own libstuff module if it has utility in other placees.
*/
struct string_list {
int nstr;
char** strs;
};
static enum expand_result expand_at(struct string_list *args,
struct string_list* at_paths, int *hint_p);
static char* get_option(char** buf);
static void string_list_add(struct string_list* list, const char* str);
static void string_list_add_argv(struct string_list* list, int argc,
char** argv);
static int string_list_find(const struct string_list* list, const char* str);
static void string_list_dest(struct string_list* list);
/*
* args_expand_at() recursively expands "@file" options as they appear in the
* argc/argv options list.
*/
int args_expand_at(int* argc_p, char** argv_p[])
{
int hint = 0;
enum expand_result result = EXPAND_CONTINUE;
struct string_list at_paths = {0};
struct string_list args = {0};
if (!argc_p || !argv_p) {
errno = EINVAL;
return -1;
}
// copy the arguments into a private structure
string_list_add_argv(&args, *argc_p, *argv_p);
// "recursively" expand at files
while (EXPAND_CONTINUE == result) {
result = expand_at(&args, &at_paths, &hint);
}
// destroy the at_paths strings
string_list_dest(&at_paths);
// return the modified values, adding a NULL terminator to the string list
if (result == EXPAND_COMPLETE) {
args.strs = reallocf(args.strs, sizeof(char*) * (args.nstr + 1));
if (!args.strs)
system_fatal("reallocf failed");
args.strs[args.nstr] = NULL;
*argc_p = args.nstr;
*argv_p = args.strs;
}
return result == EXPAND_COMPLETE ? 0 : -1;
}
/*
* expand_at is the worker function that expands "@file" options as they
* appear in the argv array. it's designed to be called interatively, so that
* we can provide recursive "@file" references without blowing out the stack
* or imposing an arbitrary maximum.
*
* args is the argc/argv options list expressed in a string_list structure. the
* contents of the struct may be modified if arguments need to be inserted into
* the options list. expand_at requires args to be a proper string_list so it
* can resize or clean up memory as necessary.
*
* expand_at will record the name of @files it encounters during the expansion
* process so that it can return an error on infinitely-recursive input. callers
* should providee memory to an empty struct string_list via at_paths to support
* this feature, and then destroy the string_list contents when the expansion
* process has completed. alternatively, callers can set at_paths to NULL to
* disable the infinite recursion check.
*
* similarly, callers an provide memory for an int via hint_p across multiple
* calls to expand_at. the initial value of *hint_p must be 0. expand_at() will
* use this value to avoid re-examining elements in the option list that have
* already been fully expanded. this optimization can be disabled by passing
* NULL to hint_p.
*
* expand_at will return one of three states:
*
* EXPAND_CONTINUE - expand_at() has modified the options list and additional
* expansion appears to be necessary. callers should re-
* invoke expand_at() with the same set of arguments.
* EXPAND_COMPLETE - expand_at() has examined the options list and no further
* expansion is necessary. expand_at() may or may not have
* modified the args string list. at this point, callers
* are free to examine the contents of args and tear down
* related data structures.
* EXPAND_ERROR - an error was encountered during the expansion process.
* an error message was printed to stderr, and callers can
* examine errno if they like.
*
* usage is typically in a while loop, such as:
*
* // "recursively" expand at files
* enum expand_result result = EXPAND_CONTINUE;
* while (EXPAND_CONTINUE == result) {
* result = expand_at(&args, &at_paths, &hint);
* }
*/
enum expand_result expand_at(struct string_list *args,
struct string_list* at_paths, int *hint_p)
{
int argc = args->nstr;
char** argv = args->strs;
int hint = hint_p ? *hint_p : 0;
struct string_list newargs = {0};
enum expand_result result = EXPAND_COMPLETE;
for (int i = hint; i < argc; ++i) {
if ('@' == argv[i][0]) {
char* at_path = &(argv[i][1]);
// error if we have seen this path before.
if (at_paths && -1 != string_list_find(at_paths, at_path)) {
fprintf(stderr, "error: recursively loading %s\n", at_path);
return EXPAND_ERROR;
}
// open the file at this path. If the file does not exist, treat the
// entry like a literal string and continue.
int fd = open(at_path, O_RDONLY);
if (-1 == fd) {
if (ENOENT == errno) {
// awkward. add this option if necessary.
if (newargs.nstr) {
string_list_add(&newargs, argv[i]);
}
continue;
}
fprintf(stderr, "error: can't open %s: %s\n", at_path, strerror(errno));
return EXPAND_ERROR;
}
// remember we have opened this file previously
if (at_paths && -1 == string_list_find(at_paths, at_path)) {
string_list_add(at_paths, at_path);
}
// attempt to map the file into memory. if the file is empty, we will
// simply treat this as an empty buffer.
struct stat sb;
if (fstat(fd, &sb)) {
fprintf(stderr, "error: can't stat %s: %s\n", at_path, strerror(errno));
close(fd);
return EXPAND_ERROR;
}
char* addr = NULL;
if (sb.st_size) {
addr = mmap(0, (size_t)sb.st_size, PROT_READ | PROT_WRITE,
MAP_FILE | MAP_PRIVATE, fd, 0);
if (!addr) {
fprintf(stderr, "error: can't mmap %s: %s\n", at_path,
strerror(errno));
close(fd);
return EXPAND_ERROR;
}
}
if (close(fd)) {
fprintf(stderr, "error: can't close %s: %s\n", at_path,
strerror(errno));
if (munmap(addr, (size_t)sb.st_size))
fprintf(stderr, "error: can't munmap %s: %s\n", at_path,
strerror(errno));
return EXPAND_ERROR;
}
// build a new argument list now
if (0 == newargs.nstr) {
string_list_add_argv(&newargs, i, args->strs);
*hint_p = i;
}
// copy the strings in from the at file. If we see another at symbol
// set result to EXPAND_CONTINUE to request additional expansion.
if (addr) {
char* p = addr;
for (char* arg = get_option(&p); arg; arg = get_option(&p)) {
string_list_add(&newargs, arg);
if ('@' == arg[0])
result = EXPAND_CONTINUE;
}
}
// unmap the file
if (addr) {
if (munmap(addr, (size_t)sb.st_size)) {
fprintf(stderr, "error: can't munmap %s: %s\n", at_path,
strerror(errno));
return EXPAND_ERROR;
}
}
}
else { // if ('@' != argv[i][0])
// add this literal option if necessary.
if (newargs.nstr) {
string_list_add(&newargs, argv[i]);
}
}
}
if (newargs.nstr) {
string_list_dest(args);
args->nstr = newargs.nstr;
args->strs = newargs.strs;
}
return result;
}
/*
* get_option() tokenizes a string of command-line options separated by
* whitespace. given a pointer to a string, get_option() will return a pointer
* to the first word in that string and adjust the pointer to point to the
* remainder of the string. this promotes usage in a simple loop:
*
* if (string) {
* char* p = string;
* for (char* arg = get_option(&p); arg; arg = get_option(&p)) {
* // do something
* }
* }
*
* the string, buf, provides all of the storage necessary for tokenization;
* both the contents of buf as well as the value of *buf will be modified by
* get_option().
*
* get_option() honors characters escaped by \ or wrapped in single or double
* quotes. using these features callers can force options to contain whitespace,
* other backslashes, or quote characters.
*
* BUG: get_option() will not return an error if an option contains an
* unterminated quote character. The string "'one more time" will yield a single
* option "'one more time". callers will need to deal with this explicitly, if
* they care.
*
* NB: get_option() will allow callers to incldude quotes in the middle of
* an option; e.g., "one' 'two" will expand to "one two" rather than
* "one" and "two". This is consistent with unix shell behavior, but not
* consistent with some implementations of the @file command line option.
*/
static char* get_option(char** buf)
{
char* p = NULL; // beginning of option
char* q = NULL; // end of option
while (buf && *buf && *(*buf)) {
char c = *(*buf);
// whitespace
// ignore the space. if in an option, end option parsing. the option
// string (q) will be terminated later.
if (' ' == c || '\t' == c || '\n' == c || '\r' == c) {
(*buf)++;
if (p)
break;
}
// backslash
// ignore the backslash, but treat the next character as a literal
// character. start an option if not yet in an option.
else if ('\\' == c) {
// ignore the backslash (don't advance q)
(*buf)++;
// start a new option if necessary
if (!p)
p = q = *buf;
// if the string continues, include that next character in the option.
if (*(*buf)) {
*q++ = *(*buf);
(*buf)++;
}
}
// single or double quote
// ignore the quote character, but treat all characters (except backslash
// escaped cahracters) until a closing character as literal characters.
//
// BUG: unterminated quotes are indistinguishable from terminated ones.
else if ('\'' == c || '"' == c) {
// ignore the quote (don't advance q)
(*buf)++;
// start a new option if necessary
if (!p)
p = q = *buf;
// consume remaining characters
while (*(*buf) && c != *(*buf)) {
if ('\\' == *(*buf)) {
// ignore the backslash (don't advance q)
(*buf)++;
// if the string continues, include that next character in the option.
if (*(*buf)) {
*q++ = *(*buf);
(*buf)++;
}
}
else {
// include this character in the option.
*q++ = *(*buf);
(*buf)++;
}
}
// ignore the closing quote if we found one (don't advance q)
if (*(*buf))
(*buf)++;
}
// default (all other characters)
// start an option if necessary, and consume the character
else {
if (!p)
p = q = *buf;
*q++ = *(*buf);
(*buf)++;
}
}
// terminate the option string
if (q)
*q = '\0';
return p;
}
/*
* string_list_add() adds a string to the list.
*/
static void string_list_add(struct string_list* list, const char* str)
{
list->strs = reallocf(list->strs, sizeof(char*) * (list->nstr + 1));
if (!list->strs) {
system_fatal("reallocf failed");
}
list->strs[list->nstr++] = strdup(str);
}
/*
* string_list_add_argv() adds an array of strings to the string list.
*/
static void string_list_add_argv(struct string_list* list, int argc,
char* argv[])
{
list->strs = reallocf(list->strs, sizeof(char*) * (list->nstr + argc));
if (!list->strs) {
system_fatal("reallocf failed");
}
for (int i = 0; i < argc; ++i) {
list->strs[list->nstr++] = strdup(argv[i]);
}
}
/*
* string_list_find() returns the index of str in the string list, or -1 if
* the string is not found.
*/
static int string_list_find(const struct string_list* list, const char* str)
{
for (int i = 0; i < list->nstr; ++i) {
if (0 == strcmp(str, list->strs[i]))
return i;
}
return -1;
}
/*
* string_list_dest() frees the individual strings being held in the strs
* array, as well as the strs array itself. it does not free the struct
* strings_list pointer; instead it zeroes out the struct members.
*
* BUG: this function is not called string_list_free() because that might
* imply it also frees the struct string_list, which it does not.
*/
static void string_list_dest(struct string_list* list)
{
for (int i = 0; i < list->nstr; ++i) {
free(list->strs[i]);
}
free(list->strs);
list->strs = NULL;
list->nstr = 0;
}