Skip to content

Truly independent web browser

LibImageDecoders: Port the ICO directory decoder to Rust

Andreas Kling6b8ff99fa81d
diff --git a/AK/Debug.h.in b/AK/Debug.h.in
index 6bb6524525a..8fe43518f4b 100644
--- a/AK/Debug.h.in
+++ b/AK/Debug.h.in
@@ -90,10 +90,6 @@
# cmakedefine01 HTTPJOB_DEBUG
#endif
-#ifndef ICO_DEBUG
-# cmakedefine01 ICO_DEBUG
-#endif
-
#ifndef IDL_DEBUG
# cmakedefine01 IDL_DEBUG
#endif
diff --git a/Libraries/LibGfx/ImageFormats/ICOLoader.cpp b/Libraries/LibGfx/ImageFormats/ICOLoader.cpp
index 829ec2c35ff..9254e2dad12 100644
--- a/Libraries/LibGfx/ImageFormats/ICOLoader.cpp
+++ b/Libraries/LibGfx/ImageFormats/ICOLoader.cpp
@@ -4,212 +4,66 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/Debug.h>
-#include <AK/Enumerate.h>
-#include <AK/MemoryStream.h>
-#include <AK/Types.h>
#include <LibGfx/ImageFormats/BMPLoader.h>
#include <LibGfx/ImageFormats/ICOLoader.h>
#include <LibGfx/ImageFormats/PNGLoader.h>
+#include <LibImageDecoders/RustFFI.h>
namespace Gfx {
-enum class IconType : u16 {
- ICO = 1,
- CUR = 2,
-};
-
-// FIXME: This is in little-endian order. Maybe need a NetworkOrdered<T> equivalent eventually.
-struct ICONDIR {
- u16 must_be_0 = 0;
- IconType type = IconType::ICO;
- u16 image_count = 0;
-};
-static_assert(AssertSize<ICONDIR, 6>());
-
-struct ICONDIRENTRY {
- u8 width;
- u8 height;
- u8 color_count;
- u8 reserved_0;
- u16 planes;
- u16 bits_per_pixel;
- u32 size;
- u32 offset;
-};
-static_assert(AssertSize<ICONDIRENTRY, 16>());
-
-};
-
-template<>
-class AK::Traits<Gfx::ICONDIR> : public DefaultTraits<Gfx::ICONDIR> {
-public:
- static constexpr bool is_trivially_serializable() { return true; }
-};
-
-template<>
-class AK::Traits<Gfx::ICONDIRENTRY> : public DefaultTraits<Gfx::ICONDIRENTRY> {
-public:
- static constexpr bool is_trivially_serializable() { return true; }
-};
-
-namespace Gfx {
-
-struct ICOImageDescriptor {
- u16 width;
- u16 height;
- u16 bits_per_pixel;
- u16 hotspot_x { 0 };
- u16 hotspot_y { 0 };
- size_t offset;
- size_t size;
- RefPtr<Gfx::Bitmap> bitmap;
-};
-
struct ICOLoadingContext {
AK_ALLOC_WITH_KMALLOC;
- enum State {
- NotDecoded = 0,
- Error,
+ enum class State : u8 {
DirectoryDecoded,
- BitmapDecoded
- };
- State state { NotDecoded };
- u8 const* data { nullptr };
- size_t data_size { 0 };
- IconType file_type { IconType::ICO };
- Vector<ICOImageDescriptor> images;
- size_t largest_index;
-};
-
-static ErrorOr<size_t> decode_ico_header(Stream& stream, IconType& out_type)
-{
- auto header = TRY(stream.read_value<ICONDIR>());
- if (header.must_be_0 != 0 || (header.type != IconType::ICO && header.type != IconType::CUR))
- return Error::from_string_literal("Invalid ICO/CUR header");
-
- out_type = header.type;
- return { header.image_count };
-}
-
-static ErrorOr<ICOImageDescriptor> decode_ico_direntry(Stream& stream, IconType file_type)
-{
- auto entry = TRY(stream.read_value<ICONDIRENTRY>());
- ICOImageDescriptor desc = {
- entry.width,
- entry.height,
- entry.bits_per_pixel,
- 0, 0,
- entry.offset,
- entry.size,
- nullptr
+ BitmapDecoded,
+ Error,
};
- if (file_type == IconType::CUR) {
- // For cursor files, hotsport coordinates are stored in the planes and bits_per_pixel fields
- desc.hotspot_x = entry.planes;
- desc.hotspot_y = entry.bits_per_pixel;
- }
-
- if (desc.width == 0)
- desc.width = 256;
- if (desc.height == 0)
- desc.height = 256;
-
- return { desc };
-}
-
-static size_t find_largest_image(ICOLoadingContext const& context)
-{
- size_t max_area = 0;
- size_t largest_index = 0;
- u16 max_bits_per_pixel = 0;
-
- for (auto const& [index, desc] : enumerate(context.images)) {
- auto area = static_cast<size_t>(desc.width) * static_cast<size_t>(desc.height);
-
- if (area > max_area || (area == max_area && desc.bits_per_pixel > max_bits_per_pixel)) {
- max_area = area;
- largest_index = index;
- max_bits_per_pixel = desc.bits_per_pixel;
- }
- }
-
- return largest_index;
-}
+ ReadonlyBytes data;
+ ImageDecoders::FFI::ICOImageInfo info {};
+ State state { State::DirectoryDecoded };
+ RefPtr<Bitmap> bitmap;
+};
-static ErrorOr<void> load_ico_directory(ICOLoadingContext& context)
+ICOImageDecoderPlugin::ICOImageDecoderPlugin(NonnullOwnPtr<ICOLoadingContext> context)
+ : m_context(move(context))
{
- FixedMemoryStream stream { { context.data, context.data_size } };
-
- auto image_count = TRY(decode_ico_header(stream, context.file_type));
- if (image_count == 0)
- return Error::from_string_literal("ICO/CUR file has no images");
-
- for (size_t i = 0; i < image_count; ++i) {
- auto desc = TRY(decode_ico_direntry(stream, context.file_type));
- if (desc.offset + desc.size < desc.offset // detect integer overflow
- || (desc.offset + desc.size) > context.data_size) {
- dbgln_if(ICO_DEBUG, "load_ico_directory: offset: {} size: {} doesn't fit in ICO size: {}", desc.offset, desc.size, context.data_size);
- return Error::from_string_literal("ICO size too large");
- }
- dbgln_if(ICO_DEBUG, "load_ico_directory: index {} width: {} height: {} offset: {} size: {}", i, desc.width, desc.height, desc.offset, desc.size);
- TRY(context.images.try_append(desc));
- }
- context.largest_index = find_largest_image(context);
- context.state = ICOLoadingContext::State::DirectoryDecoded;
- return {};
}
-ErrorOr<void> ICOImageDecoderPlugin::load_ico_bitmap(ICOLoadingContext& context)
-{
- VERIFY(context.state >= ICOLoadingContext::State::DirectoryDecoded);
-
- size_t const real_index = context.largest_index;
- if (real_index >= context.images.size())
- return Error::from_string_literal("Index out of bounds");
-
- ICOImageDescriptor& desc = context.images[real_index];
- if (PNGImageDecoderPlugin::sniff({ context.data + desc.offset, desc.size })) {
- auto png_decoder = TRY(PNGImageDecoderPlugin::create({ context.data + desc.offset, desc.size }));
- auto decoded_png_frame = TRY(png_decoder->frame(0));
- desc.bitmap = decoded_png_frame.image;
- return {};
- } else {
- auto bmp_decoder = TRY(BMPImageDecoderPlugin::create_as_included_in_ico({}, { context.data + desc.offset, desc.size }));
- auto decoded_bmp_frame = TRY(bmp_decoder->frame(0));
- desc.bitmap = decoded_bmp_frame.image;
- return {};
- }
-}
+ICOImageDecoderPlugin::~ICOImageDecoderPlugin() = default;
bool ICOImageDecoderPlugin::sniff(ReadonlyBytes data)
{
- FixedMemoryStream stream { data };
- IconType file_type;
- return !decode_ico_header(stream, file_type).is_error();
+ return ImageDecoders::FFI::ico_rust_sniff(data.data(), data.size());
}
ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> ICOImageDecoderPlugin::create(ReadonlyBytes data)
{
- auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) ICOImageDecoderPlugin(data.data(), data.size())));
- TRY(load_ico_directory(*plugin->m_context));
- return plugin;
+ ImageDecoders::FFI::ICOImageInfo info {};
+ if (!ImageDecoders::FFI::ico_rust_decode_directory(data.data(), data.size(), &info))
+ return Error::from_string_literal("ICOImageDecoderPlugin: Invalid ICO/CUR directory");
+
+ auto context = TRY(adopt_nonnull_own_or_enomem(new (nothrow) ICOLoadingContext));
+ context->data = data;
+ context->info = info;
+ return TRY(adopt_nonnull_own_or_enomem(new (nothrow) ICOImageDecoderPlugin(move(context))));
}
-ICOImageDecoderPlugin::ICOImageDecoderPlugin(u8 const* data, size_t size)
+IntSize ICOImageDecoderPlugin::size()
{
- m_context = make<ICOLoadingContext>();
- m_context->data = data;
- m_context->data_size = size;
+ return { static_cast<int>(m_context->info.width), static_cast<int>(m_context->info.height) };
}
-ICOImageDecoderPlugin::~ICOImageDecoderPlugin() = default;
-
-IntSize ICOImageDecoderPlugin::size()
+ErrorOr<NonnullRefPtr<Bitmap>> ICOImageDecoderPlugin::decode_image()
{
- return { m_context->images[m_context->largest_index].width, m_context->images[m_context->largest_index].height };
+ auto image = m_context->data.slice(m_context->info.image_offset, m_context->info.image_size);
+ if (PNGImageDecoderPlugin::sniff(image)) {
+ auto png_decoder = TRY(PNGImageDecoderPlugin::create(image));
+ return TRY(png_decoder->frame(0)).image;
+ }
+ auto bmp_decoder = TRY(BMPImageDecoderPlugin::create_as_included_in_ico({}, image));
+ return TRY(bmp_decoder->frame(0)).image;
}
ErrorOr<ImageFrameDescriptor> ICOImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
@@ -220,18 +74,17 @@ ErrorOr<ImageFrameDescriptor> ICOImageDecoderPlugin::frame(size_t index, Optiona
if (m_context->state == ICOLoadingContext::State::Error)
return Error::from_string_literal("ICOImageDecoderPlugin: Decoding failed");
- if (m_context->state < ICOLoadingContext::State::BitmapDecoded) {
- // NOTE: This forces the chunk decoding to happen.
- auto maybe_error = load_ico_bitmap(*m_context);
- if (maybe_error.is_error()) {
+ if (m_context->state == ICOLoadingContext::State::DirectoryDecoded) {
+ auto bitmap_or_error = decode_image();
+ if (bitmap_or_error.is_error()) {
m_context->state = ICOLoadingContext::State::Error;
return Error::from_string_literal("ICOImageDecoderPlugin: Decoding failed");
}
+ m_context->bitmap = bitmap_or_error.release_value();
m_context->state = ICOLoadingContext::State::BitmapDecoded;
}
- VERIFY(m_context->images[m_context->largest_index].bitmap);
- return ImageFrameDescriptor { *m_context->images[m_context->largest_index].bitmap, 0 };
+ return ImageFrameDescriptor { *m_context->bitmap, 0 };
}
}
diff --git a/Libraries/LibGfx/ImageFormats/ICOLoader.h b/Libraries/LibGfx/ImageFormats/ICOLoader.h
index d13487b97c8..45b96165036 100644
--- a/Libraries/LibGfx/ImageFormats/ICOLoader.h
+++ b/Libraries/LibGfx/ImageFormats/ICOLoader.h
@@ -24,10 +24,10 @@ public:
virtual ErrorOr<ImageFrameDescriptor> frame(size_t index, Optional<IntSize> ideal_size = {}) override;
private:
- ICOImageDecoderPlugin(u8 const*, size_t);
- static ErrorOr<void> load_ico_bitmap(ICOLoadingContext& context);
+ explicit ICOImageDecoderPlugin(NonnullOwnPtr<ICOLoadingContext>);
+ ErrorOr<NonnullRefPtr<Bitmap>> decode_image();
- OwnPtr<ICOLoadingContext> m_context;
+ NonnullOwnPtr<ICOLoadingContext> m_context;
};
}
diff --git a/Libraries/LibImageDecoders/Rust/src/ico.rs b/Libraries/LibImageDecoders/Rust/src/ico.rs
new file mode 100644
index 00000000000..62a39e7aef7
--- /dev/null
+++ b/Libraries/LibImageDecoders/Rust/src/ico.rs
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use crate::ffi::{bytes_from_raw, catch_panic_or};
+
+const ICON_TYPE_ICO: u16 = 1;
+const ICON_TYPE_CUR: u16 = 2;
+const ICONDIR_SIZE: usize = 6;
+const ICONDIRENTRY_SIZE: usize = 16;
+
+/// The image of an ICO or CUR file that should be displayed.
+#[repr(C)]
+pub struct ICOImageInfo {
+ pub width: u32,
+ pub height: u32,
+ pub image_offset: usize,
+ pub image_size: usize,
+}
+
+fn read_u16(data: &[u8], offset: usize) -> Option<u16> {
+ Some(u16::from_le_bytes(*data.get(offset..)?.first_chunk()?))
+}
+
+fn read_u32(data: &[u8], offset: usize) -> Option<u32> {
+ Some(u32::from_le_bytes(*data.get(offset..)?.first_chunk()?))
+}
+
+// Returns the number of images in the file.
+fn decode_icondir(data: &[u8]) -> Option<u16> {
+ if read_u16(data, 0)? != 0 {
+ return None;
+ }
+ let icon_type = read_u16(data, 2)?;
+ if icon_type != ICON_TYPE_ICO && icon_type != ICON_TYPE_CUR {
+ return None;
+ }
+ read_u16(data, 4)
+}
+
+fn decode_directory(data: &[u8]) -> Option<ICOImageInfo> {
+ let image_count = decode_icondir(data)?;
+ if image_count == 0 {
+ return None;
+ }
+
+ let mut largest: Option<(ICOImageInfo, u64, u16)> = None;
+ for index in 0..usize::from(image_count) {
+ let entry = data.get(ICONDIR_SIZE + index * ICONDIRENTRY_SIZE..)?;
+ let entry = entry.get(..ICONDIRENTRY_SIZE)?;
+
+ // A width or height of 0 means 256.
+ let width = if entry[0] == 0 { 256 } else { u32::from(entry[0]) };
+ let height = if entry[1] == 0 { 256 } else { u32::from(entry[1]) };
+ // NB: In CUR files, this field holds the vertical hotspot coordinate instead.
+ let bits_per_pixel = read_u16(entry, 6)?;
+ let image_size = read_u32(entry, 8)? as usize;
+ let image_offset = read_u32(entry, 12)? as usize;
+ if image_offset.checked_add(image_size)? > data.len() {
+ return None;
+ }
+
+ // Pick the largest image, and among those the one with the most bits per pixel.
+ let area = u64::from(width) * u64::from(height);
+ let is_better = match &largest {
+ None => true,
+ Some((_, largest_area, largest_bits_per_pixel)) => {
+ area > *largest_area || (area == *largest_area && bits_per_pixel > *largest_bits_per_pixel)
+ }
+ };
+ if is_better {
+ let info = ICOImageInfo {
+ width,
+ height,
+ image_offset,
+ image_size,
+ };
+ largest = Some((info, area, bits_per_pixel));
+ }
+ }
+ largest.map(|(info, _, _)| info)
+}
+
+/// # Safety
+/// `data` must be valid for `data_len` bytes.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn ico_rust_sniff(data: *const u8, data_len: usize) -> bool {
+ catch_panic_or(false, || {
+ let Some(data) = (unsafe { bytes_from_raw(data, data_len) }) else {
+ return false;
+ };
+ decode_icondir(data).is_some()
+ })
+}
+
+/// # Safety
+/// - `data` must be valid for `data_len` bytes.
+/// - `out_info` must be a valid writable pointer.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn ico_rust_decode_directory(
+ data: *const u8,
+ data_len: usize,
+ out_info: *mut ICOImageInfo,
+) -> bool {
+ catch_panic_or(false, || {
+ let Some(data) = (unsafe { bytes_from_raw(data, data_len) }) else {
+ return false;
+ };
+ let Some(out_info) = (unsafe { out_info.as_mut() }) else {
+ return false;
+ };
+ let Some(info) = decode_directory(data) else {
+ return false;
+ };
+ *out_info = info;
+ true
+ })
+}
diff --git a/Libraries/LibImageDecoders/Rust/src/lib.rs b/Libraries/LibImageDecoders/Rust/src/lib.rs
index 7c8e8f1f8ba..2f4eae9d222 100644
--- a/Libraries/LibImageDecoders/Rust/src/lib.rs
+++ b/Libraries/LibImageDecoders/Rust/src/lib.rs
@@ -18,5 +18,8 @@ mod ffi;
pub mod bmp;
pub use bmp::*;
+pub mod ico;
+pub use ico::*;
+
pub mod jpeg_xl;
pub use jpeg_xl::*;
diff --git a/Meta/CMake/all_the_debug_macros.cmake b/Meta/CMake/all_the_debug_macros.cmake
index aa5a6dff40b..07f0853d685 100644
--- a/Meta/CMake/all_the_debug_macros.cmake
+++ b/Meta/CMake/all_the_debug_macros.cmake
@@ -19,7 +19,6 @@ set(HTML_SCRIPT_DEBUG ON)
set(HTTP_DISK_CACHE_DEBUG ON)
set(HTTP_MEMORY_CACHE_DEBUG ON)
set(HTTPJOB_DEBUG ON)
-set(ICO_DEBUG ON)
set(IDL_DEBUG ON)
set(IMAGE_DECODER_DEBUG ON)
set(IMAGE_LOADER_DEBUG ON)