Coverage Report

Created: 2026-04-01 07:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/icc_codec.cc
Line
Count
Source
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
8.91k
               size_t width) {
36
8.91k
  size_t height = (size + width - 1) / width;  // amount of rows of output
37
8.91k
  PaddedBytes result(memory_manager);
38
8.91k
  JXL_ASSIGN_OR_RETURN(result,
39
8.91k
                       PaddedBytes::WithInitialSpace(memory_manager, size));
40
  // i = output index, j input index
41
8.91k
  size_t s = 0;
42
8.91k
  size_t j = 0;
43
368k
  for (size_t i = 0; i < size; i++) {
44
359k
    result[i] = data[j];
45
359k
    j += height;
46
359k
    if (j >= size) j = ++s;
47
359k
  }
48
49
368k
  for (size_t i = 0; i < size; i++) {
50
359k
    data[i] = result[i];
51
359k
  }
52
8.91k
  return true;
53
8.91k
}
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
65.7k
uint64_t DecodeVarInt(const uint8_t* input, size_t inputSize, size_t* pos) {
62
65.7k
  size_t i;
63
65.7k
  uint64_t ret = 0;
64
84.2k
  for (i = 0; *pos + i < inputSize && i < 10; ++i) {
65
84.2k
    ret |= static_cast<uint64_t>(input[*pos + i] & 127)
66
84.2k
           << static_cast<uint64_t>(7 * i);
67
    // If the next-byte flag is not set, stop
68
84.2k
    if ((input[*pos + i] & 128) == 0) break;
69
84.2k
  }
70
  // TODO(user): Return a decoding error if i == 10.
71
65.7k
  *pos += i + 1;
72
65.7k
  return ret;
73
65.7k
}
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
3.52k
Status CheckPreamble(const PaddedBytes& data, size_t enc_size) {
80
3.52k
  const uint8_t* enc = data.data();
81
3.52k
  size_t size = data.size();
82
3.52k
  size_t pos = 0;
83
3.52k
  uint64_t osize = DecodeVarInt(enc, size, &pos);
84
3.52k
  JXL_RETURN_IF_ERROR(CheckIs32Bit(osize));
85
3.52k
  if (pos >= size) return JXL_FAILURE("Out of bounds");
86
3.52k
  uint64_t csize = DecodeVarInt(enc, size, &pos);
87
3.52k
  JXL_RETURN_IF_ERROR(CheckIs32Bit(csize));
88
3.52k
  JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, csize, size));
89
  // We expect that UnpredictICC inflates input, not the other way round.
90
3.52k
  if (osize + 65536 < enc_size) return JXL_FAILURE("Malformed ICC");
91
92
  // NB(eustas): 64 MiB ICC should be enough for everything!?
93
3.52k
  const size_t output_limit = 1 << 28;
94
3.52k
  if (output_limit && osize > output_limit) {
95
0
    return JXL_FAILURE("Decoded ICC is too large");
96
0
  }
97
3.52k
  return true;
98
3.52k
}
99
100
// Decodes the result of PredictICC back to a valid ICC profile.
101
3.50k
Status UnpredictICC(const uint8_t* enc, size_t size, PaddedBytes* result) {
102
3.50k
  if (!result->empty()) return JXL_FAILURE("result must be empty initially");
103
3.50k
  JxlMemoryManager* memory_manager = result->memory_manager();
104
3.50k
  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
3.50k
  if (pos >= size) return JXL_FAILURE("Out of bounds");
111
3.50k
  uint64_t osize = DecodeVarInt(enc, size, &pos);  // Output size
112
3.50k
  JXL_RETURN_IF_ERROR(CheckIs32Bit(osize));
113
3.50k
  if (pos >= size) return JXL_FAILURE("Out of bounds");
114
3.50k
  uint64_t csize = DecodeVarInt(enc, size, &pos);  // Commands size
115
  // Every command is translated to at least on byte.
116
3.50k
  JXL_RETURN_IF_ERROR(CheckIs32Bit(csize));
117
3.50k
  size_t cpos = pos;  // pos in commands stream
118
3.50k
  JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, csize, size));
119
3.50k
  size_t commands_end = cpos + csize;
120
3.50k
  pos = commands_end;  // pos in data stream
