tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

APKOpen.cpp (20686B)


      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 /*
      6 * This custom library loading code is only meant to be called
      7 * during initialization. As a result, it takes no special
      8 * precautions to be threadsafe. Any of the library loading functions
      9 * like mozload should not be available to other code.
     10 */
     11 
     12 #include <jni.h>
     13 #include <android/log.h>
     14 #include <sys/types.h>
     15 #include <sys/stat.h>
     16 #include <sys/mman.h>
     17 #include <sys/limits.h>
     18 #include <errno.h>
     19 #include <string.h>
     20 #include <stdio.h>
     21 #include <stdlib.h>
     22 #include <fcntl.h>
     23 #include <unistd.h>
     24 #include "dlfcn.h"
     25 #include "APKOpen.h"
     26 #include <sys/time.h>
     27 #include <sys/syscall.h>
     28 #include <sys/resource.h>
     29 #include <sys/prctl.h>
     30 #include "sqlite3.h"
     31 #include "Linker.h"
     32 #include "application.ini.h"
     33 
     34 #include "mozilla/arm.h"
     35 #include "mozilla/BaseProfiler.h"
     36 #include "mozilla/Bootstrap.h"
     37 #include "mozilla/Printf.h"
     38 #include "mozilla/ProcessType.h"
     39 #include "mozilla/Sprintf.h"
     40 #include "mozilla/TimeStamp.h"
     41 #include "mozilla/Try.h"
     42 #include "mozilla/UniquePtr.h"
     43 #include "XREChildData.h"
     44 #include "XREShellData.h"
     45 
     46 /* Android headers don't define RUSAGE_THREAD */
     47 #ifndef RUSAGE_THREAD
     48 #  define RUSAGE_THREAD 1
     49 #endif
     50 
     51 #ifndef RELEASE_OR_BETA
     52 /* Official builds have the debuggable flag set to false, which disables
     53 * the backtrace dumper from bionic. However, as it is useful for native
     54 * crashes happening before the crash reporter is registered, re-enable
     55 * it on non release builds (i.e. nightly and aurora).
     56 * Using a constructor so that it is re-enabled as soon as libmozglue.so
     57 * is loaded.
     58 */
     59 __attribute__((constructor)) void make_dumpable() { prctl(PR_SET_DUMPABLE, 1); }
     60 #endif
     61 
     62 typedef int mozglueresult;
     63 
     64 using LoadGeckoLibsResult =
     65    mozilla::Result<mozilla::Ok, mozilla::BootstrapError>;
     66 
     67 enum StartupEvent {
     68 #define mozilla_StartupTimeline_Event(ev, z) ev,
     69 #include "StartupTimeline.h"
     70 #undef mozilla_StartupTimeline_Event
     71  MAX_STARTUP_EVENT_ID
     72 };
     73 
     74 using namespace mozilla;
     75 
     76 void JNI_Throw(JNIEnv* jenv, const char* classname, const char* msg) {
     77  __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Throw\n");
     78  jclass cls = jenv->FindClass(classname);
     79  if (cls == nullptr) {
     80    __android_log_print(
     81        ANDROID_LOG_ERROR, "GeckoLibLoad",
     82        "Couldn't find exception class (or exception pending) %s\n", classname);
     83    exit(FAILURE);
     84  }
     85  int rc = jenv->ThrowNew(cls, msg);
     86  if (rc < 0) {
     87    __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
     88                        "Error throwing exception %s\n", msg);
     89    exit(FAILURE);
     90  }
     91  jenv->DeleteLocalRef(cls);
     92 }
     93 
     94 namespace {
     95 JavaVM* sJavaVM;
     96 }
     97 
     98 void abortThroughJava(const char* msg) {
     99  struct sigaction sigact = {};
    100  if (__wrap_sigaction(SIGSEGV, nullptr, &sigact)) {
    101    return;  // sigaction call failed.
    102  }
    103 
    104  Dl_info info = {};
    105  if ((sigact.sa_flags & SA_SIGINFO) &&
    106      __wrap_dladdr(reinterpret_cast<void*>(sigact.sa_sigaction), &info) &&
    107      info.dli_fname && strstr(info.dli_fname, "libxul.so")) {
    108    return;  // Existing signal handler is in libxul (i.e. we have crash
    109             // reporter).
    110  }
    111 
    112  JNIEnv* env = nullptr;
    113  if (!sJavaVM ||
    114      sJavaVM->AttachCurrentThreadAsDaemon(&env, nullptr) != JNI_OK) {
    115    return;
    116  }
    117 
    118  if (!env || env->PushLocalFrame(2) != JNI_OK) {
    119    return;
    120  }
    121 
    122  jclass loader = env->FindClass("org/mozilla/gecko/mozglue/GeckoLoader");
    123  if (!loader) {
    124    return;
    125  }
    126 
    127  jmethodID method =
    128      env->GetStaticMethodID(loader, "abort", "(Ljava/lang/String;)V");
    129  jstring str = env->NewStringUTF(msg);
    130 
    131  if (method && str) {
    132    env->CallStaticVoidMethod(loader, method, str);
    133  }
    134 
    135  env->PopLocalFrame(nullptr);
    136 }
    137 
    138 constinit Bootstrap::UniquePtr gBootstrap;
    139 
    140 #ifndef MOZ_FOLD_LIBS
    141 static void* sqlite_handle = nullptr;
    142 static void* nspr_handle = nullptr;
    143 static void* plc_handle = nullptr;
    144 #else
    145 #  define sqlite_handle nss_handle
    146 #  define nspr_handle nss_handle
    147 #  define plc_handle nss_handle
    148 #endif
    149 static void* nss_handle = nullptr;
    150 
    151 static UniquePtr<char[]> getUnpackedLibraryName(const char* libraryName) {
    152  static const char* libdir = getenv("MOZ_ANDROID_LIBDIR");
    153 
    154  size_t len = strlen(libdir) + 1 /* path separator */ + strlen(libraryName) +
    155               1; /* null terminator */
    156  auto file = MakeUnique<char[]>(len);
    157  snprintf(file.get(), len, "%s/%s", libdir, libraryName);
    158  return file;
    159 }
    160 
    161 static void* dlopenLibrary(const char* libraryName) {
    162  return __wrap_dlopen(getUnpackedLibraryName(libraryName).get(),
    163                       RTLD_GLOBAL | RTLD_LAZY);
    164 }
    165 
    166 static void EnsureBaseProfilerInitialized() {
    167  // There is no single entry-point into C++ code on Android.
    168  // Instead, GeckoThread and GeckoLibLoader call various functions to load
    169  // libraries one-by-one.
    170  // We want to capture all that library loading in the profiler, so we need to
    171  // kick off the base profiler at the beginning of whichever function is called
    172  // first.
    173  // We currently assume that all these functions are called on the same thread.
    174  static bool sInitialized = false;
    175  if (sInitialized) {
    176    return;
    177  }
    178 
    179  // The stack depth we observe here will be determined by the stack of
    180  // whichever caller enters this code first. In practice this means that we may
    181  // miss some root-most frames, which hopefully shouldn't ruin profiling.
    182  int stackBase = 5;
    183  mozilla::baseprofiler::profiler_init(&stackBase);
    184  sInitialized = true;
    185 }
    186 
    187 static LoadGeckoLibsResult loadGeckoLibs() {
    188  TimeStamp t0 = TimeStamp::Now();
    189  struct rusage usage1_thread, usage1;
    190  getrusage(RUSAGE_THREAD, &usage1_thread);
    191  getrusage(RUSAGE_SELF, &usage1);
    192 
    193  static const char* libxul = getenv("MOZ_ANDROID_LIBDIR_OVERRIDE");
    194  gBootstrap = MOZ_TRY(
    195      GetBootstrap(libxul ? libxul : getUnpackedLibraryName("libxul.so").get(),
    196                   LibLoadingStrategy::ReadAhead));
    197 
    198  TimeStamp t1 = TimeStamp::Now();
    199  struct rusage usage2_thread, usage2;
    200  getrusage(RUSAGE_THREAD, &usage2_thread);
    201  getrusage(RUSAGE_SELF, &usage2);
    202 
    203 #define RUSAGE_TIMEDIFF(u1, u2, field)                    \
    204  ((u2.ru_##field.tv_sec - u1.ru_##field.tv_sec) * 1000 + \
    205   (u2.ru_##field.tv_usec - u1.ru_##field.tv_usec) / 1000)
    206 
    207  __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
    208                      "Loaded libs in %fms total, %ldms(%ldms) user, "
    209                      "%ldms(%ldms) system, %ld(%ld) faults",
    210                      (t1 - t0).ToMilliseconds(),
    211                      RUSAGE_TIMEDIFF(usage1_thread, usage2_thread, utime),
    212                      RUSAGE_TIMEDIFF(usage1, usage2, utime),
    213                      RUSAGE_TIMEDIFF(usage1_thread, usage2_thread, stime),
    214                      RUSAGE_TIMEDIFF(usage1, usage2, stime),
    215                      usage2_thread.ru_majflt - usage1_thread.ru_majflt,
    216                      usage2.ru_majflt - usage1.ru_majflt);
    217 
    218  gBootstrap->XRE_StartupTimelineRecord(LINKER_INITIALIZED, t0);
    219  gBootstrap->XRE_StartupTimelineRecord(LIBRARIES_LOADED, t1);
    220  return Ok();
    221 }
    222 
    223 static mozglueresult loadNSSLibs();
    224 
    225 static mozglueresult loadSQLiteLibs() {
    226  if (sqlite_handle) return SUCCESS;
    227 
    228 #ifdef MOZ_FOLD_LIBS
    229  if (loadNSSLibs() != SUCCESS) return FAILURE;
    230 #else
    231 
    232  sqlite_handle = dlopenLibrary("libmozsqlite3.so");
    233  if (!sqlite_handle) {
    234    __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
    235                        "Couldn't get a handle to libmozsqlite3!");
    236    return FAILURE;
    237  }
    238 #endif
    239 
    240  return SUCCESS;
    241 }
    242 
    243 static mozglueresult loadNSSLibs() {
    244  if (nss_handle && nspr_handle && plc_handle) return SUCCESS;
    245 
    246  nss_handle = dlopenLibrary("libnss3.so");
    247 
    248 #ifndef MOZ_FOLD_LIBS
    249  nspr_handle = dlopenLibrary("libnspr4.so");
    250 
    251  plc_handle = dlopenLibrary("libplc4.so");
    252 #endif
    253 
    254  if (!nss_handle) {
    255    __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
    256                        "Couldn't get a handle to libnss3!");
    257    return FAILURE;
    258  }
    259 
    260 #ifndef MOZ_FOLD_LIBS
    261  if (!nspr_handle) {
    262    __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
    263                        "Couldn't get a handle to libnspr4!");
    264    return FAILURE;
    265  }
    266 
    267  if (!plc_handle) {
    268    __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
    269                        "Couldn't get a handle to libplc4!");
    270    return FAILURE;
    271  }
    272 #endif
    273 
    274  return SUCCESS;
    275 }
    276 
    277 extern "C" APKOPEN_EXPORT void MOZ_JNICALL
    278 Java_org_mozilla_gecko_mozglue_GeckoLoader_loadGeckoLibsNative(
    279    JNIEnv* jenv, jclass jGeckoAppShellClass) {
    280  EnsureBaseProfilerInitialized();
    281 
    282  jenv->GetJavaVM(&sJavaVM);
    283 
    284  LoadGeckoLibsResult res = loadGeckoLibs();
    285  if (res.isOk()) {
    286    return;
    287  }
    288 
    289  const BootstrapError& errorInfo = res.inspectErr();
    290 
    291  auto msg = errorInfo.match(
    292      [](const nsresult& aRv) {
    293        return Smprintf("Error loading Gecko libraries: nsresult 0x%08X",
    294                        uint32_t(aRv));
    295      },
    296      [](const DLErrorType& aErr) {
    297        return Smprintf("Error loading Gecko libraries: %s", aErr.get());
    298      });
    299 
    300  JNI_Throw(jenv, "java/lang/Exception", msg.get());
    301 }
    302 
    303 extern "C" APKOPEN_EXPORT void MOZ_JNICALL
    304 Java_org_mozilla_gecko_mozglue_GeckoLoader_loadSQLiteLibsNative(
    305    JNIEnv* jenv, jclass jGeckoAppShellClass) {
    306  EnsureBaseProfilerInitialized();
    307 
    308  __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Load sqlite start\n");
    309  mozglueresult rv = loadSQLiteLibs();
    310  if (rv != SUCCESS) {
    311    JNI_Throw(jenv, "java/lang/Exception", "Error loading sqlite libraries");
    312  }
    313  __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Load sqlite done\n");
    314 }
    315 
    316 extern "C" APKOPEN_EXPORT void MOZ_JNICALL
    317 Java_org_mozilla_gecko_mozglue_GeckoLoader_loadNSSLibsNative(
    318    JNIEnv* jenv, jclass jGeckoAppShellClass) {
    319  EnsureBaseProfilerInitialized();
    320 
    321  __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Load nss start\n");
    322  mozglueresult rv = loadNSSLibs();
    323  if (rv != SUCCESS) {
    324    JNI_Throw(jenv, "java/lang/Exception", "Error loading nss libraries");
    325  }
    326  __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Load nss done\n");
    327 }
    328 
    329 static char** CreateArgvFromObjectArray(JNIEnv* jenv, jobjectArray jargs,
    330                                        int* length) {
    331  size_t stringCount = jenv->GetArrayLength(jargs);
    332 
    333  if (length) {
    334    *length = stringCount;
    335  }
    336 
    337  if (!stringCount) {
    338    return nullptr;
    339  }
    340 
    341  char** argv = new char*[stringCount + 1];
    342 
    343  argv[stringCount] = nullptr;
    344 
    345  for (size_t ix = 0; ix < stringCount; ix++) {
    346    jstring string = (jstring)(jenv->GetObjectArrayElement(jargs, ix));
    347    const char* rawString = jenv->GetStringUTFChars(string, nullptr);
    348    const int strLength = jenv->GetStringUTFLength(string);
    349    argv[ix] = strndup(rawString, strLength);
    350    jenv->ReleaseStringUTFChars(string, rawString);
    351    jenv->DeleteLocalRef(string);
    352  }
    353 
    354  return argv;
    355 }
    356 
    357 static void FreeArgv(char** argv, int argc) {
    358  for (int ix = 0; ix < argc; ix++) {
    359    // String was allocated with strndup, so need to use free to deallocate.
    360    free(argv[ix]);
    361  }
    362  delete[] (argv);
    363 }
    364 
    365 // These are mirrored in GeckoLoader.java
    366 #define PROCESS_TYPE_MAIN 0
    367 #define PROCESS_TYPE_CHILD 1
    368 #define PROCESS_TYPE_XPCSHELL 2
    369 
    370 extern "C" APKOPEN_EXPORT void MOZ_JNICALL
    371 Java_org_mozilla_gecko_mozglue_GeckoLoader_nativeRun(JNIEnv* jenv, jclass jc,
    372                                                     jobjectArray jargs,
    373                                                     jintArray jfds,
    374                                                     jint processType,
    375                                                     jstring outFilePath) {
    376  EnsureBaseProfilerInitialized();
    377 
    378  int argc = 0;
    379  char** argv = CreateArgvFromObjectArray(jenv, jargs, &argc);
    380 
    381  if (processType != PROCESS_TYPE_CHILD) {
    382    if (gBootstrap == nullptr) {
    383      FreeArgv(argv, argc);
    384      return;
    385    }
    386 
    387 #ifdef MOZ_LINKER
    388    ElfLoader::Singleton.ExpectShutdown(false);
    389 #endif
    390    gBootstrap->XRE_SetGeckoThreadEnv(jenv);
    391    if (!argv) {
    392      __android_log_print(
    393          ANDROID_LOG_FATAL, "mozglue", "Failed to get arguments for %s",
    394          processType == PROCESS_TYPE_XPCSHELL ? "XRE_XPCShellMain"
    395                                               : "XRE_main");
    396      return;
    397    }
    398 
    399    jsize size = jenv->GetArrayLength(jfds);
    400    if (size != 2) {
    401      __android_log_print(ANDROID_LOG_FATAL, "mozglue",
    402                          "Wrong number of file descriptors passed to a "
    403                          "browser/xpcshell process");
    404      return;
    405    }
    406    jint* fds = jenv->GetIntArrayElements(jfds, nullptr);
    407    int crashChildNotificationSocket = fds[0];
    408    int crashHelperSocket = fds[1];
    409    jenv->ReleaseIntArrayElements(jfds, fds, JNI_ABORT);
    410 
    411    if (processType == PROCESS_TYPE_XPCSHELL) {
    412      MOZ_ASSERT(outFilePath);
    413      const char* outFilePathRaw =
    414          jenv->GetStringUTFChars(outFilePath, nullptr);
    415      FILE* outFile = outFilePathRaw ? fopen(outFilePathRaw, "w") : nullptr;
    416      if (outFile) {
    417        XREShellData shellData;
    418        // We redirect both stdout and stderr to the same file, to conform with
    419        // what runxpcshell.py does on Desktop.
    420        shellData.outFile = outFile;
    421        shellData.errFile = outFile;
    422        shellData.crashChildNotificationSocket = crashChildNotificationSocket;
    423        shellData.crashHelperSocket = crashHelperSocket;
    424        int result =
    425            gBootstrap->XRE_XPCShellMain(argc, argv, nullptr, &shellData);
    426        fclose(shellData.outFile);
    427        if (result) {
    428          __android_log_print(ANDROID_LOG_INFO, "mozglue",
    429                              "XRE_XPCShellMain returned %d", result);
    430        }
    431      } else {
    432        __android_log_print(ANDROID_LOG_FATAL, "mozglue",
    433                            "XRE_XPCShellMain cannot open %s", outFilePathRaw);
    434      }
    435      if (outFilePathRaw) {
    436        jenv->ReleaseStringUTFChars(outFilePath, outFilePathRaw);
    437      }
    438    } else {
    439      BootstrapConfig config;
    440      config.appData = &sAppData;
    441      config.appDataPath = nullptr;
    442      config.crashChildNotificationSocket = crashChildNotificationSocket;
    443      config.crashHelperSocket = crashHelperSocket;
    444 
    445      int result = gBootstrap->XRE_main(argc, argv, config);
    446      if (result) {
    447        __android_log_print(ANDROID_LOG_INFO, "mozglue", "XRE_main returned %d",
    448                            result);
    449      }
    450    }
    451 #ifdef MOZ_LINKER
    452    ElfLoader::Singleton.ExpectShutdown(true);
    453 #endif
    454  } else {
    455    if (argc < 2) {
    456      FreeArgv(argv, argc);
    457      return;
    458    }
    459 
    460    SetGeckoProcessType(argv[--argc]);
    461    SetGeckoChildID(argv[--argc]);
    462 #if defined(MOZ_MEMORY)
    463    // XRE_IsContentProcess is not accessible here
    464    jemalloc_reset_small_alloc_randomization(
    465        /* aRandomizeSmall */ GetGeckoProcessType() !=
    466        GeckoProcessType_Content);
    467 #endif
    468 
    469    gBootstrap->XRE_SetAndroidChildFds(jenv, jfds);
    470 
    471    XREChildData childData;
    472    gBootstrap->XRE_InitChildProcess(argc, argv, &childData);
    473  }
    474 
    475 #ifdef MOZ_WIDGET_ANDROID
    476 #  ifdef MOZ_PROFILE_GENERATE
    477  gBootstrap->XRE_WriteLLVMProfData();
    478 #  endif
    479 #endif
    480  gBootstrap.reset();
    481  FreeArgv(argv, argc);
    482 }
    483 
    484 extern "C" APKOPEN_EXPORT mozglueresult ChildProcessInit(int argc,
    485                                                         char* argv[]) {
    486  EnsureBaseProfilerInitialized();
    487 
    488  if (argc < 2) {
    489    return FAILURE;
    490  }
    491 
    492  SetGeckoProcessType(argv[--argc]);
    493  SetGeckoChildID(argv[--argc]);
    494 #if defined(MOZ_MEMORY)
    495  // XRE_IsContentProcess is not accessible here
    496  jemalloc_reset_small_alloc_randomization(
    497      /* aRandomizeSmall */ GetGeckoProcessType() != GeckoProcessType_Content);
    498 #endif
    499 
    500  if (loadNSSLibs() != SUCCESS) {
    501    return FAILURE;
    502  }
    503  if (loadSQLiteLibs() != SUCCESS) {
    504    return FAILURE;
    505  }
    506  if (loadGeckoLibs().isErr()) {
    507    return FAILURE;
    508  }
    509 
    510  XREChildData childData;
    511  return NS_FAILED(gBootstrap->XRE_InitChildProcess(argc, argv, &childData));
    512 }
    513 
    514 // Does current process name end with ':media'?
    515 static bool IsMediaProcess() {
    516  pid_t pid = getpid();
    517  char str[256];
    518  SprintfLiteral(str, "/proc/%d/cmdline", pid);
    519  FILE* f = fopen(str, "r");
    520  if (f) {
    521    fgets(str, sizeof(str), f);
    522    fclose(f);
    523    const size_t strLen = strlen(str);
    524    const char suffix[] = ":media";
    525    const size_t suffixLen = sizeof(suffix) - 1;
    526    if (strLen >= suffixLen &&
    527        !strncmp(str + strLen - suffixLen, suffix, suffixLen)) {
    528      return true;
    529    }
    530  }
    531  return false;
    532 }
    533 
    534 #ifndef SYS_rt_tgsigqueueinfo
    535 #  define SYS_rt_tgsigqueueinfo __NR_rt_tgsigqueueinfo
    536 #endif
    537 /* Copy of http://androidxref.com/7.1.1_r6/xref/bionic/linker/debugger.cpp#262,
    538 * with debuggerd related code stripped.
    539 *
    540 * Copyright (C) 2008 The Android Open Source Project
    541 * All rights reserved.
    542 *
    543 * Redistribution and use in source and binary forms, with or without
    544 * modification, are permitted provided that the following conditions
    545 * are met:
    546 *  * Redistributions of source code must retain the above copyright
    547 *    notice, this list of conditions and the following disclaimer.
    548 *  * Redistributions in binary form must reproduce the above copyright
    549 *    notice, this list of conditions and the following disclaimer in
    550 *    the documentation and/or other materials provided with the
    551 *    distribution.
    552 *
    553 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    554 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    555 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
    556 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    557 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    558 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
    559 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
    560 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
    561 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    562 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
    563 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    564 * SUCH DAMAGE.
    565 */
    566 static void CatchFatalSignals(int num, siginfo_t* info, void* context) {
    567  // It's possible somebody cleared the SA_SIGINFO flag, which would mean
    568  // our "info" arg holds an undefined value.
    569  struct sigaction action = {};
    570  if ((sigaction(num, nullptr, &action) < 0) ||
    571      !(action.sa_flags & SA_SIGINFO)) {
    572    info = nullptr;
    573  }
    574 
    575  // We need to return from the signal handler so that debuggerd can dump the
    576  // thread that crashed, but returning here does not guarantee that the signal
    577  // will be thrown again, even for SIGSEGV and friends, since the signal could
    578  // have been sent manually. Resend the signal with rt_tgsigqueueinfo(2) to
    579  // preserve the SA_SIGINFO contents.
    580  signal(num, SIG_DFL);
    581 
    582  struct siginfo si;
    583  if (!info) {
    584    memset(&si, 0, sizeof(si));
    585    si.si_code = SI_USER;
    586    si.si_pid = getpid();
    587    si.si_uid = getuid();
    588    info = &si;
    589  } else if (info->si_code >= 0 || info->si_code == SI_TKILL) {
    590    // rt_tgsigqueueinfo(2)'s documentation appears to be incorrect on kernels
    591    // that contain commit 66dd34a (3.9+). The manpage claims to only allow
    592    // negative si_code values that are not SI_TKILL, but 66dd34a changed the
    593    // check to allow all si_code values in calls coming from inside the house.
    594  }
    595 
    596  int rc = syscall(SYS_rt_tgsigqueueinfo, getpid(), gettid(), num, info);
    597  if (rc != 0) {
    598    __android_log_print(ANDROID_LOG_FATAL, "mozglue",
    599                        "failed to resend signal during crash: %s",
    600                        strerror(errno));
    601    _exit(0);
    602  }
    603 }
    604 
    605 extern "C" APKOPEN_EXPORT void MOZ_JNICALL
    606 Java_org_mozilla_gecko_mozglue_GeckoLoader_suppressCrashDialog(JNIEnv* jenv,
    607                                                               jclass jc) {
    608  MOZ_RELEASE_ASSERT(IsMediaProcess(),
    609                     "Suppress crash dialog only for media process");
    610  // Restoring to SIG_DFL will crash on x86/Android M devices (see bug 1374556)
    611  // so copy Android code
    612  // (http://androidxref.com/7.1.1_r6/xref/bionic/linker/debugger.cpp#302). See
    613  // comments above CatchFatalSignals() for copyright notice.
    614  struct sigaction action;
    615  memset(&action, 0, sizeof(action));
    616  sigemptyset(&action.sa_mask);
    617  action.sa_sigaction = &CatchFatalSignals;
    618  action.sa_flags = SA_RESTART | SA_SIGINFO;
    619 
    620  // Use the alternate signal stack if available so we can catch stack
    621  // overflows.
    622  action.sa_flags |= SA_ONSTACK;
    623 
    624  sigaction(SIGABRT, &action, nullptr);
    625  sigaction(SIGBUS, &action, nullptr);
    626  sigaction(SIGFPE, &action, nullptr);
    627  sigaction(SIGILL, &action, nullptr);
    628  sigaction(SIGSEGV, &action, nullptr);
    629 #if defined(SIGSTKFLT)
    630  sigaction(SIGSTKFLT, &action, nullptr);
    631 #endif
    632  sigaction(SIGTRAP, &action, nullptr);
    633 }