Coverage Report

Created: 2026-04-28 06:57

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