121
122
  // Header
123
3.50k
  PaddedBytes header{memory_manager};
124
3.50k
  JXL_RETURN_IF_ERROR(header.append(ICCInitialHeaderPrediction(osize)));
125
452k
  for (size_t i = 0; i <= kICCHeaderSize; i++) {
126
452k
    if (result->size() == osize) {
127
1
      if (cpos != commands_end) return JXL_FAILURE("Not all commands used");
128
1
      if (pos != size) return JXL_FAILURE("Not all data used");
129
0
      return true;  // Valid end
130
1
    }
131
452k
    if (i == kICCHeaderSize) break;  // Done
132
448k
    ICCPredictHeader(result->data(), result->size(), header.data(), i);
133
448k
    if (pos >= size) return JXL_FAILURE("Out of bounds");
134
448k
    JXL_RETURN_IF_ERROR(result->push_back(enc[pos++] + header[i]));
135
448k
  }
136
3.50k
  if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
137
138
  // Tag list
139
3.50k
  uint64_t numtags = DecodeVarInt(enc, size, &cpos);
140
141
3.50k
  if (numtags != 0) {
142
3.50k
    numtags--;
143
3.50k
    JXL_RETURN_IF_ERROR(CheckIs32Bit(numtags));
144
3.50k
    JXL_RETURN_IF_ERROR(AppendUint32(numtags, result));
145
3.50k
    uint64_t prevtagstart = kICCHeaderSize + numtags * 12;
146
3.50k
    uint64_t prevtagsize = 0;
147
29.6k
    for (;;) {
148
29.6k
      if (result->size() > osize) return JXL_FAILURE("Invalid result size");
149
29.6k
      if (cpos > commands_end) return JXL_FAILURE("Out of bounds");
150
29.6k
      if (cpos == commands_end) break;  // Valid end
151
29.6k
      uint8_t command = enc[cpos++];
152
29.6k
      uint8_t tagcode = command & 63;
153
29.6k
      Tag tag;
154
29.6k
      if (tagcode == 0) {
155
3.50k
        break;
156
26.1k
      } else if (tagcode == kCommandTagUnknown) {
157
1.07k
        JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, 4, size));
158
1.07k
        tag = DecodeKeyword(enc, size, pos);
159
1.07k
        pos += 4;
160
25.0k
      } else if (tagcode == kCommandTagTRC) {
161
3.43k
        tag = kRtrcTag;
162
21.6k
      } else if (tagcode == kCommandTagXYZ) {
163
2.47k
        tag = kRxyzTag;
164
19.1k
      } else {
165
19.1k
        if (tagcode - kCommandTagStringFirst >= kNumTagStrings) {
166
1
          return JXL_FAILURE("Unknown tagcode");
167
1
        }
168
19.1k
        tag = *kTagStrings[tagcode - kCommandTagStringFirst];
169
19.1k
      }
170
26.1k
      JXL_RETURN_IF_ERROR(AppendKeyword(tag, result));
171
172
26.1k
      uint64_t tagstart;
173
26.1k
      uint64_t tagsize = prevtagsize;
174
26.1k
      if (tag == kRxyzTag || tag == kGxyzTag || tag == kBxyzTag ||
175
20.7k
          tag == kKxyzTag || tag == kWtptTag || tag == kBkptTag ||
176
17.2k
          tag == kLumiTag) {
177
8.88k
        tagsize = 20;
178
8.88k
      }
179
180
26.1k
      if (command & kFlagBitOffset) {
181
10.4k
        if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
182
10.4k
        tagstart = DecodeVarInt(enc, size, &cpos);
183
15.6k
      } else {
184
15.6k
        JXL_RETURN_IF_ERROR(CheckIs32Bit(prevtagstart));
185
15.6k
        tagstart = prevtagstart + prevtagsize;
186
15.6k
      }
187
26.1k
      JXL_RETURN_IF_ERROR(CheckIs32Bit(tagstart));
188
26.1k
      JXL_RETURN_IF_ERROR(AppendUint32(tagstart, result));
189
26.1k
      if (command & kFlagBitSize) {
190
16.7k
        if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
191
16.7k
        tagsize = DecodeVarInt(enc, size, &cpos);
192
16.7k
      }
