Coverage Report

Created: 2025-08-11 08:01

/src/libjxl/lib/jxl/icc_codec.cc
Line
Count
Source (jump to first uncovered line)
1
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
2
//
3
// Use of this source code is governed by a BSD-style
4
// license that can be found in the LICENSE file.
5
6
#include "lib/jxl/icc_codec.h"
7
8
#include <jxl/memory_manager.h>
9
10
#include <algorithm>
11
#include <cstddef>
12
#include <cstdint>
13
14
#include "lib/jxl/base/common.h"
15
#include "lib/jxl/base/status.h"
16
#include "lib/jxl/dec_ans.h"
17
#include "lib/jxl/dec_bit_reader.h"
18
#include "lib/jxl/fields.h"
19
#include "lib/jxl/icc_codec_common.h"
20
#include "lib/jxl/padded_bytes.h"
21
22
namespace jxl {
23
namespace {
24
25
// Shuffles or interleaves bytes, for example with width 2, turns "ABCDabcd"
26
// into "AaBbCcDd". Transposes a matrix of ceil(size / width) columns and
27
// width rows. There are size elements, size may be < width * height, if so the
28
// last elements of the rightmost column are missing, the missing spots are
29
// transposed along with the filled spots, and the result has the missing
30
// elements at the end of the bottom row. The input is the input matrix in
31
// scanline order but with missing elements skipped (which may occur in multiple
32
// locations), the output is the result matrix in scanline order (with
33
// no need to skip missing elements as they are past the end of the data).
34
Status Shuffle(JxlMemoryManager* memory_manager, uint8_t* data, size_t size,
35
1.41k
               size_t width) {
36
1.41k
  size_t height = (size + width - 1) / width;  // amount of rows of output
37
1.41k
  PaddedBytes result(memory_manager);
38
1.41k
  JXL_ASSIGN_OR_RETURN(result,
39
1.41k
                       PaddedBytes::WithInitialSpace(memory_manager, size));
40
  // i = output index, j input index
41
1.41k
  size_t s = 0;
42
1.41k
  size_t j = 0;
43
12.0k
  for (size_t i = 0; i < size; i++) {
44
10.6k
    result[i] = data[j];
45
10.6k
    j += height;
46
10.6k
    if (j >= size) j = ++s;
47
10.6k
  }
48
49
12.0k
  for (size_t i = 0; i < size; i++) {
50
10.6k
    data[i] = result[i];
51
10.6k
  }
52
1.41k
  return true;
53
1.41k
}
54
55
// TODO(eustas): should be 20, or even 18, once DecodeVarInt is improved;
56
//               currently DecodeVarInt does not signal the errors, and marks
57
//               11 bytes as used even if only 10 are used (and 9 is enough for
58
//               63-bit values).
59
constexpr const size_t kPreambleSize = 22;  // enough for reading 2 VarInts
60
61
9.06k
uint64_t DecodeVarInt(const uint8_t* input, size_t inputSize, size_t* pos) {
62
9.06k
  size_t i;
63
9.06k
  uint64_t ret = 0;
64
13.0k
  for (i = 0; *pos + i < inputSize && i < 10; ++i) {
65
12.9k
    ret |= static_cast<uint64_t>(input[*pos + i] & 127)
66
12.9k
           << static_cast<uint64_t>(7 * i);
67
    // If the next-byte flag is not set, stop
68
12.9k
    if ((input[*pos + i] & 128) == 0) break;
69
12.9k
  }
70
  // TODO(user): Return a decoding error if i == 10.
71
9.06k
  *pos += i + 1;
72
9.06k
  return ret;
73
9.06k
}
74
75
}  // namespace
76
77
// Mimics the beginning of UnpredictICC for quick validity check.
78
// At least kPreambleSize bytes of data should be valid at invocation time.
79
913
Status CheckPreamble(const PaddedBytes& data, size_t enc_size) {
80
913
  const uint8_t* enc = data.data();
81
913
  size_t size = data.size();
82
913
  size_t pos = 0;
83
913
  uint64_t osize = DecodeVarInt(enc, size, &pos);
84
913
  JXL_RETURN_IF_ERROR(CheckIs32Bit(osize));
85
880
  if (pos >= size) return JXL_FAILURE("Out of bounds");
86
880
  uint64_t csize = DecodeVarInt(enc, size, &pos);
87
880
  JXL_RETURN_IF_ERROR(CheckIs32Bit(csize));
88
865
  JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, csize, size));
