Debian Codegraph @

js/src/ctypes/Library.cpp

raw
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=2 sw=2 et tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "ctypes/Library.h"
8
9 #include "jsapi.h"
10 #include "prerror.h"
11 #include "prlink.h"
12
13 #include "ctypes/CTypes.h"
14 #include "js/CharacterEncoding.h"
15 #include "js/ErrorReport.h"
16 #include "js/experimental/CTypes.h" // JS::CTypesCallbacks
17 #include "js/MemoryFunctions.h"
18 #include "js/Object.h" // JS::GetReservedSlot
19 #include "js/PropertyAndElement.h" // JS_DefineFunctions
20 #include "js/PropertySpec.h"
21 #include "js/StableStringChars.h"
22 #include "js/ValueArray.h"
23 #include "vm/JSObject.h"
24
25 using JS::AutoStableStringChars;
26
27 namespace js::ctypes {
28
29 /*******************************************************************************
30 ** JSAPI function prototypes
31 *******************************************************************************/
32
33 namespace Library {
34 static void Finalize(JS::GCContext* gcx, JSObject* obj);
35
36 static bool Close(JSContext* cx, unsigned argc, Value* vp);
37 static bool Declare(JSContext* cx, unsigned argc, Value* vp);
38 } // namespace Library
39
40 /*******************************************************************************
41 ** JSObject implementation
42 *******************************************************************************/
43
44 static const JSClassOps sLibraryClassOps = {
45 nullptr, // addProperty
46 nullptr, // delProperty
47 nullptr, // enumerate
48 nullptr, // newEnumerate
49 nullptr, // resolve
50 nullptr, // mayResolve
51 Library::Finalize, // finalize
52 nullptr, // call
53 nullptr, // construct
54 nullptr, // trace
55 };
56
57 static const JSClass sLibraryClass = {
58 "Library",
59 JSCLASS_HAS_RESERVED_SLOTS(LIBRARY_SLOTS) | JSCLASS_FOREGROUND_FINALIZE,
60 &sLibraryClassOps,
61 };
62
63 #define CTYPESFN_FLAGS (JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT)
64
65 static const JSFunctionSpec sLibraryFunctions[] = {
66 JS_FN("close", Library::Close, 0, CTYPESFN_FLAGS),
67 JS_FN("declare", Library::Declare, 0, CTYPESFN_FLAGS),
68 JS_FS_END,
69 };
70
71 bool Library::Name(JSContext* cx, unsigned argc, Value* vp) {
72 CallArgs args = CallArgsFromVp(argc, vp);
73 if (args.length() != 1) {
74 JS_ReportErrorASCII(cx, "libraryName takes one argument");
75 return false;
76 }
77
78 Value arg = args[0];
79 JSString* str = nullptr;
80 if (arg.isString()) {
81 str = arg.toString();
82 } else {
83 JS_ReportErrorASCII(cx, "name argument must be a string");
84 return false;
85 }
86
87 AutoString resultString;
88 AppendString(cx, resultString, MOZ_DLL_PREFIX);
89 AppendString(cx, resultString, str);
90 AppendString(cx, resultString, MOZ_DLL_SUFFIX);
91 if (!resultString) {
92 return false;
93 }
94 auto resultStr = resultString.finish();
95
96 JSString* result =
97 JS_NewUCStringCopyN(cx, resultStr.begin(), resultStr.length());
98 if (!result) {
99 return false;
100 }
101
102 args.rval().setString(result);
103 return true;
104 }
105
106 JSObject* Library::Create(JSContext* cx, HandleValue path,
107 const JS::CTypesCallbacks* callbacks) {
108 RootedObject libraryObj(cx, JS_NewObject(cx, &sLibraryClass));
109 if (!libraryObj) {
110 return nullptr;
111 }
112
113 // initialize the library
114 JS_SetReservedSlot(libraryObj, SLOT_LIBRARY, PrivateValue(nullptr));
115
116 // attach API functions
117 if (!JS_DefineFunctions(cx, libraryObj, sLibraryFunctions)) {
118 return nullptr;
119 }
120
121 if (!path.isString()) {
122 JS_ReportErrorASCII(cx, "open takes a string argument");
123 return nullptr;
124 }
125
126 PRLibSpec libSpec;
127 Rooted<JSLinearString*> pathStr(cx,
128 JS_EnsureLinearString(cx, path.toString()));
129 if (!pathStr) {
130 return nullptr;
131 }
132 #ifdef XP_WIN
133 // On Windows, converting to native charset may corrupt path string.
134 // So, we have to use Unicode path directly.
135 JS::UniqueTwoByteChars pathZeroTerminated(JS_CopyStringCharsZ(cx, pathStr));
136 if (!pathZeroTerminated) {
137 return nullptr;
138 }
139 char16ptr_t pathChars = pathZeroTerminated.get();
140 libSpec.value.pathname_u = pathChars;
141 libSpec.type = PR_LibSpec_PathnameU;
142 #else
143 // Convert to platform native charset if the appropriate callback has been
144 // provided.
145 JS::UniqueChars pathBytes;
146 if (callbacks && callbacks->unicodeToNative) {
147 AutoStableStringChars pathStrChars(cx);
148 if (!pathStrChars.initTwoByte(cx, pathStr)) {
149 return nullptr;
150 }
151
152 pathBytes.reset(callbacks->unicodeToNative(cx, pathStrChars.twoByteChars(),
153 pathStr->length()));
154 if (!pathBytes) {
155 return nullptr;
156 }
157 } else {
158 // Fallback: assume the platform native charset is UTF-8. This is true
159 // for Mac OS X, Android, and probably Linux.
160 if (!ReportErrorIfUnpairedSurrogatePresent(cx, pathStr)) {
161 return nullptr;
162 }
163
164 size_t nbytes = JS::GetDeflatedUTF8StringLength(pathStr);
165
166 pathBytes.reset(static_cast<char*>(JS_malloc(cx, nbytes + 1)));
167 if (!pathBytes) {
168 return nullptr;
169 }
170
171 nbytes = JS::DeflateStringToUTF8Buffer(
172 pathStr, mozilla::Span(pathBytes.get(), nbytes));
173 pathBytes[nbytes] = 0;
174 }
175
176 libSpec.value.pathname = pathBytes.get();
177 libSpec.type = PR_LibSpec_Pathname;
178 #endif
179
180 PRLibrary* library = PR_LoadLibraryWithFlags(libSpec, PR_LD_NOW);
181
182 if (!library) {
183 constexpr size_t MaxErrorLength = 1024;
184 char error[MaxErrorLength] = "Cannot get error from NSPR.";
185 uint32_t errorLen = PR_GetErrorTextLength();
186 if (errorLen && errorLen < MaxErrorLength) {
187 PR_GetErrorText(error);
188 }
189
190 if (JS::UniqueChars errorUtf8 = JS::EncodeNarrowToUtf8(cx, error)) {
191 if (JS::UniqueChars pathChars = JS_EncodeStringToUTF8(cx, pathStr)) {
192 JS_ReportErrorUTF8(cx, "couldn't open library %s: %s", pathChars.get(),
193 errorUtf8.get());
194 }
195 }
196 return nullptr;
197 }
198
199 // stash the library
200 JS_SetReservedSlot(libraryObj, SLOT_LIBRARY, PrivateValue(library));
201
202 return libraryObj;
203 }
204
205 bool Library::IsLibrary(JSObject* obj) { return obj->hasClass(&sLibraryClass); }
206
207 PRLibrary* Library::GetLibrary(JSObject* obj) {
208 MOZ_ASSERT(IsLibrary(obj));
209
210 Value slot = JS::GetReservedSlot(obj, SLOT_LIBRARY);
211 return static_cast<PRLibrary*>(slot.toPrivate());
212 }
213
214 static void UnloadLibrary(JSObject* obj) {
215 PRLibrary* library = Library::GetLibrary(obj);
216 if (library) {
217 PR_UnloadLibrary(library);
218 }
219 }
220
221 void Library::Finalize(JS::GCContext* gcx, JSObject* obj) {
222 UnloadLibrary(obj);
223 }
224
225 bool Library::Open(JSContext* cx, unsigned argc, Value* vp) {
226 CallArgs args = CallArgsFromVp(argc, vp);
227 JSObject* ctypesObj = GetThisObject(cx, args, "ctypes.open");
228 if (!ctypesObj) {
229 return false;
230 }
231
232 if (!IsCTypesGlobal(ctypesObj)) {
233 JS_ReportErrorASCII(cx, "not a ctypes object");
234 return false;
235 }
236
237 if (args.length() != 1 || args[0].isUndefined()) {
238 JS_ReportErrorASCII(cx, "open requires a single argument");
239 return false;
240 }
241
242 JSObject* library = Create(cx, args[0], GetCallbacks(ctypesObj));
243 if (!library) {
244 return false;
245 }
246
247 args.rval().setObject(*library);
248 return true;
249 }
250
251 bool Library::Close(JSContext* cx, unsigned argc, Value* vp) {
252 CallArgs args = CallArgsFromVp(argc, vp);
253
254 RootedObject obj(cx, GetThisObject(cx, args, "ctypes.close"));
255 if (!obj) {
256 return false;
257 }
258
259 if (!IsLibrary(obj)) {
260 JS_ReportErrorASCII(cx, "not a library");
261 return false;
262 }
263
264 if (args.length() != 0) {
265 JS_ReportErrorASCII(cx, "close doesn't take any arguments");
266 return false;
267 }
268
269 // delete our internal objects
270 UnloadLibrary(obj);
271 JS_SetReservedSlot(obj, SLOT_LIBRARY, PrivateValue(nullptr));
272
273 args.rval().setUndefined();
274 return true;
275 }
276
277 bool Library::Declare(JSContext* cx, unsigned argc, Value* vp) {
278 CallArgs args = CallArgsFromVp(argc, vp);
279
280 RootedObject obj(cx, GetThisObject(cx, args, "ctypes.declare"));
281 if (!obj) {
282 return false;
283 }
284
285 if (!IsLibrary(obj)) {
286 JS_ReportErrorASCII(cx, "not a library");
287 return false;
288 }
289
290 PRLibrary* library = GetLibrary(obj);
291 if (!library) {
292 JS_ReportErrorASCII(cx, "library not open");
293 return false;
294 }
295
296 // We allow two API variants:
297 // 1) library.declare(name, abi, returnType, argType1, ...)
298 // declares a function with the given properties, and resolves the symbol
299 // address in the library.
300 // 2) library.declare(name, type)
301 // declares a symbol of 'type', and resolves it. The object that comes
302 // back will be of type 'type', and will point into the symbol data.
303 // This data will be both readable and writable via the usual CData
304 // accessors. If 'type' is a PointerType to a FunctionType, the result will
305 // be a function pointer, as with 1).
306 if (args.length() < 2) {
307 JS_ReportErrorASCII(cx, "declare requires at least two arguments");
308 return false;
309 }
310
311 if (!args[0].isString()) {
312 JS_ReportErrorASCII(cx, "first argument must be a string");
313 return false;
314 }
315
316 RootedObject fnObj(cx, nullptr);
317 RootedObject typeObj(cx);
318 bool isFunction = args.length() > 2;
319 if (isFunction) {
320 // Case 1).
321 // Create a FunctionType representing the function.
322 fnObj = FunctionType::CreateInternal(
323 cx, args[1], args[2],
324 HandleValueArray::subarray(args, 3, args.length() - 3));
325 if (!fnObj) {
326 return false;
327 }
328
329 // Make a function pointer type.
330 typeObj = PointerType::CreateInternal(cx, fnObj);
331 if (!typeObj) {
332 return false;
333 }
334 } else {
335 // Case 2).
336 if (args[1].isPrimitive() || !CType::IsCType(args[1].toObjectOrNull()) ||
337 !CType::IsSizeDefined(args[1].toObjectOrNull())) {
338 JS_ReportErrorASCII(cx, "second argument must be a type of defined size");
339 return false;
340 }
341
342 typeObj = args[1].toObjectOrNull();
343 if (CType::GetTypeCode(typeObj) == TYPE_pointer) {
344 fnObj = PointerType::GetBaseType(typeObj);
345 isFunction = fnObj && CType::GetTypeCode(fnObj) == TYPE_function;
346 }
347 }
348
349 void* data;
350 PRFuncPtr fnptr;
351 RootedString nameStr(cx, args[0].toString());
352 AutoCString symbol;
353 if (isFunction) {
354 // Build the symbol, with mangling if necessary.
355 FunctionType::BuildSymbolName(cx, nameStr, fnObj, symbol);
356 AppendString(cx, symbol, "\0");
357 if (!symbol) {
358 return false;
359 }
360
361 // Look up the function symbol.
362 fnptr = PR_FindFunctionSymbol(library, symbol.finish().begin());
363 if (!fnptr) {
364 JS_ReportErrorASCII(cx, "couldn't find function symbol in library");
365 return false;
366 }
367 data = &fnptr;
368
369 } else {
370 // 'typeObj' is another data type. Look up the data symbol.
371 AppendString(cx, symbol, nameStr);
372 AppendString(cx, symbol, "\0");
373 if (!symbol) {
374 return false;
375 }
376
377 data = PR_FindSymbol(library, symbol.finish().begin());
378 if (!data) {
379 JS_ReportErrorASCII(cx, "couldn't find symbol in library");
380 return false;
381 }
382 }
383
384 RootedObject result(cx, CData::Create(cx, typeObj, obj, data, isFunction));
385 if (!result) {
386 return false;
387 }
388
389 if (isFunction) {
390 JS_SetReservedSlot(result, SLOT_FUNNAME, StringValue(nameStr));
391 }
392
393 args.rval().setObject(*result);
394
395 // Seal the CData object, to prevent modification of the function pointer.
396 // This permanently associates this object with the library, and avoids
397 // having to do things like reset SLOT_REFERENT when someone tries to
398 // change the pointer value.
399 // XXX This will need to change when bug 541212 is fixed -- CData::ValueSetter
400 // could be called on a sealed object.
401 if (isFunction && !JS_FreezeObject(cx, result)) {
402 return false;
403 }
404
405 return true;
406 }
407
408 } // namespace js::ctypes