DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (c969a93b0ca7)

VCS Links

Line Code
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 389 390 391 392 393 394 395 396 397 398
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=2 sw=2 et tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "ctypes/Library.h"

#include "prerror.h"
#include "prlink.h"

#include "ctypes/CTypes.h"
#include "js/CharacterEncoding.h"
#include "js/MemoryFunctions.h"
#include "js/PropertySpec.h"
#include "js/StableStringChars.h"

using JS::AutoStableStringChars;

namespace js {
namespace ctypes {

/*******************************************************************************
** JSAPI function prototypes
*******************************************************************************/

namespace Library {
static void Finalize(JSFreeOp* fop, JSObject* obj);

static bool Close(JSContext* cx, unsigned argc, Value* vp);
static bool Declare(JSContext* cx, unsigned argc, Value* vp);
}  // namespace Library

/*******************************************************************************
** JSObject implementation
*******************************************************************************/

typedef Rooted<JSFlatString*> RootedFlatString;

static const JSClassOps sLibraryClassOps = {
    nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, Library::Finalize};

static const JSClass sLibraryClass = {
    "Library",
    JSCLASS_HAS_RESERVED_SLOTS(LIBRARY_SLOTS) | JSCLASS_FOREGROUND_FINALIZE,
    &sLibraryClassOps};

#define CTYPESFN_FLAGS (JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT)

static const JSFunctionSpec sLibraryFunctions[] = {
    JS_FN("close", Library::Close, 0, CTYPESFN_FLAGS),
    JS_FN("declare", Library::Declare, 0, CTYPESFN_FLAGS), JS_FS_END};

bool Library::Name(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  if (args.length() != 1) {
    JS_ReportErrorASCII(cx, "libraryName takes one argument");
    return false;
  }

  Value arg = args[0];
  JSString* str = nullptr;
  if (arg.isString()) {
    str = arg.toString();
  } else {
    JS_ReportErrorASCII(cx, "name argument must be a string");
    return false;
  }

  AutoString resultString;
  AppendString(cx, resultString, MOZ_DLL_PREFIX);
  AppendString(cx, resultString, str);
  AppendString(cx, resultString, MOZ_DLL_SUFFIX);
  if (!resultString) {
    return false;
  }
  auto resultStr = resultString.finish();

  JSString* result =
      JS_NewUCStringCopyN(cx, resultStr.begin(), resultStr.length());
  if (!result) {
    return false;
  }

  args.rval().setString(result);
  return true;
}

JSObject* Library::Create(JSContext* cx, HandleValue path,
                          const JSCTypesCallbacks* callbacks) {
  RootedObject libraryObj(cx, JS_NewObject(cx, &sLibraryClass));
  if (!libraryObj) {
    return nullptr;
  }

  // initialize the library
  JS_SetReservedSlot(libraryObj, SLOT_LIBRARY, PrivateValue(nullptr));

  // attach API functions
  if (!JS_DefineFunctions(cx, libraryObj, sLibraryFunctions)) {
    return nullptr;
  }

  if (!path.isString()) {
    JS_ReportErrorASCII(cx, "open takes a string argument");
    return nullptr;
  }

  PRLibSpec libSpec;
  RootedFlatString pathStr(cx, JS_FlattenString(cx, path.toString()));
  if (!pathStr) {
    return nullptr;
  }
#ifdef XP_WIN
  // On Windows, converting to native charset may corrupt path string.
  // So, we have to use Unicode path directly.
  AutoStableStringChars pathStrChars(cx);
  if (!pathStrChars.initTwoByte(cx, pathStr)) {
    return nullptr;
  }
  char16ptr_t pathChars = pathStrChars.twoByteChars();
  libSpec.value.pathname_u = pathChars;
  libSpec.type = PR_LibSpec_PathnameU;
#else
  // Convert to platform native charset if the appropriate callback has been
  // provided.
  JS::UniqueChars pathBytes;
  if (callbacks && callbacks->unicodeToNative) {
    AutoStableStringChars pathStrChars(cx);
    if (!pathStrChars.initTwoByte(cx, pathStr)) {
      return nullptr;
    }

    pathBytes.reset(callbacks->unicodeToNative(cx, pathStrChars.twoByteChars(),
                                               pathStr->length()));
    if (!pathBytes) {
      return nullptr;
    }
  } else {
    // Fallback: assume the platform native charset is UTF-8. This is true
    // for Mac OS X, Android, and probably Linux.
    if (!ReportErrorIfUnpairedSurrogatePresent(cx, pathStr)) {
      return nullptr;
    }

    size_t nbytes = JS::GetDeflatedUTF8StringLength(pathStr);

    pathBytes.reset(static_cast<char*>(JS_malloc(cx, nbytes + 1)));
    if (!pathBytes) {
      return nullptr;
    }

    JS::DeflateStringToUTF8Buffer(
        pathStr, mozilla::RangedPtr<char>(pathBytes.get(), nbytes), &nbytes);
    pathBytes[nbytes] = 0;
  }

  libSpec.value.pathname = pathBytes.get();
  libSpec.type = PR_LibSpec_Pathname;
#endif

  PRLibrary* library = PR_LoadLibraryWithFlags(libSpec, PR_LD_NOW);

  if (!library) {
#define MAX_ERROR_LEN 1024
    char error[MAX_ERROR_LEN] = "Cannot get error from NSPR.";
    uint32_t errorLen = PR_GetErrorTextLength();
    if (errorLen && errorLen < MAX_ERROR_LEN) {
      PR_GetErrorText(error);
    }
#undef MAX_ERROR_LEN

    if (JS::StringIsASCII(error)) {
      if (JS::UniqueChars pathCharsUTF8 = JS_EncodeStringToUTF8(cx, pathStr)) {
        JS_ReportErrorUTF8(cx, "couldn't open library %s: %s",
                           pathCharsUTF8.get(), error);
      }
    } else {
      if (JS::UniqueChars pathCharsLatin1 =
              JS_EncodeStringToLatin1(cx, pathStr)) {
        JS_ReportErrorLatin1(cx, "couldn't open library %s: %s",
                             pathCharsLatin1.get(), error);
      }
    }
    return nullptr;
  }

  // stash the library
  JS_SetReservedSlot(libraryObj, SLOT_LIBRARY, PrivateValue(library));

  return libraryObj;
}

bool Library::IsLibrary(JSObject* obj) {
  return JS_GetClass(obj) == &sLibraryClass;
}

PRLibrary* Library::GetLibrary(JSObject* obj) {
  MOZ_ASSERT(IsLibrary(obj));

  Value slot = JS_GetReservedSlot(obj, SLOT_LIBRARY);
  return static_cast<PRLibrary*>(slot.toPrivate());
}

static void UnloadLibrary(JSObject* obj) {
  PRLibrary* library = Library::GetLibrary(obj);
  if (library) {
    PR_UnloadLibrary(library);
  }
}

void Library::Finalize(JSFreeOp* fop, JSObject* obj) { UnloadLibrary(obj); }

bool Library::Open(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  JSObject* ctypesObj = GetThisObject(cx, args, "ctypes.open");
  if (!ctypesObj) {
    return false;
  }

  if (!IsCTypesGlobal(ctypesObj)) {
    JS_ReportErrorASCII(cx, "not a ctypes object");
    return false;
  }

  if (args.length() != 1 || args[0].isUndefined()) {
    JS_ReportErrorASCII(cx, "open requires a single argument");
    return false;
  }

  JSObject* library = Create(cx, args[0], GetCallbacks(ctypesObj));
  if (!library) {
    return false;
  }

  args.rval().setObject(*library);
  return true;
}

bool Library::Close(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  RootedObject obj(cx, GetThisObject(cx, args, "ctypes.close"));
  if (!obj) {
    return false;
  }

  if (!IsLibrary(obj)) {
    JS_ReportErrorASCII(cx, "not a library");
    return false;
  }

  if (args.length() != 0) {
    JS_ReportErrorASCII(cx, "close doesn't take any arguments");
    return false;
  }

  // delete our internal objects
  UnloadLibrary(obj);
  JS_SetReservedSlot(obj, SLOT_LIBRARY, PrivateValue(nullptr));

  args.rval().setUndefined();
  return true;
}

bool Library::Declare(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  RootedObject obj(cx, GetThisObject(cx, args, "ctypes.declare"));
  if (!obj) {
    return false;
  }

  if (!IsLibrary(obj)) {
    JS_ReportErrorASCII(cx, "not a library");
    return false;
  }

  PRLibrary* library = GetLibrary(obj);
  if (!library) {
    JS_ReportErrorASCII(cx, "library not open");
    return false;
  }

  // We allow two API variants:
  // 1) library.declare(name, abi, returnType, argType1, ...)
  //    declares a function with the given properties, and resolves the symbol
  //    address in the library.
  // 2) library.declare(name, type)
  //    declares a symbol of 'type', and resolves it. The object that comes
  //    back will be of type 'type', and will point into the symbol data.
  //    This data will be both readable and writable via the usual CData
  //    accessors. If 'type' is a PointerType to a FunctionType, the result will
  //    be a function pointer, as with 1).
  if (args.length() < 2) {
    JS_ReportErrorASCII(cx, "declare requires at least two arguments");
    return false;
  }

  if (!args[0].isString()) {
    JS_ReportErrorASCII(cx, "first argument must be a string");
    return false;
  }

  RootedObject fnObj(cx, nullptr);
  RootedObject typeObj(cx);
  bool isFunction = args.length() > 2;
  if (isFunction) {
    // Case 1).
    // Create a FunctionType representing the function.
    fnObj = FunctionType::CreateInternal(
        cx, args[1], args[2],
        HandleValueArray::subarray(args, 3, args.length() - 3));
    if (!fnObj) {
      return false;
    }

    // Make a function pointer type.
    typeObj = PointerType::CreateInternal(cx, fnObj);
    if (!typeObj) {
      return false;
    }
  } else {
    // Case 2).
    if (args[1].isPrimitive() || !CType::IsCType(args[1].toObjectOrNull()) ||
        !CType::IsSizeDefined(args[1].toObjectOrNull())) {
      JS_ReportErrorASCII(cx, "second argument must be a type of defined size");
      return false;
    }

    typeObj = args[1].toObjectOrNull();
    if (CType::GetTypeCode(typeObj) == TYPE_pointer) {
      fnObj = PointerType::GetBaseType(typeObj);
      isFunction = fnObj && CType::GetTypeCode(fnObj) == TYPE_function;
    }
  }

  void* data;
  PRFuncPtr fnptr;
  RootedString nameStr(cx, args[0].toString());
  AutoCString symbol;
  if (isFunction) {
    // Build the symbol, with mangling if necessary.
    FunctionType::BuildSymbolName(cx, nameStr, fnObj, symbol);
    AppendString(cx, symbol, "\0");
    if (!symbol) {
      return false;
    }

    // Look up the function symbol.
    fnptr = PR_FindFunctionSymbol(library, symbol.finish().begin());
    if (!fnptr) {
      JS_ReportErrorASCII(cx, "couldn't find function symbol in library");
      return false;
    }
    data = &fnptr;

  } else {
    // 'typeObj' is another data type. Look up the data symbol.
    AppendString(cx, symbol, nameStr);
    AppendString(cx, symbol, "\0");
    if (!symbol) {
      return false;
    }

    data = PR_FindSymbol(library, symbol.finish().begin());
    if (!data) {
      JS_ReportErrorASCII(cx, "couldn't find symbol in library");
      return false;
    }
  }

  RootedObject result(cx, CData::Create(cx, typeObj, obj, data, isFunction));
  if (!result) {
    return false;
  }

  if (isFunction) {
    JS_SetReservedSlot(result, SLOT_FUNNAME, StringValue(nameStr));
  }

  args.rval().setObject(*result);

  // Seal the CData object, to prevent modification of the function pointer.
  // This permanently associates this object with the library, and avoids
  // having to do things like reset SLOT_REFERENT when someone tries to
  // change the pointer value.
  // XXX This will need to change when bug 541212 is fixed -- CData::ValueSetter
  // could be called on a sealed object.
  if (isFunction && !JS_FreezeObject(cx, result)) {
    return false;
  }

  return true;
}

}  // namespace ctypes
}  // namespace js