Coverage Report

Created: 2026-02-14 07:09

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
7.48k
               size_t width) {
36
7.48k
  size_t height = (size + width - 1) / width;  // amount of rows of output
37
7.48k
  PaddedBytes result(memory_manager);
38
7.48k
  JXL_ASSIGN_OR_RETURN(result,
39
7.48k
                       PaddedBytes::WithInitialSpace(memory_manager, size));
40
  // i = output index, j input index
41
7.48k
  size_t s = 0;
42
7.48k
  size_t j = 0;
43
327k
  for (size_t i = 0; i < size; i++) {
44
319k
    result[i] = data[j];
45
319k
    j += height;
46
319k
    if (j >= size) j = ++s;
47
319k
  }
48
49
327k
  for (size_t i = 0; i < size; i++) {
50
319k
    data[i] = result[i];
51
319k
  }
52
7.48k
  return true;
53
7.48k
}
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
54.4k
uint64_t DecodeVarInt(const uint8_t* input, size_t inputSize, size_t* pos) {
62
54.4k
  size_t i;
63
54.4k
  uint64_t ret = 0;
64
69.7k
  for (i = 0; *pos + i < inputSize && i < 10; ++i) {
65
69.7k
    ret |= static_cast<uint64_t>(input[*pos + i] & 127)
66
69.7k
           << static_cast<uint64_t>(7 * i);
67
    // If the next-byte flag is not set, stop
68
69.7k
    if ((input[*pos + i] & 128) == 0) break;
69
69.7k
  }
70
  // TODO(user): Return a decoding error if i == 10.
71
54.4k
  *pos += i + 1;
72
54.4k
  return ret;
73
54.4k
}
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
2.86k
Status CheckPreamble(const PaddedBytes& data, size_t enc_size) {
80
2.86k
  const uint8_t* enc = data.data();
81
2.86k
  size_t size = data.size();
82
2.86k
  size_t pos = 0;
83
2.86k
  uint64_t osize = DecodeVarInt(enc, size, &pos);
84
2.86k
  JXL_RETURN_IF_ERROR(CheckIs32Bit(osize));
85
2.86k
  if (pos >= size) return JXL_FAILURE("Out of bounds");
86
2.86k
  uint64_t csize = DecodeVarInt(enc, size, &pos);
87
2.86k
  JXL_RETURN_IF_ERROR(CheckIs32Bit(csize));
88
2.86k
  JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, csize, size));
89
  // We expect that UnpredictICC inflates input, not the other way round.
90
2.86k
  if (osize + 65536 < enc_size) return JXL_FAILURE("Malformed ICC");
91
92
  // NB(eustas): 64 MiB ICC should be enough for everything!?
93
2.86k
  const size_t output_limit = 1 << 28;
94
2.86k
  if (output_limit && osize > output_limit) {
95
0
    return JXL_FAILURE("Decoded ICC is too large");
96
0
  }
97
2.86k
  return true;
98
2.86k
}
99
100
// Decodes the result of PredictICC back to a valid ICC profile.
101
2.85k
Status UnpredictICC(const uint8_t* enc, size_t size, PaddedBytes* result) {
102
2.85k
  if (!result->empty()) return JXL_FAILURE("result must be empty initially");
103
2.85k
  JxlMemoryManager* memory_manager = result->memory_manager();
104
2.85k
  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
2.85k
  if (pos >= size) return JXL_FAILURE("Out of bounds");
111
2.85k
  uint64_t osize = DecodeVarInt(enc, size, &pos);  // Output size
112
2.85k
  JXL_RETURN_IF_ERROR(CheckIs32Bit(osize));
113
2.85k
  if (pos >= size) return JXL_FAILURE("Out of bounds");
114
2.85k
  uint64_t csize = DecodeVarInt(enc, size, &pos);  // Commands size
115
  // Every command is translated to at least on byte.
116
2.85k
  JXL_RETURN_IF_ERROR(CheckIs32Bit(csize));
117
2.85k
  size_t cpos = pos;  // pos in commands stream
118
2.85k
  JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, csize, size));
119
2.85k
  size_t commands_end = cpos + csize;
120
2.85k
  pos = commands_end;  // pos in data stream
121
122
  // Header
123
2.85k
  PaddedBytes header{memory_manager};
124
2.85k
  JXL_RETURN_IF_ERROR(header.append(ICCInitialHeaderPrediction(osize)));
125
368k
  for (size_t i = 0; i <= kICCHeaderSize; i++) {
126
368k
    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
368k
    if (i == kICCHeaderSize) break;  // Done
132
365k
    ICCPredictHeader(result->data(), result->size(), header.data(), i);
133
365k
    if (pos >= size) return JXL_FAILURE("Out of bounds");
134
365k
    JXL_RETURN_IF_ERROR(result->push_back(enc[pos++] + header[i]));
135
365k
  }