193
26.1k
      JXL_RETURN_IF_ERROR(CheckIs32Bit(tagsize));
194
26.1k
      JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
195
26.1k
      prevtagstart = tagstart;
196
26.1k
      prevtagsize = tagsize;
197
198
26.1k
      if (tagcode == kCommandTagTRC) {
199
3.43k
        JXL_RETURN_IF_ERROR(AppendKeyword(kGtrcTag, result));
200
3.43k
        JXL_RETURN_IF_ERROR(AppendUint32(tagstart, result));
201
3.43k
        JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
202
3.43k
        JXL_RETURN_IF_ERROR(AppendKeyword(kBtrcTag, result));
203
3.43k
        JXL_RETURN_IF_ERROR(AppendUint32(tagstart, result));
204
3.43k
        JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
205
3.43k
      }
206
207
26.1k
      if (tagcode == kCommandTagXYZ) {
208
2.47k
        JXL_RETURN_IF_ERROR(CheckIs32Bit(tagstart + tagsize * 2));
209
2.47k
        JXL_RETURN_IF_ERROR(AppendKeyword(kGxyzTag, result));
210
2.47k
        JXL_RETURN_IF_ERROR(AppendUint32(tagstart + tagsize, result));
211
2.47k
        JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
212
2.47k
        JXL_RETURN_IF_ERROR(AppendKeyword(kBxyzTag, result));
213
2.47k
        JXL_RETURN_IF_ERROR(AppendUint32(tagstart + tagsize * 2, result));
214
2.47k
        JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
215
2.47k
      }
216
26.1k
    }
217
3.50k
  }
218
219
  // Main Content
220
54.3k
  for (;;) {
221
54.3k
    if (result->size() > osize) return JXL_FAILURE("Invalid result size");
222
54.3k
    if (cpos > commands_end) return JXL_FAILURE("Out of bounds");
223
54.3k
    if (cpos == commands_end) break;  // Valid end
224
50.8k
    uint8_t command = enc[cpos++];
225
50.8k
    if (command == kCommandInsert) {
226
12.0k
      if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
227
12.0k
      uint64_t num = DecodeVarInt(enc, size, &cpos);
228
12.0k
      JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, num, size));
229
4.36M
      for (size_t i = 0; i < num; i++) {
230
4.35M
        JXL_RETURN_IF_ERROR(result->push_back(enc[pos++]));
231
4.35M
      }
232
38.7k
    } else if (command == kCommandShuffle2 || command == kCommandShuffle4) {
233
8.91k
      if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
234
8.91k
      uint64_t num = DecodeVarInt(enc, size, &cpos);
235
8.91k
      JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, num, size));
236
8.91k
      PaddedBytes shuffled(memory_manager);
237
8.91k
      JXL_ASSIGN_OR_RETURN(shuffled,
238
8.91k
                           PaddedBytes::WithInitialSpace(memory_manager, num));
239
368k
      for (size_t i = 0; i < num; i++) {
240
359k
        shuffled[i] = enc[pos + i];
241
359k
      }
242
8.91k
      if (command == kCommandShuffle2) {
243
8.91k
        JXL_RETURN_IF_ERROR(Shuffle(memory_manager, shuffled.data(), num, 2));
244
8.91k
      } else if (command == kCommandShuffle4) {
245
0
        JXL_RETURN_IF_ERROR(Shuffle(memory_manager, shuffled.data(), num, 4));
246
0
      }
247
368k
      for (size_t i = 0; i < num; i++) {
248
359k
        JXL_RETURN_IF_ERROR(result->push_back(shuffled[i]));
249
359k
        pos++;
250
359k
      }
251
29.8k
    } else if (command == kCommandPredict) {
252
0
      JXL_RETURN_IF_ERROR(CheckOutOfBounds(cpos, 2, commands_end));
253
0
      uint8_t flags = enc[cpos++];
254
255
0
      size_t width = (flags & 3) + 1;
256
0
      if (width == 3) return JXL_FAILURE("Invalid width");
257
258
0
      int order = (flags & 12) >> 2;
259
0
      if (order == 3) return JXL_FAILURE("Invalid order");
260
261
0
      uint64_t stride = width;
262
0
      if (flags & 16) {
263
0
        if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
264
0
        stride = DecodeVarInt(enc, size, &cpos);
265
0
        if (stride < width) {
266
0
          return JXL_FAILURE("Invalid stride");
267
0
        }
268
0
      }
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
0
      if (result->empty() || ((result->size() - 1u) >> 2u) < stride) {
275
0
        return JXL_FAILURE("Invalid stride");
276
0
      }
277
278
0
      if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
279
0
      uint64_t num = DecodeVarInt(enc, size, &cpos);  // in bytes
280
0
      JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, num, size));
