Coverage Report

Created: 2026-01-25 06:04

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