1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// DataPack represents a read-only view onto an on-disk file that contains
// (key, value) pairs of data. It's used to store static resources like
// translation strings and images.
#ifndef UI_BASE_RESOURCE_DATA_PACK_H_
#define UI_BASE_RESOURCE_DATA_PACK_H_
#include <stddef.h>
#include <stdint.h>
#include <map>
#include <memory>
#include <optional>
#include <string_view>
#include <vector>
#include "base/component_export.h"
#include "base/files/file.h"
#include "base/files/memory_mapped_file.h"
#include "base/memory/raw_ptr.h"
#include "base/types/expected.h"
#include "build/build_config.h"
#include "ui/base/resource/resource_handle.h"
#if BUILDFLAG(IS_WIN)
#include "base/win/windows_types.h"
#endif
namespace base {
class FilePath;
class RefCountedStaticMemory;
}
namespace ui {
enum ResourceScaleFactor : int;
class COMPONENT_EXPORT(UI_DATA_PACK) DataPack : public ResourceHandle {
public:
explicit DataPack(ResourceScaleFactor resource_scale_factor);
DataPack(const DataPack&) = delete;
DataPack& operator=(const DataPack&) = delete;
~DataPack() override;
// Pack Entry and Alias. This removes padding between fields, and alignment
// requirements, which makes the structs usable for aliasing into the input
// buffer directly.
//
// TODO(davidben): Ideally we would load these structures through memcpy, or
// a little-endian variant of base/big_endian.h, rather than type-punning
// pointers. This code currently depends on Chromium disabling strict aliasing.
#pragma pack(push, 1)
struct Entry {
static int CompareById(const void* void_key, const void* void_entry);
// ID corresponding with each resources.
uint16_t resource_id;
// The offset of the resource in .pak file.
uint32_t file_offset;
};
struct Alias {
static int CompareById(const void* void_key, const void* void_entry);
// ID corresponding with each resources.
uint16_t resource_id;
// The index of the entry which has the same resource to `resource_id`'s
// resource.
uint16_t entry_index;
};
#pragma pack(pop)
// Pair of resource id and string view data.
struct ResourceData {
explicit ResourceData(uint16_t id, std::string_view data)
: id(id), data(data) {}
// Resource ID.
uint16_t id;
// Resource data.
std::string_view data;
};
// Iterator for ResourceData in `resource_table_`.
// Note that this Iterator doesn't include Alias members in `alias_table_`.
class Iterator {
public:
Iterator() = default;
~Iterator() = default;
Iterator(const Iterator&) = default;
Iterator& operator=(const Iterator&) = default;
const ResourceData& operator*() { return *resource_data_; }
Iterator& operator++() {
++entry_;
UpdateResourceData();
return *this;
}
bool operator==(const Iterator& other) const {
return entry_ == other.entry_;
}
private:
friend class DataPack;
explicit Iterator(const uint8_t* data_source, const Entry* entry)
: data_source_(data_source), entry_(entry) {
UpdateResourceData();
}
void UpdateResourceData();
raw_ptr<const uint8_t> data_source_;
raw_ptr<ResourceData> resource_data_;
raw_ptr<const Entry, AllowPtrArithmetic> entry_;
};
Iterator begin() const;
Iterator end() const;
// Abstraction of a data source (memory mapped file or in-memory buffer).
class DataSource {
public:
virtual ~DataSource() = default;
virtual size_t GetLength() const = 0;
virtual const uint8_t* GetData() const = 0;
};
// Load a pack file from |path|, returning false on error. If the final
// extension of |path| is .gz, the file will be uncompressed and stored in
// memory owned by |data_source_|. Otherwise the file will be mapped to
// memory, with the mapping owned by |data_source_|.
bool LoadFromPath(const base::FilePath& path);
enum class FailureReason {
kOpenFile,
kMapFile,
kUnzip,
kIncompleteHeader,
kBadPakVersion,
kBadEncodingType,
kTooShort,
kBoundsExceeded,
kOrderingViolation,
kAliasTableCorrupt,
};
struct ErrorState {
FailureReason reason;
#if BUILDFLAG(IS_WIN)
DWORD error;
#else
int error;
#endif
base::File::Error file_error;
friend bool operator==(const ErrorState& lhs,
const ErrorState& rhs) = default;
};
// As LoadFromPath, but returns an ErrorState on failure.
base::expected<void, DataPack::ErrorState> LoadFromPathWithError(
const base::FilePath& path);
// The static part of the implementation in LoadFromPath().
static base::expected<std::unique_ptr<DataPack::DataSource>,
DataPack::ErrorState>
LoadFromPathInternal(const base::FilePath& path);
// Invokes LoadFromFileRegion with the entire contents of |file|. Compressed
// files are not supported.
bool LoadFromFile(base::File file);
// Loads a pack file from |region| of |file|, returning false on error.
// The file region will be mapped to memory with the mapping owned by
// |data_source_|.
bool LoadFromFileRegion(base::File file,
const base::MemoryMappedFile::Region& region);
// Loads a pack file from |buffer|, returning false on error.
// Data is not copied, |buffer| should stay alive during |DataPack| lifetime.
bool LoadFromBuffer(base::span<const uint8_t> buffer);
// Writes a pack file containing |resources| to |path|. If there are any
// text resources to be written, their encoding must already agree to the
// |textEncodingType| specified. If no text resources are present, please
// indicate BINARY.
static bool WritePack(const base::FilePath& path,
const std::map<uint16_t, std::string_view>& resources,
TextEncodingType textEncodingType);
// ResourceHandle implementation:
bool HasResource(uint16_t resource_id) const override;
std::optional<std::string_view> GetStringView(
uint16_t resource_id) const override;
base::RefCountedStaticMemory* GetStaticMemory(
uint16_t resource_id) const override;
TextEncodingType GetTextEncodingType() const override;
ResourceScaleFactor GetResourceScaleFactor() const override;
#if DCHECK_IS_ON()
// Checks to see if any resource in this DataPack already exists in the list
// of resources.
void CheckForDuplicateResources(
const std::vector<std::unique_ptr<ResourceHandle>>& packs) override;
#endif
// Return Entry or Alias by index of resource or alias table.
const Entry* GetEntryByResourceTableIndex(size_t index) const {
return &resource_table_[index];
}
const Alias* GetAliasByAliasTableIndex(size_t index) const {
return &alias_table_[index];
}
// Return the size of the alias table.
size_t GetAliasTableSize() const { return alias_count_; }
// Return the size of the resource Should only be used for unit-testing
// (more specifically checking that alias table generation removes entries
// for the resources table), as this is an implementation detail.
size_t GetResourceTableSizeForTesting() const { return resource_count_; }
private:
class BufferDataSource;
class MemoryMappedDataSource;
class StringDataSource;
// Does the actual loading of a pack file.
// Called by Load and LoadFromFile and LoadFromBuffer.
base::expected<void, DataPack::FailureReason> LoadImpl(
std::unique_ptr<DataSource> data_source);
const Entry* LookupEntryById(uint16_t resource_id) const;
// Sanity check the file. If it passed the check, register `resource_table_`
// and `alias_table_`.
// `margin_to_skip` represents the size of the margin in bytes before
// resource_table information starts.
// If there is no extra data in data pack, `margin_to_skip` is equal to the
// length of file header. Returns std::nullopt on success or a FailureReason
// on failure.
base::expected<void, DataPack::FailureReason>
SanityCheckFileAndRegisterResources(size_t margin_to_skip,
const uint8_t* data,
size_t data_length);
// Returns the string between `target_offset` and `next_offset` in data pack.
static std::string_view GetStringViewFromOffset(uint32_t target_offset,
uint32_t next_offset,
const uint8_t* data_source);
std::unique_ptr<DataSource> data_source_;
raw_ptr<const Entry, AllowPtrArithmetic> resource_table_;
size_t resource_count_;
raw_ptr<const Alias, AllowPtrArithmetic> alias_table_;
size_t alias_count_;
// Type of encoding for text resources.
TextEncodingType text_encoding_type_;
// The scale of the image in this resource pack relative to images in the 1x
// resource pak.
ResourceScaleFactor resource_scale_factor_;
};
} // namespace ui
#endif // UI_BASE_RESOURCE_DATA_PACK_H_
|