Coverage Report

Created: 2026-04-12 06:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjpeg-turbo.3.0.x/cjpeg.c
Line
Count
Source
1
/*
2
 * cjpeg.c
3
 *
4
 * This file was part of the Independent JPEG Group's software:
5
 * Copyright (C) 1991-1998, Thomas G. Lane.
6
 * Modified 2003-2011 by Guido Vollbeding.
7
 * Lossless JPEG Modifications:
8
 * Copyright (C) 1999, Ken Murchison.
9
 * libjpeg-turbo Modifications:
10
 * Copyright (C) 2010, 2013-2014, 2017, 2019-2022, 2024-2026,
11
 *           D. R. Commander.
12
 * For conditions of distribution and use, see the accompanying README.ijg
13
 * file.
14
 *
15
 * This file contains a command-line user interface for the JPEG compressor.
16
 * It should work on any system with Unix- or MS-DOS-style command lines.
17
 *
18
 * Two different command line styles are permitted, depending on the
19
 * compile-time switch TWO_FILE_COMMANDLINE:
20
 *      cjpeg [options]  inputfile outputfile
21
 *      cjpeg [options]  [inputfile]
22
 * In the second style, output is always to standard output, which you'd
23
 * normally redirect to a file or pipe to some other program.  Input is
24
 * either from a named file or from standard input (typically redirected).
25
 * The second style is convenient on Unix but is unhelpful on systems that
26
 * don't support pipes.  Also, you MUST use the first style if your system
27
 * doesn't do binary I/O to stdin/stdout.
28
 * To simplify script writing, the "-outfile" switch is provided.  The syntax
29
 *      cjpeg [options]  -outfile outputfile  inputfile
30
 * works regardless of which command line style is used.
31
 */
32
33
#ifdef _MSC_VER
34
#define _CRT_SECURE_NO_DEPRECATE
35
#endif
36
37
#ifdef CJPEG_FUZZER
38
#define JPEG_INTERNALS
39
#endif
40
#include "cdjpeg.h"             /* Common decls for cjpeg/djpeg applications */
41
#include "jversion.h"           /* for version message */
42
#include "jconfigint.h"
43
44
45
/* Create the add-on message string table. */
46
47
#define JMESSAGE(code, string)  string,
48
49
static const char * const cdjpeg_message_table[] = {
50
#include "cderror.h"
51
  NULL
52
};
53
54
55
/*
56
 * This routine determines what format the input file is,
57
 * and selects the appropriate input-reading module.
58
 *
59
 * To determine which family of input formats the file belongs to,
60
 * we may look only at the first byte of the file, since C does not
61
 * guarantee that more than one character can be pushed back with ungetc.
62
 * Looking at additional bytes would require one of these approaches:
63
 *     1) assume we can fseek() the input file (fails for piped input);
64
 *     2) assume we can push back more than one character (works in
65
 *        some C implementations, but unportable);
66
 *     3) provide our own buffering (breaks input readers that want to use
67
 *        stdio directly);
68
 * or  4) don't put back the data, and modify the input_init methods to assume
69
 *        they start reading after the start of file.
70
 * #1 is attractive for MS-DOS but is untenable on Unix.
71
 *
72
 * The most portable solution for file types that can't be identified by their
73
 * first byte is to make the user tell us what they are.  This is also the
74
 * only approach for "raw" file types that contain only arbitrary values.
75
 * We presently apply this method for Targa files.  Most of the time Targa
76
 * files start with 0x00, so we recognize that case.  Potentially, however,
77
 * a Targa file could start with any byte value (byte 0 is the length of the
78
 * seldom-used ID field), so we provide a switch to force Targa input mode.
79
 */