89
  // We expect that UnpredictICC inflates input, not the other way round.
90
840
  if (osize + 65536 < enc_size) return JXL_FAILURE("Malformed ICC");
91
92
  // NB(eustas): 64 MiB ICC should be enough for everything!?
93
823
  const size_t output_limit = 1 << 28;
94
823
  if (output_limit && osize > output_limit) {
95
8
    return JXL_FAILURE("Decoded ICC is too large");
96
8
  }
97
815
  return true;
98
823
}
99
100
// Decodes the result of PredictICC back to a valid ICC profile.
101
718
Status UnpredictICC(const uint8_t* enc, size_t size, PaddedBytes* result) {
102
718
  if (!result->empty()) return JXL_FAILURE("result must be empty initially");
103
718
  JxlMemoryManager* memory_manager = result->memory_manager();
104
718
  size_t pos = 0;
105
  // TODO(lode): technically speaking we need to check that the entire varint
106
  // decoding never goes out of bounds, not just the first byte. This requires
107
  // a DecodeVarInt function that returns an error code. It is safe to use
108
  // DecodeVarInt with out of bounds values, it silently returns, but the
109
  // specification requires an error. Idem for all DecodeVarInt below.
110
718
  if (pos >= size) return JXL_FAILURE("Out of bounds");
111
693
  uint64_t osize = DecodeVarInt(enc, size, &pos);  // Output size
112
693
  JXL_RETURN_IF_ERROR(CheckIs32Bit(osize));
113
687
  if (pos >= size) return JXL_FAILURE("Out of bounds");
114
683
  uint64_t csize = DecodeVarInt(enc, size, &pos);  // Commands size
115
  // Every command is translated to at least on byte.
116
683
  JXL_RETURN_IF_ERROR(CheckIs32Bit(csize));
117
681
  size_t cpos = pos;  // pos in commands stream
118
681
  JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, csize, size));
119
655
  size_t commands_end = cpos + csize;
120
655
  pos = commands_end;  // pos in data stream
121
122
  // Header
123
655
  PaddedBytes header{memory_manager};
124
655
  JXL_RETURN_IF_ERROR(header.append(ICCInitialHeaderPrediction(osize)));
125
48.9k
  for (size_t i = 0; i <= kICCHeaderSize; i++) {
126
48.9k
    if (result->size() == osize) {
127
285
      if (cpos != commands_end) return JXL_FAILURE("Not all commands used");
128
109
      if (pos != size) return JXL_FAILURE("Not all data used");
129
12
      return true;  // Valid end
130
109
    }
131
48.6k
    if (i == kICCHeaderSize) break;  // Done
132
48.2k
    ICCPredictHeader(result->data(), result->size(), header.data(), i);
133
48.2k
    if (pos >= size) return JXL_FAILURE("Out of bounds");
134
48.2k
    JXL_RETURN_IF_ERROR(result->push_back(enc[pos++] + header[i]));
135
48.2k
  }
136
363
  if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
137
138
  // Tag list
139
359
  uint64_t numtags = DecodeVarInt(enc, size, &cpos);