281
282
0
      PaddedBytes shuffled(memory_manager);
283
0
      JXL_ASSIGN_OR_RETURN(shuffled,
284
0
                           PaddedBytes::WithInitialSpace(memory_manager, num));
285
286
0
      for (size_t i = 0; i < num; i++) {
287
0
        shuffled[i] = enc[pos + i];
288
0
      }
289
0
      if (width > 1) {
290
0
        JXL_RETURN_IF_ERROR(
291
0
            Shuffle(memory_manager, shuffled.data(), num, width));
292
0
      }
293
294
0
      size_t start = result->size();
295
0
      for (size_t i = 0; i < num; i++) {
296
0
        uint8_t predicted = LinearPredictICCValue(result->data(), start, i,
297
0
                                                  stride, width, order);
298
0
        JXL_RETURN_IF_ERROR(result->push_back(predicted + shuffled[i]));
299
0
      }
300
0
      pos += num;
301
29.8k
    } else if (command == kCommandXYZ) {
302
13.8k
      JXL_RETURN_IF_ERROR(AppendKeyword(kXyz_Tag, result));
303
69.1k
      for (int i = 0; i < 4; i++) {
304
55.3k
        JXL_RETURN_IF_ERROR(result->push_back(0));
305
55.3k
      }
306
13.8k
      JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, 12, size));
307
179k
      for (size_t i = 0; i < 12; i++) {
308
165k
        JXL_RETURN_IF_ERROR(result->push_back(enc[pos++]));
309
165k
      }
310
15.9k
    } else if (command >= kCommandTypeStartFirst &&
311
15.9k
               command < kCommandTypeStartFirst + kNumTypeStrings) {
312
15.9k
      JXL_RETURN_IF_ERROR(AppendKeyword(
313
15.9k
          *kTypeStrings[command - kCommandTypeStartFirst], result));
314
79.8k
      for (size_t i = 0; i < 4; i++) {
315
63.9k
        JXL_RETURN_IF_ERROR(result->push_back(0));
316
63.9k
      }
317
15.9k
    } else {
318
0
      return JXL_FAILURE("Unknown command");
319
0
    }
320
50.8k
  }
321
322
3.50k
  if (pos != size) return JXL_FAILURE("Not all data used");
323
3.49k
  if (result->size() != osize) return JXL_FAILURE("Invalid result size");
324
325
3.49k
  return true;
