Repository navigation
Expand file tree
/
Copy pathstruct_value.rs
More file actions
383 lines (358 loc) · 13.3 KB
/
Copy pathstruct_value.rs
File metadata and controls
383 lines (358 loc) · 13.3 KB
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
//! WinRT value structs (classic engine): plain JS snapshots built from a per-isolate,
//! per-type template, so all values of a type share one map and the constructor's prototype.
use crate::helpers::strip_generic_suffix;
use crate::property_call::{align_up, sig_size_align_pub};
use crate::value::{read_value_from_ptr, NativeType};
use metadata::declarations::declaration::{Declaration, DeclarationKind};
use metadata::declarations::struct_declaration::StructDeclaration;
use metadata::meta_data_reader::MetadataReader;
use metadata::signature::Signature;
use parking_lot::RwLock;
use std::cell::{OnceCell, RefCell};
use std::ffi::c_void;
use std::mem::ManuallyDrop;
use std::rc::Rc;
use std::sync::Arc;
use windows::core::HSTRING;
const MAX_SAFE_INTEGER: f64 = 9007199254740991.0;
enum FieldKind {
/// Primitive, HSTRING, or enum (as Int32).
Value(NativeType),
Struct(Rc<StructType>),
/// Not marshaled (e.g. `Guid`, `IReference<T>`); exposed as `null`.
Opaque,
}
struct Field {
/// Internalized.
key: v8::Global<v8::String>,
name: String,
offset: usize,
kind: FieldKind,
}
/// Layout and templates for one struct type. The cache keeps it alive for the constructor's raw pointer.
pub(crate) struct StructType {
name: String,
fields: Vec<Field>,
tmpl: OnceCell<v8::Global<v8::FunctionTemplate>>,
instance_tmpl: OnceCell<v8::Global<v8::ObjectTemplate>>,
}
/// Per-isolate struct types by full name (isolate slot).
#[derive(Default)]
pub(crate) struct StructCache {
types: RefCell<ahash::AHashMap<String, Rc<StructType>>>,
}
fn cache(scope: &mut v8::PinScope<'_, '_>) -> &'static StructCache {
if scope.get_slot::<StructCache>().is_none() {
scope.set_slot(StructCache::default());
}
// Slot lives as long as the isolate; detach the borrow from `scope`.
let cache = scope.get_slot::<StructCache>().unwrap();
unsafe { &*(cache as *const StructCache) }
}
fn struct_type_for(
scope: &mut v8::PinScope<'_, '_>,
declaration: &Arc<RwLock<dyn Declaration>>,
) -> Option<Rc<StructType>> {
let lock = declaration.read();
let cache = cache(scope);
if let Some(ty) = cache.types.borrow().get(lock.full_name()) {
return Some(Rc::clone(ty));
}
let sd = lock.as_any().downcast_ref::<StructDeclaration>()?;
let full_name = lock.full_name().to_string();
let simple_name = lock.name().to_string();
let mut fields = Vec::with_capacity(sd.fields().len());
let mut offset = 0usize;
for f in sd.fields().iter() {
let Some(m) = f.base().metadata() else {
continue;
};
let sig = Signature::to_string(m, &f.type_());
// Same layout as the serializer.
let (size, align) = sig_size_align_pub(&sig);
offset = align_up(offset, align);
let kind = if sig.contains('.') {
let nested = MetadataReader::find_by_name(strip_generic_suffix(&sig));
let nested_kind = nested.as_ref().map(|d| d.read().kind());
match (nested, nested_kind) {
(Some(d), Some(DeclarationKind::Struct)) => struct_type_for(scope, &d)
.map(FieldKind::Struct)
.unwrap_or(FieldKind::Opaque),
(_, Some(DeclarationKind::Enum)) => FieldKind::Value(NativeType::I32),
_ => FieldKind::Opaque,
}
} else {
match NativeType::try_from(sig.as_str()) {
Ok(NativeType::Pointer | NativeType::Buffer | NativeType::Function)
| Ok(NativeType::Struct(_) | NativeType::Void)
| Err(_) => FieldKind::Opaque,
Ok(nt) => FieldKind::Value(nt),
}
};
let key =
v8::String::new_from_utf8(scope, f.name().as_bytes(), v8::NewStringType::Internalized)?;
fields.push(Field {
key: v8::Global::new(scope, key),
name: f.name().to_string(),
offset,
kind,
});
offset += size;
}
drop(lock);
let ty = Rc::new(StructType {
name: simple_name,
fields,
tmpl: OnceCell::new(),
instance_tmpl: OnceCell::new(),
});
let data = v8::External::new(scope, Rc::as_ptr(&ty) as *mut c_void);
let tmpl = v8::FunctionTemplate::builder(construct)
.data(data.into())
.build(scope);
if let Some(class_name) = v8::String::new(scope, &ty.name) {
tmpl.set_class_name(class_name);
}
let instance_tmpl = tmpl.instance_template(scope);
for field in ty.fields.iter() {
let key = v8::Local::new(scope, &field.key);
let placeholder: v8::Local<v8::Data> = match field.kind {
FieldKind::Value(NativeType::String) => v8::String::empty(scope).into(),
FieldKind::Value(NativeType::Bool) => v8::Boolean::new(scope, false).into(),
FieldKind::Value(_) => v8::Integer::new(scope, 0).into(),
FieldKind::Struct(_) | FieldKind::Opaque => v8::null(scope).into(),
};
instance_tmpl.set(key.into(), placeholder);
}
let tag = v8::Symbol::get_to_string_tag(scope);
if let Some(tag_value) = v8::String::new(scope, &full_name) {
tmpl.prototype_template(scope).set_with_attr(
tag.into(),
tag_value.into(),
v8::PropertyAttribute::READ_ONLY | v8::PropertyAttribute::DONT_ENUM,
);
}
let _ = ty.tmpl.set(v8::Global::new(scope, tmpl));
let _ = ty.instance_tmpl.set(v8::Global::new(scope, instance_tmpl));
cache.types.borrow_mut().insert(full_name, Rc::clone(&ty));
Some(ty)
}
fn instantiate<'a>(
scope: &mut v8::PinScope<'a, '_>,
ty: &StructType,
) -> Option<v8::Local<'a, v8::Object>> {
let tmpl = v8::Local::new(scope, ty.instance_tmpl.get()?);
tmpl.new_instance(scope)
}
/// The JS constructor for a struct type (`Windows.Foundation.Rect`).
pub(crate) fn constructor<'a>(
scope: &mut v8::PinScope<'a, '_>,
declaration: &Arc<RwLock<dyn Declaration>>,
) -> v8::Local<'a, v8::Value> {
struct_type_for(scope, declaration)
.and_then(|ty| {
let tmpl = v8::Local::new(scope, ty.tmpl.get()?);
tmpl.get_function(scope)
})
.map(Into::into)
.unwrap_or_else(|| v8::undefined(scope).into())
}
/// Copies a native struct into a JS value. `raw` is borrowed (HSTRINGs are not released); null gives zeros.
pub(crate) fn from_raw<'a>(
scope: &mut v8::PinScope<'a, '_>,
declaration: &Arc<RwLock<dyn Declaration>>,
raw: *const c_void,
) -> Option<v8::Local<'a, v8::Object>> {
let ty = struct_type_for(scope, declaration)?;
read_struct(scope, &ty, raw as *const u8)
}
/// Serializes `obj` into `scratch` (must outlive the call) and returns its address.
pub(crate) fn serialize_into(
scope: &mut v8::PinScope<'_, '_>,
declaration: &Arc<RwLock<dyn Declaration>>,
obj: v8::Local<v8::Object>,
scratch: &mut Vec<Vec<u8>>,
) -> *mut c_void {
let mut buf = Vec::new();
{
let lock = declaration.read();
if let Some(sd) = lock.as_any().downcast_ref::<StructDeclaration>() {
crate::property_call::append_struct_object_bytes(&mut buf, scope, obj, sd);
}
}
if buf.is_empty() {
buf.push(0);
}
let ptr = buf.as_mut_ptr() as *mut c_void;
scratch.push(buf);
ptr
}
pub(crate) fn type_name_declaration() -> Option<Arc<RwLock<dyn Declaration>>> {
MetadataReader::find_by_name("Windows.UI.Xaml.Interop.TypeName")
}
fn read_struct<'a>(
scope: &mut v8::PinScope<'a, '_>,
ty: &StructType,
raw: *const u8,
) -> Option<v8::Local<'a, v8::Object>> {
let obj = instantiate(scope, ty)?;
if raw.is_null() {
return Some(obj);
}
for field in ty.fields.iter() {
let ptr = unsafe { raw.add(field.offset) };
let value: v8::Local<v8::Value> = match &field.kind {
FieldKind::Value(NativeType::String) => unsafe {
let raw_hstring = std::ptr::read_unaligned(ptr as *const usize);
let hstring = ManuallyDrop::new(std::mem::transmute::<usize, HSTRING>(raw_hstring));
crate::value::two_byte_string(scope, &hstring).into()
},
FieldKind::Value(nt) => unsafe {
read_value_from_ptr(ptr as *const c_void, scope, nt.clone())
},
FieldKind::Struct(nested) => match read_struct(scope, nested, ptr) {
Some(v) => v.into(),
None => continue,
},
FieldKind::Opaque => continue,
};
let key = v8::Local::new(scope, &field.key);
obj.set(scope, key.into(), value);
}
Some(obj)
}
/// `new Rect({ X, Y, Width, Height })`, `new Rect(x, y, w, h)` or `new Rect()`; missing fields are zero.
fn construct<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
let Ok(data) = v8::Local::<v8::External>::try_from(args.data()) else {
return;
};
let ty = unsafe { &*(data.value() as *const StructType) };
let this = if args.new_target().is_undefined() {
match instantiate(scope, ty) {
Some(obj) => obj,
None => return,
}
} else {
args.this()
};
// One object argument: named fields; otherwise positional.
let first = args.get(0);
let named = if args.length() == 1 && first.is_object() {
first.to_object(scope)
} else {
None
};
let filled = fill_fields(scope, ty, this, |scope, i, key| match named {
Some(obj) => obj.get(scope, key.into()),
None => Some(args.get(i as i32)),
});
if filled.is_some() {
rv.set(this.into());
}
}
/// Coerces and stores each field; `None` means a TypeError was thrown.
fn fill_fields<'a>(
scope: &mut v8::PinScope<'a, '_>,
ty: &StructType,
target: v8::Local<'a, v8::Object>,
mut source: impl FnMut(
&mut v8::PinScope<'a, '_>,
usize,
v8::Local<'a, v8::String>,
) -> Option<v8::Local<'a, v8::Value>>,
) -> Option<()> {
for (i, field) in ty.fields.iter().enumerate() {
let key = v8::Local::new(scope, &field.key);
let input = source(scope, i, key)?;
let value = coerce_field(scope, ty, field, input)?;
target.set(scope, key.into(), value)?;
}
Some(())
}
fn coerce_field<'a>(
scope: &mut v8::PinScope<'a, '_>,
owner: &StructType,
field: &Field,
input: v8::Local<'a, v8::Value>,
) -> Option<v8::Local<'a, v8::Value>> {
let missing = input.is_null_or_undefined();
match &field.kind {
FieldKind::Value(NativeType::Bool) => {
Some(v8::Boolean::new(scope, !missing && input.boolean_value(scope)).into())
}
FieldKind::Value(NativeType::String) => {
if missing {
Some(v8::String::empty(scope).into())
} else if input.is_string() {
Some(input)
} else {
type_error(scope, owner, field, "a string")
}
}
// BigInt stays BigInt only beyond the safe-integer range, as the reader does.
FieldKind::Value(nt @ (NativeType::I64 | NativeType::U64)) if input.is_big_int() => {
let bi = v8::Local::<v8::BigInt>::try_from(input).ok()?;
let n = match nt {
NativeType::U64 => bi.u64_value().0 as f64,
_ => bi.i64_value().0 as f64,
};
if n.abs() <= MAX_SAFE_INTEGER {
Some(v8::Number::new(scope, n).into())
} else {
Some(input)
}
}
FieldKind::Value(nt) => {
if missing {
return Some(v8::Integer::new(scope, 0).into());
}
if !input.is_number() {
return type_error(scope, owner, field, "a number");
}
let n = input.number_value(scope).unwrap_or(0.0);
// Same casts as the serializer.
let n = match nt {
NativeType::F32 => n as f32 as f64,
NativeType::I32 => n as i32 as f64,
NativeType::U32 => n as u32 as f64,
NativeType::I16 => n as i16 as f64,
NativeType::U16 => n as u16 as f64,
NativeType::I8 => n as i8 as f64,
NativeType::U8 => n as u8 as f64,
NativeType::I64 => n as i64 as f64,
NativeType::U64 => n as u64 as f64,
_ => n,
};
Some(v8::Number::new(scope, n).into())
}
FieldKind::Struct(nested) => {
let obj = instantiate(scope, nested)?;
if missing {
return Some(obj.into());
}
let Some(src) = input.to_object(scope).filter(|_| input.is_object()) else {
return type_error(scope, owner, field, "an object");
};
fill_fields(scope, nested, obj, |scope, _, key| src.get(scope, key.into()))?;
Some(obj.into())
}
FieldKind::Opaque => Some(if missing { v8::null(scope).into() } else { input }),
}
}
fn type_error<'a, T>(
scope: &mut v8::PinScope<'a, '_>,
owner: &StructType,
field: &Field,
expected: &str,
) -> Option<T> {
let message = format!("{}.{} expects {}", owner.name, field.name, expected);
if let Some(message) = v8::String::new(scope, &message) {
let error = v8::Exception::type_error(scope, message);
scope.throw_exception(error);
}
None
}