80
81
static boolean is_targa;        /* records user -targa switch */
82
83
84
LOCAL(cjpeg_source_ptr)
85
select_file_type(j_compress_ptr cinfo, FILE *infile)
86
12.8k
{
87
12.8k
  int c;
88
89
12.8k
  if (is_targa) {
90
6.43k
#ifdef TARGA_SUPPORTED
91
6.43k
    return jinit_read_targa(cinfo);
92
#else
93
    ERREXIT(cinfo, JERR_TGA_NOTCOMP);
94
#endif
95
6.43k
  }
96
97
6.43k
  if ((c = getc(infile)) == EOF)
98
0
    ERREXIT(cinfo, JERR_INPUT_EMPTY);
99
6.43k
  if (ungetc(c, infile) == EOF)
100
0
    ERREXIT(cinfo, JERR_UNGETC_FAILED);
101
102
6.43k
  switch (c) {
103
0
#ifdef BMP_SUPPORTED
104
1.33k
  case 'B':
105
1.33k
    return jinit_read_bmp(cinfo, TRUE);
106
0
#endif
107
0
#ifdef GIF_SUPPORTED
108
1.81k
  case 'G':
109
1.81k
    if (cinfo->data_precision == 16) {
110
0
#ifdef C_LOSSLESS_SUPPORTED
111
0
      return j16init_read_gif(cinfo);
112
#else
113
      ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
114
      break;
115
#endif
116
1.81k
    } else if (cinfo->data_precision == 12)
117
0
      return j12init_read_gif(cinfo);
118
1.81k
    else
119
1.81k
      return jinit_read_gif(cinfo);
120
0
#endif
121
0
#ifdef PPM_SUPPORTED
122
2.00k
  case 'P':
123
2.00k
    if (cinfo->data_precision == 16) {
124
0
#ifdef C_LOSSLESS_SUPPORTED
125
0
      return j16init_read_ppm(cinfo);
126
#else
127
      ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
128
      break;
129
#endif
130
2.00k
    } else if (cinfo->data_precision == 12)
131
0
      return j12init_read_ppm(cinfo);
132
2.00k
    else
133
2.00k
      return jinit_read_ppm(cinfo);
134
0
#endif
135
0
#ifdef TARGA_SUPPORTED
136
854
  case 0x00:
137
854
    return jinit_read_targa(cinfo);
138
0
#endif
139
432
  default:
140
432
    ERREXIT(cinfo, JERR_UNKNOWN_FORMAT);
141
432
    break;
142
6.43k
  }
143
144
0
  return NULL;                  /* suppress compiler warnings */
145
6.43k
}
146
147
148
/*
149
 * Argument-parsing code.
150
 * The switch parser is designed to be useful with DOS-style command line
151
 * syntax, ie, intermixed switches and file names, where only the switches
152
 * to the left of a given file name affect processing of that file.
153
 * The main program in this file doesn't actually use this capability...
154
 */
155
156
157
static const char *progname;    /* program name for error messages */
158
static char *icc_filename;      /* for -icc switch */
159
static char *outfilename;       /* for -outfile switch */
160
static boolean memdst;          /* for -memdst switch */
161
static boolean report;          /* for -report switch */
162
static boolean strict;          /* for -strict switch */
163
164
165
#ifdef CJPEG_FUZZER
166
167
#include <setjmp.h>
168
169
struct my_error_mgr {
170
  struct jpeg_error_mgr pub;
171
  jmp_buf setjmp_buffer;
172
};
173
174
static void my_error_exit(j_common_ptr cinfo)
175
10.9k
{
176
10.9k
  struct my_error_mgr *myerr = (struct my_error_mgr *)cinfo->err;
177
178
10.9k
  longjmp(myerr->setjmp_buffer, 1);
179
10.9k
}
180
181
static void my_emit_message_fuzzer(j_common_ptr cinfo, int msg_level)
182
447M
{
183
447M
  if (msg_level < 0)
184
447M
    cinfo->err->num_warnings++;
185
447M
}
186
187
10.9k
#define HANDLE_ERROR() { \
188
10.9k
  if (cinfo.global_state > CSTATE_START) { \
189
2.10k
    if (memdst && outbuffer) \
190
2.10k
      (*cinfo.dest->term_destination) (&cinfo); \
191
2.10k
    jpeg_abort_compress(&cinfo); \
192
2.10k
  } \
193
10.9k
  jpeg_destroy_compress(&cinfo); \
194
10.9k
  if (memdst) \
195
10.9k
    free(outbuffer); \
196
10.9k
  free(icc_profile); \
197
10.9k
  return EXIT_FAILURE; \