326
3.49k
}
327
328
3.78k
Status ICCReader::Init(BitReader* reader) {
329
3.78k
  JXL_RETURN_IF_ERROR(CheckEOI(reader));
330
3.78k
  JxlMemoryManager* memory_manager = decompressed_.memory_manager();
331
3.78k
  used_bits_base_ = reader->TotalBitsConsumed();
332
3.78k
  if (bits_to_skip_ == 0) {
333
3.64k
    enc_size_ = U64Coder::Read(reader);
334
3.64k
    if (enc_size_ > 268435456) {
335
      // Avoid too large memory allocation for invalid file.
336
0
      return JXL_FAILURE("Too large encoded profile");
337
0
    }
338
3.64k
    JXL_RETURN_IF_ERROR(DecodeHistograms(
339
3.64k
        memory_manager, reader, kNumICCContexts, &code_, &context_map_));
340
7.05k
    JXL_ASSIGN_OR_RETURN(ans_reader_, ANSSymbolReader::Create(&code_, reader));
341
7.05k
    i_ = 0;
342
7.05k
    JXL_RETURN_IF_ERROR(
343
7.05k
        decompressed_.resize(std::min<size_t>(i_ + 0x400, enc_size_)));
344
10.5k
    for (; i_ < std::min<size_t>(2, enc_size_); i_++) {
345
7.05k
      decompressed_[i_] = ans_reader_.ReadHybridUint(
346
7.05k
          ICCANSContext(i_, i_ > 0 ? decompressed_[i_ - 1] : 0,
347
7.05k
                        i_ > 1 ? decompressed_[i_ - 2] : 0),
348
7.05k
          reader, context_map_);
349
7.05k
    }
350
3.52k
    if (enc_size_ > kPreambleSize) {
351
74.0k
      for (; i_ < kPreambleSize; i_++) {
352
70.5k
        decompressed_[i_] = ans_reader_.ReadHybridUint(
353
70.5k
            ICCANSContext(i_, decompressed_[i_ - 1], decompressed_[i_ - 2]),
354
70.5k
            reader, context_map_);
355
70.5k
      }
356
3.52k
      JXL_RETURN_IF_ERROR(CheckEOI(reader));
357
3.52k
      JXL_RETURN_IF_ERROR(CheckPreamble(decompressed_, enc_size_));
358
3.52k
    }
359
3.52k
    bits_to_skip_ = reader->TotalBitsConsumed() - used_bits_base_;
360
3.52k
  } else {
361
139
    reader->SkipBits(bits_to_skip_);
362
139
  }
363
3.66k
  return true;
364
3.78k
}
365
366
3.66k
Status ICCReader::Process(BitReader* reader, PaddedBytes* icc) {
367
3.66k
  auto checkpoint = jxl::make_unique<ANSSymbolReader::Checkpoint>();
368
3.66k
  size_t saved_i = 0;
369
56.0k
  auto save = [&]() {
370
56.0k
    ans_reader_.Save(checkpoint.get());
371
56.0k
    bits_to_skip_ = reader->TotalBitsConsumed() - used_bits_base_;
372
56.0k
    saved_i = i_;
373
56.0k
  };
374
3.66k
  save();
375
56.0k
  auto check_and_restore = [&]() -> Status {
376
56.0k
    Status status = CheckEOI(reader);
377
56.0k
    if (!status) {
378
      // not enough bytes.
379
160
      ans_reader_.Restore(*checkpoint);
380
160
      i_ = saved_i;
381
160
      return status;
382
160
    }
383
55.8k
    return true;
384
56.0k
  };
385
27.7M
  for (; i_ < enc_size_; i_++) {
386
27.7M
    if (i_ % ANSSymbolReader::kMaxCheckpointInterval == 0 && i_ > 0) {
387
52.3k
      JXL_RETURN_IF_ERROR(check_and_restore());
388
52.3k
      save();
389
52.3k
      if ((i_ > 0) && (((i_ & 0xFFFF) == 0))) {
390
359
        float used_bytes =
391
359
            (reader->TotalBitsConsumed() - used_bits_base_) / 8.0f;
392
359
        if (i_ > used_bytes * 256) return JXL_FAILURE("Corrupted stream");
393
359
      }
394
52.3k
      JXL_RETURN_IF_ERROR(
395
52.3k
          decompressed_.resize(std::min<size_t>(i_ + 0x400, enc_size_)));
396
52.3k
    }
397
27.7M
    JXL_ENSURE(i_ >= 2);
398
27.7M
    decompressed_[i_] = ans_reader_.ReadHybridUint(
399
27.7M
        ICCANSContext(i_, decompressed_[i_ - 1], decompressed_[i_ - 2]), reader,
400
27.7M
        context_map_);
401
27.7M
  }
402
3.64k
  JXL_RETURN_IF_ERROR(check_and_restore());
403
3.50k
  bits_to_skip_ = reader->TotalBitsConsumed() - used_bits_base_;
404
3.50k
  if (!ans_reader_.CheckANSFinalState()) {
405
0
    return JXL_FAILURE("Corrupted ICC profile");
406
0
  }
407
408
3.50k
  icc->clear();
409
3.50k
  return UnpredictICC(decompressed_.data(), decompressed_.size(), icc);
410
3.50k
}
411
412
63.3k
Status ICCReader::CheckEOI(BitReader* reader) {
413
63.3k
  if (reader->AllReadsWithinBounds()) return true;
414
160
  return JXL_NOT_ENOUGH_BYTES("Not enough bytes for reading ICC profile");
415
63.3k
}
416
417
}  // namespace jxl