140
141
359
  if (numtags != 0) {
142
216
    numtags--;
143
216
    JXL_RETURN_IF_ERROR(CheckIs32Bit(numtags));
144
182
    JXL_RETURN_IF_ERROR(AppendUint32(numtags, result));
145
182
    uint64_t prevtagstart = kICCHeaderSize + numtags * 12;
146
182
    uint64_t prevtagsize = 0;
147
8.12k
    for (;;) {
148
8.12k
      if (result->size() > osize) return JXL_FAILURE("Invalid result size");
149
8.12k
      if (cpos > commands_end) return JXL_FAILURE("Out of bounds");
150
8.11k
      if (cpos == commands_end) break;  // Valid end
151
8.07k
      uint8_t command = enc[cpos++];
152
8.07k
      uint8_t tagcode = command & 63;
153
8.07k
      Tag tag;
154
8.07k
      if (tagcode == 0) {
155
93
        break;
156
7.98k
      } else if (tagcode == kCommandTagUnknown) {
157
322
        JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, 4, size));
158
321
        tag = DecodeKeyword(enc, size, pos);
159
321
        pos += 4;
160
7.66k
      } else if (tagcode == kCommandTagTRC) {
161
633
        tag = kRtrcTag;
162
7.02k
      } else if (tagcode == kCommandTagXYZ) {
163
393
        tag = kRxyzTag;
164
6.63k
      } else {
165
6.63k
        if (tagcode - kCommandTagStringFirst >= kNumTagStrings) {
166
17
          return JXL_FAILURE("Unknown tagcode");
167
17
        }
168
6.61k
        tag = *kTagStrings[tagcode - kCommandTagStringFirst];
169
6.61k
      }
170
7.96k
      JXL_RETURN_IF_ERROR(AppendKeyword(tag, result));
171
172
7.96k
      uint64_t tagstart;
173
7.96k
      uint64_t tagsize = prevtagsize;
174
7.96k
      if (tag == kRxyzTag || tag == kGxyzTag || tag == kBxyzTag ||
175
7.96k
          tag == kKxyzTag || tag == kWtptTag || tag == kBkptTag ||
176
7.96k
          tag == kLumiTag) {
177
3.83k
        tagsize = 20;
178
3.83k
      }
179
180
7.96k
      if (command & kFlagBitOffset) {
181
941
        if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
182
937
        tagstart = DecodeVarInt(enc, size, &cpos);
183
7.02k
      } else {
184
7.02k
        JXL_RETURN_IF_ERROR(CheckIs32Bit(prevtagstart));
185
7.02k
        tagstart = prevtagstart + prevtagsize;
186
7.02k
      }
187
7.96k
      JXL_RETURN_IF_ERROR(CheckIs32Bit(tagstart));
188
7.95k
      JXL_RETURN_IF_ERROR(AppendUint32(tagstart, result));
189
7.95k
      if (command & kFlagBitSize) {
190
1.42k
        if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
191
1.41k
        tagsize = DecodeVarInt(enc, size, &cpos);
192
1.41k
      }
193
7.95k
      JXL_RETURN_IF_ERROR(CheckIs32Bit(tagsize));
194
7.94k
      JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
195
7.94k
      prevtagstart = tagstart;
196
7.94k
      prevtagsize = tagsize;
197
198
7.94k
      if (tagcode == kCommandTagTRC) {
199
630
        JXL_RETURN_IF_ERROR(AppendKeyword(kGtrcTag, result));
200
630
        JXL_RETURN_IF_ERROR(AppendUint32(tagstart, result));
201
630
        JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
202
630
        JXL_RETURN_IF_ERROR(AppendKeyword(kBtrcTag, result));
203
630
        JXL_RETURN_IF_ERROR(AppendUint32(tagstart, result));
204
630
        JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
205
630
      }
206
207
7.94k
      if (tagcode == kCommandTagXYZ) {
208
393
        JXL_RETURN_IF_ERROR(CheckIs32Bit(tagstart + tagsize * 2));
209
393
        JXL_RETURN_IF_ERROR(AppendKeyword(kGxyzTag, result));
210
393
        JXL_RETURN_IF_ERROR(AppendUint32(tagstart + tagsize, result));
211
393
        JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
212
393
        JXL_RETURN_IF_ERROR(AppendKeyword(kBxyzTag, result));
213
393
        JXL_RETURN_IF_ERROR(AppendUint32(tagstart + tagsize * 2, result));
214
393
        JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
215
393
      }
