forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathctypes.rs
More file actions
388 lines (339 loc) · 12.3 KB
/
Copy pathctypes.rs
File metadata and controls
388 lines (339 loc) · 12.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
384
385
386
387
388
// spell-checker:disable
pub(crate) mod array;
pub(crate) mod base;
pub(crate) mod field;
pub(crate) mod function;
pub(crate) mod library;
pub(crate) mod pointer;
pub(crate) mod structure;
pub(crate) mod thunk;
pub(crate) mod union;
use crate::builtins::PyModule;
use crate::class::PyClassImpl;
use crate::stdlib::ctypes::base::{PyCData, PyCSimple, PyCSimpleType};
use crate::{Py, PyRef, VirtualMachine};
pub fn extend_module_nodes(vm: &VirtualMachine, module: &Py<PyModule>) {
let ctx = &vm.ctx;
PyCSimpleType::make_class(ctx);
array::PyCArrayType::make_class(ctx);
field::PyCFieldType::make_class(ctx);
pointer::PyCPointerType::make_class(ctx);
extend_module!(vm, module, {
"_CData" => PyCData::make_class(ctx),
"_SimpleCData" => PyCSimple::make_class(ctx),
"Array" => array::PyCArray::make_class(ctx),
"CField" => field::PyCField::make_class(ctx),
"CFuncPtr" => function::PyCFuncPtr::make_class(ctx),
"_Pointer" => pointer::PyCPointer::make_class(ctx),
"_pointer_type_cache" => ctx.new_dict(),
"Structure" => structure::PyCStructure::make_class(ctx),
"CThunkObject" => thunk::PyCThunk::make_class(ctx),
"Union" => union::PyCUnion::make_class(ctx),
})
}
pub(crate) fn make_module(vm: &VirtualMachine) -> PyRef<PyModule> {
let module = _ctypes::make_module(vm);
extend_module_nodes(vm, &module);
module
}
#[pymodule]
pub(crate) mod _ctypes {
use super::base::PyCSimple;
use crate::builtins::PyTypeRef;
use crate::class::StaticType;
use crate::function::{Either, FuncArgs, OptionalArg};
use crate::stdlib::ctypes::library;
use crate::{AsObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine};
use crossbeam_utils::atomic::AtomicCell;
use std::ffi::{
c_double, c_float, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, c_ulong,
c_ulonglong,
};
use std::mem;
use widestring::WideChar;
#[pyattr(name = "__version__")]
const __VERSION__: &str = "1.1.0";
// TODO: get properly
#[pyattr(name = "RTLD_LOCAL")]
const RTLD_LOCAL: i32 = 0;
// TODO: get properly
#[pyattr(name = "RTLD_GLOBAL")]
const RTLD_GLOBAL: i32 = 0;
#[cfg(target_os = "windows")]
#[pyattr(name = "SIZEOF_TIME_T")]
pub const SIZEOF_TIME_T: usize = 8;
#[cfg(not(target_os = "windows"))]
#[pyattr(name = "SIZEOF_TIME_T")]
pub const SIZEOF_TIME_T: usize = 4;
#[pyattr(name = "CTYPES_MAX_ARGCOUNT")]
pub const CTYPES_MAX_ARGCOUNT: usize = 1024;
#[pyattr]
pub const FUNCFLAG_STDCALL: u32 = 0x0;
#[pyattr]
pub const FUNCFLAG_CDECL: u32 = 0x1;
#[pyattr]
pub const FUNCFLAG_HRESULT: u32 = 0x2;
#[pyattr]
pub const FUNCFLAG_PYTHONAPI: u32 = 0x4;
#[pyattr]
pub const FUNCFLAG_USE_ERRNO: u32 = 0x8;
#[pyattr]
pub const FUNCFLAG_USE_LASTERROR: u32 = 0x10;
#[pyattr]
pub const TYPEFLAG_ISPOINTER: u32 = 0x100;
#[pyattr]
pub const TYPEFLAG_HASPOINTER: u32 = 0x200;
#[pyattr]
pub const DICTFLAG_FINAL: u32 = 0x1000;
#[pyattr(name = "ArgumentError", once)]
fn argument_error(vm: &VirtualMachine) -> PyTypeRef {
vm.ctx.new_exception_type(
"_ctypes",
"ArgumentError",
Some(vec![vm.ctx.exceptions.exception_type.to_owned()]),
)
}
#[pyattr(name = "FormatError", once)]
fn format_error(vm: &VirtualMachine) -> PyTypeRef {
vm.ctx.new_exception_type(
"_ctypes",
"FormatError",
Some(vec![vm.ctx.exceptions.exception_type.to_owned()]),
)
}
pub fn get_size(ty: &str) -> usize {
match ty {
"u" => mem::size_of::<WideChar>(),
"c" | "b" => mem::size_of::<c_schar>(),
"h" => mem::size_of::<c_short>(),
"H" => mem::size_of::<c_short>(),
"i" => mem::size_of::<c_int>(),
"I" => mem::size_of::<c_uint>(),
"l" => mem::size_of::<c_long>(),
"q" => mem::size_of::<c_longlong>(),
"L" => mem::size_of::<c_ulong>(),
"Q" => mem::size_of::<c_ulonglong>(),
"f" => mem::size_of::<c_float>(),
"d" | "g" => mem::size_of::<c_double>(),
"?" | "B" => mem::size_of::<c_uchar>(),
"P" | "z" | "Z" => mem::size_of::<usize>(),
"O" => mem::size_of::<PyObjectRef>(),
_ => unreachable!(),
}
}
const SIMPLE_TYPE_CHARS: &str = "cbBhHiIlLdfguzZPqQ?O";
pub fn new_simple_type(
cls: Either<&PyObjectRef, &PyTypeRef>,
vm: &VirtualMachine,
) -> PyResult<PyCSimple> {
let cls = match cls {
Either::A(obj) => obj,
Either::B(typ) => typ.as_object(),
};
if let Ok(_type_) = cls.get_attr("_type_", vm) {
if _type_.is_instance((&vm.ctx.types.str_type).as_ref(), vm)? {
let tp_str = _type_.str(vm)?.to_string();
if tp_str.len() != 1 {
Err(vm.new_value_error(
format!("class must define a '_type_' attribute which must be a string of length 1, str: {tp_str}"),
))
} else if !SIMPLE_TYPE_CHARS.contains(tp_str.as_str()) {
Err(vm.new_attribute_error(format!("class must define a '_type_' attribute which must be\n a single character string containing one of {SIMPLE_TYPE_CHARS}, currently it is {tp_str}.")))
} else {
Ok(PyCSimple {
_type_: tp_str,
value: AtomicCell::new(vm.ctx.none()),
})
}
} else {
Err(vm.new_type_error("class must define a '_type_' string attribute"))
}
} else {
Err(vm.new_attribute_error("class must define a '_type_' attribute"))
}
}
#[pyfunction(name = "sizeof")]
pub fn size_of(tp: Either<PyTypeRef, PyObjectRef>, vm: &VirtualMachine) -> PyResult<usize> {
match tp {
Either::A(type_) if type_.fast_issubclass(PyCSimple::static_type()) => {
let zelf = new_simple_type(Either::B(&type_), vm)?;
Ok(get_size(zelf._type_.as_str()))
}
Either::B(obj) if obj.has_attr("size_of_instances", vm)? => {
let size_of_method = obj.get_attr("size_of_instances", vm)?;
let size_of_return = size_of_method.call(vec![], vm)?;
Ok(usize::try_from_object(vm, size_of_return)?)
}
_ => Err(vm.new_type_error("this type has no size")),
}
}
#[cfg(windows)]
#[pyfunction(name = "LoadLibrary")]
fn load_library_windows(
name: String,
_load_flags: OptionalArg<i32>,
vm: &VirtualMachine,
) -> PyResult<usize> {
// TODO: audit functions first
// TODO: load_flags
let cache = library::libcache();
let mut cache_write = cache.write();
let (id, _) = cache_write.get_or_insert_lib(&name, vm).unwrap();
Ok(id)
}
#[cfg(not(windows))]
#[pyfunction(name = "dlopen")]
fn load_library_unix(
name: Option<String>,
_load_flags: OptionalArg<i32>,
vm: &VirtualMachine,
) -> PyResult<usize> {
// TODO: audit functions first
// TODO: load_flags
match name {
Some(name) => {
let cache = library::libcache();
let mut cache_write = cache.write();
let (id, _) = cache_write
.get_or_insert_lib(&name, vm)
.map_err(|e| vm.new_os_error(e.to_string()))?;
Ok(id)
}
None => {
// If None, call libc::dlopen(null, mode) to get the current process handle
let handle = unsafe { libc::dlopen(std::ptr::null(), libc::RTLD_NOW) };
if handle.is_null() {
return Err(vm.new_os_error("dlopen() error"));
}
Ok(handle as usize)
}
}
}
#[pyfunction(name = "FreeLibrary")]
fn free_library(handle: usize) -> PyResult<()> {
let cache = library::libcache();
let mut cache_write = cache.write();
cache_write.drop_lib(handle);
Ok(())
}
#[pyfunction(name = "POINTER")]
pub fn create_pointer_type(cls: PyObjectRef, vm: &VirtualMachine) -> PyResult {
// Get the _pointer_type_cache
let ctypes_module = vm.import("_ctypes", 0)?;
let cache = ctypes_module.get_attr("_pointer_type_cache", vm)?;
// Check if already in cache using __getitem__
if let Ok(cached) = vm.call_method(&cache, "__getitem__", (cls.clone(),))
&& !vm.is_none(&cached)
{
return Ok(cached);
}
// Get the _Pointer base class
let pointer_base = ctypes_module.get_attr("_Pointer", vm)?;
// Create the name for the pointer type
let name = if let Ok(type_obj) = cls.get_attr("__name__", vm) {
format!("LP_{}", type_obj.str(vm)?)
} else if let Ok(s) = cls.str(vm) {
format!("LP_{}", s)
} else {
"LP_unknown".to_string()
};
// Create a new type that inherits from _Pointer
let type_type = &vm.ctx.types.type_type;
let bases = vm.ctx.new_tuple(vec![pointer_base]);
let dict = vm.ctx.new_dict();
dict.set_item("_type_", cls.clone(), vm)?;
let new_type = type_type
.as_object()
.call((vm.ctx.new_str(name), bases, dict), vm)?;
// Store in cache using __setitem__
vm.call_method(&cache, "__setitem__", (cls, new_type.clone()))?;
Ok(new_type)
}
#[pyfunction(name = "pointer")]
pub fn create_pointer_inst(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
// Get the type of the object
let obj_type = obj.class().to_owned();
// Create pointer type for this object's type
let ptr_type = create_pointer_type(obj_type.into(), vm)?;
// Create an instance of the pointer type with the object
ptr_type.call((obj,), vm)
}
#[pyfunction]
fn _pointer_type_cache() -> PyObjectRef {
todo!()
}
#[cfg(target_os = "windows")]
#[pyfunction(name = "_check_HRESULT")]
pub fn check_hresult(_self: PyObjectRef, hr: i32, _vm: &VirtualMachine) -> PyResult<i32> {
// TODO: fixme
if hr < 0 {
// vm.ctx.new_windows_error(hr)
todo!();
} else {
Ok(hr)
}
}
#[pyfunction]
fn addressof(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
if obj.is_instance(PyCSimple::static_type().as_ref(), vm)? {
let simple = obj.downcast_ref::<PyCSimple>().unwrap();
Ok(simple.value.as_ptr() as usize)
} else {
Err(vm.new_type_error("expected a ctypes instance"))
}
}
#[pyfunction]
fn byref(_args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
// TODO: RUSTPYTHON
Err(vm.new_value_error("not implemented"))
}
#[pyfunction]
fn alignment(_args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
// TODO: RUSTPYTHON
Err(vm.new_value_error("not implemented"))
}
#[pyfunction]
fn resize(_args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
// TODO: RUSTPYTHON
Err(vm.new_value_error("not implemented"))
}
#[pyfunction]
fn get_errno() -> i32 {
errno::errno().0
}
#[pyfunction]
fn set_errno(value: i32) {
errno::set_errno(errno::Errno(value));
}
#[cfg(windows)]
#[pyfunction]
fn get_last_error() -> PyResult<u32> {
Ok(unsafe { windows_sys::Win32::Foundation::GetLastError() })
}
#[cfg(windows)]
#[pyfunction]
fn set_last_error(value: u32) -> PyResult<()> {
unsafe { windows_sys::Win32::Foundation::SetLastError(value) };
Ok(())
}
#[pyattr]
fn _memmove_addr(_vm: &VirtualMachine) -> usize {
let f = libc::memmove;
f as usize
}
#[pyattr]
fn _memset_addr(_vm: &VirtualMachine) -> usize {
let f = libc::memset;
f as usize
}
#[pyattr]
fn _string_at_addr(_vm: &VirtualMachine) -> usize {
let f = libc::strnlen;
f as usize
}
#[pyattr]
fn _cast_addr(_vm: &VirtualMachine) -> usize {
// TODO: RUSTPYTHON
0
}
}