136
2.85k
  if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
137
138
  // Tag list
139
2.85k
  uint64_t numtags = DecodeVarInt(enc, size, &cpos);
140
141
2.85k
  if (numtags != 0) {
142
2.85k
    numtags--;
143
2.85k
    JXL_RETURN_IF_ERROR(CheckIs32Bit(numtags));
144
2.85k
    JXL_RETURN_IF_ERROR(AppendUint32(numtags, result));
145
2.85k
    uint64_t prevtagstart = kICCHeaderSize + numtags * 12;
146
2.85k
    uint64_t prevtagsize = 0;
147
24.7k
    for (;;) {
148
24.7k
      if (result->size() > osize) return JXL_FAILURE("Invalid result size");
149
24.7k
      if (cpos > commands_end) return JXL_FAILURE("Out of bounds");
150
24.7k
      if (cpos == commands_end) break;  // Valid end
151
24.7k
      uint8_t command = enc[cpos++];
152
24.7k
      uint8_t tagcode = command & 63;
153
24.7k
      Tag tag;
154
24.7k
      if (tagcode == 0) {
155
2.85k
        break;
156
21.9k
      } else if (tagcode == kCommandTagUnknown) {
157
1.08k
        JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, 4, size));
158
1.08k
        tag = DecodeKeyword(enc, size, pos);
159
1.08k
        pos += 4;
160
20.8k
      } else if (tagcode == kCommandTagTRC) {
161
2.77k
        tag = kRtrcTag;
162
18.0k
      } else if (tagcode == kCommandTagXYZ) {
163
1.88k
        tag = kRxyzTag;
164
16.1k
      } else {
165
16.1k
        if (tagcode - kCommandTagStringFirst >= kNumTagStrings) {
166
0
          return JXL_FAILURE("Unknown tagcode");
167
0
        }
168
16.1k
        tag = *kTagStrings[tagcode - kCommandTagStringFirst];
169
16.1k
      }
170
21.9k
      JXL_RETURN_IF_ERROR(AppendKeyword(tag, result));
171
172
21.9k
      uint64_t tagstart;
173
21.9k
      uint64_t tagsize = prevtagsize;
174
21.9k
      if (tag == kRxyzTag || tag == kGxyzTag || tag == kBxyzTag ||
175
17.3k
          tag == kKxyzTag || tag == kWtptTag || tag == kBkptTag ||
176
14.4k
          tag == kLumiTag) {
177
7.45k
        tagsize = 20;
178
7.45k
      }
179
180
21.9k
      if (command & kFlagBitOffset) {
181
8.56k
        if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
182
8.56k
        tagstart = DecodeVarInt(enc, size, &cpos);
183
13.3k
      } else {
184
13.3k
        JXL_RETURN_IF_ERROR(CheckIs32Bit(prevtagstart));
185
13.3k
        tagstart = prevtagstart + prevtagsize;
186
13.3k
      }
187
21.9k
      JXL_RETURN_IF_ERROR(CheckIs32Bit(tagstart));
188
21.9k
      JXL_RETURN_IF_ERROR(AppendUint32(tagstart, result));
189
21.9k
      if (command & kFlagBitSize) {
190
14.0k
        if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
191
14.0k
        tagsize = DecodeVarInt(enc, size, &cpos);
192
14.0k
      }
193
21.9k
      JXL_RETURN_IF_ERROR(CheckIs32Bit(tagsize));
194
21.9k
      JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
195
21.9k
      prevtagstart = tagstart;
196
21.9k
      prevtagsize = tagsize;
197
198
21.9k
      if (tagcode == kCommandTagTRC) {
199
2.77k
        JXL_RETURN_IF_ERROR(AppendKeyword(kGtrcTag, result));
200
2.77k
        JXL_RETURN_IF_ERROR(AppendUint32(tagstart, result));
201
2.77k
        JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
202
2.77k
        JXL_RETURN_IF_ERROR(AppendKeyword(kBtrcTag, result));
203
2.77k
        JXL_RETURN_IF_ERROR(AppendUint32(tagstart, result));
204
2.77k
        JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
205
2.77k
      }
206
207
21.9k
      if (tagcode == kCommandTagXYZ) {
208
1.88k
        JXL_RETURN_IF_ERROR(CheckIs32Bit(tagstart + tagsize * 2));
209
1.88k
        JXL_RETURN_IF_ERROR(AppendKeyword(kGxyzTag, result));
210
1.88k
        JXL_RETURN_IF_ERROR(AppendUint32(tagstart + tagsize, result));
211
1.88k
        JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
212
1.88k
        JXL_RETURN_IF_ERROR(AppendKeyword(kBxyzTag, result));
213
1.88k
        JXL_RETURN_IF_ERROR(AppendUint32(tagstart + tagsize * 2, result));
214
1.88k
        JXL_RETURN_IF_ERROR(AppendUint32(tagsize, result));
215
1.88k
      }
