]> icculus.org git repositories - icculus/xz.git/blob - src/xz/args.c
Add --no-warn.
[icculus/xz.git] / src / xz / args.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       args.c
4 /// \brief      Argument parsing
5 ///
6 /// \note       Filter-specific options parsing is in options.c.
7 //
8 //  Author:     Lasse Collin
9 //
10 //  This file has been put into the public domain.
11 //  You can do whatever you want with this file.
12 //
13 ///////////////////////////////////////////////////////////////////////////////
14
15 #include "private.h"
16
17 #include "getopt.h"
18 #include <ctype.h>
19
20
21 bool opt_stdout = false;
22 bool opt_force = false;
23 bool opt_keep_original = false;
24
25 // We don't modify or free() this, but we need to assign it in some
26 // non-const pointers.
27 const char *stdin_filename = "(stdin)";
28
29
30 static void
31 parse_real(args_info *args, int argc, char **argv)
32 {
33         enum {
34                 OPT_SUBBLOCK = INT_MIN,
35                 OPT_X86,
36                 OPT_POWERPC,
37                 OPT_IA64,
38                 OPT_ARM,
39                 OPT_ARMTHUMB,
40                 OPT_SPARC,
41                 OPT_DELTA,
42                 OPT_LZMA1,
43                 OPT_LZMA2,
44
45                 OPT_FILES,
46                 OPT_FILES0,
47         };
48
49         static const char short_opts[]
50                         = "cC:defF:hHlkM:qQrS:tT:vVz0123456789";
51
52         static const struct option long_opts[] = {
53                 // Operation mode
54                 { "compress",       no_argument,       NULL,  'z' },
55                 { "decompress",     no_argument,       NULL,  'd' },
56                 { "uncompress",     no_argument,       NULL,  'd' },
57                 { "test",           no_argument,       NULL,  't' },
58                 { "list",           no_argument,       NULL,  'l' },
59
60                 // Operation modifiers
61                 { "keep",           no_argument,       NULL,  'k' },
62                 { "force",          no_argument,       NULL,  'f' },
63                 { "stdout",         no_argument,       NULL,  'c' },
64                 { "to-stdout",      no_argument,       NULL,  'c' },
65                 { "suffix",         required_argument, NULL,  'S' },
66                 // { "recursive",      no_argument,       NULL,  'r' }, // TODO
67                 { "files",          optional_argument, NULL,  OPT_FILES },
68                 { "files0",         optional_argument, NULL,  OPT_FILES0 },
69
70                 // Basic compression settings
71                 { "format",         required_argument, NULL,  'F' },
72                 { "check",          required_argument, NULL,  'C' },
73                 { "memory",         required_argument, NULL,  'M' },
74                 { "threads",        required_argument, NULL,  'T' },
75
76                 { "extreme",        no_argument,       NULL,  'e' },
77                 { "fast",           no_argument,       NULL,  '0' },
78                 { "best",           no_argument,       NULL,  '9' },
79
80                 // Filters
81                 { "lzma1",          optional_argument, NULL,  OPT_LZMA1 },
82                 { "lzma2",          optional_argument, NULL,  OPT_LZMA2 },
83                 { "x86",            no_argument,       NULL,  OPT_X86 },
84                 { "bcj",            no_argument,       NULL,  OPT_X86 },
85                 { "powerpc",        no_argument,       NULL,  OPT_POWERPC },
86                 { "ppc",            no_argument,       NULL,  OPT_POWERPC },
87                 { "ia64",           no_argument,       NULL,  OPT_IA64 },
88                 { "itanium",        no_argument,       NULL,  OPT_IA64 },
89                 { "arm",            no_argument,       NULL,  OPT_ARM },
90                 { "armthumb",       no_argument,       NULL,  OPT_ARMTHUMB },
91                 { "sparc",          no_argument,       NULL,  OPT_SPARC },
92                 { "delta",          optional_argument, NULL,  OPT_DELTA },
93                 { "subblock",       optional_argument, NULL,  OPT_SUBBLOCK },
94
95                 // Other options
96                 { "quiet",          no_argument,       NULL,  'q' },
97                 { "verbose",        no_argument,       NULL,  'v' },
98                 { "no-warn",        no_argument,       NULL,  'Q' },
99                 { "help",           no_argument,       NULL,  'h' },
100                 { "long-help",      no_argument,       NULL,  'H' },
101                 { "version",        no_argument,       NULL,  'V' },
102
103                 { NULL,                 0,                 NULL,   0 }
104         };
105
106         int c;
107
108         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL))
109                         != -1) {
110                 switch (c) {
111                 // Compression preset (also for decompression if --format=raw)
112                 case '0': case '1': case '2': case '3': case '4':
113                 case '5': case '6': case '7': case '8': case '9':
114                         coder_set_preset(c - '0');
115                         break;
116
117                 // --memory
118                 case 'M': {
119                         // Support specifying the limit as a percentage of
120                         // installed physical RAM.
121                         size_t len = strlen(optarg);
122                         if (len > 0 && optarg[len - 1] == '%') {
123                                 optarg[len - 1] = '\0';
124                                 hardware_memlimit_set_percentage(
125                                                 str_to_uint64(
126                                                 "memory%", optarg, 1, 100));
127                         } else {
128                                 // On 32-bit systems, SIZE_MAX would make more
129                                 // sense than UINT64_MAX. But use UINT64_MAX
130                                 // still so that scripts that assume > 4 GiB
131                                 // values don't break.
132                                 hardware_memlimit_set(str_to_uint64(
133                                                 "memory", optarg,
134                                                 0, UINT64_MAX));
135                         }
136
137                         break;
138                 }
139
140                 // --suffix
141                 case 'S':
142                         suffix_set(optarg);
143                         break;
144
145                 case 'T':
146                         hardware_threadlimit_set(str_to_uint64(
147                                         "threads", optarg, 0, UINT32_MAX));
148                         break;
149
150                 // --version
151                 case 'V':
152                         // This doesn't return.
153                         message_version();
154
155                 // --stdout
156                 case 'c':
157                         opt_stdout = true;
158                         break;
159
160                 // --decompress
161                 case 'd':
162                         opt_mode = MODE_DECOMPRESS;
163                         break;
164
165                 // --extreme
166                 case 'e':
167                         coder_set_extreme();
168                         break;
169
170                 // --force
171                 case 'f':
172                         opt_force = true;
173                         break;
174
175                 // --help
176                 case 'h':
177                         // This doesn't return.
178                         message_help(false);
179
180                 // --long-help
181                 case 'H':
182                         // This doesn't return.
183                         message_help(true);
184
185                 // --list
186                 case 'l':
187                         opt_mode = MODE_LIST;
188                         break;
189
190                 // --keep
191                 case 'k':
192                         opt_keep_original = true;
193                         break;
194
195                 // --quiet
196                 case 'q':
197                         message_verbosity_decrease();
198                         break;
199
200                 case 'Q':
201                         set_exit_no_warn();
202                         break;
203
204                 case 't':
205                         opt_mode = MODE_TEST;
206                         break;
207
208                 // --verbose
209                 case 'v':
210                         message_verbosity_increase();
211                         break;
212
213                 case 'z':
214                         opt_mode = MODE_COMPRESS;
215                         break;
216
217                 // Filter setup
218
219                 case OPT_SUBBLOCK:
220                         coder_add_filter(LZMA_FILTER_SUBBLOCK,
221                                         options_subblock(optarg));
222                         break;
223
224                 case OPT_X86:
225                         coder_add_filter(LZMA_FILTER_X86, NULL);
226                         break;
227
228                 case OPT_POWERPC:
229                         coder_add_filter(LZMA_FILTER_POWERPC, NULL);
230                         break;
231
232                 case OPT_IA64:
233                         coder_add_filter(LZMA_FILTER_IA64, NULL);
234                         break;
235
236                 case OPT_ARM:
237                         coder_add_filter(LZMA_FILTER_ARM, NULL);
238                         break;
239
240                 case OPT_ARMTHUMB:
241                         coder_add_filter(LZMA_FILTER_ARMTHUMB, NULL);
242                         break;
243
244                 case OPT_SPARC:
245                         coder_add_filter(LZMA_FILTER_SPARC, NULL);
246                         break;
247
248                 case OPT_DELTA:
249                         coder_add_filter(LZMA_FILTER_DELTA,
250                                         options_delta(optarg));
251                         break;
252
253                 case OPT_LZMA1:
254                         coder_add_filter(LZMA_FILTER_LZMA1,
255                                         options_lzma(optarg));
256                         break;
257
258                 case OPT_LZMA2:
259                         coder_add_filter(LZMA_FILTER_LZMA2,
260                                         options_lzma(optarg));
261                         break;
262
263                 // Other
264
265                 // --format
266                 case 'F': {
267                         // Just in case, support both "lzma" and "alone" since
268                         // the latter was used for forward compatibility in
269                         // LZMA Utils 4.32.x.
270                         static const struct {
271                                 char str[8];
272                                 enum format_type format;
273                         } types[] = {
274                                 { "auto",   FORMAT_AUTO },
275                                 { "xz",     FORMAT_XZ },
276                                 { "lzma",   FORMAT_LZMA },
277                                 { "alone",  FORMAT_LZMA },
278                                 // { "gzip",   FORMAT_GZIP },
279                                 // { "gz",     FORMAT_GZIP },
280                                 { "raw",    FORMAT_RAW },
281                         };
282
283                         size_t i = 0;
284                         while (strcmp(types[i].str, optarg) != 0)
285                                 if (++i == ARRAY_SIZE(types))
286                                         message_fatal(_("%s: Unknown file "
287                                                         "format type"),
288                                                         optarg);
289
290                         opt_format = types[i].format;
291                         break;
292                 }
293
294                 // --check
295                 case 'C': {
296                         static const struct {
297                                 char str[8];
298                                 lzma_check check;
299                         } types[] = {
300                                 { "none",   LZMA_CHECK_NONE },
301                                 { "crc32",  LZMA_CHECK_CRC32 },
302                                 { "crc64",  LZMA_CHECK_CRC64 },
303                                 { "sha256", LZMA_CHECK_SHA256 },
304                         };
305
306                         size_t i = 0;
307                         while (strcmp(types[i].str, optarg) != 0) {
308                                 if (++i == ARRAY_SIZE(types))
309                                         message_fatal(_("%s: Unsupported "
310                                                         "integrity "
311                                                         "check type"), optarg);
312                         }
313
314                         // Use a separate check in case we are using different
315                         // liblzma than what was used to compile us.
316                         if (!lzma_check_is_supported(types[i].check))
317                                 message_fatal(_("%s: Unsupported integrity "
318                                                 "check type"), optarg);
319
320                         coder_set_check(types[i].check);
321                         break;
322                 }
323
324                 case OPT_FILES:
325                         args->files_delim = '\n';
326
327                 // Fall through
328
329                 case OPT_FILES0:
330                         if (args->files_name != NULL)
331                                 message_fatal(_("Only one file can be "
332                                                 "specified with `--files'"
333                                                 "or `--files0'."));
334
335                         if (optarg == NULL) {
336                                 args->files_name = (char *)stdin_filename;
337                                 args->files_file = stdin;
338                         } else {
339                                 args->files_name = optarg;
340                                 args->files_file = fopen(optarg,
341                                                 c == OPT_FILES ? "r" : "rb");
342                                 if (args->files_file == NULL)
343                                         message_fatal("%s: %s", optarg,
344                                                         strerror(errno));
345                         }
346
347                         break;
348
349                 default:
350                         message_try_help();
351                         my_exit(E_ERROR);
352                 }
353         }
354
355         return;
356 }
357
358
359 static void
360 parse_environment(args_info *args, char *argv0)
361 {
362         char *env = getenv("XZ_OPT");
363         if (env == NULL)
364                 return;
365
366         // We modify the string, so make a copy of it.
367         env = xstrdup(env);
368
369         // Calculate the number of arguments in env. argc stats at one
370         // to include space for the program name.
371         int argc = 1;
372         bool prev_was_space = true;
373         for (size_t i = 0; env[i] != '\0'; ++i) {
374                 if (isspace(env[i])) {
375                         prev_was_space = true;
376                 } else if (prev_was_space) {
377                         prev_was_space = false;
378
379                         // Keep argc small enough to fit into a singed int
380                         // and to keep it usable for memory allocation.
381                         if (++argc == MIN(INT_MAX, SIZE_MAX / sizeof(char *)))
382                                 message_fatal(_("The environment variable "
383                                                 "XZ_OPT contains too many "
384                                                 "arguments"));
385                 }
386         }
387
388         // Allocate memory to hold pointers to the arguments. Add one to get
389         // space for the terminating NULL (if some systems happen to need it).
390         char **argv = xmalloc(((size_t)(argc) + 1) * sizeof(char *));
391         argv[0] = argv0;
392         argv[argc] = NULL;
393
394         // Go through the string again. Split the arguments using '\0'
395         // characters and add pointers to the resulting strings to argv.
396         argc = 1;
397         prev_was_space = true;
398         for (size_t i = 0; env[i] != '\0'; ++i) {
399                 if (isspace(env[i])) {
400                         prev_was_space = true;
401                         env[i] = '\0';
402                 } else if (prev_was_space) {
403                         prev_was_space = false;
404                         argv[argc++] = env + i;
405                 }
406         }
407
408         // Parse the argument list we got from the environment. All non-option
409         // arguments i.e. filenames are ignored.
410         parse_real(args, argc, argv);
411
412         // Reset the state of the getopt_long() so that we can parse the
413         // command line options too. There are two incompatible ways to
414         // do it.
415 #ifdef HAVE_OPTRESET
416         // BSD
417         optind = 1;
418         optreset = 1;
419 #else
420         // GNU, Solaris
421         optind = 0;
422 #endif
423
424         // We don't need the argument list from environment anymore.
425         free(argv);
426         free(env);
427
428         return;
429 }
430
431
432 extern void
433 args_parse(args_info *args, int argc, char **argv)
434 {
435         // Initialize those parts of *args that we need later.
436         args->files_name = NULL;
437         args->files_file = NULL;
438         args->files_delim = '\0';
439
440         // Check how we were called.
441         {
442 #ifdef DOSLIKE
443                 // We adjusted argv[0] in the beginning of main() so we don't
444                 // need to do anything here.
445                 const char *name = argv[0];
446 #else
447                 // Remove the leading path name, if any.
448                 const char *name = strrchr(argv[0], '/');
449                 if (name == NULL)
450                         name = argv[0];
451                 else
452                         ++name;
453 #endif
454
455                 // NOTE: It's possible that name[0] is now '\0' if argv[0]
456                 // is weird, but it doesn't matter here.
457
458                 // If the command name contains "lz",
459                 // it implies --format=lzma.
460                 if (strstr(name, "lz") != NULL)
461                         opt_format = FORMAT_LZMA;
462
463                 // Operation mode
464                 if (strstr(name, "cat") != NULL) {
465                         // Imply --decompress --stdout
466                         opt_mode = MODE_DECOMPRESS;
467                         opt_stdout = true;
468                 } else if (strstr(name, "un") != NULL) {
469                         // Imply --decompress
470                         opt_mode = MODE_DECOMPRESS;
471                 }
472         }
473
474         // First the flags from environment
475         parse_environment(args, argv[0]);
476
477         // Then from the command line
478         optind = 1;
479         parse_real(args, argc, argv);
480
481         // Never remove the source file when the destination is not on disk.
482         // In test mode the data is written nowhere, but setting opt_stdout
483         // will make the rest of the code behave well.
484         if (opt_stdout || opt_mode == MODE_TEST) {
485                 opt_keep_original = true;
486                 opt_stdout = true;
487         }
488
489         // When compressing, if no --format flag was used, or it
490         // was --format=auto, we compress to the .xz format.
491         if (opt_mode == MODE_COMPRESS && opt_format == FORMAT_AUTO)
492                 opt_format = FORMAT_XZ;
493
494         // Compression settings need to be validated (options themselves and
495         // their memory usage) when compressing to any file format. It has to
496         // be done also when uncompressing raw data, since for raw decoding
497         // the options given on the command line are used to know what kind
498         // of raw data we are supposed to decode.
499         if (opt_mode == MODE_COMPRESS || opt_format == FORMAT_RAW)
500                 coder_set_compression_settings();
501
502         // If no filenames are given, use stdin.
503         if (argv[optind] == NULL && args->files_name == NULL) {
504                 // We don't modify or free() the "-" constant. The caller
505                 // modifies this so don't make the struct itself const.
506                 static char *names_stdin[2] = { (char *)"-", NULL };
507                 args->arg_names = names_stdin;
508                 args->arg_count = 1;
509         } else {
510                 // We got at least one filename from the command line, or
511                 // --files or --files0 was specified.
512                 args->arg_names = argv + optind;
513                 args->arg_count = argc - optind;
514         }
515
516         return;
517 }