198
10.9k
}
199
200
#endif
201
202
203
LOCAL(void)
204
usage(void)
205
/* complain about bad command line */
206
0
{
207
0
  fprintf(stderr, "usage: %s [switches] ", progname);
208
#ifdef TWO_FILE_COMMANDLINE
209
  fprintf(stderr, "inputfile outputfile\n");
210
#else
211
0
  fprintf(stderr, "[inputfile]\n");
212
0
#endif
213
214
0
  fprintf(stderr, "Switches (names may be abbreviated):\n");
215
0
  fprintf(stderr, "  -quality N[,...]   Compression quality (0..100; 5-95 is most useful range,\n");
216
0
  fprintf(stderr, "                     default is 75)\n");
217
0
  fprintf(stderr, "  -grayscale     Create monochrome JPEG file\n");
218
0
  fprintf(stderr, "  -rgb           Create RGB JPEG file\n");
219
0
#ifdef ENTROPY_OPT_SUPPORTED
220
0
  fprintf(stderr, "  -optimize      Optimize Huffman table (smaller file, but slow compression)\n");
221
0
#endif
222
0
#ifdef C_PROGRESSIVE_SUPPORTED
223
0
  fprintf(stderr, "  -progressive   Create progressive JPEG file\n");
224
0
#endif
225
0
#ifdef TARGA_SUPPORTED
226
0
  fprintf(stderr, "  -targa         Input file is Targa format (usually not needed)\n");
227
0
#endif
228
0
  fprintf(stderr, "Switches for advanced users:\n");
229
0
  fprintf(stderr, "  -precision N   Create JPEG file with N-bit data precision\n");
230
0
#ifdef C_LOSSLESS_SUPPORTED
231
0
  fprintf(stderr, "                 (N is 8, 12, or 16; default is 8; if N is 16, then -lossless\n");
232
0
  fprintf(stderr, "                 must also be specified)\n");
233
#else
234
  fprintf(stderr, "                 (N is 8 or 12; default is 8)\n");
235
#endif
236
0
#ifdef C_LOSSLESS_SUPPORTED
237
0
  fprintf(stderr, "  -lossless psv[,Pt]  Create lossless JPEG file\n");
238
0
#endif
239
0
#ifdef C_ARITH_CODING_SUPPORTED
240
0
  fprintf(stderr, "  -arithmetic    Use arithmetic coding\n");
241
0
#endif
242
0
#ifdef DCT_ISLOW_SUPPORTED
243
0
  fprintf(stderr, "  -dct int       Use accurate integer DCT method%s\n",
244
0
          (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
245
0
#endif
246
0
#ifdef DCT_IFAST_SUPPORTED
247
0
  fprintf(stderr, "  -dct fast      Use less accurate integer DCT method [legacy feature]%s\n",
248
0
          (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
249
0
#endif
250
0
#ifdef DCT_FLOAT_SUPPORTED
251
0
  fprintf(stderr, "  -dct float     Use floating-point DCT method [legacy feature]%s\n",
252
0
          (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
253
0
#endif
254
0
  fprintf(stderr, "  -icc FILE      Embed ICC profile contained in FILE\n");
255
0
  fprintf(stderr, "  -restart N     Set restart interval in rows, or in blocks with B\n");
256
0
#ifdef INPUT_SMOOTHING_SUPPORTED
257
0
  fprintf(stderr, "  -smooth N      Smooth dithered input (N=1..100 is strength)\n");
258
0
#endif
259
0
  fprintf(stderr, "  -maxmemory N   Maximum memory to use (in kbytes)\n");
260
0
  fprintf(stderr, "  -outfile name  Specify name for output file\n");
261
0
  fprintf(stderr, "  -memdst        Compress to memory instead of file (useful for benchmarking)\n");
262
0
  fprintf(stderr, "  -report        Report compression progress\n");
263
0
  fprintf(stderr, "  -strict        Treat all warnings as fatal\n");
264
0
  fprintf(stderr, "  -verbose  or  -debug   Emit debug output\n");
265
0
  fprintf(stderr, "  -version       Print version information and exit\n");
266
0
  fprintf(stderr, "Switches for wizards:\n");
267
0
  fprintf(stderr, "  -baseline      Force baseline quantization tables\n");
268
0
  fprintf(stderr, "  -qtables FILE  Use quantization tables given in FILE\n");
269
0
  fprintf(stderr, "  -qslots N[,...]    Set component quantization tables\n");
270
0
  fprintf(stderr, "  -sample HxV[,...]  Set component sampling factors\n");
271
0
#ifdef C_MULTISCAN_FILES_SUPPORTED
272
0
  fprintf(stderr, "  -scans FILE    Create multi-scan JPEG per script FILE\n");
273
0
#endif
274
0
  exit(EXIT_FAILURE);
275
0
}
276
277
278
LOCAL(int)
279
parse_switches(j_compress_ptr cinfo, int argc, char **argv,
280
               int last_file_arg_seen, boolean for_real)
281
/* Parse optional switches.
282
 * Returns argv[] index of first file-name argument (== argc if none).
283
 * Any file names with indexes <= last_file_arg_seen are ignored;
284
 * they have presumably been processed in a previous iteration.
285
 * (Pass 0 for last_file_arg_seen on the first or only iteration.)
286
 * for_real is FALSE on the first (dummy) pass; we may skip any expensive
287
 * processing.
288
 */
289
17.4k
{
290
17.4k
  int argn;
291
17.4k
  char *arg;
292
17.4k
#ifdef C_LOSSLESS_SUPPORTED
293
17.4k
  int psv = 0, pt = 0;
294
17.4k
#endif
295
17.4k
  boolean force_baseline;
296
17.4k
#ifdef C_PROGRESSIVE_SUPPORTED
297
17.4k
  boolean simple_progressive;
298
17.4k
#endif
299
17.4k
  char *qualityarg = NULL;      /* saves -quality parm if any */
300
17.4k
  char *qtablefile = NULL;      /* saves -qtables filename if any */
301
17.4k
  char *qslotsarg = NULL;       /* saves -qslots parm if any */
302
17.4k
  char *samplearg = NULL;       /* saves -sample parm if any */
303
17.4k
#ifdef C_MULTISCAN_FILES_SUPPORTED
304
17.4k
  char *scansarg = NULL;        /* saves -scans parm if any */
305
17.4k
#endif
306
307
  /* Set up default JPEG parameters. */
308
309
17.4k
  force_baseline = FALSE;       /* by default, allow 16-bit quantizers */
310
17.4k
#ifdef C_PROGRESSIVE_SUPPORTED
311
17.4k
  simple_progressive = FALSE;
312
17.4k
#endif
313
17.4k
  is_targa = FALSE;
314
17.4k
  icc_filename = NULL;
315
17.4k
  outfilename = NULL;
316
17.4k
  memdst = FALSE;
317
17.4k
  report = FALSE;
318
17.4k
  strict = FALSE;
319
17.4k
  cinfo->err->trace_level = 0;
320
321
  /* Scan command line options, adjust parameters */
322
323
138k
  for (argn = 1; argn < argc; argn++) {
324
120k
    arg = argv[argn];
325
120k
    if (*arg != '-') {
326
      /* Not a switch, must be a file name argument */
327
0
      if (argn <= last_file_arg_seen) {
328
0
        outfilename = NULL;     /* -outfile applies to just one input file */
329
0
        continue;               /* ignore this name if previously processed */
330
0
      }
331
0
      break;                    /* else done parsing switches */
332
0
    }
333
120k
    arg++;                      /* advance past switch marker character */
334
335
120k
    if (keymatch(arg, "arithmetic", 1)) {
336
      /* Use arithmetic coding. */
337
8.73k
#ifdef C_ARITH_CODING_SUPPORTED
338
8.73k
      cinfo->arith_code = TRUE;
339
#else
340
      fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
341
              progname);
342
      exit(EXIT_FAILURE);
343
#endif
344
345
112k
    } else if (keymatch(arg, "baseline", 1)) {
346
      /* Force baseline-compatible output (8-bit quantizer values). */
347
0
      force_baseline = TRUE;
348
349
112k
    } else if (keymatch(arg, "dct", 2)) {
350
      /* Select DCT algorithm. */
351
17.4k
      if (++argn >= argc)       /* advance to next argument */
352
0
        usage();
353
17.4k
      if (keymatch(argv[argn], "int", 1)) {
354
0
        cinfo->dct_method = JDCT_ISLOW;
355
17.4k
      } else if (keymatch(argv[argn], "fast", 2)) {
356
0
        cinfo->dct_method = JDCT_IFAST;
357
17.4k
      } else if (keymatch(argv[argn], "float", 2)) {
358
17.4k
        cinfo->dct_method = JDCT_FLOAT;
359
17.4k
      } else
360
0
        usage();
361
362
94.7k
    } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
363
      /* Enable debug printouts. */
364
      /* On first -d, print version identification */
365
0
      static boolean printed_version = FALSE;
366
367
0
      if (!printed_version) {
368
0
        fprintf(stderr, "%s version %s (build %s)\n",
369
0
                PACKAGE_NAME, VERSION, BUILD);
370
0
        fprintf(stderr, JCOPYRIGHT1);
371
0
        fprintf(stderr, JCOPYRIGHT2 "\n");
372
0
        fprintf(stderr, "Emulating The Independent JPEG Group's software, version %s\n\n",
373
0
                JVERSION);
374
0
        printed_version = TRUE;
375
0
      }
376
0
      cinfo->err->trace_level++;
377
378
94.7k
    } else if (keymatch(arg, "version", 4)) {
379
0
      fprintf(stderr, "%s version %s (build %s)\n",
380
0
              PACKAGE_NAME, VERSION, BUILD);
381
0
      exit(EXIT_SUCCESS);
382
383
94.7k
    } else if (keymatch(arg, "grayscale", 2) ||
384
94.7k
               keymatch(arg, "greyscale", 2)) {
385
      /* Force a monochrome JPEG file to be generated. */
386
0
      jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
387
388
94.7k
    } else if (keymatch(arg, "rgb", 3)) {
389
      /* Force an RGB JPEG file to be generated. */
390
8.73k
      jpeg_set_colorspace(cinfo, JCS_RGB);
391
392
85.9k
    } else if (keymatch(arg, "icc", 1)) {
393
      /* Set ICC filename. */
394
0
      if (++argn >= argc)       /* advance to next argument */
395
0
        usage();
396
0
      icc_filename = argv[argn];
397
398
85.9k
    } else if (keymatch(arg, "lossless", 1)) {
399
      /* Enable lossless mode. */
400
0
#ifdef C_LOSSLESS_SUPPORTED
401
0
      char ch = ',', *ptr;
402
403
0
      if (++argn >= argc)       /* advance to next argument */
404
0
        usage();
405
0
      if (sscanf(argv[argn], "%d%c", &psv, &ch) < 1 || ch != ',')
406
0
        usage();
407
0
      ptr = argv[argn];
408
0
      while (*ptr && *ptr++ != ','); /* advance to next segment of arg
409
                                        string */
410
0
      if (*ptr)
411
0
        sscanf(ptr, "%d", &pt);
412
413
      /* We must postpone execution until data_precision is known. */
414
#else
415
      fprintf(stderr, "%s: sorry, lossless output was not compiled\n",
416
              progname);
417
      exit(EXIT_FAILURE);
418
#endif
419
420
85.9k
    } else if (keymatch(arg, "maxmemory", 3)) {
421
      /* Maximum memory in Kb (or Mb with 'm'). */
422
0
      long lval;
423
0
      char ch = 'x';
424
425
0
      if (++argn >= argc)       /* advance to next argument */
426
0
        usage();
427
0
      if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
428
0
        usage();
429
0
      if (ch == 'm' || ch == 'M')
430
0
        lval *= 1000L;
431
0
      cinfo->mem->max_memory_to_use = lval * 1000L;
432
433
85.9k
    } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
434
      /* Enable entropy parm optimization. */
435
8.73k
#ifdef ENTROPY_OPT_SUPPORTED
436
8.73k
      cinfo->optimize_coding = TRUE;
437
#else
438
      fprintf(stderr, "%s: sorry, entropy optimization was not compiled in\n",
439
              progname);
440
      exit(EXIT_FAILURE);
441
#endif
442
443
77.2k
    } else if (keymatch(arg, "outfile", 4)) {
444
      /* Set output file name. */
445
0
      if (++argn >= argc)       /* advance to next argument */
446
0
        usage();
447
0
      outfilename = argv[argn]; /* save it away for later use */
448
449
77.2k
    } else if (keymatch(arg, "precision", 3)) {
450
      /* Set data precision. */
451
0
      int val;
452
453
0
      if (++argn >= argc)       /* advance to next argument */
454
0
        usage();
455
0
      if (sscanf(argv[argn], "%d", &val) != 1)
456
0
        usage();
457
0
#ifdef C_LOSSLESS_SUPPORTED
458
0
      if (val != 8 && val != 12 && val != 16)
459
#else
460
      if (val != 8 && val != 12)
461
#endif
462
0
        usage();
463
0
      cinfo->data_precision = val;
464
465
77.2k
    } else if (keymatch(arg, "progressive", 1)) {
466
      /* Select simple progressive mode. */
467
0
#ifdef C_PROGRESSIVE_SUPPORTED
468
0
      simple_progressive = TRUE;
469
      /* We must postpone execution until num_components is known. */
470
#else
471
      fprintf(stderr, "%s: sorry, progressive output was not compiled in\n",
472
              progname);
473
      exit(EXIT_FAILURE);
474
#endif
475
476
77.2k
    } else if (keymatch(arg, "memdst", 2)) {
477
      /* Use in-memory destination manager */
478
17.4k
      memdst = TRUE;
479
480
59.7k
    } else if (keymatch(arg, "quality", 1)) {
481
      /* Quality ratings (quantization table scaling factors). */
482
17.4k
      if (++argn >= argc)       /* advance to next argument */
483
0
        usage();
484
17.4k
      qualityarg = argv[argn];
485
486
42.3k
    } else if (keymatch(arg, "qslots", 2)) {
487
      /* Quantization table slot numbers. */
488
0
      if (++argn >= argc)       /* advance to next argument */
489
0
        usage();
490
0
      qslotsarg = argv[argn];
491
      /* Must delay setting qslots until after we have processed any
492
       * colorspace-determining switches, since jpeg_set_colorspace sets
493
       * default quant table numbers.
494
       */
495
496
42.3k
    } else if (keymatch(arg, "qtables", 2)) {
497
      /* Quantization tables fetched from file. */
498
0
      if (++argn >= argc)       /* advance to next argument */
499
0
        usage();
500
0
      qtablefile = argv[argn];
501
      /* We postpone actually reading the file in case -quality comes later. */
502
503
42.3k
    } else if (keymatch(arg, "report", 3)) {
504
0
      report = TRUE;
505
506
42.3k
    } else if (keymatch(arg, "restart", 1)) {
507
      /* Restart interval in MCU rows (or in MCUs with 'b'). */
508
8.73k
      long lval;
509
8.73k
      char ch = 'x';
510
511
8.73k
      if (++argn >= argc)       /* advance to next argument */
512
0
        usage();
513
8.73k
      if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
514
0
        usage();
515
8.73k
      if (lval < 0 || lval > 65535L)
516
0
        usage();
517
8.73k
      if (ch == 'b' || ch == 'B') {
518
0
        cinfo->restart_interval = (unsigned int)lval;
519
0
        cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
520
8.73k
      } else {
521
8.73k
        cinfo->restart_in_rows = (int)lval;
522
        /* restart_interval will be computed during startup */
523
8.73k
      }
524
525
33.5k
    } else if (keymatch(arg, "sample", 2)) {
526
      /* Set sampling factors. */
527
17.4k
      if (++argn >= argc)       /* advance to next argument */
528
0
        usage();
529
17.4k
      samplearg = argv[argn];
530
      /* Must delay setting sample factors until after we have processed any
531
       * colorspace-determining switches, since jpeg_set_colorspace sets
532
       * default sampling factors.
533
       */
534
535
17.4k
    } else if (keymatch(arg, "scans", 2)) {
536
      /* Set scan script. */
537
0
#ifdef C_MULTISCAN_FILES_SUPPORTED
538
0
      if (++argn >= argc)       /* advance to next argument */
539
0
        usage();
540
0
      scansarg = argv[argn];
541
      /* We must postpone reading the file in case -progressive appears. */
542
#else
543
      fprintf(stderr, "%s: sorry, multi-scan output was not compiled in\n",
544
              progname);
545
      exit(EXIT_FAILURE);
546
#endif
547
548
16.1k
    } else if (keymatch(arg, "smooth", 2)) {
549
      /* Set input smoothing factor. */
550
8.73k
      int val;
551
552
8.73k
      if (++argn >= argc)       /* advance to next argument */
553
0
        usage();
554
8.73k
      if (sscanf(argv[argn], "%d", &val) != 1)
555
0
        usage();
556
8.73k
      if (val < 0 || val > 100)
557
0
        usage();
558
8.73k
      cinfo->smoothing_factor = val;
559
560
8.73k
    } else if (keymatch(arg, "strict", 2)) {
561
0
      strict = TRUE;
562
563
7.38k
    } else if (keymatch(arg, "targa", 1)) {
564
      /* Input file is Targa format. */
565
7.38k
      is_targa = TRUE;
566
567
7.38k
    } else {
568
0
      usage();                  /* bogus switch */
569
0
    }
570
120k
  }
571
572
  /* Post-switch-scanning cleanup */
573
574
17.4k
  if (for_real) {
575
576
    /* Set quantization tables for selected quality. */
577
    /* Some or all may be overridden if -qtables is present. */
578
4.59k
    if (qualityarg != NULL)     /* process -quality if it was present */
579
4.59k
      if (!set_quality_ratings(cinfo, qualityarg, force_baseline))
580
0
        usage();
581
582
4.59k
    if (qtablefile != NULL)     /* process -qtables if it was present */
583
0
      if (!read_quant_tables(cinfo, qtablefile, force_baseline))
584
0
        usage();
585
586
4.59k
    if (qslotsarg != NULL)      /* process -qslots if it was present */
587
0
      if (!set_quant_slots(cinfo, qslotsarg))
588
0
        usage();
589
590
4.59k
    if (samplearg != NULL)      /* process -sample if it was present */
591
4.59k
      if (!set_sample_factors(cinfo, samplearg))
592
0
        usage();
593
594
4.59k
#ifdef C_PROGRESSIVE_SUPPORTED
595
4.59k
    if (simple_progressive)     /* process -progressive; -scans can override */
596
0
      jpeg_simple_progression(cinfo);
597
4.59k
#endif
598
599
4.59k
#ifdef C_LOSSLESS_SUPPORTED
600
4.59k
    if (psv != 0)               /* process -lossless */
601
0
      jpeg_enable_lossless(cinfo, psv, pt);
602
4.59k
#endif
603
604
4.59k
#ifdef C_MULTISCAN_FILES_SUPPORTED
605
4.59k
    if (scansarg != NULL)       /* process -scans if it was present */
606
0
      if (!read_scan_script(cinfo, scansarg))
607
0
        usage();
608
4.59k
#endif
609
4.59k
  }
610
611
17.4k
  return argn;                  /* return index of next arg (file name) */
612
17.4k
}
613
614
615
METHODDEF(void)
616
my_emit_message(j_common_ptr cinfo, int msg_level)
617
0
{
618
0
  if (msg_level < 0) {
619
    /* Treat warning as fatal */
620
0
    cinfo->err->error_exit(cinfo);
621
0
  } else {
622
0
    if (cinfo->err->trace_level >= msg_level)
623
0
      cinfo->err->output_message(cinfo);
624
0
  }
625
0
}
626
627
628
/*
629
 * The main program.
630
 */
631
632
#ifdef CJPEG_FUZZER
633
static int
634
cjpeg_fuzzer(int argc, char **argv, FILE *input_file)
635
#else
636
int
637
main(int argc, char **argv)
638
#endif
639
12.8k
{
640
12.8k
  struct jpeg_compress_struct cinfo;
641
12.8k
#ifdef CJPEG_FUZZER
642
12.8k
  struct my_error_mgr myerr;
643
12.8k
  struct jpeg_error_mgr &jerr = myerr.pub;
644
#else
645
  struct jpeg_error_mgr jerr;
646
#endif
647
12.8k
  struct cdjpeg_progress_mgr progress;
648
12.8k
  int file_index;
649
12.8k
  cjpeg_source_ptr src_mgr;
650
#ifndef CJPEG_FUZZER
651
  FILE *input_file = NULL;
652
#endif
653
12.8k
  FILE *icc_file;
654
12.8k
  JOCTET *icc_profile = NULL;
655
12.8k
  long icc_len = 0;
656
12.8k
  FILE *output_file = NULL;
657
12.8k
  unsigned char *outbuffer = NULL;
658
12.8k
  unsigned long outsize = 0;
659
12.8k
  JDIMENSION num_scanlines;
660
661
12.8k
  progname = argv[0];
662
12.8k
  if (progname == NULL || progname[0] == 0)
663
0
    progname = "cjpeg";         /* in case C library doesn't provide it */
664
665
  /* Initialize the JPEG compression object with default error handling. */
666
12.8k
  cinfo.err = jpeg_std_error(&jerr);
667
12.8k
  jpeg_create_compress(&cinfo);
668
  /* Add some application-specific error messages (from cderror.h) */
669
12.8k
  jerr.addon_message_table = cdjpeg_message_table;
670
12.8k
  jerr.first_addon_message = JMSG_FIRSTADDONCODE;
671
12.8k
  jerr.last_addon_message = JMSG_LASTADDONCODE;
672
673
  /* Initialize JPEG parameters.
674
   * Much of this may be overridden later.
675
   * In particular, we don't yet know the input file's color space,
676
   * but we need to provide some value for jpeg_set_defaults() to work.
677
   */
678
679
12.8k
  cinfo.in_color_space = JCS_RGB; /* arbitrary guess */
680
12.8k
  jpeg_set_defaults(&cinfo);
681
682
  /* Scan command line to find file names.
683
   * It is convenient to use just one switch-parsing routine, but the switch
684
   * values read here are ignored; we will rescan the switches after opening
685
   * the input file.
686
   */
687
688
12.8k
  file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
689
690
12.8k
  if (strict)
691
0
    jerr.emit_message = my_emit_message;
692
693
#ifdef TWO_FILE_COMMANDLINE
694
  if (!memdst) {
695
    /* Must have either -outfile switch or explicit output file name */
696
    if (outfilename == NULL) {
697
      if (file_index != argc - 2) {
698
        fprintf(stderr, "%s: must name one input and one output file\n",
699
                progname);
700
        usage();
701
      }
702
      outfilename = argv[file_index + 1];
703
    } else {
704
      if (file_index != argc - 1) {
705
        fprintf(stderr, "%s: must name one input and one output file\n",
706
                progname);
707
        usage();
708
      }
709
    }
710
  }
711
#else
712
  /* Unix style: expect zero or one file name */
713
12.8k
  if (file_index < argc - 1) {
714
0
    fprintf(stderr, "%s: only one input file\n", progname);
715
0
    usage();
716
0
  }
717
12.8k
#endif /* TWO_FILE_COMMANDLINE */
718
719
#ifndef CJPEG_FUZZER
720
  /* Open the input file. */
721
  if (file_index < argc) {
722
    if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
723
      fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
724
      exit(EXIT_FAILURE);
725
    }
726
  } else {
727
    /* default input file is stdin */
728
    input_file = read_stdin();
729
  }
730
#endif
731
732
  /* Open the output file. */
733
12.8k
  if (outfilename != NULL) {
734
0
    if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
735
0
      fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
736
0
      exit(EXIT_FAILURE);
737
0
    }
738
12.8k
  } else if (!memdst) {
739
    /* default output file is stdout */
740
0
    output_file = write_stdout();
741
0
  }
742
743
12.8k
  if (icc_filename != NULL) {
744
0
    if ((icc_file = fopen(icc_filename, READ_BINARY)) == NULL) {
745
0
      fprintf(stderr, "%s: can't open %s\n", progname, icc_filename);
746
0
      exit(EXIT_FAILURE);
747
0
    }
748
0
    if (fseek(icc_file, 0, SEEK_END) < 0 ||
749
0
        (icc_len = ftell(icc_file)) < 1 ||
750
0
        fseek(icc_file, 0, SEEK_SET) < 0) {
751
0
      fprintf(stderr, "%s: can't determine size of %s\n", progname,
752
0
              icc_filename);
753
0
      exit(EXIT_FAILURE);
754
0
    }
755
0
    if ((icc_profile = (JOCTET *)malloc(icc_len)) == NULL) {
756
0
      fprintf(stderr, "%s: can't allocate memory for ICC profile\n", progname);
757
0
      fclose(icc_file);
758
0
      exit(EXIT_FAILURE);
759
0
    }
760
0
    if (fread(icc_profile, icc_len, 1, icc_file) < 1) {
761
0
      fprintf(stderr, "%s: can't read ICC profile from %s\n", progname,
762
0
              icc_filename);
763
0
      free(icc_profile);
764
0
      fclose(icc_file);
765
0
      exit(EXIT_FAILURE);
766
0
    }
767
0
    fclose(icc_file);
768
0
  }
769
770
12.8k
#ifdef CJPEG_FUZZER
771
12.8k
  jerr.error_exit = my_error_exit;
772
12.8k
  jerr.emit_message = my_emit_message_fuzzer;
773
12.8k
  if (setjmp(myerr.setjmp_buffer))
774
8.28k
    HANDLE_ERROR()
775
4.59k
#endif
776
777
4.59k
  if (report) {
778
0
    start_progress_monitor((j_common_ptr)&cinfo, &progress);
779
0
    progress.report = report;
780
0
  }
781
782
  /* Figure out the input file format, and set up to read it. */
783
4.59k
  src_mgr = select_file_type(&cinfo, input_file);
784
4.59k
  src_mgr->input_file = input_file;
785
4.59k
#ifdef CJPEG_FUZZER
786
4.59k
  src_mgr->max_pixels = 1048576;
787
4.59k
#endif
788
789
  /* Read the input file header to obtain file size & colorspace. */
790
4.59k
  (*src_mgr->start_input) (&cinfo, src_mgr);
791
792
  /* Now that we know input colorspace, fix colorspace-dependent defaults */
793
4.59k
  jpeg_default_colorspace(&cinfo);
794
795
  /* Adjust default compression parameters by re-parsing the options */
796
4.59k
  file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
797
798
  /* Specify data destination for compression */
799
4.59k
  if (memdst)
800
4.59k
    jpeg_mem_dest(&cinfo, &outbuffer, &outsize);
801
0
  else
802
0
    jpeg_stdio_dest(&cinfo, output_file);
803
804
4.59k
#ifdef CJPEG_FUZZER
805
4.59k
  if (setjmp(myerr.setjmp_buffer))
806
2.68k
    HANDLE_ERROR()
807
1.90k
#endif
808
809
  /* Start compressor */
810
1.90k
  jpeg_start_compress(&cinfo, TRUE);
811
812
1.90k
  if (icc_profile != NULL)
813
0
    jpeg_write_icc_profile(&cinfo, icc_profile, (unsigned int)icc_len);
814
815
  /* Process data */
816
1.90k
  if (cinfo.data_precision == 16) {
817
0
#ifdef C_LOSSLESS_SUPPORTED
818
0
    while (cinfo.next_scanline < cinfo.image_height) {
819
0
      num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
820
0
      (void)jpeg16_write_scanlines(&cinfo, src_mgr->buffer16, num_scanlines);
821
0
    }
822
#else
823
    ERREXIT1(&cinfo, JERR_BAD_PRECISION, cinfo.data_precision);
824
#endif
825
1.90k
  } else if (cinfo.data_precision == 12) {
826
0
    while (cinfo.next_scanline < cinfo.image_height) {
827
0
      num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
828
0
      (void)jpeg12_write_scanlines(&cinfo, src_mgr->buffer12, num_scanlines);
829
0
    }
830
1.90k
  } else {
831
25.7M
    while (cinfo.next_scanline < cinfo.image_height) {
832
25.7M
      num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
833
25.7M
      (void)jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines);
834
25.7M
    }
835
1.90k
  }
836
837
  /* Finish compression and release memory */
838
1.90k
  (*src_mgr->finish_input) (&cinfo, src_mgr);
839
1.90k
  jpeg_finish_compress(&cinfo);
840
1.90k
  jpeg_destroy_compress(&cinfo);
841
842
  /* Close files, if we opened them */
843
#ifndef CJPEG_FUZZER
844
  if (input_file != stdin)
845
    fclose(input_file);
846
#endif
847
1.90k
  if (output_file != stdout && output_file != NULL)
848
0
    fclose(output_file);
849
850
1.90k
  if (report)
851
0
    end_progress_monitor((j_common_ptr)&cinfo);
852
853
1.90k
  if (memdst) {
854
#ifndef CJPEG_FUZZER
855
    fprintf(stderr, "Compressed size:  %lu bytes\n", outsize);
856
#endif
857
1.90k
    free(outbuffer);
858
1.90k
  }
859
860
1.90k
  free(icc_profile);
861
862
  /* All done. */
863
1.90k
  return (jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
864
4.59k
}