216
21.9k
    }
217
2.85k
  }
218
219
  // Main Content
220
44.9k
  for (;;) {
221
44.9k
    if (result->size() > osize) return JXL_FAILURE("Invalid result size");
222
44.9k
    if (cpos > commands_end) return JXL_FAILURE("Out of bounds");
223
44.9k
    if (cpos == commands_end) break;  // Valid end
224
42.0k
    uint8_t command = enc[cpos++];
225
42.0k
    if (command == kCommandInsert) {
226
10.1k
      if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
227
10.1k
      uint64_t num = DecodeVarInt(enc, size, &cpos);
228
10.1k
      JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, num, size));
229
4.68M
      for (size_t i = 0; i < num; i++) {
230
4.67M
        JXL_RETURN_IF_ERROR(result->push_back(enc[pos++]));
231
4.67M
      }
232
31.9k
    } else if (command == kCommandShuffle2 || command == kCommandShuffle4) {
233
7.48k
      if (cpos >= commands_end) return JXL_FAILURE("Out of bounds");
234
7.48k
      uint64_t num = DecodeVarInt(enc, size, &cpos);
235
7.48k
      JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, num, size));
236
7.48k
      PaddedBytes shuffled(memory_manager);
237
7.48k
      JXL_ASSIGN_OR_RETURN(shuffled,
238
7.48k
                           PaddedBytes::WithInitialSpace(memory_manager, num));
239
327k
      for (size_t i = 0; i < num; i++) {
240
319k
        shuffled[i] = enc[pos + i];
241
319k
      }
242
7.48k
      if (command == kCommandShuffle2) {
243
7.48k
        JXL_RETURN_IF_ERROR(Shuffle(memory_manager, shuffled.data(), num, 2));
244
7.48k
      } else if (command == kCommandShuffle4) {
245
0
        JXL_RETURN_IF_ERROR(Shuffle(memory_manager, shuffled.data(), num, 4));
246
0
      }
247
327k
      for (size_t i = 0; i < num; i++) {
248
319k
        JXL_RETURN_IF_ERROR(result->push_back(shuffled[i]));
249
319k
        pos++;
250
319k
      }
251
24.4k
    } 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
24.4k
    } else if (command == kCommandXYZ) {
302
11.2k
      JXL_RETURN_IF_ERROR(AppendKeyword(kXyz_Tag, result));
303
56.0k
      for (int i = 0; i < 4; i++) {
304
44.8k
        JXL_RETURN_IF_ERROR(result->push_back(0));
305
44.8k
      }
306
11.2k
      JXL_RETURN_IF_ERROR(CheckOutOfBounds(pos, 12, size));
307
145k
      for (size_t i = 0; i < 12; i++) {
308
134k
        JXL_RETURN_IF_ERROR(result->push_back(enc[pos++]));
309
134k
      }
310
13.2k
    } else if (command >= kCommandTypeStartFirst &&
311
13.2k
               command < kCommandTypeStartFirst + kNumTypeStrings) {
312
13.2k
      JXL_RETURN_IF_ERROR(AppendKeyword(
313
13.2k
          *kTypeStrings[command - kCommandTypeStartFirst], result));
314
66.2k
      for (size_t i = 0; i < 4; i++) {
315
53.0k
        JXL_RETURN_IF_ERROR(result->push_back(0));
316
53.0k
      }
317
13.2k
    } else {
318
1
      return JXL_FAILURE("Unknown command");
319
1
    }
320
42.0k
  }
321
322
2.85k
  if (pos != size) return JXL_FAILURE("Not all data used");
323
2.85k
  if (result->size() != osize) return JXL_FAILURE("Invalid result size");
324
325
2.85k
  return true;