216
7.94k
    }
217
182
  }
218
219
  // Main Content
220
4.81k
  for (;;) {
221
4.81k
    if (result->size() > osize) return JXL_FAILURE("Invalid result size");
222
4.80k
    if (cpos > commands_end) return JXL_FAILURE("Out of bounds");
223
4.80k
    if (cpos == commands_end) break;  // Valid end
224
4.74k
    uint8_t command = enc[cpos++];
225
4.74k
    if (command == kCommandInsert) {
226
348
      if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
227
345
      uint64_t num = DecodeVarInt(enc, size, &cpos);
228
345
      JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, num, size));
229
856
      for (size_t i = 0; i < num; i++) {
230
534
        JXL_RETURN_IF_ERROR(result->push_back(enc[pos++]));
231
534
      }
232
4.40k
    } else if (command == kCommandShuffle2 || command == kCommandShuffle4) {
233
853
      if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
234
849
      uint64_t num = DecodeVarInt(enc, size, &cpos);
235
849
      JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, num, size));
236
836
      PaddedBytes shuffled(memory_manager);
237
836
      JXL_ASSIGN_OR_RETURN(shuffled,
238
836
                           PaddedBytes::WithInitialSpace(memory_manager, num));
239
6.90k
      for (size_t i = 0; i < num; i++) {
240
6.07k
        shuffled[i] = enc[pos + i];
241
6.07k
      }
242
836
      if (command == kCommandShuffle2) {
243
165
        JXL_RETURN_IF_ERROR(Shuffle(memory_manager, shuffled.data(), num, 2));
244
671
      } else if (command == kCommandShuffle4) {
245
671
        JXL_RETURN_IF_ERROR(Shuffle(memory_manager, shuffled.data(), num, 4));
246
671
      }
247
6.90k
      for (size_t i = 0; i < num; i++) {
248
6.07k
        JXL_RETURN_IF_ERROR(result->push_back(shuffled[i]));
249
6.07k
        pos++;
250
6.07k
      }
251
3.54k
    } else if (command == kCommandPredict) {
252
1.64k
      JXL_RETURN_IF_ERROR(CheckOutOfBounds(cpos, 2, commands_end));
253
1.63k
      uint8_t flags = enc[cpos++];
254
255
1.63k
      size_t width = (flags & 3) + 1;
256
1.63k
      if (width == 3) return JXL_FAILURE("Invalid width");
257
258
1.63k
      int order = (flags & 12) >> 2;
259
1.63k
      if (order == 3) return JXL_FAILURE("Invalid order");
260
261
1.63k
      uint64_t stride = width;
262
1.63k
      if (flags & 16) {
263
409
        if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
264
409
        stride = DecodeVarInt(enc, size, &cpos);
265
409
        if (stride < width) {
266
1
          return JXL_FAILURE("Invalid stride");
267
1
        }
268
409
      }
269
      // If stride * 4 >= result->size(), return failure. The check
270
      // "size == 0 || ((size - 1) >> 2) < stride" corresponds to
271
      // "stride * 4 >= size", but does not suffer from integer overflow.
272
      // This check is more strict than necessary but follows the specification
273
      // and the encoder should ensure this is followed.
274
1.63k
      if (result->empty() || ((result->size() - 1u) >> 2u) < stride) {
275
55
        return JXL_FAILURE("Invalid stride");
276
55
      }
277
278
1.57k
      if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
279
1.57k
      uint64_t num = DecodeVarInt(enc, size, &cpos);  // in bytes
280
1.57k
      JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, num, size));
281
282
1.55k
      PaddedBytes shuffled(memory_manager);
