Debian Codegraph @

third_party/rust/uniffi_core/src/metadata.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 //! Pack UniFFI interface metadata into byte arrays
6 //!
7 //! In order to generate foreign bindings, we store interface metadata inside the library file
8 //! using exported static byte arrays. The foreign bindings code reads that metadata from the
9 //! library files and generates bindings based on that.
10 //!
11 //! The metadata static variables are generated by the proc-macros, which is an issue because the
12 //! proc-macros don't have knowledge of the entire interface -- they can only see the item they're
13 //! wrapping. For example, when a proc-macro sees a type name, it doesn't know anything about the
14 //! actual type: it could be a Record, an Enum, or even a type alias for a `Vec<>`/`Result<>`.
15 //!
16 //! This module helps bridge the gap by providing tools that allow the proc-macros to generate code
17 //! to encode the interface metadata:
18 //! - A set of const functions to build up metadata buffers with const expressions
19 //! - The `export_static_metadata_var!` macro, which creates the static variable from a const metadata
20 //! buffer.
21 //! - The `FfiConverter::TYPE_ID_META` const which encodes an identifier for that type in a
22 //! metadata buffer.
23 //!
24 //! `uniffi_bindgen::macro_metadata` contains the code to read the metadata from a library file.
25 //! `fixtures/metadata` has the tests.
26
27 /// Metadata constants, make sure to keep this in sync with copy in `uniffi_meta::metadata::codes`
28 pub mod codes {
29 // Top-level metadata item codes
30 pub const FUNC: u8 = 0;
31 pub const METHOD: u8 = 1;
32 pub const RECORD: u8 = 2;
33 pub const ENUM: u8 = 3;
34 pub const INTERFACE: u8 = 4;
35 pub const NAMESPACE: u8 = 6;
36 pub const CONSTRUCTOR: u8 = 7;
37 pub const UDL_FILE: u8 = 8;
38 pub const CALLBACK_INTERFACE: u8 = 9;
39 pub const TRAIT_METHOD: u8 = 10;
40 pub const UNIFFI_TRAIT: u8 = 11;
41 pub const TRAIT_INTERFACE: u8 = 12;
42 pub const CALLBACK_TRAIT_INTERFACE: u8 = 13;
43 pub const OBJECT_TRAIT_IMPL: u8 = 14;
44 pub const CUSTOM_TYPE: u8 = 15;
45
46 // Type codes
47 pub const TYPE_U8: u8 = 0;
48 pub const TYPE_U16: u8 = 1;
49 pub const TYPE_U32: u8 = 2;
50 pub const TYPE_U64: u8 = 3;
51 pub const TYPE_I8: u8 = 4;
52 pub const TYPE_I16: u8 = 5;
53 pub const TYPE_I32: u8 = 6;
54 pub const TYPE_I64: u8 = 7;
55 pub const TYPE_F32: u8 = 8;
56 pub const TYPE_F64: u8 = 9;
57 pub const TYPE_BOOL: u8 = 10;
58 pub const TYPE_STRING: u8 = 11;
59 pub const TYPE_OPTION: u8 = 12;
60 pub const TYPE_RECORD: u8 = 13;
61 pub const TYPE_ENUM: u8 = 14;
62 // 15 no longer used.
63 pub const TYPE_INTERFACE: u8 = 16;
64 pub const TYPE_VEC: u8 = 17;
65 pub const TYPE_HASH_MAP: u8 = 18;
66 pub const TYPE_SYSTEM_TIME: u8 = 19;
67 pub const TYPE_DURATION: u8 = 20;
68 pub const TYPE_CALLBACK_INTERFACE: u8 = 21;
69 pub const TYPE_CUSTOM: u8 = 22;
70 pub const TYPE_RESULT: u8 = 23;
71 pub const TYPE_TRAIT_INTERFACE: u8 = 24;
72 pub const TYPE_CALLBACK_TRAIT_INTERFACE: u8 = 25;
73 pub const TYPE_UNIT: u8 = 255;
74
75 // Literal codes for LiteralMetadata
76 pub const LIT_STR: u8 = 0;
77 pub const LIT_INT: u8 = 1;
78 pub const LIT_FLOAT: u8 = 2;
79 pub const LIT_BOOL: u8 = 3;
80 pub const LIT_NONE: u8 = 4;
81 pub const LIT_SOME: u8 = 5;
82 pub const LIT_EMPTY_SEQ: u8 = 6;
83 }
84
85 // For large errors (e.g. enums) a buffer size of ~4k - ~8k
86 // is not enough. See issues on Github: #1968 and #2041 and
87 // for an example see fixture/large-error
88 const BUF_SIZE: usize = 16384;
89
90 // This struct is a kludge around the fact that Rust const generic support doesn't quite handle our
91 // needs.
92 //
93 // We'd like to have code like this in `FfiConverter`:
94 //
95 // ```
96 // const TYPE_ID_META_SIZE: usize;
97 // const TYPE_ID_META: [u8, Self::TYPE_ID_META_SIZE];
98 // ```
99 //
100 // This would define a metadata buffer, correctly size for the data needed. However, associated
101 // consts as generic params aren't supported yet.
102 //
103 // To work around this, we use `const MetadataBuffer` values, which contain fixed-sized buffers
104 // with enough capacity to store our largest metadata arrays. Since the `MetadataBuffer` values
105 // are const, they're only stored at compile time and the extra bytes don't end up contributing to
106 // the final binary size. This was tested on Rust `1.66.0` with `--release` by increasing
107 // `BUF_SIZE` and checking the compiled library sizes.
108 #[derive(Debug)]
109 pub struct MetadataBuffer {
110 pub bytes: [u8; BUF_SIZE],
111 pub size: usize,
112 }
113
114 impl MetadataBuffer {
115 pub const fn new() -> Self {
116 Self {
117 bytes: [0; BUF_SIZE],
118 size: 0,
119 }
120 }
121
122 pub const fn from_code(value: u8) -> Self {
123 Self::new().concat_value(value)
124 }
125
126 // Concatenate another buffer to this one.
127 //
128 // This consumes self, which is convenient for the proc-macro code and also allows us to avoid
129 // allocated an extra buffer.
130 pub const fn concat(mut self, other: MetadataBuffer) -> MetadataBuffer {
131 assert!(self.size + other.size <= BUF_SIZE);
132 // It would be nice to use `copy_from_slice()`, but that's not allowed in const functions
133 // as of Rust 1.66.
134 let mut i = 0;
135 while i < other.size {
136 self.bytes[self.size] = other.bytes[i];
137 self.size += 1;
138 i += 1;
139 }
140 self
141 }
142
143 // Concatenate a `u8` value to this buffer
144 //
145 // This consumes self, which is convenient for the proc-macro code and also allows us to avoid
146 // allocated an extra buffer.
147 pub const fn concat_value(mut self, value: u8) -> Self {
148 assert!(self.size < BUF_SIZE);
149 self.bytes[self.size] = value;
150 self.size += 1;
151 self
152 }
153
154 // Concatenate a `u32` value to this buffer
155 //
156 // This consumes self, which is convenient for the proc-macro code and also allows us to avoid
157 // allocated an extra buffer.
158 pub const fn concat_u32(mut self, value: u32) -> Self {
159 assert!(self.size + 4 <= BUF_SIZE);
160 // store the value as little-endian
161 self.bytes[self.size] = value as u8;
162 self.bytes[self.size + 1] = (value >> 8) as u8;
163 self.bytes[self.size + 2] = (value >> 16) as u8;
164 self.bytes[self.size + 3] = (value >> 24) as u8;
165 self.size += 4;
166 self
167 }
168
169 // Concatenate a `bool` value to this buffer
170 //
171 // This consumes self, which is convenient for the proc-macro code and also allows us to avoid
172 // allocated an extra buffer.
173 pub const fn concat_bool(self, value: bool) -> Self {
174 self.concat_value(value as u8)
175 }
176
177 // Concatenate a string to this buffer. The maximum string length is 255 bytes. For longer strings,
178 // use `concat_long_str()`.
179 //
180 // Strings are encoded as a `u8` length, followed by the utf8 data.
181 //
182 // This consumes self, which is convenient for the proc-macro code and also allows us to avoid
183 // allocated an extra buffer.
184 pub const fn concat_str(mut self, string: &str) -> Self {
185 assert!(string.len() < 256);
186 assert!(self.size + string.len() < BUF_SIZE);
187 self.bytes[self.size] = string.len() as u8;
188 self.size += 1;
189 let bytes = string.as_bytes();
190 let mut i = 0;
191 while i < bytes.len() {
192 self.bytes[self.size] = bytes[i];
193 self.size += 1;
194 i += 1;
195 }
196 self
197 }
198
199 // Concatenate a longer string to this buffer.
200 //
201 // Strings are encoded as a `u16` length, followed by the utf8 data.
202 //
203 // This consumes self, which is convenient for the proc-macro code and also allows us to avoid
204 // allocated an extra buffer.
205 pub const fn concat_long_str(mut self, string: &str) -> Self {
206 assert!(self.size + string.len() + 1 < BUF_SIZE);
207 let [lo, hi] = (string.len() as u16).to_le_bytes();
208 self.bytes[self.size] = lo;
209 self.bytes[self.size + 1] = hi;
210 self.size += 2;
211 let bytes = string.as_bytes();
212 let mut i = 0;
213 while i < bytes.len() {
214 self.bytes[self.size] = bytes[i];
215 self.size += 1;
216 i += 1;
217 }
218 self
219 }
220
221 // Create an array from this MetadataBuffer
222 //
223 // SIZE should always be `self.size`. This is part of the kludge to hold us over until Rust
224 // gets better const generic support.
225 pub const fn into_array<const SIZE: usize>(self) -> [u8; SIZE] {
226 let mut result: [u8; SIZE] = [0; SIZE];
227 let mut i = 0;
228 while i < SIZE {
229 result[i] = self.bytes[i];
230 i += 1;
231 }
232 result
233 }
234
235 // Create a checksum from this MetadataBuffer
236 //
237 // This is used by the bindings code to verify that the library they link to is the same one
238 // that the bindings were generated from.
239 pub const fn checksum(&self) -> u16 {
240 calc_checksum(&self.bytes, self.size)
241 }
242 }
243
244 impl Default for MetadataBuffer {
245 fn default() -> Self {
246 Self::new()
247 }
248 }
249
250 impl AsRef<[u8]> for MetadataBuffer {
251 fn as_ref(&self) -> &[u8] {
252 &self.bytes[..self.size]
253 }
254 }
255
256 // Create a checksum for a MetadataBuffer
257 //
258 // This is used by the bindings code to verify that the library they link to is the same one
259 // that the bindings were generated from.
260 pub const fn checksum_metadata(buf: &[u8]) -> u16 {
261 calc_checksum(buf, buf.len())
262 }
263
264 const fn calc_checksum(bytes: &[u8], size: usize) -> u16 {
265 // Taken from the fnv_hash() function from the FNV crate (https://github.com/servo/rust-fnv/blob/master/lib.rs).
266 // fnv_hash() hasn't been released in a version yet.
267 const INITIAL_STATE: u64 = 0xcbf29ce484222325;
268 const PRIME: u64 = 0x100000001b3;
269
270 let mut hash = INITIAL_STATE;
271 let mut i = 0;
272 while i < size {
273 hash ^= bytes[i] as u64;
274 hash = hash.wrapping_mul(PRIME);
275 i += 1;
276 }
277 // Convert the 64-bit hash to a 16-bit hash by XORing everything together
278 (hash ^ (hash >> 16) ^ (hash >> 32) ^ (hash >> 48)) as u16
279 }