326
2.85k
}
327
328
2.86k
Status ICCReader::Init(BitReader* reader) {
329
2.86k
  JXL_RETURN_IF_ERROR(CheckEOI(reader));
330
2.86k
  JxlMemoryManager* memory_manager = decompressed_.memory_manager();
331
2.86k
  used_bits_base_ = reader->TotalBitsConsumed();
332
2.86k
  if (bits_to_skip_ == 0) {
333
2.86k
    enc_size_ = U64Coder::Read(reader);
334
2.86k
    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
2.86k
    JXL_RETURN_IF_ERROR(DecodeHistograms(
339
2.86k
        memory_manager, reader, kNumICCContexts, &code_, &context_map_));
340
5.72k
    JXL_ASSIGN_OR_RETURN(ans_reader_, ANSSymbolReader::Create(&code_, reader));
341
5.72k
    i_ = 0;
342
5.72k
    JXL_RETURN_IF_ERROR(
343
5.72k
        decompressed_.resize(std::min<size_t>(i_ + 0x400, enc_size_)));
344
8.58k
    for (; i_ < std::min<size_t>(2, enc_size_); i_++) {
345
5.72k
      decompressed_[i_] = ans_reader_.ReadHybridUint(
346
5.72k
          ICCANSContext(i_, i_ > 0 ? decompressed_[i_ - 1] : 0,
347
5.72k
                        i_ > 1 ? decompressed_[i_ - 2] : 0),
348
5.72k
          reader, context_map_);
349
5.72k
    }
350
2.86k
    if (enc_size_ > kPreambleSize) {
351
60.1k
      for (; i_ < kPreambleSize; i_++) {
352
57.2k
        decompressed_[i_] = ans_reader_.ReadHybridUint(
353
57.2k
            ICCANSContext(i_, decompressed_[i_ - 1], decompressed_[i_ - 2]),
354
57.2k
            reader, context_map_);
355
57.2k
      }
356
2.86k
      JXL_RETURN_IF_ERROR(CheckEOI(reader));
357
2.86k
      JXL_RETURN_IF_ERROR(CheckPreamble(decompressed_, enc_size_));
358
2.86k
    }
359
2.86k
    bits_to_skip_ = reader->TotalBitsConsumed() - used_bits_base_;
360
2.86k
  } else {
361
5
    reader->SkipBits(bits_to_skip_);
362
5
  }
363
2.86k
  return true;
364
2.86k
}
365
366
2.86k
Status ICCReader::Process(BitReader* reader, PaddedBytes* icc) {
367
2.86k
  auto checkpoint = jxl::make_unique<ANSSymbolReader::Checkpoint>();
368
2.86k
  size_t saved_i = 0;
369
25.8k
  auto save = [&]() {
370
25.8k
    ans_reader_.Save(checkpoint.get());
371
25.8k
    bits_to_skip_ = reader->TotalBitsConsumed() - used_bits_base_;
372
25.8k
    saved_i = i_;
373
25.8k
  };
374
2.86k
  save();
375
25.8k
  auto check_and_restore = [&]() -> Status {
376
25.8k
    Status status = CheckEOI(reader);
377
25.8k
    if (!status) {
378
      // not enough bytes.
379
13
      ans_reader_.Restore(*checkpoint);
380
13
      i_ = saved_i;
381
13
      return status;
382
13
    }
383
25.8k
    return true;
384
25.8k
  };
385
12.4M
  for (; i_ < enc_size_; i_++) {
386
12.4M
    if (i_ % ANSSymbolReader::kMaxCheckpointInterval == 0 && i_ > 0) {
387
22.9k
      JXL_RETURN_IF_ERROR(check_and_restore());
388
22.9k
      save();
389
22.9k
      if ((i_ > 0) && (((i_ & 0xFFFF) == 0))) {
390
138
        float used_bytes =
391
138
            (reader->TotalBitsConsumed() - used_bits_base_) / 8.0f;
392
138
        if (i_ > used_bytes * 256) return JXL_FAILURE("Corrupted stream");
393
138
      }
394
22.9k
      JXL_RETURN_IF_ERROR(
395
22.9k
          decompressed_.resize(std::min<size_t>(i_ + 0x400, enc_size_)));
396
22.9k
    }
397
12.4M
    JXL_ENSURE(i_ >= 2);
398
12.4M
    decompressed_[i_] = ans_reader_.ReadHybridUint(
399
12.4M
        ICCANSContext(i_, decompressed_[i_ - 1], decompressed_[i_ - 2]), reader,
400
12.4M
        context_map_);
401
12.4M
  }
402
2.85k
  JXL_RETURN_IF_ERROR(check_and_restore());
403
2.85k
  bits_to_skip_ = reader->TotalBitsConsumed() - used_bits_base_;
404
2.85k
  if (!ans_reader_.CheckANSFinalState()) {
405
0
    return JXL_FAILURE("Corrupted ICC profile");
406
0
  }
407
408
2.85k
  icc->clear();
409
2.85k
  return UnpredictICC(decompressed_.data(), decompressed_.size(), icc);
410
2.85k
}
411
412
31.5k
Status ICCReader::CheckEOI(BitReader* reader) {
413
31.5k
  if (reader->AllReadsWithinBounds()) return true;
414
13
  return JXL_NOT_ENOUGH_BYTES("Not enough bytes for reading ICC profile");
415
31.5k
}
416
417
}  // namespace jxl