283
1.55k
      JXL_ASSIGN_OR_RETURN(shuffled,
284
1.55k
                           PaddedBytes::WithInitialSpace(memory_manager, num));
285
286
22.2k
      for (size_t i = 0; i < num; i++) {
287
20.7k
        shuffled[i] = enc[pos + i];
288
20.7k
      }
289
1.55k
      if (width > 1) {
290
579
        JXL_RETURN_IF_ERROR(
291
579
            Shuffle(memory_manager, shuffled.data(), num, width));
292
579
      }
293
294
1.55k
      size_t start = result->size();
295
22.2k
      for (size_t i = 0; i < num; i++) {
296
20.7k
        uint8_t predicted = LinearPredictICCValue(result->data(), start, i,
297
20.7k
                                                  stride, width, order);
298
20.7k
        JXL_RETURN_IF_ERROR(result->push_back(predicted + shuffled[i]));
299
20.7k
      }
300
1.55k
      pos += num;
301
1.90k
    } else if (command == kCommandXYZ) {
302
837
      JXL_RETURN_IF_ERROR(AppendKeyword(kXyz_Tag, result));
303
4.18k
      for (int i = 0; i < 4; i++) {
304
3.34k
        JXL_RETURN_IF_ERROR(result->push_back(0));
305
3.34k
      }
306
837
      JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, 12, size));
307
10.8k
      for (size_t i = 0; i < 12; i++) {
308
9.98k
        JXL_RETURN_IF_ERROR(result->push_back(enc[pos++]));
309
9.98k
      }
310
1.06k
    } else if (command >= kCommandTypeStartFirst &&
311
1.06k
               command < kCommandTypeStartFirst + kNumTypeStrings) {
312
992
      JXL_RETURN_IF_ERROR(AppendKeyword(
313
992
          *kTypeStrings[command - kCommandTypeStartFirst], result));
314
4.96k
      for (size_t i = 0; i < 4; i++) {
315
3.96k
        JXL_RETURN_IF_ERROR(result->push_back(0));
316
3.96k
      }
317
992
    } else {
318
76
      return JXL_FAILURE("Unknown command");
319
76
    }
320
4.74k
  }
321
322
59
  if (pos != size) return JXL_FAILURE("Not all data used");
323
1
  if (result->size() != osize) return JXL_FAILURE("Invalid result size");
324
325
0
  return true;
326
1
}
327
328
1.58k
Status ICCReader::Init(BitReader* reader) {
329
1.58k
  JXL_RETURN_IF_ERROR(CheckEOI(reader));
330
1.58k
  JxlMemoryManager* memory_manager = decompressed_.memory_manager();
331
1.58k
  used_bits_base_ = reader->TotalBitsConsumed();
332
1.58k
  if (bits_to_skip_ == 0) {
333
1.49k
    enc_size_ = U64Coder::Read(reader);
334
1.49k
    if (enc_size_ > 268435456) {
335
      // Avoid too large memory allocation for invalid file.
336
57
      return JXL_FAILURE("Too large encoded profile");
337
57
    }
338
1.43k
    JXL_RETURN_IF_ERROR(DecodeHistograms(
339
1.43k
        memory_manager, reader, kNumICCContexts, &code_, &context_map_));
340
2.45k
    JXL_ASSIGN_OR_RETURN(ans_reader_, ANSSymbolReader::Create(&code_, reader));
341
2.45k
    i_ = 0;
342
2.45k
    JXL_RETURN_IF_ERROR(
343
2.45k
        decompressed_.resize(std::min<size_t>(i_ + 0x400, enc_size_)));
344
3.48k
    for (; i_ < std::min<size_t>(2, enc_size_); i_++) {
345
2.26k
      decompressed_[i_] = ans_reader_.ReadHybridUint(
346
2.26k
          ICCANSContext(i_, i_ > 0 ? decompressed_[i_ - 1] : 0,
347
2.26k
                        i_ > 1 ? decompressed_[i_ - 2] : 0),
348
2.26k
          reader, context_map_);
349
2.26k
    }
350
1.22k
    if (enc_size_ > kPreambleSize) {
351
21.5k
      for (; i_ < kPreambleSize; i_++) {
352
20.5k
        decompressed_[i_] = ans_reader_.ReadHybridUint(
353
20.5k
            ICCANSContext(i_, decompressed_[i_ - 1], decompressed_[i_ - 2]),
354
20.5k
            reader, context_map_);
355
20.5k
      }
356
1.02k
      JXL_RETURN_IF_ERROR(CheckEOI(reader));
357
913
      JXL_RETURN_IF_ERROR(CheckPreamble(decompressed_, enc_size_));
358
913
    }
359
1.01k
    bits_to_skip_ = reader->TotalBitsConsumed() - used_bits_base_;
360
1.01k
  } else {
361
89
    reader->SkipBits(bits_to_skip_);
362
89
  }
363
1.10k
  return true;
364
1.58k
}
365
366
1.00k
Status ICCReader::Process(BitReader* reader, PaddedBytes* icc) {
367
1.00k
  auto checkpoint = jxl::make_unique<ANSSymbolReader::Checkpoint>();
368
1.00k
  size_t saved_i = 0;
369
18.5k
  auto save = [&]() {
370
18.5k
    ans_reader_.Save(checkpoint.get());
371
18.5k
    bits_to_skip_ = reader->TotalBitsConsumed() - used_bits_base_;
372
18.5k
    saved_i = i_;
373
18.5k
  };
374
1.00k
  save();
375
18.5k
  auto check_and_restore = [&]() -> Status {
376
18.5k
    Status status = CheckEOI(reader);
377
18.5k
    if (!status) {
378
      // not enough bytes.
379
282
      ans_reader_.Restore(*checkpoint);
380
282
      i_ = saved_i;
381
282
      return status;
382
282
    }
383
18.2k
    return true;
384
18.5k
  };
385
9.21M
  for (; i_ < enc_size_; i_++) {
386
9.20M
    if (i_ % ANSSymbolReader::kMaxCheckpointInterval == 0 && i_ > 0) {
387
17.7k
      JXL_RETURN_IF_ERROR(check_and_restore());
388
17.5k
      save();
389
17.5k
      if ((i_ > 0) && (((i_ & 0xFFFF) == 0))) {
390
115
        float used_bytes =
391
115
            (reader->TotalBitsConsumed() - used_bits_base_) / 8.0f;
392
115
        if (i_ > used_bytes * 256) return JXL_FAILURE("Corrupted stream");
393
115
      }
394
17.5k
      JXL_RETURN_IF_ERROR(
395
17.5k
          decompressed_.resize(std::min<size_t>(i_ + 0x400, enc_size_)));
396
17.5k
    }
397
9.20M
    JXL_ENSURE(i_ >= 2);
398
9.20M
    decompressed_[i_] = ans_reader_.ReadHybridUint(
399
9.20M
        ICCANSContext(i_, decompressed_[i_ - 1], decompressed_[i_ - 2]), reader,
400
9.20M
        context_map_);
401
9.20M
  }
402
829
  JXL_RETURN_IF_ERROR(check_and_restore());
403
718
  bits_to_skip_ = reader->TotalBitsConsumed() - used_bits_base_;
404
718
  if (!ans_reader_.CheckANSFinalState()) {
405
0
    return JXL_FAILURE("Corrupted ICC profile");
406
0
  }
407
408
718
  icc->clear();
409
718
  return UnpredictICC(decompressed_.data(), decompressed_.size(), icc);
410
718
}
411
412
21.1k
Status ICCReader::CheckEOI(BitReader* reader) {
413
21.1k
  if (reader->AllReadsWithinBounds()) return true;
414
395
  return JXL_NOT_ENOUGH_BYTES("Not enough bytes for reading ICC profile");
415
21.1k
}
416
417
}  // namespace jxl