diff --git a/.craft.yml b/.craft.yml index a828802521..cfebd614a8 100644 --- a/.craft.yml +++ b/.craft.yml @@ -3,17 +3,23 @@ changelogPolicy: auto targets: - name: github includeNames: /^(sentry-native).*\.zip$/ + excludeNames: /^sentry-native\.zip$/ - name: registry sdks: github:getsentry/sentry-native: maven:io.sentry:sentry-native-ndk: - name: gcs - includeNames: /^(sentry-native\.zip)$/ + includeNames: /^sentry-native-\d+\.\d+\.\d+.*\.zip$/ bucket: sentry-sdk-assets paths: - path: /sentry-native/{{version}}/ metadata: cacheControl: public, max-age=2592000 + - name: gcs + id: latest + includeNames: /^sentry-native\.zip$/ + bucket: sentry-sdk-assets + paths: - path: /sentry-native/latest/ metadata: cacheControl: public, max-age=600 @@ -32,4 +38,5 @@ targets: batchType: android bundleIdPrefix: sentry-native-ndk- requireNames: - - /^sentry-native.zip$/ + - /^sentry-native-\d+\.\d+\.\d+.*\.zip$/ + - /^sentry-native\.zip$/ diff --git a/.github/problem-matchers.json b/.github/problem-matchers.json new file mode 100644 index 0000000000..dcad1f4903 --- /dev/null +++ b/.github/problem-matchers.json @@ -0,0 +1,59 @@ +{ + "problemMatcher": [ + { + "owner": "cmake", + "pattern": [ + { + "regexp": "^CMake Error at (.+):(\\d+) \\(.+\\):$", + "file": 1, + "line": 2 + }, + { + "regexp": "^\\s+(.+)$", + "message": 1 + } + ] + }, + { + "owner": "gcc", + "pattern": [ + { + "regexp": "^(?:C/C\\+\\+: )?(.+?):(\\d+):(?:(\\d+):)? (?:fatal )?error: (.*)$", + "file": 1, + "line": 2, + "column": 3, + "message": 4 + } + ] + }, + { + "owner": "msvc", + "pattern": [ + { + "regexp": "^\\s*(.+?)\\((\\d+)(?:,(\\d+))?\\)\\s*: (?:fatal )?error(?! C2220)(?: (\\w+))?\\s*: (.*?)(?: \\[[^\\]]+\\.vcxproj\\])?$", + "file": 1, + "line": 2, + "column": 3, + "code": 4, + "message": 5 + } + ] + }, + { + "owner": "msvc-wx", + "pattern": [ + { + "regexp": "^\\s*.+?\\(\\d+(?:,\\d+)?\\)\\s*: error C2220: " + }, + { + "regexp": "^\\s*(.+?)\\((\\d+)(?:,(\\d+))?\\)\\s*: warning (\\w+)\\s*: (.*?)(?: \\[[^\\]]+\\.vcxproj\\])?$", + "file": 1, + "line": 2, + "column": 3, + "code": 4, + "message": 5 + } + ] + } + ] +} diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index a16e95c14b..8635537b15 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -4,6 +4,7 @@ on: push: branches: - master + - v1 paths-ignore: - "*.md" pull_request: @@ -35,6 +36,9 @@ jobs: with: submodules: recursive + - name: Annotate build errors + run: echo "::add-matcher::.github/problem-matchers.json" + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" @@ -59,5 +63,5 @@ jobs: tool: customSmallerIsBetter output-file-path: benchmark.json github-token: ${{ secrets.GITHUB_TOKEN }} - benchmark-data-dir-path: ./ + benchmark-data-dir-path: ${{ github.ref_name == 'v1' && 'v1/' || './' }} auto-push: true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 348f5866dd..0c0bd40e45 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -69,12 +69,18 @@ jobs: CC: gcc-9 CXX: g++-9 TEST_X86: 1 - - name: Linux Arm32 (gcc-arm-linux-gnueabihf + qemu-user) + - name: Linux Arm32 (cross-GCC + QEMU) os: ubuntu-24.04-arm CC: arm-linux-gnueabihf-gcc CXX: arm-linux-gnueabihf-g++ TEST_ARM32: 1 TEST_QEMU: 1 + - name: Linux RISC-V (cross-GCC + QEMU) + os: ubuntu-24.04-arm + CC: riscv64-linux-gnu-gcc + CXX: riscv64-linux-gnu-g++ + TEST_RISCV: 1 + TEST_QEMU: 1 - name: Linux (GCC 9.5.0) os: ubuntu-24.04 CC: gcc-9 @@ -95,6 +101,7 @@ jobs: os: ubuntu-24.04 CC: gcc-14 CXX: g++-14 + ERROR_ON_WARNINGS: off # analyzer false positives RUN_ANALYZER: gcc - name: Linux (GCC 15 + runtime curl) os: ubuntu-26.04 @@ -119,31 +126,26 @@ jobs: os: ubuntu-24.04 CC: clang-20 CXX: clang++-20 - ERROR_ON_WARNINGS: 1 RUN_ANALYZER: asan,llvm-cov - name: Linux Arm64 (clang 20 + asan + llvm-cov) os: ubuntu-24.04-arm CC: clang-20 CXX: clang++-20 - ERROR_ON_WARNINGS: 1 RUN_ANALYZER: asan,llvm-cov - name: Linux (clang 20 + tsan) os: ubuntu-24.04 CC: clang-20 CXX: clang++-20 - ERROR_ON_WARNINGS: 1 RUN_ANALYZER: tsan - name: Linux Arm64 (clang 20 + tsan) os: ubuntu-24.04-arm CC: clang-20 CXX: clang++-20 - ERROR_ON_WARNINGS: 1 RUN_ANALYZER: tsan - name: Linux (clang 20 + kcov) os: ubuntu-24.04 CC: clang-20 CXX: clang++-20 - ERROR_ON_WARNINGS: 1 RUN_ANALYZER: kcov - name: Linux (GCC 13.3.0 + valgrind) CC: gcc-13 @@ -166,28 +168,23 @@ jobs: CMAKE_DEFINES: -DSENTRY_LIBUNWIND_SYSTEM=ON - name: macOS 15 (xcode llvm) os: macos-15 - ERROR_ON_WARNINGS: 1 SYSTEM_VERSION_COMPAT: 0 TEST_SYSTEM_PROXY: 1 - name: macOS 26 (xcode llvm) os: macos-26 - ERROR_ON_WARNINGS: 1 SYSTEM_VERSION_COMPAT: 0 - name: macOS 15 (xcode llvm + universal) os: macos-15 - ERROR_ON_WARNINGS: 1 SYSTEM_VERSION_COMPAT: 0 CMAKE_DEFINES: -DCMAKE_OSX_ARCHITECTURES=arm64;x86_64 - name: macOS 15 (clang 18 + asan + llvm-cov) os: macos-15-large CC: clang CXX: clang++ - ERROR_ON_WARNINGS: 1 SYSTEM_VERSION_COMPAT: 0 RUN_ANALYZER: asan,llvm-cov - name: macOS 26 (arm64e + PAC test) os: macos-26 - ERROR_ON_WARNINGS: 1 SYSTEM_VERSION_COMPAT: 0 CMAKE_DEFINES: -DCMAKE_OSX_ARCHITECTURES=arm64e - name: Windows (old VS, 32-bit) @@ -260,11 +257,12 @@ jobs: TEST_MINGW: ${{ matrix.TEST_MINGW }} TEST_WINE: ${{ matrix.TEST_WINE }} TEST_ARM32: ${{ matrix.TEST_ARM32 }} + TEST_RISCV: ${{ matrix.TEST_RISCV }} TEST_QEMU: ${{ matrix.TEST_QEMU }} TEST_SYSTEM_PROXY: ${{ matrix.TEST_SYSTEM_PROXY }} USE_SCCACHE: ${{ matrix.USE_SCCACHE }} SCCACHE_GHA_ENABLED: ${{ matrix.USE_SCCACHE && 'true' || '' }} - ERROR_ON_WARNINGS: ${{ matrix.ERROR_ON_WARNINGS }} + ERROR_ON_WARNINGS: ${{ matrix.ERROR_ON_WARNINGS || 1 }} RUN_ANALYZER: ${{ matrix.RUN_ANALYZER }} ANDROID_API: ${{ matrix.ANDROID_API }} ANDROID_NDK: ${{ matrix.ANDROID_NDK }} @@ -275,12 +273,16 @@ jobs: SYSTEM_PYTHON: ${{ matrix.SYSTEM_PYTHON }} UTF8_TEST_CWD: ${{ matrix.UTF8_TEST_CWD }} SENTRY_TEST_OOM_LIMIT: "4095" # ~4GB, to speed up OOM tests + SENTRY_TEST_BUILD_ERROR_LIMIT: "10" # give up when the same build error repeats steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: submodules: recursive + - name: Annotate build errors + run: echo "::add-matcher::.github/problem-matchers.json" + - name: Debug runner architecture if: ${{ runner.os == 'macOS' }} run: | @@ -297,7 +299,7 @@ jobs: [ -n "$CC" ] && [ -n "$CXX" ] || { echo "Ubuntu runner configurations require toolchain selection via CC and CXX" >&2; exit 1; } - name: Installing Linux Dependencies - if: ${{ runner.os == 'Linux' && !env['TEST_X86'] && !env['TEST_ARM32'] && !env['ANDROID_API'] && !matrix.container }} + if: ${{ runner.os == 'Linux' && !env['TEST_X86'] && !env['TEST_ARM32'] && !env['TEST_RISCV'] && !env['ANDROID_API'] && !matrix.container }} run: | sudo apt update # Install common dependencies @@ -368,11 +370,29 @@ jobs: libstdc++6:armhf - name: Installing qemu-user - if: ${{ runner.os == 'Linux' && env['TEST_QEMU'] && !matrix.container }} + if: ${{ runner.os == 'Linux' && env['TEST_ARM32'] && !matrix.container }} run: | sudo apt update sudo apt install -y qemu-user-static binfmt-support + - name: Installing Linux RISC-V Dependencies + if: ${{ runner.os == 'Linux' && env['TEST_RISCV'] && !matrix.container }} + run: | + sudo dpkg --add-architecture riscv64 + sudo apt-get update + sudo apt-get install -y \ + cmake \ + gcc-riscv64-linux-gnu g++-riscv64-linux-gnu \ + zlib1g-dev:riscv64 libssl-dev:riscv64 \ + libcurl4-openssl-dev:riscv64 liblzma-dev:riscv64 \ + libstdc++6:riscv64 + echo "PKG_CONFIG_LIBDIR=/usr/lib/riscv64-linux-gnu/pkgconfig:/usr/share/pkgconfig" >> "$GITHUB_ENV" + + - uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 + if: ${{ runner.os == 'Linux' && env['TEST_RISCV'] && !matrix.container }} + with: + platforms: riscv64 + - name: Installing Alpine Linux Dependencies if: ${{ contains(matrix.container, 'alpine') }} run: | @@ -502,20 +522,29 @@ jobs: - name: Test (Android) if: ${{ env['ANDROID_API'] }} + id: android-test + continue-on-error: ${{ env.ANDROID_BOOTED != 'true' }} uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d # v2.38.0 - with: + with: &android-options api-level: ${{ env.ANDROID_API }} ndk: ${{ env.ANDROID_NDK }} arch: ${{ env.ANDROID_ARCH }} - target: google_apis + target: default emulator-boot-timeout: 1200 script: | + echo "ANDROID_BOOTED=true" >> "$GITHUB_ENV" # Sync emulator clock with host to avoid timestamp assertion failures adb shell cmd alarm set-time $(date +%s000) || adb shell su root date $(date -u +%m%d%H%M%Y.%S) scripts/setup-android-sanitizer.sh "$RUN_ANALYZER" pip install --upgrade --requirement tests/requirements.txt pytest --capture=no --verbose tests (cd ndk && ./gradlew :sentry-native-ndk:connectedDebugAndroidTest --stacktrace) + (cd ndk && ./gradlew :sentry-native-ndk-outproc:connectedDebugAndroidTest --stacktrace) + + - name: Retry emulator (Android) + if: ${{ steps.android-test.outcome == 'failure' && env.ANDROID_BOOTED != 'true' }} + uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d # v2.38.0 + with: *android-options - name: Test if: ${{ !env['ANDROID_API'] }} @@ -586,8 +615,11 @@ jobs: - name: Create source archive run: | + version=$(sed -nE 's/^#[[:space:]]*define[[:space:]]+SENTRY_SDK_VERSION[[:space:]]+"([^"]+)".*/\1/p' include/sentry.h) + test -n "$version" rm -rf build .c* .e* .git* scripts Makefile external/breakpad/src/tools external/breakpad/src/processor - zip -r sentry-native.zip . + zip -r "sentry-native-$version.zip" . + cp "sentry-native-$version.zip" sentry-native.zip - name: Build NDK artifacts working-directory: ndk @@ -599,6 +631,35 @@ jobs: name: ${{ github.sha }} if-no-files-found: error path: | + sentry-native-*.zip sentry-native.zip ndk/lib/build/distributions/*.zip + ndk/native/build/distributions/*.zip ndk/lib/build/intermediates/merged_native_libs/release/mergeReleaseNativeLibs/out/lib/* + ndk/native/build/intermediates/merged_native_libs/release/mergeReleaseNativeLibs/out/lib/* + + check-aar: + name: Check NDK AARs + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + submodules: recursive + + - name: Setup Java Version + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: "temurin" + java-version: "17" + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # pin@v6.4.1 + + - name: Build NDK AARs + working-directory: ndk + run: ./gradlew :sentry-native-ndk:assembleRelease :sentry-native-ndk-outproc:assembleRelease + + - name: Check NDK AARs + run: | + python3 scripts/check-aar.py ndk/lib/build/outputs/aar/sentry-native-ndk-release.aar + python3 scripts/check-aar.py ndk/native/build/outputs/aar/sentry-native-ndk-outproc-release.aar diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index aca192eb6e..33b49cb690 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -2,10 +2,10 @@ name: 'CodeQL' on: push: - branches: [master] + branches: [master, v1] pull_request: # The branches below must be a subset of the branches above - branches: [master] + branches: [master, v1] schedule: - cron: '17 23 * * 3' diff --git a/.github/workflows/console-check.yml b/.github/workflows/console-check.yml index 2a8d7b060a..2738803fa7 100644 --- a/.github/workflows/console-check.yml +++ b/.github/workflows/console-check.yml @@ -72,6 +72,20 @@ jobs: echo "mode=BUILD_ONLY" >> "$GITHUB_OUTPUT" fi + - name: Resolve console branch + id: ref + env: + GH_TOKEN: ${{ github.token }} + SHA: ${{ github.event.pull_request.head.sha || github.sha }} + run: | + ahead() { gh api "repos/$GITHUB_REPOSITORY/compare/$1...$SHA?per_page=1" --jq .ahead_by; } + ref=main nearest=$(ahead master) + # version branches build against the same console branch + for branch in v1; do + if n=$(ahead "$branch" 2>/dev/null) && [[ $n -lt $nearest ]]; then ref=$branch nearest=$n; fi + done + echo "console_ref=$ref" >> "$GITHUB_OUTPUT" + # gh workflow run sends a workflow_dispatch event to the console repo. # native-compat-check.yml must exist on the default branch (main) of # the console repo for this to work. @@ -84,11 +98,12 @@ jobs: CALLBACK_SHA: ${{ github.event.pull_request.head.sha || github.sha }} CALLBACK_CONTEXT: ${{ matrix.context }} MODE: ${{ steps.mode.outputs.mode }} + CONSOLE_REF: ${{ steps.ref.outputs.console_ref }} PR_NUMBER: ${{ github.event.pull_request.number || github.ref_name }} run: | gh workflow run native-compat-check.yml \ --repo "$MATRIX_REPO" \ - --ref main \ + --ref "$CONSOLE_REF" \ -f native_ref="$NATIVE_REF" \ -f callback_repo="$CALLBACK_REPO" \ -f callback_sha="$CALLBACK_SHA" \ diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.yml index ff5a67ce10..8d81ec38c0 100644 --- a/.github/workflows/e2e-test.yml +++ b/.github/workflows/e2e-test.yml @@ -31,11 +31,19 @@ jobs: with: submodules: recursive + - name: Annotate build errors + run: echo "::add-matcher::.github/problem-matchers.json" + - name: Install dependencies (Linux) if: runner.os == 'Linux' run: | sudo apt update - sudo apt install -y cmake libcurl4-openssl-dev + sudo apt install -y cmake libcurl4-openssl-dev zlib1g-dev + + - name: Set up zlib for Windows + if: runner.os == 'Windows' + shell: powershell + run: . "scripts\install-zlib.ps1" - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 @@ -61,3 +69,76 @@ jobs: SENTRY_E2E_ORG: ${{ secrets.SENTRY_E2E_ORG }} SENTRY_E2E_PROJECT: ${{ secrets.SENTRY_E2E_PROJECT }} run: pytest --capture=no --verbose tests/test_e2e_sentry.py + + android: + name: ${{ matrix.name }} + strategy: + fail-fast: false + matrix: + include: + - name: E2E Test (Android API 36, NDK 30) + ANDROID_API: 36 + ANDROID_NDK_VERSION: 30.0.16138531 + runs-on: ubuntu-latest + env: + ANDROID_API: ${{ matrix.ANDROID_API }} + ANDROID_ARCH: x86_64 + ANDROID_NDK_VERSION: ${{ matrix.ANDROID_NDK_VERSION }} + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + submodules: recursive + + - name: Annotate build errors + run: echo "::add-matcher::.github/problem-matchers.json" + + - name: Check out sentry-java + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: getsentry/sentry-java + # first release with sentry-android-ndk-outproc, bump only when + # sentry-native-ndk-outproc changes need matching sentry-java changes + ref: 8.64.0 + path: sentry-java + + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.12" + + - name: Install test dependencies + run: pip install -r tests/requirements.txt + + - name: Set up Java + uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + with: + distribution: "temurin" + java-version: "21" + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # pin@v6.3.0 + + - name: Enable KVM group perms + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + + - name: Set up and run Android E2E tests + uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d # v2.38.0 + env: + SENTRY_E2E_DSN: ${{ secrets.SENTRY_E2E_DSN }} + SENTRY_E2E_AUTH_TOKEN: ${{ secrets.SENTRY_E2E_AUTH_TOKEN }} + SENTRY_E2E_ORG: ${{ secrets.SENTRY_E2E_ORG }} + SENTRY_E2E_PROJECT: ${{ secrets.SENTRY_E2E_PROJECT }} + with: + api-level: ${{ env.ANDROID_API }} + ndk: ${{ env.ANDROID_NDK_VERSION }} + arch: ${{ env.ANDROID_ARCH }} + target: google_apis + emulator-boot-timeout: 1200 + script: | + export ANDROID_NDK="$ANDROID_HOME/ndk/$ANDROID_NDK_VERSION" + python scripts/setup-android-e2e.py sentry-java + pytest --capture=no --verbose tests/test_e2e_sentry.py diff --git a/.github/workflows/enforce-license-compliance.yml b/.github/workflows/enforce-license-compliance.yml index 158a26fcca..7eaf0a0635 100644 --- a/.github/workflows/enforce-license-compliance.yml +++ b/.github/workflows/enforce-license-compliance.yml @@ -4,7 +4,7 @@ on: push: branches: [master, main, release/*] pull_request: - branches: [master, main] + branches: [master, main, v1] jobs: enforce-license-compliance: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fd407f34f2..17cf2615fc 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -38,3 +38,4 @@ jobs: version: ${{ github.event.inputs.version }} force: ${{ github.event.inputs.force }} merge_target: ${{ github.event.inputs.merge_target }} + craft_config_from_merge_target: true diff --git a/CHANGELOG.md b/CHANGELOG.md index 64edc7acab..6c583a617c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,68 @@ ## Unreleased +**Fixes**: + +- Native: retain crash envelopes on OOM in the crash daemon. ([#2320](https://github.com/getsentry/sentry-native/pull/2320)) +- Native: omit crash metadata in minidump-only mode. ([#2324](https://github.com/getsentry/sentry-native/pull/2324)) + +## 1.0.0-beta.1 + +**Breaking / Important behavior changes**: + +- The `native` backend is now the default on Linux, macOS, and Windows. ([#2186](https://github.com/getsentry/sentry-native/pull/2186)) +- macOS/Linux: shared libraries now use ABI-versioned filenames, such as `libsentry.1.dylib` or `libsentry.so.1` for 1.x. Windows, Android, and static libraries remain unchanged. ([#2103](https://github.com/getsentry/sentry-native/pull/2103)) + - NOTE: Applications must package the real versioned library and its symlinks, including `libsentry.1.dylib` or `libsentry.so.1`, because they link to and load the ABI-versioned name. +- Release archives now include the SDK version in the filename, such as `sentry-native-1.0.0.zip`. ([#2105](https://github.com/getsentry/sentry-native/pull/2105)) +- Remove deprecated APIs. Migrate to the following alternatives: ([#2230](https://github.com/getsentry/sentry-native/pull/2230)) + - `sentry_new_function_transport`: use `sentry_transport_new` and `sentry_transport_set_state`. The send callback now receives a mutable envelope, takes ownership of it, and must free it with `sentry_envelope_free`. + - `sentry_event_value_add_stacktrace`: create a thread with `sentry_value_new_thread`, set its stack with `sentry_value_set_stacktrace`, and add it to the event with `sentry_event_add_thread`. + - `sentry_shutdown`: use `sentry_close`. + - `sentry_sdk_name` and `sentry_sdk_user_agent`: use `sentry_options_get_sdk_name` and `sentry_options_get_user_agent`, or `SENTRY_SDK_NAME` and `SENTRY_SDK_USER_AGENT` for build-time values. + - `sentry_options_set_http_proxy` and `sentry_options_set_http_proxy_n`: use `sentry_options_set_proxy` and `sentry_options_set_proxy_n`. + - `sentry_value_new_user_feedback` and `sentry_value_new_user_feedback_n`: use `sentry_value_new_feedback` and `sentry_value_new_feedback_n`. The constructor arguments are now message, contact email, name, and associated event ID, with lengths following each string in the `_n` variant. + - `sentry_capture_user_feedback`: use `sentry_capture_feedback`. + - `sentry_options_add_view_hierarchy`, `sentry_options_add_view_hierarchy_n`, `sentry_options_add_view_hierarchyw`, and `sentry_options_add_view_hierarchyw_n`: create an attachment with `sentry_attachment_from_file` or its `_n`/wide-string variants, set its type to `SENTRY_ATTACHMENT_TYPE_VIEW_HIERARCHY` with `sentry_attachment_set_type`, and add it with `sentry_add_attachment`. For startup configuration, use `sentry_scope_add_attachment` in a `sentry_options_set_initial_scope` callback. + - `sentry_capture_event_with_scope(event, scope)`: use `sentry_scope_capture_event(scope, event, NULL)`. + - `sentry_clear_crashed_last_run`: remove the call. `sentry_init` clears the crash marker automatically. + - `sentry_regenerate_trace`: use `sentry_start_new_trace`. + +**Features**: + +- Add `sentry_scope_begin_read`/`sentry_scope_end_read` and `sentry_scope_begin_write`/`sentry_scope_end_write` for consistent reads of multiple scope properties and applying multiple scope changes with a single scope flush. ([#2107](https://github.com/getsentry/sentry-native/pull/2107)) +- Add `sentry_scope_acquire` and `sentry_scope_release` to access the isolation scope. ([#2160](https://github.com/getsentry/sentry-native/pull/2160)) +- Native: Provide exception metadata, registers, and a basic crashing-thread stack to `on_crash` for crash identification. ([#2174](https://github.com/getsentry/sentry-native/pull/2174)) +- Native: reduce disk I/O on scope changes by sending incremental updates to the crash daemon over IPC. ([#2155](https://github.com/getsentry/sentry-native/pull/2155), [#2157](https://github.com/getsentry/sentry-native/pull/2157)) +- Add pkg-config support for shared builds. ([#1411](https://github.com/getsentry/sentry-native/pull/1411)) +- Native: install handlers for the daemon's own fatal signals and unhandled exceptions, allowing best-effort recovery actions such as dumping pending envelopes before termination. ([#2220](https://github.com/getsentry/sentry-native/pull/2220)) +- Linux: add RISC-V 64 support. ([#2232](https://github.com/getsentry/sentry-native/pull/2232)) +- Report the host OS in the OS context under Wine and Proton, instead of the Windows version that Wine emulates. On Linux, prefer the host `os-release` inside Steam Runtime and Flatpak containers, and report SteamOS and Bazzite as the OS name. ([#2241](https://github.com/getsentry/sentry-native/pull/2241)) +- Add `sentry_scope_set_trace` for per-scope traces. ([#2236](https://github.com/getsentry/sentry-native/pull/2236)) +- Add `sentry_continue_trace` to continue incoming traces without a transaction. ([#2237](https://github.com/getsentry/sentry-native/pull/2237)) +- Add `sentry_iter_trace_propagation_headers` to propagate traces without a span. ([#2240](https://github.com/getsentry/sentry-native/pull/2240)) +- Resume interrupted TUS attachment uploads from the server-provided upload offset. ([#2058](https://github.com/getsentry/sentry-native/pull/2058)) +- Compress TUS attachment uploads when `SENTRY_TRANSPORT_COMPRESSION` is enabled. ([#2222](https://github.com/getsentry/sentry-native/pull/2222)) +- Native: allow crash uploads up to 10 seconds by default in async crash upload mode, unless `shutdown_timeout` is set. ([#2278](https://github.com/getsentry/sentry-native/pull/2278)) +- Native: add Android support. ([#1725](https://github.com/getsentry/sentry-native/pull/1725)) + +**Fixes**: + +- Native/Inproc: provide `debug_meta.images` in events passed to `on_crash`. ([#2184](https://github.com/getsentry/sentry-native/pull/2184)) +- Native/Linux: reduce daemon stack usage during minidump creation to avoid stack overflows in environments with limited stack space. ([#2211](https://github.com/getsentry/sentry-native/pull/2211)) +- Native/Linux: reduce stack usage when unwinding the crashed thread. ([#2212](https://github.com/getsentry/sentry-native/pull/2212)) +- Native/Unix: Preserve existing alternate signal stacks to prevent ASan aborts when the initializing thread exits before SDK shutdown. ([#2219](https://github.com/getsentry/sentry-native/pull/2219)) +- Native/Linux: fix oversized `debug_meta.images` entries that overlapped other libraries when a file was mapped more than once. ([#2228](https://github.com/getsentry/sentry-native/pull/2228)) +- Fix const-correctness of `sentry_options_get_*`, `sentry_span_iter_headers`, and `sentry_transaction_iter_headers`. ([#2277](https://github.com/getsentry/sentry-native/pull/2277)) +- Native/Linux: back the crash context with a memfd to prevent `SIGBUS` during `sentry_init` when `/dev/shm` is full. ([#1725](https://github.com/getsentry/sentry-native/pull/1725)) +- Native/Unix: capture complete memory regions in `SENTRY_MINIDUMP_MODE_FULL` instead of truncating each region to 4 MB. ([#2281](https://github.com/getsentry/sentry-native/pull/2281)) +- Native: upload large minidumps separately if `sentry_options_set_enable_large_attachments` is enabled. ([#2281](https://github.com/getsentry/sentry-native/pull/2281)) + +**Thank you**: + +- [nmandelblit](https://github.com/nmandelblit) + +## Unreleased + **Features**: - Session replay: add user input events (such as mouse clicks and touches) provided in the replay sidecar to the replay recording. ([#2288](https://github.com/getsentry/sentry-native/pull/2288)) diff --git a/CMakeLists.txt b/CMakeLists.txt index d23b50f044..85392691a8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -124,6 +124,7 @@ option(SENTRY_TRANSPORT_COMPRESSION "Enable transport gzip compression" OFF) option(SENTRY_BUILD_TESTS "Build sentry-native tests" "${SENTRY_MAIN_PROJECT}") option(SENTRY_BUILD_EXAMPLES "Build sentry-native example(s)" "${SENTRY_MAIN_PROJECT}") option(SENTRY_BUILD_BENCHMARKS "Build sentry-native benchmarks" OFF) +option(SENTRY_ERROR_ON_WARNINGS "Treat warnings in sentry and sentry-crash as errors on GCC and Clang" OFF) option(SENTRY_INTEGRATION_PLATFORM "Enable the downstream-provided platform integration" OFF) @@ -200,6 +201,8 @@ elseif(SENTRY_TRANSPORT STREQUAL "curl") set(SENTRY_TRANSPORT_CURL TRUE) elseif(SENTRY_TRANSPORT STREQUAL "none") set(SENTRY_TRANSPORT_NONE TRUE) +elseif(SENTRY_TRANSPORT STREQUAL "stdout") + set(SENTRY_TRANSPORT_STDOUT TRUE) elseif(SENTRY_TRANSPORT STREQUAL "pshttp") # Not implemented here, but in the downstream SDK if(NOT PROSPERO) @@ -244,6 +247,7 @@ if("${CMAKE_SOURCE_DIR}" STREQUAL "${PROJECT_SOURCE_DIR}") endif() option(SENTRY_ENABLE_INSTALL "Enable sentry installation" "${SENTRY_MAIN_PROJECT}") +option(SENTRY_INSTALL_PKGCONFIG "Generate and install pkg-config file for shared builds" ON) if(MSVC AND CMAKE_GENERATOR_TOOLSET MATCHES "_xp$") message(WARNING "Crashpad is not supported for MSVC with XP toolset. Default backend was switched to 'breakpad'") @@ -251,7 +255,7 @@ if(MSVC AND CMAKE_GENERATOR_TOOLSET MATCHES "_xp$") elseif(MSVC AND (XBOX OR WINGDK)) set(SENTRY_DEFAULT_BACKEND "breakpad") elseif((APPLE AND NOT IOS) OR WIN32 OR LINUX) - set(SENTRY_DEFAULT_BACKEND "crashpad") + set(SENTRY_DEFAULT_BACKEND "native") else() set(SENTRY_DEFAULT_BACKEND "inproc") endif() @@ -271,6 +275,10 @@ elseif(SENTRY_BACKEND STREQUAL "inproc") elseif(SENTRY_BACKEND STREQUAL "breakpad") set(SENTRY_BACKEND_BREAKPAD TRUE) elseif(SENTRY_BACKEND STREQUAL "native") + if(ANDROID) + message(WARNING "The 'native' backend on Android is experimental. " + "It may have incomplete features or unexpected behavior.") + endif() set(SENTRY_BACKEND_NATIVE TRUE) elseif(SENTRY_BACKEND STREQUAL "none") set(SENTRY_BACKEND_NONE TRUE) @@ -389,6 +397,27 @@ add_library(sentry ${SENTRY_LIBRARY_TYPE} "${PROJECT_SOURCE_DIR}/src/sentry_mpac if (XBOX) set_target_properties(sentry PROPERTIES VS_USER_PROPS gdk_build.props) endif() + +set_target_properties(sentry PROPERTIES + VERSION "${SENTRY_VERSION_BASE}" + SOVERSION "${SENTRY_VERSION_MAJOR}") + +if(WIN32 AND SENTRY_BUILD_SHARED_LIBS) + set(_SENTRY_IMAGE_VERSION "${SENTRY_VERSION_MAJOR}.${SENTRY_VERSION_MINOR}") + if(CMAKE_GENERATOR MATCHES "^Visual Studio " AND CMAKE_VERSION VERSION_LESS 4.1) + # VS generators before CMake 4.1 ignore VERSION for the PE image header. + target_link_options(sentry PRIVATE "/VERSION:${_SENTRY_IMAGE_VERSION}") + elseif(MINGW) + include(CheckLinkerFlag) + check_linker_flag(C "LINKER:/version:0.0" _SENTRY_LINKER_SUPPORTS_PE_VERSION) + if(_SENTRY_LINKER_SUPPORTS_PE_VERSION) + # lld silently ignores CMake's GNU image-version flags. + target_link_options(sentry PRIVATE "LINKER:/version:${_SENTRY_IMAGE_VERSION}") + endif() + endif() + unset(_SENTRY_IMAGE_VERSION) +endif() + target_sources(sentry PRIVATE "${PROJECT_SOURCE_DIR}/include/sentry.h") add_library(sentry::sentry ALIAS sentry) @@ -397,10 +426,10 @@ if(SENTRY_EMBED_INFO) # SENTRY_BUILD_ID cache variable takes precedence if(SENTRY_BUILD_ID) set(SENTRY_EMBEDDED_BUILD_ID "${SENTRY_BUILD_ID}") - elseif(SENTRY_VERSION_FULL MATCHES "^[0-9]+\\.[0-9]+\\.[0-9]+\\+(.+)$") - # Extract build ID from SENTRY_VERSION_FULL if present (format: major.minor.patch+build-id) + elseif(SENTRY_VERSION_FULL MATCHES "^[0-9]+\\.[0-9]+\\.[0-9]+(-[^+]+)?\\+(.+)$") + # Extract build ID from SENTRY_VERSION_FULL if present (format: major.minor.patch[-prerelease]+build-id) # This handles cases where downstream SDKs modify sentry.h to include build metadata - set(SENTRY_EMBEDDED_BUILD_ID "${CMAKE_MATCH_1}") + set(SENTRY_EMBEDDED_BUILD_ID "${CMAKE_MATCH_2}") else() # No build ID found in version or provided, use timestamp as default # Format: YYYYMMDD-HHMMSS (semver-compliant: alphanumerics and hyphens only) @@ -604,12 +633,17 @@ if(MSVC) endif() else() target_compile_options(sentry PRIVATE $) + if(SENTRY_ERROR_ON_WARNINGS) + target_compile_options(sentry PRIVATE $) + endif() # The crashpad and breakpad headers generate the following warnings that we # ignore specifically if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") target_compile_options(sentry PRIVATE $) else() target_compile_options(sentry PRIVATE $) + # glibc 2.43 headers expand `memchr` and friends to `_Generic` + target_compile_options(sentry PRIVATE $) endif() # ignore all warnings for mpack set_source_files_properties( @@ -707,8 +741,9 @@ if(MINGW) -Wno-unused-variable -Wno-unused-parameter -Wno-format - -Wno-incompatible-pointer-types + $<$:-Wno-incompatible-pointer-types> -Wno-incompatible-function-pointer-types + -Wno-cast-function-type ) endif() @@ -955,12 +990,23 @@ elseif(SENTRY_BACKEND_NATIVE) target_compile_definitions(sentry-crash PRIVATE SENTRY_WITH_UNWINDER_LIBUNWIND_REMOTE) endif() + # Copy warning options from sentry target + if(NOT MSVC) + get_target_property(SENTRY_COMPILE_OPTIONS sentry COMPILE_OPTIONS) + target_compile_options(sentry-crash PRIVATE ${SENTRY_COMPILE_OPTIONS}) + endif() + # Copy include directories from sentry target target_include_directories(sentry-crash PRIVATE ${PROJECT_SOURCE_DIR}/include ${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}/src/backends/native ) + if(SENTRY_WITH_LIBUNWINDSTACK) + target_include_directories(sentry-crash PRIVATE + ${PROJECT_SOURCE_DIR}/external/libunwindstack-ndk/include + ) + endif() # Link same libraries as sentry target_link_libraries(sentry-crash PRIVATE ${_SENTRY_PLATFORM_LIBS}) @@ -1015,12 +1061,12 @@ elseif(SENTRY_BACKEND_NATIVE) endif() # Install daemon - install(TARGETS sentry-crash - RUNTIME DESTINATION bin + sentry_install(TARGETS sentry-crash + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ) if(WIN32) - install(TARGETS sentry-wer - RUNTIME DESTINATION bin + sentry_install(TARGETS sentry-wer + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" ) @@ -1159,7 +1205,7 @@ if(SENTRY_BUILD_TESTS) else() # Disable all optimizations for the `sentry_test_integration` in gcc/clang. This allows us to keep crash triggers simple. # The effects besides reproducible code-gen across compiler versions, will be negligible for build- and runtime. - target_compile_options(sentry_test_integration PRIVATE $) + target_compile_options(sentry_test_integration PRIVATE $) endif() if(CMAKE_GENERATOR STREQUAL "Xcode") @@ -1192,3 +1238,34 @@ if(SENTRY_BUILD_SHARED_LIBS) "$<$:-Wl,-z,max-page-size=16384>" ) endif() + +# Generate and install pkg-config file +if(SENTRY_INSTALL_PKGCONFIG AND SENTRY_BUILD_SHARED_LIBS) + set(PREFIX "${CMAKE_INSTALL_PREFIX}") + set(PKGCONFIG_VERSION "${SENTRY_VERSION_FULL}") + # Use absolute paths for libdir, includedir, and bindir to support non-standard layouts (e.g., lib64) + if(IS_ABSOLUTE "${CMAKE_INSTALL_LIBDIR}") + set(PKGCONFIG_LIBDIR "${CMAKE_INSTALL_LIBDIR}") + else() + set(PKGCONFIG_LIBDIR "\${prefix}/${CMAKE_INSTALL_LIBDIR}") + endif() + if(IS_ABSOLUTE "${CMAKE_INSTALL_INCLUDEDIR}") + set(PKGCONFIG_INCLUDEDIR "${CMAKE_INSTALL_INCLUDEDIR}") + else() + set(PKGCONFIG_INCLUDEDIR "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}") + endif() + if(IS_ABSOLUTE "${CMAKE_INSTALL_BINDIR}") + set(PKGCONFIG_BINDIR "${CMAKE_INSTALL_BINDIR}") + else() + set(PKGCONFIG_BINDIR "\${prefix}/${CMAKE_INSTALL_BINDIR}") + endif() + configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/sentry.pc.in" + "${CMAKE_CURRENT_BINARY_DIR}/sentry.pc" + @ONLY + ) + sentry_install( + FILES "${CMAKE_CURRENT_BINARY_DIR}/sentry.pc" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig" + ) +endif() diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 37639d00da..965b3a934f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -207,7 +207,7 @@ The fixture currently supports the following commands: Only on Linux using crashpad: - `crashpad-wait-for-upload`: Couples application shutdown to complete the upload in the `crashpad_handler`. -Only on Windows using crashpad with its WER handler module: +Only on Windows using the native or crashpad backend with its WER handler module: - `fastfail`: Crashes the application using the `__fastfail` intrinsic directly, thus by-passing SEH. - `stack-buffer-overrun`: Triggers the Windows Control Flow Guard, which also fast fails and in turn by-passes SEH. diff --git a/Makefile b/Makefile index 8685a12d3c..5826afba73 100644 --- a/Makefile +++ b/Makefile @@ -25,7 +25,8 @@ test-unit: update-test-discovery CMakeLists.txt @cd unit-build; cmake \ -DCMAKE_RUNTIME_OUTPUT_DIRECTORY=$(PWD)/unit-build \ -DCMAKE_RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO=$(PWD)/unit-build \ - -DSENTRY_BACKEND=none \ + -DSENTRY_BACKEND=$(or $(SENTRY_BACKEND),none) \ + $(if $(SENTRY_TRANSPORT),-DSENTRY_TRANSPORT=$(SENTRY_TRANSPORT)) \ .. @cmake --build unit-build --target sentry_test_unit --parallel --config RelWithDebInfo ./unit-build/sentry_test_unit @@ -39,7 +40,8 @@ test-leaks: update-test-discovery CMakeLists.txt @mkdir -p leak-build @cd leak-build; cmake \ -DCMAKE_RUNTIME_OUTPUT_DIRECTORY=$(PWD)/leak-build \ - -DSENTRY_BACKEND=none \ + -DSENTRY_BACKEND=$(or $(SENTRY_BACKEND),none) \ + $(if $(SENTRY_TRANSPORT),-DSENTRY_TRANSPORT=$(SENTRY_TRANSPORT)) \ -DWITH_ASAN_OPTION=ON \ -DCMAKE_C_COMPILER=/opt/homebrew/opt/llvm/bin/clang \ -DCMAKE_CXX_COMPILER=/opt/homebrew/opt/llvm/bin/clang++ \ diff --git a/README.md b/README.md index a75860bee5..6b0c646f8c 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ The SDK bundle contains the following folders: The SDK currently supports and is tested on the following OS/Compiler variations: -- Linux (x86, x64, arm32 and arm64) with GCC 9+ and Clang 11+ +- Linux (x86, x64 and arm64) with GCC 9+ and Clang 11+ - Windows (x86, x64 and arm64) with MSVC (Visual Studio 2022+) and LLVM-MinGW - macOS 15+ with Apple Clang and LLVM Clang 15+ - Android API 21+ with NDK 23+ @@ -80,9 +80,11 @@ The SDK currently supports and is tested on the following OS/Compiler variations - Nintendo Switch via [sentry-switch](https://github.com/getsentry/sentry-switch). See [Nintendo Switch documentation](https://docs.sentry.io/platforms/nintendo-switch/) to get access. Additionally, the SDK should support the following platforms, although they are -not automatically tested, so breakage may occur: +not fully tested, so breakage may occur: -- Windows Versions lower than Windows 10 / Windows Server 2016 +- Windows versions lower than Windows 10 / Windows Server 2016: not tested in CI. +- Linux arm32 and riscv64: cross-compiled in CI, with only a subset of non-crash + tests run under QEMU. The SDK supports different features on the target platform: @@ -107,7 +109,7 @@ Building the Breakpad and Crashpad backends requires a `C++17` compatible compil **Build example**: ```sh -# configure the cmake build into the `build` directory, with crashpad (on macOS) +# configure the cmake build into the `build` directory, with native (on macOS) $ cmake -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo # build the project $ cmake --build build --parallel @@ -117,18 +119,23 @@ $ cmake --install build --prefix install --config RelWithDebInfo $ eza --tree install install ├── bin -│ └── crashpad_handler +│ └── sentry-crash ├── include │ └── sentry.h └── lib ├── cmake │ └── sentry - ├── libsentry.dylib - └── libsentry.dylib.dSYM + ├── libsentry.1.0.0.dylib + ├── libsentry.1.dylib -> libsentry.1.0.0.dylib + ├── libsentry.dylib -> libsentry.1.dylib + └── libsentry.1.0.0.dylib.dSYM ``` Please refer to the CMake Manual for more details. +Starting with 1.0.0, shared libraries on macOS and Linux use ABI-versioned +runtime names such as `libsentry.1.dylib` or `libsentry.so.1`. + **Android**: The CMake project can also be configured to correctly work with the Android NDK, @@ -144,7 +151,7 @@ The `ndk` folder provides a Gradle project that adds a Java JNI layer for Androi **MinGW**: 64-bit is the only platform supported for now. -LLVM + Clang are mandatory here : they are required to generate .pdb files, used by Crashpad for the report generation. +LLVM + Clang are mandatory here : they are required to generate .pdb files, used to symbolicate crash reports. For your application to generate the appropriate .pdb output, you need to activate CodeView file format generation on your application target. To do so, update your own CMakeLists.txt with something like `target_compile_options(${yourApplicationTarget} PRIVATE -gcodeview)`. @@ -246,20 +253,34 @@ using `cmake -D BUILD_SHARED_LIBS=OFF ..`. Windows and is the default there. - **none**: Do not build any HTTP transport. This should be used if users want to handle uploads themselves + - **custom**: Provide an external + `sentry_transport_t *sentry_transport_new_default(void)` implementation + (with `extern "C"` linkage if written in C++). Return a transport created + with `sentry_transport_new` or `sentry_http_transport_new`, or `NULL` to + disable uploads. + +- `SENTRY_SCREENSHOT` (Default: `windows` on Windows, `none` elsewhere): + Selects the screenshot implementation. Set it to `custom` and provide an + external `int sentry_screenshot_capture(const char *path, uint32_t pid)` + implementation (with `extern "C"` linkage if written in C++). + Save a PNG screenshot to `path` and return `0` on success, nonzero on failure. + `pid` selects whose windows to capture: `0` for the current process, or the + crashed application's PID when capture runs in a separate daemon. The path is + UTF-8 on Windows. - `SENTRY_BACKEND` (Default: depending on platform): Sentry can use different backends depending on the platform. - **crashpad**: This uses the out-of-process crashpad handler. It is currently - only supported on Desktop OSes and used as the default on Windows, Linux, and macOS. + only supported on Desktop OSes. - **breakpad**: This uses the in-process breakpad handler. It is currently only supported on Desktop OSs. - **inproc**: A small in-process handler that is supported on all platforms, and is used as a default on Android. - **native**: An out-of-process crash handler that uses a lightweight daemon to monitor the application, generate minidumps, and send crash reports. - Supports Linux, macOS, and Windows. Compatible with TSAN and ASAN - sanitizers. + Supports Linux, macOS, and Windows, where it is the default. Compatible with TSAN and ASAN + sanitizers. Support on Android is **experimental**. - **none**: This builds `sentry-native` without a backend, so it does not handle crashes. It is primarily used for tests. @@ -346,8 +367,8 @@ using `cmake -D BUILD_SHARED_LIBS=OFF ..`. | - none | ✓ | ✓ | ✓ | ☑ | ☑ | | | | | | | | | Backends | | | | | | -| - crashpad | ☑ | ☑ | ☑ | | | -| - native | ✓ | ✓ | ✓ | | | +| - crashpad | ✓ | ✓ | ✓ | | | +| - native | ☑ | ☑ | ☑ | (✓)*** | | | - breakpad | ✓ | ✓ | ✓ | (✓)* | (✓)* | | - inproc | ✓ | ✓ | ✓ | ☑ | | | - none | ✓ | ✓ | ✓ | ✓ | | @@ -359,6 +380,7 @@ Legend: - (✓) supported with limitations - `*`: `breakpad` on Android and iOS builds and should work according to upstream but is untested. - `**`: `curl` as a transport works on Android but isn't used in any supported configuration to reduce the size of our artifacts. +- `***`: The `native` backend on Android is experimental. In addition to platform support, the "Advanced Usage" section of the SDK docs now [describes the tradeoffs](https://docs.sentry.io/platforms/native/advanced-usage/backend-tradeoffs/) involved in choosing a suitable backend for a particular use case. diff --git a/include/sentry.h b/include/sentry.h index fbaaf18b02..4144db8dc6 100644 --- a/include/sentry.h +++ b/include/sentry.h @@ -109,15 +109,15 @@ extern "C" { * checks, or `sentry_sdk_version()` for the runtime version. */ #ifndef SENTRY_SDK_VERSION -# define SENTRY_SDK_VERSION "0.17.6" +# define SENTRY_SDK_VERSION "1.0.0-beta.1" #endif /** * Compile-time SDK version `major.minor.patch` as individual numbers. */ -#define SENTRY_SDK_VERSION_MAJOR 0 -#define SENTRY_SDK_VERSION_MINOR 17 -#define SENTRY_SDK_VERSION_PATCH 6 +#define SENTRY_SDK_VERSION_MAJOR 1 +#define SENTRY_SDK_VERSION_MINOR 0 +#define SENTRY_SDK_VERSION_PATCH 0 /** * Checks whether the compile-time SDK version is at least `major.minor.patch`. @@ -774,20 +774,6 @@ SENTRY_API sentry_value_t sentry_value_from_msgpack( SENTRY_API sentry_value_t sentry_value_from_msgpack_stream( const char *buf, size_t buf_len); -/** - * Adds a stack trace to an event. - * - * The stack trace is added as part of a new thread object. - * - * If `ips` is NULL, the current stack trace is captured. Otherwise, `len` - * stack trace instruction pointers are attached to the event. - */ -SENTRY_DEPRECATED( - "Use `sentry_value_new_stacktrace` in combination with " - "`sentry_value_new_thread` and `sentry_event_add_thread` instead") -SENTRY_EXPERIMENTAL_API void sentry_event_value_add_stacktrace( - sentry_value_t event, void **ips, size_t len); - /** * This represents the OS-dependent user context in the case of a crash and can * be used to manually capture a crash. @@ -1096,8 +1082,7 @@ SENTRY_API void sentry_transport_set_shutdown_func( * extended network outages may exhaust retry attempts that might have * succeeded with the SDK's built-in exponential backoff. */ -SENTRY_EXPERIMENTAL_API void sentry_transport_retry( - sentry_transport_t *transport); +SENTRY_API void sentry_transport_retry(sentry_transport_t *transport); /** * Generic way to free transport. @@ -1163,7 +1148,8 @@ SENTRY_EXPERIMENTAL_API const char *sentry_http_request_get_body( * Returns the path to a file that should be streamed as the request body of * `req`, and writes its size to `*len_out`. Returns `NULL` unless `req` * requires a file-backed body -- see `sentry_http_request_get_body`, which - * also covers requests with no body at all. + * also covers requests with no body at all. Custom HTTP clients must honor + * `sentry_http_request_get_body_file_offset` when streaming the file. * * The path is in a platform-specific filesystem path encoding, which on * Windows is UTF-8 rather than the ANSI code page the narrow Win32 APIs @@ -1174,6 +1160,15 @@ SENTRY_EXPERIMENTAL_API const char *sentry_http_request_get_body( SENTRY_EXPERIMENTAL_API const char *sentry_http_request_get_body_file_path( const sentry_http_request_t *req, size_t *len_out); +/** + * Returns the byte offset at which a file-backed request body starts. The + * client must seek to this position before streaming the number of bytes + * returned by `sentry_http_request_get_body_file_path`. Returns `0` for + * requests without a file-backed body. + */ +SENTRY_EXPERIMENTAL_API size_t sentry_http_request_get_body_file_offset( + const sentry_http_request_t *req); + #ifdef SENTRY_PLATFORM_WINDOWS /** * Wide char version of `sentry_http_request_get_body_file_path`. @@ -1200,10 +1195,11 @@ SENTRY_EXPERIMENTAL_API void sentry_http_response_set_status_code( /** * Records a response header on `resp`. `key` is matched case-insensitively * against the headers sentry-native cares about (currently `Retry-After`, - * `X-Sentry-Rate-Limits`, and `Location`); anything else is ignored. Pass - * every header the HTTP response actually had -- sentry-native, not the - * client, decides which ones matter, so headers Sentry starts caring about - * later don't require client changes. + * `X-Sentry-Rate-Limits`, `Location`, `Upload-Offset`, `Upload-Min-Chunk-Size`, + * `Upload-Max-Chunk-Size`, and `Upload-Chunk-Granularity`); anything else is + * ignored. Pass every header the HTTP response actually had -- sentry-native, + * not the client, decides which ones matter, so headers Sentry starts caring + * about later don't require client changes. */ SENTRY_EXPERIMENTAL_API void sentry_http_response_set_header( sentry_http_response_t *resp, const char *key, const char *value); @@ -1316,17 +1312,6 @@ SENTRY_EXPERIMENTAL_API void sentry_http_transport_set_client_shutdown_func( sentry_transport_t *transport, void (*shutdown_func)(sentry_http_client_t *client)); -/** - * Create a new function transport. - * - * It is a convenience function that works with a borrowed `data`, and will - * automatically free the envelope, so the user-provided function does not need - * to do that. - */ -SENTRY_DEPRECATED("Use `sentry_transport_new` instead") -SENTRY_API sentry_transport_t *sentry_new_function_transport( - void (*func)(const sentry_envelope_t *envelope, void *data), void *data); - /** * This represents an interface for user-defined backends. * @@ -1385,6 +1370,11 @@ typedef enum { * Most comprehensive debugging information but slowest to generate * and upload. Best for development/staging environments or critical * crash investigations. + * + * On macOS, the application and `sentry-crash` must be signed with the + * `com.apple.security.cs.debugger` and `com.apple.security.get-task-allow` + * entitlements. Uploading large dumps requires + * `sentry_options_set_enable_large_attachments`. */ SENTRY_MINIDUMP_MODE_FULL = 2, } sentry_minidump_mode_t; @@ -1506,7 +1496,7 @@ SENTRY_API void sentry_options_free(sentry_options_t *opts); * The callback is invoked synchronously once during `sentry_init`, after * option-derived defaults are applied and before the crash backend is started. * The scope is borrowed. Configure it with `sentry_scope_*` functions rather - * than global scope functions such as `sentry_set_tag`. + * than top-level scope functions such as `sentry_set_tag`. */ typedef void (*sentry_initial_scope_function_t)( sentry_scope_t *scope, void *user_data); @@ -1609,7 +1599,7 @@ SENTRY_API void sentry_options_set_before_send( * The hint is always provided and can be used to modify attachments on the * event. * - * Only the `inproc` backend currently fills the passed-in event with crash + * Only the `inproc` and `native` backends fill the passed-in event with crash * meta-data. Since both `breakpad` and `crashpad` use minidumps to capture the * crash state, the passed-in event is empty when using these backends. Changes * to the event from inside the hooks will be passed along, but in the case of @@ -1632,7 +1622,7 @@ SENTRY_API void sentry_options_set_before_send( * - if you are not interested in normal events, but only want to act on * crashes (within the limits mentioned below), then only define an * `on_crash` callback with the option to filter (on all backends) or enrich - * (only inproc) the crash event + * (inproc and native) the crash event * * This function may be invoked inside a signal handler and must be safe for * that purpose, see https://man7.org/linux/man-pages/man7/signal-safety.7.html. @@ -1792,19 +1782,6 @@ SENTRY_API void sentry_options_set_proxy_n( */ SENTRY_API const char *sentry_options_get_proxy(const sentry_options_t *opts); -/** - * Configures the proxy. - * - * The given proxy has to include the full scheme, - * e.g., `http://some.proxy/. - */ -SENTRY_DEPRECATED("Use `sentry_options_set_proxy` instead") -SENTRY_API void sentry_options_set_http_proxy( - sentry_options_t *opts, const char *proxy); -SENTRY_DEPRECATED("Use `sentry_options_set_proxy_n` instead") -SENTRY_API void sentry_options_set_http_proxy_n( - sentry_options_t *opts, const char *proxy, size_t proxy_len); - /** * Returns the configured proxy. */ @@ -2061,26 +2038,6 @@ SENTRY_API void sentry_options_add_attachment( SENTRY_API void sentry_options_add_attachment_n( sentry_options_t *opts, const char *path, size_t path_len); -/** - * Adds a new view hierarchy attachment to be sent along. - * - * The primary use-case is for downstream SDKs (like sentry-godot). The - * view-hierarchy.json file should follow the representation defined in RFC#33 - * https://github.com/getsentry/rfcs/blob/main/text/0033-view-hierarchy.md - * - * `path` is assumed to be in platform-specific filesystem path encoding. - * API Users on windows are encouraged to use - * `sentry_options_add_view_hierarchyw` instead. - */ -SENTRY_DEPRECATED("Use `sentry_attach_*` with `sentry_attachment_set_type` and " - "`SENTRY_ATTACHMENT_TYPE_VIEW_HIERARCHY` instead") -SENTRY_API void sentry_options_add_view_hierarchy( - sentry_options_t *opts, const char *path); -SENTRY_DEPRECATED("Use `sentry_attach_*` with `sentry_attachment_set_type` and " - "`SENTRY_ATTACHMENT_TYPE_VIEW_HIERARCHY` instead") -SENTRY_API void sentry_options_add_view_hierarchy_n( - sentry_options_t *opts, const char *path, size_t path_len); - /** * Enables or disables attaching screenshots to fatal error events. Disabled by * default. @@ -2093,7 +2050,7 @@ SENTRY_API void sentry_options_add_view_hierarchy_n( * To decide per-event whether a screenshot should be captured, set a * `before_screenshot` callback via `sentry_options_set_before_screenshot`. */ -SENTRY_EXPERIMENTAL_API void sentry_options_set_attach_screenshot( +SENTRY_API void sentry_options_set_attach_screenshot( sentry_options_t *opts, int val); /** @@ -2122,9 +2079,8 @@ typedef int (*sentry_before_screenshot_function_t)( * See the `sentry_before_screenshot_function_t` typedef above for more * information. */ -SENTRY_EXPERIMENTAL_API void sentry_options_set_before_screenshot( - sentry_options_t *opts, sentry_before_screenshot_function_t func, - void *user_data); +SENTRY_API void sentry_options_set_before_screenshot(sentry_options_t *opts, + sentry_before_screenshot_function_t func, void *user_data); /** * Enables capturing a short retroactive video replay on crash. Currently only @@ -2148,10 +2104,11 @@ SENTRY_EXPERIMENTAL_API void sentry_options_set_session_replay_duration( sentry_options_t *opts, uint32_t duration_ms); /** - * Sets the path to the crashpad handler if the crashpad backend is used. + * Sets the path to the crash handler if the native or crashpad backend is used. * - * The path defaults to the `crashpad_handler`/`crashpad_handler.exe` - * executable in the same directory as the application executable. + * The path defaults to the `sentry-crash`/`sentry-crash.exe` executable for the + * native backend or `crashpad_handler`/`crashpad_handler.exe` for the crashpad + * backend, in the same directory as the application executable. * * Meaning if your application resides in * @@ -2159,7 +2116,7 @@ SENTRY_EXPERIMENTAL_API void sentry_options_set_session_replay_duration( * * then the handler path will be set (by default) to * - * "C:\path\to\your\crashpad_handler.exe" + * "C:\path\to\your\sentry-crash.exe" when using the native backend. * * It is recommended that library users set an explicit handler path, depending * on the directory/executable structure of their app. @@ -2241,18 +2198,6 @@ SENTRY_API void sentry_options_add_attachmentw( SENTRY_API void sentry_options_add_attachmentw_n( sentry_options_t *opts, const wchar_t *path, size_t path_len); -/** - * Wide char version of `sentry_options_add_view_hierarchy`. - */ -SENTRY_DEPRECATED("Use `sentry_attach_*` with `sentry_attachment_set_type` and " - "`SENTRY_ATTACHMENT_TYPE_VIEW_HIERARCHY` instead") -SENTRY_API void sentry_options_add_view_hierarchyw( - sentry_options_t *opts, const wchar_t *path); -SENTRY_DEPRECATED("Use `sentry_attach_*` with `sentry_attachment_set_type` and " - "`SENTRY_ATTACHMENT_TYPE_VIEW_HIERARCHY` instead") -SENTRY_API void sentry_options_add_view_hierarchyw_n( - sentry_options_t *opts, const wchar_t *path, size_t path_len); - /** * Wide char version of `sentry_options_set_handler_path`. */ @@ -2472,6 +2417,8 @@ SENTRY_API void sentry_options_set_crash_memory_reserve( /** * Sets the maximum time (in milliseconds) to wait for the asynchronous * tasks to end on shutdown before attempting a forced termination. + * Defaults to 2 seconds. With `SENTRY_CRASH_UPLOAD_MODE_ASYNC`, the native + * crash daemon instead defaults to 10 seconds for uploading crashes. */ SENTRY_API void sentry_options_set_shutdown_timeout( sentry_options_t *opts, uint64_t shutdown_timeout); @@ -2480,7 +2427,8 @@ SENTRY_API void sentry_options_set_shutdown_timeout( * Gets the maximum time (in milliseconds) to wait for the asynchronous tasks to * end on shutdown before attempting a forced termination. */ -SENTRY_API uint64_t sentry_options_get_shutdown_timeout(sentry_options_t *opts); +SENTRY_API uint64_t sentry_options_get_shutdown_timeout( + const sentry_options_t *opts); /** * Sets the timeout (in milliseconds) for HTTP transfer operations. @@ -2500,7 +2448,8 @@ SENTRY_API void sentry_options_set_transfer_timeout( /** * Gets the timeout (in milliseconds) for HTTP transfer operations. */ -SENTRY_API uint64_t sentry_options_get_transfer_timeout(sentry_options_t *opts); +SENTRY_API uint64_t sentry_options_get_transfer_timeout( + const sentry_options_t *opts); /** * Sets a user-defined backend. @@ -2566,21 +2515,13 @@ SENTRY_API int sentry_flush(uint64_t timeout); */ SENTRY_API int sentry_close(void); -/** - * Shuts down the sentry client and forces transports to flush out. - * - * Returns the number of envelopes that have been dumped. - */ -SENTRY_DEPRECATED("Use `sentry_close` instead") -SENTRY_API int sentry_shutdown(void); - /** * This will lazily load and cache a list of all the loaded libraries. * * Returns a new reference to an immutable, frozen list. * The reference must be released with `sentry_value_decref`. */ -SENTRY_EXPERIMENTAL_API sentry_value_t sentry_get_modules_list(void); +SENTRY_API sentry_value_t sentry_get_modules_list(void); /** * Clears the internal module cache. @@ -2591,7 +2532,7 @@ SENTRY_EXPERIMENTAL_API sentry_value_t sentry_get_modules_list(void); * `sentry_clear_modulecache` when doing so to make sure that the next call to * `sentry_capture_event` will have an up-to-date module list. */ -SENTRY_EXPERIMENTAL_API void sentry_clear_modulecache(void); +SENTRY_API void sentry_clear_modulecache(void); /** * Re-initializes the Sentry backend. @@ -2637,6 +2578,33 @@ SENTRY_API sentry_user_consent_t sentry_user_consent_get(void); */ SENTRY_API int sentry_user_consent_is_required(void); +/** + * Acquires the isolation scope used by top-level scope functions. + * + * Returns an owned reference that must be released with `sentry_scope_release`. + * + * A separate isolation scope is used for each SDK run. The scope should be + * acquired after `sentry_init`, since scope changes made before initialization + * are not carried over. An explicitly acquired reference remains valid after + * the SDK is closed, but modifying the scope no longer has any effect. + * + * Note: The SDK operates in global mode: all threads share the same + * process-wide isolation scope, which inherits global data such as release and + * environment from the global scope. Changes made through top-level scope + * functions or the acquired scope are shared across all threads. + * + * For details on Sentry's scope model, see: + * https://develop.sentry.dev/sdk/foundations/state-management/scopes/#isolation-scope + */ +SENTRY_API sentry_scope_t *sentry_scope_acquire(void); + +/** + * Releases a reference acquired with `sentry_scope_acquire`. + * + * This is an alias for `sentry_scope_free`. + */ +SENTRY_API void sentry_scope_release(sentry_scope_t *scope); + /** * Creates a local scope. * @@ -2657,6 +2625,70 @@ SENTRY_API sentry_scope_t *sentry_local_scope_new(void); */ SENTRY_API sentry_scope_t *sentry_scope_new(void); +/** + * Begins a batch read of `scope` and its parent scopes. + * + * Tip: Individual scope property reads acquire a read lock automatically. + * Use this function to batch multiple reads. + * + * The scope remains read-locked until the matching `sentry_scope_end_read` call + * on the same thread, so multiple properties can be read consistently. Other + * threads may read the scope concurrently, but cannot modify it until the read + * lock is released. Reads may be nested for the same scope, including inside a + * write batch, which keeps its write lock. + * + * Warning: A read lock allows only reads. Use `sentry_scope_begin_write` if + * you need to modify the scope. Calling a scope-mutating function while + * read-locked triggers an assertion in debug builds and may deadlock in + * release builds. + * + * Returns 0 on success or 1 if `scope` is NULL or allocation fails. Each + * successful call must be matched by `sentry_scope_end_read` before freeing the + * scope. + */ +SENTRY_API int sentry_scope_begin_read(const sentry_scope_t *scope); + +/** + * Ends a read batch begun by `sentry_scope_begin_read`. + * + * The final matching call releases the scope read lock. Reads nested inside a + * write batch leave the scope write-locked until the final matching + * `sentry_scope_end_write`. This must be called on the same thread as the + * matching begin call. + */ +SENTRY_API void sentry_scope_end_read(const sentry_scope_t *scope); + +/** + * Begins a batch write of `scope`. + * + * Tip: Individual scope property accesses acquire the appropriate read or + * write lock automatically. Use this function to batch multiple reads, writes, + * or both under one write lock. + * + * The scope remains write-locked and its parent scopes read-locked until the + * matching `sentry_scope_end_write` call on the same thread, so inherited + * properties can be read consistently. A write lock allows reads and writes. + * Writes may be nested for the same scope. + * + * Note: A read lock cannot be upgraded to a write lock. If this thread already + * holds a read lock on the scope, this function returns 1 without changing + * the lock. + * + * Returns 0 on success or 1 if `scope` is NULL, allocation fails, or the + * calling thread already holds a read lock on the scope. Each successful call + * must be matched by `sentry_scope_end_write` before freeing the scope. + */ +SENTRY_API int sentry_scope_begin_write(sentry_scope_t *scope); + +/** + * Ends a write batch begun by `sentry_scope_begin_write`. + * + * The final matching call releases the scope write lock and flushes any + * pending isolation scope changes to the backend. This must be called on the + * same thread as the matching begin call. + */ +SENTRY_API void sentry_scope_end_write(sentry_scope_t *scope); + /** * Frees a scope created via `sentry_scope_new`, `sentry_scope_clone`, or * `sentry_local_scope_new`. @@ -2680,7 +2712,7 @@ SENTRY_API sentry_scope_t *sentry_scope_clone(const sentry_scope_t *scope); SENTRY_API void sentry_scope_clear(sentry_scope_t *scope); /** - * Returns the ID of the last event sent with the global scope. + * Returns the ID of the last event sent with the isolation scope. * * Returns a nil UUID if no event has been sent. */ @@ -2718,15 +2750,6 @@ SENTRY_API sentry_uuid_t sentry_capture_event(sentry_value_t event); SENTRY_API sentry_uuid_t sentry_scope_capture_event( sentry_scope_t *scope, sentry_value_t event, sentry_hint_t *hint); -/** - * Deprecated alias for `sentry_scope_capture_event`. Note the reversed argument - * order: the replacement takes the scope first. This alias will be removed in - * 2027. - */ -SENTRY_DEPRECATED("Use `sentry_scope_capture_event` instead") -SENTRY_API sentry_uuid_t sentry_capture_event_with_scope( - sentry_value_t event, sentry_scope_t *scope); - /** * Allows capturing independently created minidumps. * @@ -3003,6 +3026,32 @@ SENTRY_API void sentry_set_trace( const char *trace_id, const char *parent_span_id); SENTRY_API void sentry_set_trace_n(const char *trace_id, size_t trace_id_len, const char *parent_span_id, size_t parent_span_id_len); +SENTRY_API void sentry_scope_set_trace( + sentry_scope_t *scope, const char *trace_id, const char *parent_span_id); +SENTRY_API void sentry_scope_set_trace_n(sentry_scope_t *scope, + const char *trace_id, size_t trace_id_len, const char *parent_span_id, + size_t parent_span_id_len); + +/** + * Continues a trace from the `sentry-trace` and `baggage` headers of an + * incoming request, without starting a transaction. Either header may be NULL. + * + * Events and transactions afterwards continue the incoming trace and inherit + * its sampling decision. If the headers carry no valid trace, or strict trace + * continuation rejects it, a new trace is started instead. + * + * As with `sentry_set_trace`, transactions no longer act as automatic trace + * boundaries. + */ +SENTRY_API void sentry_continue_trace( + const char *sentry_trace, const char *baggage); +SENTRY_API void sentry_continue_trace_n(const char *sentry_trace, + size_t sentry_trace_len, const char *baggage, size_t baggage_len); +SENTRY_API void sentry_scope_continue_trace( + sentry_scope_t *scope, const char *sentry_trace, const char *baggage); +SENTRY_API void sentry_scope_continue_trace_n(sentry_scope_t *scope, + const char *sentry_trace, size_t sentry_trace_len, const char *baggage, + size_t baggage_len); /** * Generates a new random `trace_id` and `span_id` and sets these onto @@ -3019,9 +3068,6 @@ SENTRY_API void sentry_set_trace_n(const char *trace_id, size_t trace_id_len, */ SENTRY_API void sentry_start_new_trace(void); -SENTRY_DEPRECATED("Use `sentry_start_new_trace` instead") -SENTRY_API void sentry_regenerate_trace(void); - /** * Sets the transaction. */ @@ -3056,7 +3102,7 @@ SENTRY_API void sentry_options_set_max_spans( * Gets the maximum number of spans that can be attached to a * transaction. */ -SENTRY_API size_t sentry_options_get_max_spans(sentry_options_t *opts); +SENTRY_API size_t sentry_options_get_max_spans(const sentry_options_t *opts); /** * Sets the sample rate for transactions. Should be a double between @@ -3069,7 +3115,8 @@ SENTRY_API void sentry_options_set_traces_sample_rate( /** * Returns the sample rate for transactions. */ -SENTRY_API double sentry_options_get_traces_sample_rate(sentry_options_t *opts); +SENTRY_API double sentry_options_get_traces_sample_rate( + const sentry_options_t *opts); /** * A sentry Transaction Context. @@ -3155,10 +3202,9 @@ SENTRY_API int sentry_options_get_strict_trace_continuation( * * Disabled by default. */ -SENTRY_EXPERIMENTAL_API void sentry_options_set_http_retry( +SENTRY_API void sentry_options_set_http_retry( sentry_options_t *opts, int enabled); -SENTRY_EXPERIMENTAL_API int sentry_options_get_http_retry( - const sentry_options_t *opts); +SENTRY_API int sentry_options_get_http_retry(const sentry_options_t *opts); /** * Enables or disables attaching a stack trace to events that carry none. @@ -3301,13 +3347,13 @@ SENTRY_API log_return_value_t sentry_log( * Sends a structured log with a scope. * * Behaves like `sentry_log`, except the log also carries the attributes and - * trace of `scope`, layered on top of the global scope. An attribute set in - * more than one place resolves to the most specific: `attributes` > `scope` > - * global scope. + * trace of `scope`, layered on top of its isolation and global scopes. + * An attribute set in more than one place resolves to the most + * specific: `attributes` > `scope` > isolation scope > global scope. * * Scope ownership works as in `sentry_scope_capture_event`: a local scope * is freed by this function, a user-owned one is not. Pass `NULL` to apply the - * global scope only. + * isolation and global scopes. */ SENTRY_API log_return_value_t sentry_scope_capture_log(sentry_scope_t *scope, sentry_level_t level, const char *body, sentry_value_t attributes); @@ -3477,15 +3523,15 @@ typedef enum { * Records a metric of the given type with a scope. * * Behaves like the `sentry_metrics_*` functions, except the metric also carries - * the attributes and trace of `scope`, layered on top of the global scope. An - * attribute set in more than one place resolves to the most specific: - * `attributes` > `scope` > global scope. + * the attributes and trace of `scope`, layered on top of its isolation and + * global scopes. An attribute set in more than one place resolves to + * the most specific: `attributes` > `scope` > isolation scope > global scope. * * Ownership of `value` is transferred to this function, on top of `attributes`. * * Scope ownership works as in `sentry_scope_capture_event`: a local scope * is freed by this function, a user-owned one is not. Pass `NULL` to apply the - * global scope only. + * isolation and global scopes. */ SENTRY_API sentry_metrics_result_t sentry_scope_capture_metric( sentry_scope_t *scope, sentry_metric_type_t type, const char *name, @@ -3496,8 +3542,8 @@ SENTRY_API sentry_metrics_result_t sentry_scope_capture_metric( /** * Returns the currently set strategy for the handler. * - * This option works for the `inproc` backend on `Linux` and `Android`, and for - * the `native` backend on `Linux`. + * This option works for the `inproc` and `native` backends on `Linux` and + * `Android`. * * The main use-case is when the Native SDK is used in the context of the * CLR/Mono runtimes which convert some POSIX signals into managed-code @@ -4226,28 +4272,6 @@ SENTRY_API void sentry_transaction_set_name( SENTRY_API void sentry_transaction_set_name_n( sentry_transaction_t *transaction, const char *name, size_t name_len); -/** - * Creates a deprecated User Report with a specific name, email, and comments. - * - * See - * https://develop.sentry.dev/sdk/data-model/envelope-items/#user-report---deprecated - */ -SENTRY_DEPRECATED("Use `sentry_value_new_feedback` instead") -SENTRY_API sentry_value_t sentry_value_new_user_feedback( - const sentry_uuid_t *uuid, const char *name, const char *email, - const char *comments); -SENTRY_DEPRECATED("Use `sentry_value_new_feedback_n` instead") -SENTRY_API sentry_value_t sentry_value_new_user_feedback_n( - const sentry_uuid_t *uuid, const char *name, size_t name_len, - const char *email, size_t email_len, const char *comments, - size_t comments_len); - -/** - * Captures a deprecated User Report and sends it to Sentry. - */ -SENTRY_DEPRECATED("Use `sentry_capture_feedback` instead") -SENTRY_API void sentry_capture_user_feedback(sentry_value_t user_report); - /** * Creates a new User Feedback with a specific message (required), and optional * contact_email, name, message, and associated_event_id. @@ -4484,15 +4508,29 @@ typedef void (*sentry_iter_headers_function_t)( /** * Iterates the distributed tracing HTTP headers for the given span. */ -SENTRY_API void sentry_span_iter_headers(sentry_span_t *span, +SENTRY_API void sentry_span_iter_headers(const sentry_span_t *span, sentry_iter_headers_function_t callback, void *userdata); /** * Iterates the distributed tracing HTTP headers for the given transaction. */ -SENTRY_API void sentry_transaction_iter_headers(sentry_transaction_t *tx, +SENTRY_API void sentry_transaction_iter_headers(const sentry_transaction_t *tx, sentry_iter_headers_function_t callback, void *userdata); +/** + * Iterates the distributed tracing HTTP headers for the current trace: of the + * span or transaction bound to the scope, if any, otherwise of the scope's + * propagation context. This allows propagating a trace without a span. + * + * Without a span, the `sentry-trace` header carries a sampling decision only + * if one was inherited with `sentry_continue_trace`. + */ +SENTRY_API void sentry_iter_trace_propagation_headers( + sentry_iter_headers_function_t callback, void *userdata); +SENTRY_API void sentry_scope_iter_trace_propagation_headers( + const sentry_scope_t *scope, sentry_iter_headers_function_t callback, + void *userdata); + /** * Returns whether the application has crashed on the last run. * @@ -4507,19 +4545,6 @@ SENTRY_API void sentry_transaction_iter_headers(sentry_transaction_t *tx, */ SENTRY_API int sentry_get_crashed_last_run(void); -/** - * Clear the persisted status of the "crashed-last-run". - * - * Notes: - * * This doesn't change the value of sentry_get_crashed_last_run() yet. - * However, if sentry_init() is called again, the value will change. - * * This may only be called after sentry_init() and before sentry_close(). - * - * Returns 0 on success, 1 on error. - */ -SENTRY_DEPRECATED("The crash marker is cleared by `sentry_init()`.") -SENTRY_EXPERIMENTAL_API int sentry_clear_crashed_last_run(void); - /** * Returns the runtime SDK version as string. * @@ -4529,18 +4554,6 @@ SENTRY_EXPERIMENTAL_API int sentry_clear_crashed_last_run(void); */ SENTRY_API const char *sentry_sdk_version(void); -/** - * Sentry SDK name set during build time. - */ -SENTRY_DEPRECATED("Use `sentry_options_get_sdk_name` instead") -SENTRY_EXPERIMENTAL_API const char *sentry_sdk_name(void); - -/** - * Sentry SDK User-Agent set during build time. - */ -SENTRY_DEPRECATED("Use `sentry_options_get_user_agent` instead") -SENTRY_EXPERIMENTAL_API const char *sentry_sdk_user_agent(void); - #ifdef __cplusplus } #endif diff --git a/ndk/Makefile b/ndk/Makefile index fbb03eb1aa..aac0403eb8 100644 --- a/ndk/Makefile +++ b/ndk/Makefile @@ -18,4 +18,4 @@ api: # Run tests and lint check: - ./gradlew :sentry-native-ndk:check + ./gradlew :sentry-native-ndk:check :sentry-native-ndk-outproc:check diff --git a/ndk/README.md b/ndk/README.md index 90b8abcfd2..87da673e00 100644 --- a/ndk/README.md +++ b/ndk/README.md @@ -73,3 +73,11 @@ The `ndk` project uses the Gradle build system in combination with CMake. You ca ## Development Please see the [contribution guide](../CONTRIBUTING.md). + +## Crash backends + +`sentry-native-ndk` uses the inproc backend. The opt-in +`sentry-native-ndk-outproc` package includes the **experimental** native backend +and crash daemon, which runs in the Android crash service from +`sentry-android-ndk-outproc`. Both native packages provide `libsentry.so` and +must not be used together. diff --git a/ndk/build.gradle.kts b/ndk/build.gradle.kts index be4a8ce147..51cc25b84f 100644 --- a/ndk/build.gradle.kts +++ b/ndk/build.gradle.kts @@ -1,3 +1,4 @@ +import com.android.build.api.dsl.LibraryExtension import com.diffplug.gradle.spotless.SpotlessPlugin import com.diffplug.spotless.LineEnding import com.vanniktech.maven.publish.MavenPublishBaseExtension @@ -73,6 +74,11 @@ subprojects { } } } + if (name == "sentry-native-ndk-outproc") { + plugins.withId("com.android.library") { + configureNdkLibrary() + } + } plugins.withId("io.gitlab.arturbosch.detekt") { configure { @@ -91,6 +97,16 @@ subprojects { assignAarTypes() } + // the inproc and outproc backends exclude each other + afterEvaluate { + configurations.matching { + it.name.startsWith("releaseVariant") && it.name.endsWith("Publication") + }.configureEach { + outgoing.capability("$group:${project.name}:$version") + outgoing.capability("$group:sentry-ndk-backend:$version") + } + } + configure { getByName("main").contents { // non android modules @@ -224,5 +240,200 @@ fun MavenPublishBaseExtension.assignAarTypes() { } apiValidation { - ignoredProjects.addAll(listOf("sample")) + ignoredProjects.addAll(listOf("sample", "sentry-native-ndk-outproc")) +} + +fun Project.configureNdkLibrary() { + var sentryNativeSrc: String = "${project.projectDir}/../.." + val nativeBackend = project.name == "sentry-native-ndk-outproc" + val sentryBackend = if (nativeBackend) "native" else providers.gradleProperty("sentryBackend").orElse("inproc").get() + val libDir = rootProject.file("lib") + val sanitizer = + System.getenv("RUN_ANALYZER").orEmpty().split(',') + .firstOrNull { it == "asan" || it == "tsan" } + + configure { + compileSdk = 37 + // retain AGP 8.7.3's default NDK to avoid changing the compiler and libc++ in a hotfix + ndkVersion = System.getenv("ANDROID_NDK")?.let { File(it).name } ?: "27.0.12077973" + namespace = "io.sentry.ndk" + + testBuildType = "debug" + + defaultConfig { + minSdk = 21 + + aarMetadata { + // avoid requiring consumers to compile against API 37 + minCompileSdk = 1 + } + + externalNativeBuild { + cmake { + arguments.add(0, "-DSENTRY_BACKEND=$sentryBackend") + if (sentryBackend == "inproc") { + arguments.add(0, "-DSENTRY_TRANSPORT=none") + } + arguments.add(0, "-DANDROID_STL=${if (sanitizer != null) "c++_shared" else "c++_static"}") + arguments.add(0, "-DSENTRY_NATIVE_SRC=$sentryNativeSrc") + if (sanitizer == "asan") { + arguments.add(0, "-DWITH_ASAN_OPTION=ON") + } + if (sanitizer == "tsan") { + arguments.add(0, "-DWITH_TSAN_OPTION=ON") + } + } + } + + ndk { + abiFilters.addAll( + if (sanitizer == "tsan") { + listOf("x86_64", "arm64-v8a") + } else { + listOf("x86", "armeabi-v7a", "x86_64", "arm64-v8a") + }, + ) + } + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + if (nativeBackend) { + sourceSets.all { setRoot("$libDir/src/$name") } + } + + if (sanitizer != null) { + sourceSets.getByName("androidTest") { + jniLibs.srcDir("$libDir/build/$sanitizer/jniLibs") + resources.srcDir("$libDir/build/$sanitizer/resources") + } + } + + // we use the default NDK and CMake versions based on the AGP's version + // https://developer.android.com/studio/projects/install-ndk#apply-specific-version + externalNativeBuild { + cmake { + path("$libDir/CMakeLists.txt") + } + } + + buildTypes { + getByName("debug") { + externalNativeBuild { + cmake { + arguments.add(0, "-DENABLE_TESTS=ON") + } + } + } + getByName("release") { + consumerProguardFiles("$libDir/proguard-rules.pro") + } + } + + buildFeatures { + prefab = true + prefabPublishing = true + buildConfig = true + } + + // creates + // lib.aar/prefab/modules/sentry-android/libs//.so + // lib.aar/prefab/modules/sentry-android/include/sentry.h + prefab { + create("sentry-android") {} + create("sentry") { + headers = "../../include" + } + } + + testOptions { + animationsDisabled = true + unitTests.apply { + isReturnDefaultValues = true + isIncludeAndroidResources = true + } + } + + lint { + warningsAsErrors = true + checkDependencies = true + checkReleaseBuilds = true + disable.addAll(listOf("NewerVersionAvailable", "GradleDependency", "AndroidGradlePluginVersion")) + } + + packaging { + jniLibs { + useLegacyPackaging = true + } + } + } + + // legacy pre-prefab support + // creates lib.aar/jni/include/sentry.h alongside AGP's lib.aar/jni//.so + tasks.withType().configureEach { + if (name.startsWith("bundle") && name.endsWith("Aar")) { + from("../../include") { + into("jni/include") + } + } + } + + dependencies { + "compileOnly"("org.jetbrains:annotations:23.0.0") + + "testImplementation"("androidx.test.ext:junit:1.3.0") + + "androidTestImplementation"("androidx.test:runner:1.7.0") + "androidTestImplementation"("androidx.test.ext:junit:1.3.0") + "androidTestImplementation"("androidx.test:rules:1.7.0") + } + + /* + * Prefab doesn't support c++_static, so we need to change it to none. + * This should be fine, as we don't expose any conflicting symbols. + * Based on: https://github.com/bugsnag/bugsnag-android/blob/59460018551750dfcce4fd4e9f612eae7826559e/bugsnag-plugin-android-ndk/build.gradle.kts + * + * Copyright (c) 2012 Bugsnag + + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + afterEvaluate { + tasks.matching { it.name.startsWith("prefab") && it.name.endsWith("Package") }.configureEach { + doLast { + project.fileTree("build/intermediates/") { + include("**/abi.json") + include("**/prefab.json") + include("**/prefab_publication.json/*") + }.forEach { file -> + val contents = file.readText().replace("c++_static", "none") + file.writeText( + if (nativeBackend) { + contents.replace("\"name\": \"${project.name}\"", "\"name\": \"sentry-native-ndk\"") + .replace("\"packageName\": \"${project.name}\"", "\"packageName\": \"sentry-native-ndk\"") + } else { + contents + }, + ) + } + } + } + } } diff --git a/ndk/gradle.properties b/ndk/gradle.properties index bcd239c9d7..7b03e07735 100644 --- a/ndk/gradle.properties +++ b/ndk/gradle.properties @@ -14,7 +14,7 @@ android.newDsl=false android.sdk.defaultTargetSdkToCompileSdkIfUnset=false # Release information, used for maven publishing -versionName=0.17.6 +versionName=1.0.0-beta.1 # disable renderscript, it's enabled by default android.defaults.buildfeatures.renderscript=false diff --git a/ndk/lib/CMakeLists.txt b/ndk/lib/CMakeLists.txt index 211acf1771..5a0cf3a9cd 100644 --- a/ndk/lib/CMakeLists.txt +++ b/ndk/lib/CMakeLists.txt @@ -2,7 +2,13 @@ cmake_minimum_required(VERSION 3.10) project(Sentry-Android LANGUAGES C CXX) # Add sentry-android shared library -add_library(sentry-android SHARED src/main/jni/sentry.c) +add_library(sentry-android SHARED + src/main/jni/sentry.c + src/main/jni/sentry_http.c +) + +# Export only the JNI functions +set_property(TARGET sentry-android PROPERTY C_VISIBILITY_PRESET hidden) # Conditionally add test library if ENABLE_TESTS is set if(ENABLE_TESTS) @@ -13,9 +19,24 @@ endif() set(BUILD_SHARED_LIBS ON) set(SENTRY_BUILD_SHARED_LIBS ON) +if(SENTRY_BACKEND STREQUAL "native") + set(SENTRY_TRANSPORT "none" CACHE STRING "" FORCE) +endif() + # Adding sentry-native project add_subdirectory(${SENTRY_NATIVE_SRC} sentry_build) +# Package the daemon executable only for the instrumented tests, which fork/exec +# it. Apps run the daemon from libsentry.so in the sentry-java crash service. +if(SENTRY_BACKEND STREQUAL "native" AND ENABLE_TESTS) + set_target_properties(sentry-crash PROPERTIES + PREFIX "lib" + OUTPUT_NAME "sentry-crash" + SUFFIX ".so" + ) + target_link_options(sentry-crash PRIVATE "-Wl,-z,max-page-size=16384") +endif() + if(WITH_ASAN_OPTION) set(SENTRY_ANDROID_SANITIZER address) elseif(WITH_TSAN_OPTION) diff --git a/ndk/lib/api/sentry-native-ndk.api b/ndk/lib/api/sentry-native-ndk.api index 35780f414e..072749ecb6 100644 --- a/ndk/lib/api/sentry-native-ndk.api +++ b/ndk/lib/api/sentry-native-ndk.api @@ -109,9 +109,28 @@ public final class io/sentry/ndk/NdkOptions { public final class io/sentry/ndk/SentryNdk { public static fun close ()V + public static fun createCrashShm ()I + public static fun dupCrashShmFd ()I public static fun init (Lio/sentry/ndk/NdkOptions;)V + public static fun initCrashDaemon (IIII)V public static fun loadNativeLibraries ()V public static fun preload ()V + public static fun reattachCrashDaemon (III)Z + public static fun runCrashDaemon (IJIIII)Lio/sentry/ndk/SentryNdk$CrashDaemon; +} + +public final class io/sentry/ndk/SentryNdk$CrashDaemon : java/lang/AutoCloseable { + public fun close ()V + public fun getEnvelopePath ()Ljava/lang/String; + public fun sendEnvelope (Ljava/lang/String;J)Lio/sentry/ndk/SentryNdk$CrashDaemon$SendResult; +} + +public final class io/sentry/ndk/SentryNdk$CrashDaemon$SendResult : java/lang/Enum { + public static final field FAILED Lio/sentry/ndk/SentryNdk$CrashDaemon$SendResult; + public static final field KEPT Lio/sentry/ndk/SentryNdk$CrashDaemon$SendResult; + public static final field SENT Lio/sentry/ndk/SentryNdk$CrashDaemon$SendResult; + public static fun valueOf (Ljava/lang/String;)Lio/sentry/ndk/SentryNdk$CrashDaemon$SendResult; + public static fun values ()[Lio/sentry/ndk/SentryNdk$CrashDaemon$SendResult; } public final class io/sentry/ndk/SentryNdkPreloadProvider : android/content/ContentProvider { diff --git a/ndk/lib/proguard-rules.pro b/ndk/lib/proguard-rules.pro index b4b1a0152c..6f5f7b4975 100644 --- a/ndk/lib/proguard-rules.pro +++ b/ndk/lib/proguard-rules.pro @@ -6,6 +6,8 @@ # The JNI layer uses this class through reflection -keep class io.sentry.ndk.NdkOptions { *; } -keep class io.sentry.ndk.DebugImage { *; } +-keep class io.sentry.ndk.SentryHttpClient { *; } +-keep class io.sentry.ndk.SentryHttpClient$Response { *; } # For native methods, see http://proguard.sourceforge.net/manual/examples.html#native -keepclasseswithmembernames,includedescriptorclasses class io.sentry.ndk.** { diff --git a/ndk/lib/src/main/java/io/sentry/ndk/SentryHttpClient.java b/ndk/lib/src/main/java/io/sentry/ndk/SentryHttpClient.java new file mode 100644 index 0000000000..2a45ac17c1 --- /dev/null +++ b/ndk/lib/src/main/java/io/sentry/ndk/SentryHttpClient.java @@ -0,0 +1,225 @@ +package io.sentry.ndk; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManagerFactory; +import org.jetbrains.annotations.Nullable; + +class SentryHttpClient { + private final Object lock = new Object(); + private final ScheduledExecutorService timer = + Executors.newSingleThreadScheduledExecutor( + task -> { + final Thread thread = new Thread(task, "sentry-http-timeout"); + thread.setDaemon(true); + return thread; + }); + private @Nullable HttpURLConnection connection; + private boolean stopped; + private long timeout; + private String userAgent = ""; + private @Nullable Proxy proxy; + private @Nullable SSLSocketFactory socketFactory; + + void configure(long timeout, @Nullable String proxy, @Nullable String caCerts, String userAgent) + throws IOException, GeneralSecurityException { + this.timeout = timeout; + this.userAgent = userAgent; + if (proxy != null && proxy.isEmpty()) { + this.proxy = Proxy.NO_PROXY; + } else if (proxy != null) { + final URL url = new URL(proxy.contains("://") ? proxy : "http://" + proxy); + if (!"http".equals(url.getProtocol()) || url.getUserInfo() != null) { + throw new IOException("Only unauthenticated HTTP proxies are supported"); + } + this.proxy = + new Proxy( + Proxy.Type.HTTP, + new InetSocketAddress(url.getHost(), url.getPort() < 0 ? 80 : url.getPort())); + } + if (caCerts != null) { + final KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType()); + store.load(null, null); + try (InputStream input = new FileInputStream(caCerts)) { + int index = 0; + for (Certificate certificate : + CertificateFactory.getInstance("X.509").generateCertificates(input)) { + store.setCertificateEntry(Integer.toString(index++), certificate); + } + } + final TrustManagerFactory factory = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + factory.init(store); + final SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, factory.getTrustManagers(), null); + socketFactory = context.getSocketFactory(); + } + } + + HttpURLConnection openConnection(URL url) throws IOException { + return (HttpURLConnection) (proxy == null ? url.openConnection() : url.openConnection(proxy)); + } + + Response send( + String method, + String url, + String[] headers, + @Nullable ByteBuffer body, + @Nullable String bodyPath, + long bodyOffset, + long bodyLength) + throws IOException { + final HttpURLConnection connection = openConnection(new URL(url)); + final AtomicBoolean expired = new AtomicBoolean(); + final @Nullable ScheduledFuture deadline; + synchronized (lock) { + if (stopped) { + connection.disconnect(); + throw new IOException("HTTP client is shut down"); + } + this.connection = connection; + deadline = + timeout > 0 + ? timer.schedule( + () -> { + expired.set(true); + connection.disconnect(); + }, + timeout, + TimeUnit.MILLISECONDS) + : null; + } + try { + connection.setConnectTimeout((int) Math.min(timeout > 0 ? timeout : 15000, 15000)); + connection.setReadTimeout((int) Math.min(timeout, Integer.MAX_VALUE)); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(false); + connection.setRequestMethod(method); + connection.setRequestProperty("User-Agent", userAgent); + if (socketFactory != null && connection instanceof HttpsURLConnection) { + ((HttpsURLConnection) connection).setSSLSocketFactory(socketFactory); + } + for (int i = 0; i < headers.length; i += 2) { + connection.setRequestProperty(headers[i], headers[i + 1]); + } + checkCancelled(expired); + final byte[] buffer = new byte[8192]; + if (body != null || bodyPath != null) { + connection.setDoOutput(true); + connection.setFixedLengthStreamingMode(bodyLength); + try (OutputStream output = connection.getOutputStream()) { + if (bodyPath != null) { + try (FileInputStream input = new FileInputStream(bodyPath)) { + input.getChannel().position(bodyOffset); + long remaining = bodyLength; + while (remaining > 0) { + final int count = input.read(buffer, 0, (int) Math.min(buffer.length, remaining)); + if (count == -1) { + break; + } + checkCancelled(expired); + output.write(buffer, 0, count); + remaining -= count; + } + } + } else { + while (body.hasRemaining()) { + checkCancelled(expired); + final int count = Math.min(body.remaining(), buffer.length); + body.get(buffer, 0, count); + output.write(buffer, 0, count); + } + } + } + } + checkCancelled(expired); + final int statusCode = connection.getResponseCode(); + if (statusCode < 0) { + throw new IOException("Invalid HTTP response"); + } + final List responseHeaders = new ArrayList<>(); + for (Map.Entry> header : connection.getHeaderFields().entrySet()) { + if (header.getKey() != null) { + for (String value : header.getValue()) { + responseHeaders.add(header.getKey()); + responseHeaders.add(value); + } + } + } + try (InputStream input = + statusCode >= 400 ? connection.getErrorStream() : connection.getInputStream()) { + if (input != null) { + while (input.read(buffer) != -1) { + checkCancelled(expired); + } + } + } + checkCancelled(expired); + return new Response(statusCode, responseHeaders.toArray(new String[0])); + } finally { + if (deadline != null) { + deadline.cancel(false); + } + synchronized (lock) { + this.connection = null; + } + connection.disconnect(); + } + } + + private void checkCancelled(AtomicBoolean expired) throws IOException { + if (expired.get()) { + throw new SocketTimeoutException("HTTP request timed out"); + } + synchronized (lock) { + if (stopped) { + throw new IOException("HTTP client is shut down"); + } + } + } + + void shutdown() { + final @Nullable HttpURLConnection connection; + synchronized (lock) { + stopped = true; + connection = this.connection; + } + timer.shutdownNow(); + if (connection != null) { + connection.disconnect(); + } + } + + static final class Response { + final int statusCode; + final String[] headers; + + Response(int statusCode, String[] headers) { + this.statusCode = statusCode; + this.headers = headers; + } + } +} diff --git a/ndk/lib/src/main/java/io/sentry/ndk/SentryNdk.java b/ndk/lib/src/main/java/io/sentry/ndk/SentryNdk.java index d583275c7d..5281676f3f 100644 --- a/ndk/lib/src/main/java/io/sentry/ndk/SentryNdk.java +++ b/ndk/lib/src/main/java/io/sentry/ndk/SentryNdk.java @@ -2,6 +2,7 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @ApiStatus.Internal public final class SentryNdk { @@ -20,6 +21,25 @@ private SentryNdk() {} */ private static native int initSentryNative(@NotNull final NdkOptions options); + private static native int nativeCreateCrashShm(); + + private static native void nativeInitCrashDaemon( + int shmFd, int notifyFd, int readyFd, int messageFd); + + private static native long nativeRunCrashDaemon( + int appPid, long appTid, int notifyFd, int readyFd, int messageFd, int shmFd); + + private static native int nativeDupCrashShmFd(); + + private static native boolean nativeReattachCrashDaemon( + int notifyFd, int readyFd, int messageFd); + + private static native @NotNull String nativeGetCrashEnvelopePath(long handle); + + private static native int nativeSendEnvelope(long handle, @NotNull String path, long timeout); + + private static native void nativeCloseCrashDaemon(long handle); + private static native void shutdown(); /** @@ -55,6 +75,88 @@ public static void init(@NotNull final NdkOptions options) { } } + /** Creates the shared memory of the crash IPC, or returns -1 if that fails. Needs API 30+. */ + public static int createCrashShm() { + loadNativeLibraries(); + return nativeCreateCrashShm(); + } + + public static void initCrashDaemon(int shmFd, int notifyFd, int readyFd, int messageFd) { + loadNativeLibraries(); + nativeInitCrashDaemon(shmFd, notifyFd, readyFd, messageFd); + } + + /** Runs a crash daemon for an app process until it exits or crashes. */ + public static @Nullable CrashDaemon runCrashDaemon( + int appPid, long appTid, int notifyFd, int readyFd, int messageFd, int shmFd) { + loadNativeLibraries(); + final long handle = nativeRunCrashDaemon(appPid, appTid, notifyFd, readyFd, messageFd, shmFd); + return handle == 0 ? null : new CrashDaemon(handle); + } + + /** + * Returns a duplicate of the crash IPC's shared memory file for a restarted crash service, or -1 + * if the app has none to reattach. + */ + public static int dupCrashShmFd() { + loadNativeLibraries(); + return nativeDupCrashShmFd(); + } + + /** + * Switches the crash IPC to the daemon of a restarted crash service and sends it the current + * scope. Takes ownership of the fds. + * + * @return false if the app could not reattach, for example while handling a crash + */ + public static boolean reattachCrashDaemon(int notifyFd, int readyFd, int messageFd) { + loadNativeLibraries(); + return nativeReattachCrashDaemon(notifyFd, readyFd, messageFd); + } + + @ApiStatus.Internal + public static final class CrashDaemon implements AutoCloseable { + private final @NotNull String envelopePath; + private long handle; + + private CrashDaemon(long handle) { + this.handle = handle; + envelopePath = nativeGetCrashEnvelopePath(handle); + } + + public @NotNull String getEnvelopePath() { + return envelopePath; + } + + /** Sends the merged envelope and closes the daemon. */ + public synchronized @NotNull SendResult sendEnvelope(@NotNull String path, long timeout) { + final long handle = this.handle; + this.handle = 0; + return handle != 0 + ? SendResult.values()[nativeSendEnvelope(handle, path, timeout)] + : SendResult.FAILED; + } + + @Override + public synchronized void close() { + final long handle = this.handle; + this.handle = 0; + if (handle != 0) { + nativeCloseCrashDaemon(handle); + } + } + + /** The outcome of {@link #sendEnvelope(String, long)}. */ + public enum SendResult { + /** The envelope was neither sent nor kept. */ + FAILED, + /** The envelope was sent. */ + SENT, + /** The envelope was not sent and is kept for the next launch. */ + KEPT + } + } + /** Closes the NDK integration */ public static void close() { loadNativeLibraries(); diff --git a/ndk/lib/src/main/jni/sentry.c b/ndk/lib/src/main/jni/sentry.c index e31b2cc702..92d8d9355a 100644 --- a/ndk/lib/src/main/jni/sentry.c +++ b/ndk/lib/src/main/jni/sentry.c @@ -4,8 +4,30 @@ #include #include #include +#include #include #include +#include + +#include "sentry_http.h" + +extern int sentry_android_crash_daemon_create_shm(void) __attribute__((weak)); +extern void sentry_android_crash_daemon_init(int shm_fd, int notify_fd, + int ready_fd, int message_fd) __attribute__((weak)); +typedef struct sentry_crash_daemon_s sentry_crash_daemon_t; +extern sentry_crash_daemon_t *sentry_android_crash_daemon_run(int app_pid, + uint64_t app_tid, int notify_fd, int ready_fd, int message_fd, int shm_fd, + sentry_transport_t *transport) __attribute__((weak)); +extern const char *sentry_android_crash_daemon_get_envelope_path( + const sentry_crash_daemon_t *daemon) __attribute__((weak)); +extern int sentry_android_crash_daemon_send( + sentry_crash_daemon_t *daemon, const char *path, + uint64_t timeout) __attribute__((weak)); +extern void sentry_android_crash_daemon_close( + sentry_crash_daemon_t *daemon) __attribute__((weak)); +extern int sentry_android_crash_daemon_dup_shm_fd(void) __attribute__((weak)); +extern bool sentry_android_crash_daemon_reattach( + int notify_fd, int ready_fd, int message_fd) __attribute__((weak)); #define ENSURE(Expr) \ if (!(Expr)) \ @@ -433,6 +455,11 @@ Java_io_sentry_ndk_SentryNdk_initSentryNative( options = sentry_options_new(); ENSURE_OR_FAIL(options); + // Minidumps take precedence over native envelopes during processing and + // make crash envelopes large. Send native envelopes only, like inproc. + sentry_options_set_crash_reporting_mode( + options, SENTRY_CRASH_REPORTING_MODE_NATIVE); + // Android SDK needs to retain the marker timestamp for session finalization // and cleans it up when appropriate sentry__retain_crash_marker(options); @@ -540,6 +567,121 @@ Java_io_sentry_ndk_SentryNdk_initSentryNative( return (jint)-1; } +JNIEXPORT jint JNICALL +Java_io_sentry_ndk_SentryNdk_nativeCreateCrashShm(JNIEnv *env, jclass cls) { + return sentry_android_crash_daemon_create_shm + ? (jint) sentry_android_crash_daemon_create_shm() + : -1; +} + +JNIEXPORT void JNICALL +Java_io_sentry_ndk_SentryNdk_nativeInitCrashDaemon( + JNIEnv *env, + jclass cls, + jint shm_fd, + jint notify_fd, + jint ready_fd, + jint message_fd) { + ENSURE_OR_FAIL(sentry_android_crash_daemon_init); + + sentry_android_crash_daemon_init( + (int) shm_fd, (int) notify_fd, (int) ready_fd, (int) message_fd); + return; + +fail: + close(shm_fd); + close(notify_fd); + close(ready_fd); + close(message_fd); +} + +JNIEXPORT jlong JNICALL +Java_io_sentry_ndk_SentryNdk_nativeRunCrashDaemon( + JNIEnv *env, + jclass cls, + jint app_pid, + jlong app_tid, + jint notify_fd, + jint ready_fd, + jint message_fd, + jint shm_fd) { + ENSURE_OR_FAIL(sentry_android_crash_daemon_run); + + sentry_crash_daemon_t *daemon = sentry_android_crash_daemon_run( + (int) app_pid, (uint64_t) app_tid, (int) notify_fd, (int) ready_fd, + (int) message_fd, (int) shm_fd, + sentry_android_http_transport_new(env)); + + return (jlong)(uintptr_t)daemon; + +fail: + close(notify_fd); + close(ready_fd); + close(message_fd); + if (shm_fd >= 0) { + close(shm_fd); + } + return 0; +} + +JNIEXPORT jint JNICALL +Java_io_sentry_ndk_SentryNdk_nativeDupCrashShmFd(JNIEnv *env, jclass cls) { + return sentry_android_crash_daemon_dup_shm_fd + ? (jint) sentry_android_crash_daemon_dup_shm_fd() + : -1; +} + +JNIEXPORT jboolean JNICALL +Java_io_sentry_ndk_SentryNdk_nativeReattachCrashDaemon( + JNIEnv *env, + jclass cls, + jint notify_fd, + jint ready_fd, + jint message_fd) { + if (!sentry_android_crash_daemon_reattach) { + close(notify_fd); + close(ready_fd); + close(message_fd); + return JNI_FALSE; + } + return sentry_android_crash_daemon_reattach( + (int) notify_fd, (int) ready_fd, (int) message_fd) + ? JNI_TRUE + : JNI_FALSE; +} + +JNIEXPORT jstring JNICALL +Java_io_sentry_ndk_SentryNdk_nativeGetCrashEnvelopePath( + JNIEnv *env, jclass cls, jlong handle) { + return (*env)->NewStringUTF(env, + sentry_android_crash_daemon_get_envelope_path( + (sentry_crash_daemon_t *)(uintptr_t)handle)); +} + +JNIEXPORT jint JNICALL +Java_io_sentry_ndk_SentryNdk_nativeSendEnvelope( + JNIEnv *env, + jclass cls, + jlong handle, + jstring path, + jlong timeout) { + const char *path_chars = (*env)->GetStringUTFChars(env, path, 0); + int result = sentry_android_crash_daemon_send( + (sentry_crash_daemon_t *)(uintptr_t)handle, path_chars, + (uint64_t) timeout); + if (path_chars) { + (*env)->ReleaseStringUTFChars(env, path, path_chars); + } + return (jint) result; +} + +JNIEXPORT void JNICALL +Java_io_sentry_ndk_SentryNdk_nativeCloseCrashDaemon( + JNIEnv *env, jclass cls, jlong handle) { + sentry_android_crash_daemon_close( + (sentry_crash_daemon_t *)(uintptr_t)handle); +} + JNIEXPORT void JNICALL Java_io_sentry_ndk_NativeModuleListLoader_nativeClearModuleList( JNIEnv *env, jclass cls) diff --git a/ndk/lib/src/main/jni/sentry_http.c b/ndk/lib/src/main/jni/sentry_http.c new file mode 100644 index 0000000000..a709ae8a28 --- /dev/null +++ b/ndk/lib/src/main/jni/sentry_http.c @@ -0,0 +1,326 @@ +#include "sentry_http.h" + +#include +#include +#include +#include +#include +#include + +static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER; +static JavaVM *g_vm; +static jclass g_client_class; +static jmethodID g_constructor; +static jmethodID g_configure; +static jmethodID g_send; +static jmethodID g_shutdown; +static jfieldID g_status_code; +static jfieldID g_headers; + +// FindClass finds the app's classes only when called from Java +static bool +load_client_class(JNIEnv *env) +{ + if (g_client_class) { + return true; + } + if ((*env)->GetJavaVM(env, &g_vm) != JNI_OK) { + return false; + } + jclass cls = (*env)->FindClass(env, "io/sentry/ndk/SentryHttpClient"); + if (!cls) { + return false; + } + g_client_class = (*env)->NewGlobalRef(env, cls); + (*env)->DeleteLocalRef(env, cls); + if (!g_client_class) { + return false; + } + jclass response + = (*env)->FindClass(env, "io/sentry/ndk/SentryHttpClient$Response"); + if (!response + || !(g_constructor + = (*env)->GetMethodID(env, g_client_class, "", "()V")) + || !(g_configure = (*env)->GetMethodID(env, g_client_class, "configure", + "(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V")) + || !(g_send = (*env)->GetMethodID(env, g_client_class, "send", + "(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;" + "Ljava/nio/ByteBuffer;Ljava/lang/String;JJ)" + "Lio/sentry/ndk/SentryHttpClient$Response;")) + || !(g_shutdown + = (*env)->GetMethodID(env, g_client_class, "shutdown", "()V")) + || !(g_status_code + = (*env)->GetFieldID(env, response, "statusCode", "I")) + || !(g_headers = (*env)->GetFieldID( + env, response, "headers", "[Ljava/lang/String;"))) { + (*env)->DeleteGlobalRef(env, g_client_class); + g_client_class = NULL; + return false; + } + (*env)->DeleteLocalRef(env, response); + return true; +} + +static JNIEnv * +get_env(bool *attached) +{ + JNIEnv *env = NULL; + *attached = false; + jint rv = (*g_vm)->GetEnv(g_vm, (void **)&env, JNI_VERSION_1_6); + if (rv == JNI_EDETACHED) { + if ((*g_vm)->AttachCurrentThread(g_vm, &env, NULL) != JNI_OK) { + return NULL; + } + *attached = true; + } else if (rv != JNI_OK) { + return NULL; + } + return env; +} + +static bool +clear_exception(JNIEnv *env) +{ + if (!(*env)->ExceptionCheck(env)) { + return false; + } + (*env)->ExceptionDescribe(env); + (*env)->ExceptionClear(env); + __android_log_write( + ANDROID_LOG_WARN, "sentry-native", "Android HTTP client failed"); + return true; +} + +static void +release_env(JNIEnv *env, bool attached) +{ + clear_exception(env); + if (attached) { + (*g_vm)->DetachCurrentThread(g_vm); + } +} + +static sentry_http_client_t * +client_new(void *data) +{ + (void)data; + bool attached; + JNIEnv *env = get_env(&attached); + if (!env) { + return NULL; + } + jobject client = (*env)->NewObject(env, g_client_class, g_constructor); + jobject ref = client ? (*env)->NewGlobalRef(env, client) : NULL; + if (client) { + (*env)->DeleteLocalRef(env, client); + } + release_env(env, attached); + return ref; +} + +static int +client_start(sentry_http_client_t *client, const sentry_options_t *options) +{ + bool attached; + JNIEnv *env = get_env(&attached); + if (!env) { + return 1; + } + int rv = 1; + if ((*env)->PushLocalFrame(env, 4) != JNI_OK) { + release_env(env, attached); + return rv; + } + const char *proxy = sentry_options_get_proxy(options); + const char *ca_certs = sentry_options_get_ca_certs(options); + const char *user_agent = sentry_options_get_user_agent(options); + jstring jproxy = proxy ? (*env)->NewStringUTF(env, proxy) : NULL; + if (proxy && !jproxy) { + goto done; + } + jstring jca_certs = ca_certs ? (*env)->NewStringUTF(env, ca_certs) : NULL; + if (ca_certs && !jca_certs) { + goto done; + } + jstring juser_agent = (*env)->NewStringUTF( + env, user_agent ? user_agent : SENTRY_SDK_USER_AGENT); + if (!juser_agent) { + goto done; + } + uint64_t timeout + = sentry_options_get_transfer_timeout((sentry_options_t *)options); + (*env)->CallVoidMethod(env, client, g_configure, + (jlong)(timeout > INT64_MAX ? INT64_MAX : timeout), jproxy, jca_certs, + juser_agent); + rv = clear_exception(env) ? 1 : 0; + +done: + clear_exception(env); + (*env)->PopLocalFrame(env, NULL); + release_env(env, attached); + return rv; +} + +static int +client_send(sentry_http_client_t *client, sentry_http_request_t *req, + sentry_http_response_t *resp) +{ + bool attached; + JNIEnv *env = get_env(&attached); + if (!env) { + return 0; + } + int rv = 0; + if ((*env)->PushLocalFrame(env, 16) != JNI_OK) { + release_env(env, attached); + return 0; + } + + jstring method + = (*env)->NewStringUTF(env, sentry_http_request_get_method(req)); + if (!method) { + goto done; + } + jstring url = (*env)->NewStringUTF(env, sentry_http_request_get_url(req)); + if (!url) { + goto done; + } + size_t count = sentry_http_request_get_header_count(req); + if (count > INT_MAX / 2) { + goto done; + } + jclass string_class = (*env)->FindClass(env, "java/lang/String"); + if (!string_class) { + goto done; + } + jobjectArray headers + = (*env)->NewObjectArray(env, (jsize)(count * 2), string_class, NULL); + if (!headers) { + goto done; + } + for (size_t i = 0; i < count; i++) { + const char *key, *value; + sentry_http_request_get_header(req, i, &key, &value); + jstring jkey = (*env)->NewStringUTF(env, key); + if (!jkey) { + goto done; + } + jstring jvalue = (*env)->NewStringUTF(env, value); + if (!jvalue) { + goto done; + } + (*env)->SetObjectArrayElement(env, headers, (jsize)(i * 2), jkey); + (*env)->SetObjectArrayElement(env, headers, (jsize)(i * 2 + 1), jvalue); + (*env)->DeleteLocalRef(env, jkey); + (*env)->DeleteLocalRef(env, jvalue); + if ((*env)->ExceptionCheck(env)) { + goto done; + } + } + + size_t body_len; + const char *body = sentry_http_request_get_body(req, &body_len); + jobject buffer = NULL; + jstring path = NULL; + if (body) { + if (body_len > INT_MAX) { + goto done; + } + buffer + = (*env)->NewDirectByteBuffer(env, (void *)body, (jlong)body_len); + if (!buffer) { + goto done; + } + } else { + const char *body_path + = sentry_http_request_get_body_file_path(req, &body_len); + if (body_path) { + path = (*env)->NewStringUTF(env, body_path); + if (!path) { + goto done; + } + } + } + jobject response = (*env)->CallObjectMethod(env, client, g_send, method, + url, headers, buffer, path, + (jlong)sentry_http_request_get_body_file_offset(req), (jlong)body_len); + if (clear_exception(env) || !response) { + goto done; + } + sentry_http_response_set_status_code( + resp, (*env)->GetIntField(env, response, g_status_code)); + jobjectArray response_headers + = (*env)->GetObjectField(env, response, g_headers); + jsize len = (*env)->GetArrayLength(env, response_headers); + for (jsize i = 0; i < len; i += 2) { + jstring key = (*env)->GetObjectArrayElement(env, response_headers, i); + jstring value + = (*env)->GetObjectArrayElement(env, response_headers, i + 1); + const char *ckey = (*env)->GetStringUTFChars(env, key, NULL); + if (!ckey) { + goto done; + } + const char *cvalue = (*env)->GetStringUTFChars(env, value, NULL); + if (cvalue) { + sentry_http_response_set_header(resp, ckey, cvalue); + (*env)->ReleaseStringUTFChars(env, value, cvalue); + } + (*env)->ReleaseStringUTFChars(env, key, ckey); + (*env)->DeleteLocalRef(env, key); + (*env)->DeleteLocalRef(env, value); + if (!cvalue) { + goto done; + } + } + rv = 1; + +done: + clear_exception(env); + (*env)->PopLocalFrame(env, NULL); + release_env(env, attached); + return rv; +} + +static void +client_shutdown(sentry_http_client_t *client) +{ + bool attached; + JNIEnv *env = get_env(&attached); + if (env) { + (*env)->CallVoidMethod(env, client, g_shutdown); + release_env(env, attached); + } +} + +static void +client_free(sentry_http_client_t *client) +{ + client_shutdown(client); + bool attached; + JNIEnv *env = get_env(&attached); + if (env) { + (*env)->DeleteGlobalRef(env, client); + release_env(env, attached); + } +} + +sentry_transport_t * +sentry_android_http_transport_new(JNIEnv *env) +{ + pthread_mutex_lock(&g_mutex); + bool loaded = load_client_class(env); + pthread_mutex_unlock(&g_mutex); + if (!loaded) { + clear_exception(env); + return NULL; + } + + sentry_transport_t *transport + = sentry_http_transport_new(client_new, NULL, client_send, client_free); + if (transport) { + sentry_http_transport_set_client_start_func(transport, client_start); + sentry_http_transport_set_client_shutdown_func( + transport, client_shutdown); + } + return transport; +} diff --git a/ndk/lib/src/main/jni/sentry_http.h b/ndk/lib/src/main/jni/sentry_http.h new file mode 100644 index 0000000000..e793858470 --- /dev/null +++ b/ndk/lib/src/main/jni/sentry_http.h @@ -0,0 +1,9 @@ +#ifndef SENTRY_ANDROID_HTTP_H_INCLUDED +#define SENTRY_ANDROID_HTTP_H_INCLUDED + +#include +#include + +sentry_transport_t *sentry_android_http_transport_new(JNIEnv *env); + +#endif diff --git a/ndk/lib/src/test/java/io/sentry/ndk/SentryHttpClientTest.java b/ndk/lib/src/test/java/io/sentry/ndk/SentryHttpClientTest.java new file mode 100644 index 0000000000..148833c5aa --- /dev/null +++ b/ndk/lib/src/test/java/io/sentry/ndk/SentryHttpClientTest.java @@ -0,0 +1,353 @@ +package io.sentry.ndk; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SentryHttpClientTest { + private Connection connection; + private SentryHttpClient client; + + @Before + public void setUp() throws Exception { + connection = new Connection(); + client = + new SentryHttpClient() { + @Override + HttpURLConnection openConnection(URL url) { + return connection; + } + }; + client.configure(5000, null, null, "sentry-native/test"); + } + + @After + public void tearDown() { + client.shutdown(); + } + + @Test + public void sendsBinaryEnvelope() throws Exception { + final byte[] body = {0, 1, (byte) 0xff, 0, 42}; + final SentryHttpClient.Response response = + client.send( + "POST", + connection.getURL().toString(), + new String[] {"Content-Type", "application/x-sentry-envelope", "X-Sentry-Auth", "auth"}, + ByteBuffer.wrap(body), + null, + 0, + body.length); + + assertEquals(200, response.statusCode); + assertEquals("POST", connection.getRequestMethod()); + assertEquals("auth", connection.getRequestProperty("X-Sentry-Auth")); + assertEquals("sentry-native/test", connection.getRequestProperty("User-Agent")); + assertEquals("application/x-sentry-envelope", connection.getRequestProperty("Content-Type")); + assertEquals(body.length, connection.bodyLength()); + assertArrayEquals(body, connection.output.toByteArray()); + assertFalse(connection.getUseCaches()); + assertFalse(connection.getInstanceFollowRedirects()); + assertTrue(connection.disconnected); + } + + @Test + public void streamsAttachment() throws Exception { + final File file = File.createTempFile("sentry-http", ".attachment"); + try { + final byte[] body = new byte[20000]; + Arrays.fill(body, (byte) 0xff); + try (OutputStream output = new FileOutputStream(file)) { + output.write(body); + } + client.send( + "PATCH", + connection.getURL().toString(), + new String[] {"Tus-Resumable", "1.0.0"}, + null, + file.getPath(), + 0, + body.length); + + assertEquals("PATCH", connection.getRequestMethod()); + assertEquals(body.length, connection.bodyLength()); + assertArrayEquals(body, connection.output.toByteArray()); + } finally { + assertTrue(file.delete()); + } + } + + @Test + public void streamsAttachmentChunk() throws Exception { + final File file = File.createTempFile("sentry-http", ".attachment"); + try { + final byte[] body = new byte[20000]; + for (int i = 0; i < body.length; i++) { + body[i] = (byte) i; + } + try (OutputStream output = new FileOutputStream(file)) { + output.write(body); + } + client.send( + "PATCH", + connection.getURL().toString(), + new String[] {"Tus-Resumable", "1.0.0"}, + null, + file.getPath(), + 5000, + 10000); + + assertEquals(10000, connection.bodyLength()); + assertArrayEquals(Arrays.copyOfRange(body, 5000, 15000), connection.output.toByteArray()); + } finally { + assertTrue(file.delete()); + } + } + + @Test + public void sendsBodylessRequest() throws Exception { + client.send("POST", connection.getURL().toString(), new String[0], null, null, 0, 0); + + assertEquals("POST", connection.getRequestMethod()); + assertFalse(connection.getDoOutput()); + assertEquals(0, connection.output.size()); + } + + @Test + public void returnsErrorStatusAndHeaders() throws Exception { + connection.statusCode = 429; + connection.headers.put(null, Collections.singletonList("HTTP/1.1 429 Too Many Requests")); + connection.headers.put("Retry-After", Collections.singletonList("60")); + connection.headers.put("X-Sentry-Rate-Limits", Collections.singletonList("60:error:key")); + connection.headers.put("Location", Collections.singletonList("/upload/1")); + connection.headers.put("Other", Arrays.asList("one", "two")); + + final SentryHttpClient.Response response = + client.send("POST", connection.getURL().toString(), new String[0], null, null, 0, 0); + + assertEquals(429, response.statusCode); + assertArrayEquals( + new String[] { + "Retry-After", + "60", + "X-Sentry-Rate-Limits", + "60:error:key", + "Location", + "/upload/1", + "Other", + "one", + "Other", + "two" + }, + response.headers); + } + + @Test + public void disconnectsOnFailure() { + connection.failure = new IOException("network unavailable"); + + assertThrows( + IOException.class, + () -> client.send("POST", connection.getURL().toString(), new String[0], null, null, 0, 0)); + + assertTrue(connection.disconnected); + } + + @Test + public void cancelsTimedOutRequest() throws Exception { + client.configure(20, null, null, "test"); + connection.block = true; + + assertThrows( + IOException.class, + () -> client.send("POST", connection.getURL().toString(), new String[0], null, null, 0, 0)); + + assertTrue(connection.disconnected); + } + + @Test + public void shutdownCancelsRequest() throws Exception { + connection.block = true; + final ExecutorService worker = Executors.newSingleThreadExecutor(); + try { + final Future failure = + worker.submit( + () -> + assertThrows( + IOException.class, + () -> + client.send( + "POST", + connection.getURL().toString(), + new String[0], + null, + null, + 0, + 0))); + assertTrue(connection.entered.await(2, TimeUnit.SECONDS)); + client.shutdown(); + + assertNotNull(failure.get(2, TimeUnit.SECONDS)); + assertTrue(connection.disconnected); + } finally { + worker.shutdownNow(); + } + } + + @Test + public void rejectsRequestsAfterShutdown() { + client.shutdown(); + + assertThrows( + IOException.class, + () -> client.send("POST", connection.getURL().toString(), new String[0], null, null, 0, 0)); + } + + @Test + public void rejectsInvalidResponse() { + connection.statusCode = -1; + + assertThrows( + IOException.class, + () -> client.send("POST", connection.getURL().toString(), new String[0], null, null, 0, 0)); + + assertTrue(connection.disconnected); + } + + @Test + public void shutdownBeforeConnectPreventsUpload() { + connection.beforeRequest = client::shutdown; + + assertThrows( + IOException.class, + () -> + client.send( + "POST", + connection.getURL().toString(), + new String[0], + ByteBuffer.wrap(new byte[] {1}), + null, + 0, + 1)); + + assertEquals(0, connection.output.size()); + } + + @Test + public void emptyProxyConnectsDirectly() throws Exception { + final SentryHttpClient direct = new SentryHttpClient(); + try { + direct.configure(5000, "", null, "test"); + + assertFalse(direct.openConnection(new URL("http://localhost/")).usingProxy()); + } finally { + direct.shutdown(); + } + } + + private static final class Connection extends HttpURLConnection { + final ByteArrayOutputStream output = new ByteArrayOutputStream(); + final Map> headers = new LinkedHashMap<>(); + final CountDownLatch entered = new CountDownLatch(1); + final CountDownLatch cancelled = new CountDownLatch(1); + volatile boolean disconnected; + boolean block; + int statusCode = 200; + IOException failure; + Runnable beforeRequest; + + Connection() throws Exception { + super(new URL("http://localhost/envelope/")); + } + + long bodyLength() { + return fixedContentLengthLong; + } + + @Override + public void setRequestMethod(String method) { + this.method = method; + if (beforeRequest != null) { + beforeRequest.run(); + } + } + + @Override + public OutputStream getOutputStream() { + return output; + } + + @Override + public int getResponseCode() throws IOException { + if (failure != null) { + throw failure; + } + if (block) { + entered.countDown(); + try { + assertTrue(cancelled.await(2, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + throw new IOException("cancelled"); + } + return statusCode; + } + + @Override + public Map> getHeaderFields() { + return headers; + } + + @Override + public InputStream getInputStream() { + return new ByteArrayInputStream(new byte[0]); + } + + @Override + public InputStream getErrorStream() { + return null; + } + + @Override + public void disconnect() { + disconnected = true; + cancelled.countDown(); + } + + @Override + public boolean usingProxy() { + return false; + } + + @Override + public void connect() {} + } +} diff --git a/ndk/native/build.gradle.kts b/ndk/native/build.gradle.kts new file mode 100644 index 0000000000..48ba031565 --- /dev/null +++ b/ndk/native/build.gradle.kts @@ -0,0 +1,4 @@ +plugins { + id("com.android.library") + kotlin("android") +} diff --git a/ndk/native/gradle.properties b/ndk/native/gradle.properties new file mode 100644 index 0000000000..46b4aaa4ee --- /dev/null +++ b/ndk/native/gradle.properties @@ -0,0 +1 @@ +POM_ARTIFACT_ID=sentry-native-ndk-outproc diff --git a/ndk/sample/src/main/AndroidManifest.xml b/ndk/sample/src/main/AndroidManifest.xml index 882d9c1e80..b7eab55e03 100644 --- a/ndk/sample/src/main/AndroidManifest.xml +++ b/ndk/sample/src/main/AndroidManifest.xml @@ -2,6 +2,8 @@ + + = 8 and fields[0][:-1].isdigit() and fields[6] != "UND": + symbols.add(fields[7].split("@")[0]) + return symbols + + +def needed_libraries(path): + return set(re.findall(r"\(NEEDED\).*\[(.+)\]", readelf("--dynamic", path))) + + +def load_alignments(path): + output = readelf("--segments", path) + return [int(a, 16) for a in re.findall(r"^\s*LOAD\s.*\s(0x\w+)$", output, re.M)] + + +def check_library(name, path, required): + errors = [] + module = PurePosixPath(name).stem[len("lib") :] + symbols = exported_symbols(path) + missing = required[module] - symbols + if missing: + errors.append(f"{name}: missing exports: {sorted(missing)}") + unexpected = {s for s in symbols if not re.fullmatch(EXPORTS[module], s)} + if unexpected: + errors.append(f"{name}: unexpected exports: {sorted(unexpected)}") + unknown = needed_libraries(path) - NEEDED + if unknown: + errors.append(f"{name}: unexpected dependencies: {sorted(unknown)}") + if any(alignment < PAGE_SIZE for alignment in load_alignments(path)): + errors.append(f"{name}: LOAD segments are not 16 KB aligned") + return errors + + +def main(): + errors = [] + expected = expected_files() + required = {"sentry": declared_functions(), "sentry-android": native_methods()} + with zipfile.ZipFile(sys.argv[1]) as aar, tempfile.TemporaryDirectory() as tmp: + files = { + name + for name in aar.namelist() + if name.startswith(("jni/", "prefab/")) and not name.endswith("/") + } + errors += [f"{name}: unexpected file" for name in sorted(files - expected)] + errors += [f"{name}: missing file" for name in sorted(expected - files)] + for name in sorted(files & expected): + if name.endswith(".so"): + errors += check_library(name, aar.extract(name, tmp), required) + elif name.endswith("/abi.json"): + stl = json.loads(aar.read(name))["stl"] + if stl != "none": + errors.append(f"{name}: unexpected STL: {stl}") + elif name == "prefab/prefab.json": + package = json.loads(aar.read(name))["name"] + if package != "sentry-native-ndk": + errors.append(f"{name}: unexpected package: {package}") + if errors: + sys.exit("\n".join(errors)) + print(f"{sys.argv[1]}: OK") + + +if __name__ == "__main__": + main() diff --git a/scripts/setup-android-e2e.py b/scripts/setup-android-e2e.py new file mode 100644 index 0000000000..9d183c2a86 --- /dev/null +++ b/scripts/setup-android-e2e.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 + +import argparse +import os +import re +import shutil +import subprocess +import tomllib +import uuid +from pathlib import Path + +PROJECT_DIR = Path(__file__).resolve().parent.parent + + +def main(): + parser = argparse.ArgumentParser( + description="Build the Android native E2E fixture APK" + ) + parser.add_argument( + "sentry_java", + type=Path, + help="sentry-java checkout with the native crash service", + ) + parser.add_argument( + "--build-dir", type=Path, default=PROJECT_DIR / "build/android-e2e" + ) + args = parser.parse_args() + java = args.sentry_java.expanduser().resolve() + if not (java / "sentry-android-ndk-outproc").is_dir(): + parser.error("sentry-java must contain the native crash service") + for name in ["ANDROID_HOME", "ANDROID_NDK", "ANDROID_ARCH"]: + if not os.environ.get(name): + parser.error(f"{name} must be set") + + build_dir = args.build_dir.expanduser().resolve() + app = build_dir / "app" + shutil.copytree(PROJECT_DIR / "tests/fixtures/android_e2e", app, dirs_exist_ok=True) + repo = build_dir / "maven" + version = f"0.0.0-e2e-{uuid.uuid4().hex}" + init = build_dir / "ndk.gradle" + # override the downstream SDK's pinned NDK version without editing its catalog + init.write_text(f""" +gradle.settingsEvaluated {{ settings -> + settings.dependencyResolutionManagement.repositories {{ + maven {{ url = uri('{repo.as_uri()}') }} + }} +}} +allprojects {{ + configurations.configureEach {{ + resolutionStrategy.force('io.sentry:sentry-native-ndk-outproc:{version}') + }} +}} +""") + + def gradle(project, *args): + command = [ + str(project / "gradlew"), + "--console=plain", + f"-PversionName={version}", + f"-Dmaven.repo.local={repo}", + *args, + ] + print("+ " + " ".join(command), flush=True) + subprocess.run(command, cwd=project, check=True) + + gradle(PROJECT_DIR / "ndk", ":sentry-native-ndk-outproc:publishToMavenLocal") + gradle( + java, + "--init-script", + str(init), + ":sentry:publishToMavenLocal", + ":sentry-android-core:publishToMavenLocal", + ":sentry-android-ndk:publishToMavenLocal", + ":sentry-android-ndk-outproc:publishToMavenLocal", + ":sentry-bom:publishToMavenLocal", + ) + + versions = tomllib.loads((java / "gradle/libs.versions.toml").read_text())[ + "versions" + ] + agp = re.search( + r'id\("com.android.application"\) version "([^"]+)"', + (PROJECT_DIR / "ndk/build.gradle.kts").read_text(), + ).group(1) + subprocess.run( + [ + str(java / "gradlew"), + "--console=plain", + f"-PagpVersion={agp}", + f"-PcompileSdk={versions['compileSdk']}", + f"-PcompileSdkMinor={versions.get('compileSdkMinor', '0')}", + f"-PtargetSdk={versions['targetSdk']}", + f"-PsentryVersion={version}", + f"-PlocalRepo={repo}", + "assembleDebug", + "assembleNondebuggable", + ], + cwd=app, + check=True, + ) + print(f"Prepared APKs: {app / 'build/outputs/apk'}") + + +if __name__ == "__main__": + main() diff --git a/sentry.pc.in b/sentry.pc.in new file mode 100644 index 0000000000..0de461e287 --- /dev/null +++ b/sentry.pc.in @@ -0,0 +1,12 @@ +prefix=@PREFIX@ +exec_prefix=${prefix} +libdir=@PKGCONFIG_LIBDIR@ +includedir=@PKGCONFIG_INCLUDEDIR@ +bindir=@PKGCONFIG_BINDIR@ + +Name: sentry +Description: Sentry SDK for C, C++ and native applications +Version: @PKGCONFIG_VERSION@ +URL: https://sentry.io/ +Libs: -L${libdir} -lsentry +Cflags: -I${includedir} diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index c66ff02610..c69e60d646 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -79,7 +79,6 @@ sentry_target_sources_cwd(sentry path/sentry_path.c screenshot/sentry_screenshot.c session_replay/sentry_session_replay.c - transports/sentry_function_transport.c transports/sentry_http_transport.c transports/sentry_http_transport.h unwinder/sentry_unwinder.c @@ -147,6 +146,10 @@ elseif(SENTRY_TRANSPORT_NONE) sentry_target_sources_cwd(sentry transports/sentry_transport_none.c ) +elseif(SENTRY_TRANSPORT_STDOUT) + sentry_target_sources_cwd(sentry + transports/sentry_transport_stdout.c + ) endif() # backends @@ -177,12 +180,26 @@ elseif(SENTRY_BACKEND_NATIVE) backends/native/sentry_crash_ipc.c backends/native/sentry_crash_handler.c ) + if(ANDROID) + sentry_target_sources_cwd(sentry + backends/native/sentry_crash_daemon.c + backends/native/minidump/sentry_minidump_common.c + backends/native/minidump/sentry_minidump_indirect.c + backends/native/minidump/sentry_minidump_linux.c + ) + endif() + if(SENTRY_WITH_LIBUNWINDSTACK) + target_compile_definitions(sentry PRIVATE SENTRY_WITH_UNWINDER_LIBUNWINDSTACK_REMOTE) + sentry_target_sources_cwd(sentry + unwinder/sentry_unwinder_libunwindstack_remote.cpp + ) + endif() # Add include directory for native backend headers target_include_directories(sentry PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/backends/native) # Platform-specific libraries for native backend - if(LINUX OR ANDROID) + if(LINUX AND NOT ANDROID) # Linux needs pthread and rt for shared memory target_link_libraries(sentry PRIVATE pthread rt) elseif(APPLE) @@ -266,6 +283,12 @@ if(WIN32) sentry_target_sources_cwd(sentry unwinder/sentry_unwinder_dbghelp.c ) + if(MINGW AND CMAKE_C_COMPILER_ID STREQUAL "Clang") + set_source_files_properties( + "${CMAKE_CURRENT_SOURCE_DIR}/unwinder/sentry_unwinder_dbghelp.c" + DIRECTORY "${PROJECT_SOURCE_DIR}" + PROPERTIES COMPILE_OPTIONS -fms-extensions) + endif() endif() if(PROSPERO) diff --git a/src/backends/native/minidump/sentry_minidump_common.c b/src/backends/native/minidump/sentry_minidump_common.c index 84fb4d0bc6..a90f6e4d87 100644 --- a/src/backends/native/minidump/sentry_minidump_common.c +++ b/src/backends/native/minidump/sentry_minidump_common.c @@ -213,10 +213,111 @@ sentry__minidump_get_context_size(void) return sizeof(minidump_context_x86_t); # elif defined(__arm__) return sizeof(minidump_context_arm_t); +# elif defined(__riscv) && __riscv_xlen == 64 + return sizeof(minidump_context_riscv64_t); # else # error "Unsupported architecture" # endif } +// Copy regions in chunks, because they can exceed what the daemon can allocate +# define MEMORY64_CHUNK_SIZE (4 * 1024 * 1024) + +int +sentry__minidump_write_memory64_list(minidump_writer_base_t *writer, + minidump_directory_t *dir, minidump_memory64_list_t *list, + sentry_minidump_read_fn_t read_memory) +{ + void *buf = sentry_malloc(MEMORY64_CHUNK_SIZE); + if (!buf) { + return -1; + } + + // Reserve space for the list, and fill it in once the sizes are known + size_t list_size = sizeof(*list) + list->count * sizeof(list->ranges[0]); + minidump_rva_t rva = sentry__minidump_write_data(writer, list, list_size); + if (!rva) { + sentry_free(buf); + return -1; + } + list->base_rva = writer->current_offset; + + uint64_t count = 0; + bool writable = true; + for (uint64_t i = 0; writable && i < list->count; i++) { + uint64_t start = list->ranges[i].start_address; + uint64_t size = list->ranges[i].size; + uint64_t offset = 0; + + while (offset < size) { + size_t len = size - offset < MEMORY64_CHUNK_SIZE + ? (size_t)(size - offset) + : MEMORY64_CHUNK_SIZE; + ssize_t nread = read_memory(writer, start + offset, buf, len); + if (nread <= 0) { + break; + } + if (write(writer->fd, buf, (size_t)nread) != nread) { + SENTRY_WARNF("minidump write failed: %s", strerror(errno)); + writable = false; + break; + } + writer->current_offset += (uint64_t)nread; + offset += (uint64_t)nread; + } + + if (offset > 0) { + list->ranges[count].start_address = start; + list->ranges[count].size = offset; + count++; + } + } + sentry_free(buf); + + list->count = count; + list_size = sizeof(*list) + count * sizeof(list->ranges[0]); + if (pwrite(writer->fd, list, list_size, rva) != (ssize_t)list_size) { + SENTRY_WARNF("minidump write failed: %s", strerror(errno)); + return -1; + } + + dir->stream_type = MINIDUMP_STREAM_MEMORY64_LIST; + dir->rva = rva; + dir->data_size = (uint32_t)list_size; + return 0; +} + +bool +sentry__minidump_add_range(minidump_memory64_list_t **list, uint64_t *capacity, + uint64_t region, uint64_t start, uint64_t size) +{ + minidump_memory64_list_t *old = *list; + if (old->count > 0 && start > region) { + minidump_memory64_descriptor_t *last = &old->ranges[old->count - 1]; + if (last->start_address + last->size == start) { + last->size += size; + return true; + } + } + + if (old->count == *capacity) { + minidump_memory64_list_t *grown = sentry_malloc(sizeof(*grown) + + *capacity * 2 * sizeof(minidump_memory64_descriptor_t)); + if (!grown) { + return false; + } + memcpy(grown, old, + sizeof(*old) + old->count * sizeof(minidump_memory64_descriptor_t)); + sentry_free(old); + *list = grown; + *capacity *= 2; + } + + minidump_memory64_descriptor_t *range = &(*list)->ranges[(*list)->count++]; + range->start_address = start; + range->size = size; + return true; +} + #endif // SENTRY_PLATFORM_LINUX || SENTRY_PLATFORM_ANDROID || // SENTRY_PLATFORM_MACOS diff --git a/src/backends/native/minidump/sentry_minidump_common.h b/src/backends/native/minidump/sentry_minidump_common.h index 1a9aaa205a..51410e24a2 100644 --- a/src/backends/native/minidump/sentry_minidump_common.h +++ b/src/backends/native/minidump/sentry_minidump_common.h @@ -4,6 +4,7 @@ #include "sentry_minidump_format.h" #include #include +#include /** * Common minidump writer base structure @@ -54,4 +55,51 @@ minidump_rva_t sentry__minidump_write_string( */ size_t sentry__minidump_get_context_size(void); +/** + * Read memory from the crashed process + * + * @param writer Pointer to writer base + * @param addr Address to read from + * @param buf Buffer to read into + * @param size Number of bytes to read + * @return Number of bytes read, or a negative value on failure + */ +typedef ssize_t (*sentry_minidump_read_fn_t)( + minidump_writer_base_t *writer, uint64_t addr, void *buf, size_t size); + +/** + * Write a Memory64List stream with the memory of the given regions + * + * Must be the last stream, because the memory can extend past the 4GB limit + * of 32-bit RVAs. + * + * On return, `list` describes the captured memory. A region ends at its first + * unreadable byte, and regions with no readable bytes are dropped. + * + * @param writer Pointer to writer base + * @param dir Directory entry to fill in + * @param list Regions to capture + * @param read_memory Function to read the memory with + * @return 0 on success, -1 on failure + */ +int sentry__minidump_write_memory64_list(minidump_writer_base_t *writer, + minidump_directory_t *dir, minidump_memory64_list_t *list, + sentry_minidump_read_fn_t read_memory); + +/** + * Add a range of a region to the list, growing the list as needed + * + * Extends the last range if it is contiguous and in the same region. Regions + * stay separate, because a range ends at its first unreadable byte. + * + * @param list List to add to, replaced when it grows + * @param capacity Number of ranges the list can hold + * @param region Start address of the region + * @param start Start address of the range + * @param size Size of the range + * @return true on success, false on allocation failure + */ +bool sentry__minidump_add_range(minidump_memory64_list_t **list, + uint64_t *capacity, uint64_t region, uint64_t start, uint64_t size); + #endif // SENTRY_MINIDUMP_COMMON_H_INCLUDED diff --git a/src/backends/native/minidump/sentry_minidump_format.h b/src/backends/native/minidump/sentry_minidump_format.h index 6daf02f360..9770c5b7e8 100644 --- a/src/backends/native/minidump/sentry_minidump_format.h +++ b/src/backends/native/minidump/sentry_minidump_format.h @@ -50,6 +50,7 @@ typedef enum { MINIDUMP_CPU_ARM = 5, // PROCESSOR_ARCHITECTURE_ARM MINIDUMP_CPU_X86_64 = 9, // PROCESSOR_ARCHITECTURE_AMD64 MINIDUMP_CPU_ARM64 = 12, // PROCESSOR_ARCHITECTURE_ARM64 + MINIDUMP_CPU_RISCV64 = 0x8006, // MD_CPU_ARCHITECTURE_RISCV64 (Breakpad) } minidump_cpu_type_t; // OS types (must match Breakpad MDOSPlatform values) @@ -318,6 +319,18 @@ typedef struct { uint32_t fpextra[8]; } PACKED_ATTR minidump_context_arm_t; PACKED_STRUCT_END + +#elif defined(__riscv) && __riscv_xlen == 64 +PACKED_STRUCT_BEGIN +typedef struct { + uint32_t context_flags; + uint32_t version; + uint64_t regs[32]; // PC, X1-X31 + uint64_t fpregs[32]; // F0-F31 + uint32_t fcsr; + uint32_t reserved; +} PACKED_ATTR minidump_context_riscv64_t; +PACKED_STRUCT_END #endif /** diff --git a/src/backends/native/minidump/sentry_minidump_linux.c b/src/backends/native/minidump/sentry_minidump_linux.c index 6fe38e5332..203edea0c3 100644 --- a/src/backends/native/minidump/sentry_minidump_linux.c +++ b/src/backends/native/minidump/sentry_minidump_linux.c @@ -27,6 +27,7 @@ # include "sentry_minidump_format.h" # include "sentry_minidump_indirect.h" # include "sentry_minidump_writer.h" +# include "sentry_os.h" // NT_PRSTATUS is defined in linux/elf.h but we can't include that // because it conflicts with elf.h. Define it here if not available. @@ -67,9 +68,6 @@ struct fpsimd_context { # endif # endif -// Use process_vm_readv to read memory from crashed process -# include - // Use shared constants from crash context # include "../sentry_crash_context.h" @@ -261,6 +259,18 @@ ptrace_get_thread_registers(pid_t tid, ucontext_t *uctx) SENTRY_DEBUGF("ptrace(PTRACE_GETREGSET) failed for thread %d: %s", tid, strerror(errno)); } +# elif defined(__riscv) && __riscv_xlen == 64 + struct iovec iov + = { uctx->uc_mcontext.__gregs, sizeof(uctx->uc_mcontext.__gregs) }; + if (ptrace(PTRACE_GETREGSET, tid, (void *)NT_PRSTATUS, &iov) == 0) { + success = true; + struct iovec fp_iov = { &uctx->uc_mcontext.__fpregs.__d, + sizeof(uctx->uc_mcontext.__fpregs.__d) }; + ptrace(PTRACE_GETREGSET, tid, (void *)NT_FPREGSET, &fp_iov); + } else { + SENTRY_DEBUGF("ptrace(PTRACE_GETREGSET) failed for thread %d: %s", tid, + strerror(errno)); + } # elif defined(__i386__) struct user_regs_struct regs; if (ptrace(PTRACE_GETREGS, tid, NULL, ®s) == 0) { @@ -348,7 +358,8 @@ read_process_memory( struct iovec remote_iov = { .iov_base = (void *)(uintptr_t)addr, .iov_len = len }; - ssize_t nread = process_vm_readv(tid, &local_iov, 1, &remote_iov, 1, 0); + ssize_t nread + = sentry__process_vm_readv(tid, &local_iov, 1, &remote_iov, 1, 0); if (nread > 0) { return nread; } @@ -550,6 +561,8 @@ write_system_info_stream(minidump_writer_t *writer, minidump_directory_t *dir) sysinfo.processor_architecture = MINIDUMP_CPU_X86; # elif defined(__arm__) sysinfo.processor_architecture = MINIDUMP_CPU_ARM; +# elif defined(__riscv) && __riscv_xlen == 64 + sysinfo.processor_architecture = MINIDUMP_CPU_RISCV64; # endif # if defined(SENTRY_PLATFORM_ANDROID) @@ -858,17 +871,31 @@ write_thread_context( return write_data(writer, &context, sizeof(context)); +# elif defined(__riscv) && __riscv_xlen == 64 + (void)tid; + + minidump_context_riscv64_t context = { 0 }; + context.context_flags = 0x08000003; // RISCV64 | Integer | Floating point + context.version = 1; + memcpy(context.regs, uctx->uc_mcontext.__gregs, sizeof(context.regs)); + memcpy(context.fpregs, uctx->uc_mcontext.__fpregs.__d.__f, + sizeof(context.fpregs)); + context.fcsr = uctx->uc_mcontext.__fpregs.__d.__fcsr; + + return write_data(writer, &context, sizeof(context)); + # else # error "Unsupported architecture for Linux" # endif } /** - * Extract Build ID from ELF file + * Extract Build ID from the ELF image at `elf_offset` in a file * Returns the Build ID length, or 0 if not found */ static size_t -extract_elf_build_id(const char *elf_path, uint8_t *build_id, size_t max_len) +extract_elf_build_id(const char *elf_path, uint64_t elf_offset, + uint8_t *build_id, size_t max_len) { int fd = sentry__elf_open(elf_path); if (fd < 0) { @@ -876,13 +903,14 @@ extract_elf_build_id(const char *elf_path, uint8_t *build_id, size_t max_len) } // Read ELF header -# if defined(__x86_64__) || defined(__aarch64__) +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) Elf64_Ehdr ehdr; # else Elf32_Ehdr ehdr; # endif - if (read(fd, &ehdr, sizeof(ehdr)) != sizeof(ehdr)) { + if (pread(fd, &ehdr, sizeof(ehdr), (off_t)elf_offset) != sizeof(ehdr)) { close(fd); return 0; } @@ -908,14 +936,16 @@ extract_elf_build_id(const char *elf_path, uint8_t *build_id, size_t max_len) return 0; } - if (lseek(fd, ehdr.e_shoff, SEEK_SET) != (off_t)ehdr.e_shoff + uint64_t shoff = elf_offset + ehdr.e_shoff; + if (lseek(fd, (off_t)shoff, SEEK_SET) != (off_t)shoff || read(fd, shdr_buf, shdr_size) != (ssize_t)shdr_size) { sentry_free(shdr_buf); close(fd); return 0; } -# if defined(__x86_64__) || defined(__aarch64__) +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) Elf64_Shdr *sections = (Elf64_Shdr *)shdr_buf; # else Elf32_Shdr *sections = (Elf32_Shdr *)shdr_buf; @@ -934,8 +964,8 @@ extract_elf_build_id(const char *elf_path, uint8_t *build_id, size_t max_len) if (!note_buf) continue; - if (lseek(fd, sections[i].sh_offset, SEEK_SET) - == (off_t)sections[i].sh_offset + uint64_t note_offset = elf_offset + sections[i].sh_offset; + if (lseek(fd, (off_t)note_offset, SEEK_SET) == (off_t)note_offset && read(fd, note_buf, note_size) == (ssize_t)note_size) { // Find the GNU build-id note. SHT_NOTE uses 4-byte alignment. size_t desc_size = 0; @@ -960,87 +990,6 @@ extract_elf_build_id(const char *elf_path, uint8_t *build_id, size_t max_len) return build_id_len; } -/** - * Compute the virtual memory size of an ELF file from its PT_LOAD segments. - * This matches Crashpad's behavior: size = max(p_vaddr + p_memsz) - - * min(p_vaddr) across all PT_LOAD segments, rather than using page-aligned - * /proc/maps sizes. - * Returns the computed size, or 0 on failure (caller should fall back to - * /proc/maps size). - */ -static uint64_t -compute_elf_size_from_phdrs(const char *elf_path) -{ - int fd = sentry__elf_open(elf_path); - if (fd < 0) { - return 0; - } - -# if defined(__x86_64__) || defined(__aarch64__) - Elf64_Ehdr ehdr; -# else - Elf32_Ehdr ehdr; -# endif - - if (read(fd, &ehdr, sizeof(ehdr)) != sizeof(ehdr) - || memcmp(ehdr.e_ident, ELFMAG, SELFMAG) != 0 || ehdr.e_phnum == 0) { - close(fd); - return 0; - } - - if (!sentry__elf_has_phdr_size(ehdr.e_ident, ehdr.e_phentsize)) { - close(fd); - return 0; - } - - // Read program headers - size_t phdr_size = (size_t)ehdr.e_phentsize * ehdr.e_phnum; - void *phdr_buf = sentry_malloc(phdr_size); - if (!phdr_buf) { - close(fd); - return 0; - } - - if (lseek(fd, ehdr.e_phoff, SEEK_SET) != (off_t)ehdr.e_phoff - || read(fd, phdr_buf, phdr_size) != (ssize_t)phdr_size) { - sentry_free(phdr_buf); - close(fd); - return 0; - } - -# if defined(__x86_64__) || defined(__aarch64__) - Elf64_Phdr *phdrs = (Elf64_Phdr *)phdr_buf; -# else - Elf32_Phdr *phdrs = (Elf32_Phdr *)phdr_buf; -# endif - - uint64_t min_vaddr = UINT64_MAX; - uint64_t max_vaddr = 0; - bool found_load = false; - - for (int i = 0; i < ehdr.e_phnum; i++) { - if (phdrs[i].p_type == PT_LOAD) { - found_load = true; - if (phdrs[i].p_vaddr < min_vaddr) { - min_vaddr = phdrs[i].p_vaddr; - } - uint64_t end = phdrs[i].p_vaddr + phdrs[i].p_memsz; - if (end > max_vaddr) { - max_vaddr = end; - } - } - } - - sentry_free(phdr_buf); - close(fd); - - if (!found_load || max_vaddr <= min_vaddr) { - return 0; - } - - return max_vaddr - min_vaddr; -} - /** * Read the DT_SONAME from an ELF file's dynamic section. * Crashpad uses SONAME as the module name, falling back to the /proc/maps @@ -1049,14 +998,16 @@ compute_elf_size_from_phdrs(const char *elf_path) * Returns true if SONAME was found and written to soname_buf. */ static bool -read_elf_soname(const char *elf_path, char *soname_buf, size_t soname_buf_size) +read_elf_soname(const char *elf_path, uint64_t elf_offset, char *soname_buf, + size_t soname_buf_size) { int fd = sentry__elf_open(elf_path); if (fd < 0) { return false; } -# if defined(__x86_64__) || defined(__aarch64__) +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) Elf64_Ehdr ehdr; typedef Elf64_Dyn DynT; typedef Elf64_Shdr ShdrT; @@ -1068,7 +1019,7 @@ read_elf_soname(const char *elf_path, char *soname_buf, size_t soname_buf_size) bool result = false; - if (read(fd, &ehdr, sizeof(ehdr)) != sizeof(ehdr) + if (pread(fd, &ehdr, sizeof(ehdr), (off_t)elf_offset) != sizeof(ehdr) || memcmp(ehdr.e_ident, ELFMAG, SELFMAG) != 0) { close(fd); return false; @@ -1087,7 +1038,8 @@ read_elf_soname(const char *elf_path, char *soname_buf, size_t soname_buf_size) return false; } - if (lseek(fd, ehdr.e_shoff, SEEK_SET) != (off_t)ehdr.e_shoff + uint64_t shoff = elf_offset + ehdr.e_shoff; + if (lseek(fd, (off_t)shoff, SEEK_SET) != (off_t)shoff || read(fd, shdr_buf, shdr_size) != (ssize_t)shdr_size) { sentry_free(shdr_buf); close(fd); @@ -1125,7 +1077,7 @@ read_elf_soname(const char *elf_path, char *soname_buf, size_t soname_buf_size) // Read .dynstr char *dynstr = sentry__elf_read_metadata_section( - fd, dynstr_shdr->sh_offset, dynstr_shdr->sh_size); + fd, elf_offset + dynstr_shdr->sh_offset, dynstr_shdr->sh_size); if (!dynstr) { sentry_free(shdr_buf); close(fd); @@ -1135,7 +1087,7 @@ read_elf_soname(const char *elf_path, char *soname_buf, size_t soname_buf_size) // Read .dynamic entries and find DT_SONAME void *dyn_buf = sentry__elf_read_metadata_section( - fd, dynamic_shdr->sh_offset, dynamic_shdr->sh_size); + fd, elf_offset + dynamic_shdr->sh_offset, dynamic_shdr->sh_size); if (!dyn_buf) { sentry_free(dynstr); sentry_free(shdr_buf); @@ -1392,6 +1344,8 @@ ptrace_capture_thread( ptrace_sp = (uint32_t)ptrace_ctx.uc_mcontext.gregs[REG_ESP]; # elif defined(__arm__) ptrace_sp = ptrace_ctx.uc_mcontext.arm_sp; +# elif defined(__riscv) && __riscv_xlen == 64 + ptrace_sp = ptrace_ctx.uc_mcontext.__gregs[REG_SP]; # endif if (ptrace_sp != 0) { @@ -1479,6 +1433,8 @@ write_thread_list_stream(minidump_writer_t *writer, minidump_directory_t *dir) sp = (uint32_t)uctx->uc_mcontext.gregs[REG_ESP]; # elif defined(__arm__) sp = uctx->uc_mcontext.arm_sp; +# elif defined(__riscv) && __riscv_xlen == 64 + sp = uctx->uc_mcontext.__gregs[REG_SP]; # endif SENTRY_DEBUGF("Thread %u: has context, SP=0x%llx", @@ -1542,6 +1498,7 @@ typedef struct { uint64_t end; // End of last mapping for this file char *name; // Pointer into mappings[].name (not owned) char soname[256]; // SONAME from ELF dynamic section (empty if not found) + uint64_t elf_offset; // File offset of the ELF image (non-zero in an APK) uint64_t elf_size; // Size from PT_LOAD segments (0 = use maps size) uint8_t build_id[32]; size_t build_id_len; @@ -1564,6 +1521,11 @@ typedef struct { * * base_of_image is set to the address of the offset==0 mapping — the real * ELF load address — which is what Breakpad/Crashpad/rust-minidump expect. + * + * Android maps uncompressed libraries straight from the APK, so one file can + * hold several ELF images. Such an image starts at the mapping whose file + * offset holds the ELF header, and its other segments are grouped by the + * image's load range instead of by file name. */ static size_t resolve_modules(const minidump_writer_t *writer, resolved_module_t *modules, @@ -1598,15 +1560,21 @@ resolve_modules(const minidump_writer_t *writer, resolved_module_t *modules, break; } } - if (already_skipped) { + // A non-ELF file can still hold ELF images at non-zero offsets. + if (already_skipped && mapping->offset == 0) { continue; } // Find an existing module entry by name. This merges across // non-contiguous /proc/maps lines — fixes duplicate ld-linux entries. + // An ELF image inside a larger file only owns its load range. resolved_module_t *mod = NULL; for (size_t j = 0; j < module_count; j++) { - if (strcmp(modules[j].name, mapping->name) == 0) { + if (strcmp(modules[j].name, mapping->name) == 0 + && (modules[j].elf_offset == 0 + || (mapping->start >= modules[j].base + && mapping->start + < modules[j].base + modules[j].elf_size))) { mod = &modules[j]; break; } @@ -1629,10 +1597,18 @@ resolve_modules(const minidump_writer_t *writer, resolved_module_t *modules, continue; } + // An ELF image can also start inside a larger file, such as a library + // that Android maps straight from an APK. + bool embedded = mapping->offset != 0 + && sentry__elf_is_file_at(mapping->name, mapping->offset); + if (!embedded && already_skipped) { + continue; + } + // First time we see this file — confirm it's actually an ELF before // adding it as a module. This drops sentry-native's own IPC shm, // deleted semaphores, and any other non-ELF named mapping. - if (!sentry__elf_is_file(mapping->name)) { + if (!embedded && !sentry__elf_is_file(mapping->name)) { if (skip_count < SENTRY_CRASH_MAX_MODULES) { skip_names[skip_count++] = mapping->name; } @@ -1649,15 +1625,18 @@ resolve_modules(const minidump_writer_t *writer, resolved_module_t *modules, mod->name = (char *)mapping->name; mod->base = mapping->start; mod->end = mapping->end; + mod->elf_offset = embedded ? mapping->offset : 0; + mod->elf_size + = sentry__elf_compute_size_from_phdrs(mod->name, mod->elf_offset); } - // Extract Build IDs, ELF sizes, and SONAMEs for each resolved module + // Extract Build IDs and SONAMEs for each resolved module for (size_t i = 0; i < module_count; i++) { - modules[i].build_id_len = extract_elf_build_id( - modules[i].name, modules[i].build_id, sizeof(modules[i].build_id)); - modules[i].elf_size = compute_elf_size_from_phdrs(modules[i].name); - if (!read_elf_soname(modules[i].name, modules[i].soname, - sizeof(modules[i].soname))) { + modules[i].build_id_len + = extract_elf_build_id(modules[i].name, modules[i].elf_offset, + modules[i].build_id, sizeof(modules[i].build_id)); + if (!read_elf_soname(modules[i].name, modules[i].elf_offset, + modules[i].soname, sizeof(modules[i].soname))) { modules[i].soname[0] = '\0'; } } @@ -2093,7 +2072,7 @@ linux_indirect_read_memory(void *ctx, uint64_t addr, void *buf, size_t len) struct iovec local_iov = { .iov_base = buf, .iov_len = len }; struct iovec remote_iov = { .iov_base = (void *)(uintptr_t)addr, .iov_len = len }; - return process_vm_readv(tid, &local_iov, 1, &remote_iov, 1, 0); + return sentry__process_vm_readv(tid, &local_iov, 1, &remote_iov, 1, 0); } /** @@ -2146,6 +2125,11 @@ walk_indirect_registers_for_tid(minidump_writer_t *writer, pid_t tid, sentry__indirect_consider(acc, base, (uint64_t)(uint32_t)uctx->uc_mcontext.gregs[x86_gprs[i]], ops); } +# elif defined(__riscv) && __riscv_xlen == 64 + for (int r = 1; r < 32; r++) { + sentry__indirect_consider( + acc, base, (uint64_t)uctx->uc_mcontext.__gregs[r], ops); + } # elif defined(__arm__) // ARMv7's mcontext fields are individual struct members rather than // an array; walk them explicitly. Most heap pointers we care about @@ -2217,12 +2201,105 @@ capture_indirect_memory( } } +static ssize_t +read_region( + minidump_writer_base_t *writer, uint64_t addr, void *buf, size_t size) +{ + return read_process_memory((minidump_writer_t *)writer, addr, buf, size); +} + +// Pages to query at a time +# define PAGE_QUERY_COUNT 1024 +// Pagemap entry bits of pages in memory or swap +# define PAGEMAP_IN_USE ((1ULL << 63) | (1ULL << 62)) + +/** + * Add the pages of a mapping that are in memory or swap to the list. Other + * pages were never touched and read back as zeros, or are still in the mapped + * file. Add the whole mapping if the pagemap is not available. + */ +static bool +add_mapping_pages(int pagemap, const memory_mapping_t *mapping, + minidump_memory64_list_t **list, uint64_t *capacity) +{ + uint64_t pages[PAGE_QUERY_COUNT]; + uint64_t page_size = (uint64_t)sysconf(_SC_PAGESIZE); + uint64_t address = mapping->start; + + while (address < mapping->end) { + uint64_t count = (mapping->end - address) / page_size; + if (count > PAGE_QUERY_COUNT) { + count = PAGE_QUERY_COUNT; + } + + ssize_t nread = pread(pagemap, pages, count * sizeof(pages[0]), + (off_t)(address / page_size * sizeof(pages[0]))); + if (nread < (ssize_t)sizeof(pages[0])) { + return sentry__minidump_add_range(list, capacity, mapping->start, + address, mapping->end - address); + } + + count = (uint64_t)nread / sizeof(pages[0]); + for (uint64_t i = 0; i < count; i++) { + if ((pages[i] & PAGEMAP_IN_USE) != 0 + && !sentry__minidump_add_range(list, capacity, mapping->start, + address + i * page_size, page_size)) { + return false; + } + } + address += count * page_size; + } + return true; +} + +/** + * Write memory64 list stream (all readable mappings) + */ +static int +write_memory64_list_stream(minidump_writer_t *writer, minidump_directory_t *dir) +{ + uint64_t capacity = writer->mapping_count; + minidump_memory64_list_t *list = sentry_malloc( + sizeof(*list) + capacity * sizeof(minidump_memory64_descriptor_t)); + if (!list) { + return -1; + } + + char pagemap_path[64]; + snprintf(pagemap_path, sizeof(pagemap_path), "/proc/%d/pagemap", + writer->crash_ctx->crashed_pid); + int pagemap = open(pagemap_path, O_RDONLY | O_CLOEXEC); + + bool added = true; + list->count = 0; + for (size_t i = 0; added && i < writer->mapping_count; i++) { + const memory_mapping_t *mapping = &writer->mappings[i]; + if (should_include_region(mapping, SENTRY_MINIDUMP_MODE_FULL, 0)) { + added = add_mapping_pages(pagemap, mapping, &list, &capacity); + } + } + if (pagemap >= 0) { + close(pagemap); + } + + int rv = added + ? sentry__minidump_write_memory64_list( + (minidump_writer_base_t *)writer, dir, list, read_region) + : -1; + sentry_free(list); + return rv; +} + /** * Write memory list stream (heap memory based on minidump mode) */ static int write_memory_list_stream(minidump_writer_t *writer, minidump_directory_t *dir) { + if (writer->crash_ctx->minidump_mode == SENTRY_MINIDUMP_MODE_FULL) { + return write_memory64_list_stream(writer, dir); + } + // Get crash address for SMART mode filtering uint64_t crash_addr = (uint64_t)(uintptr_t)writer->crash_ctx->platform.siginfo.si_addr; @@ -2865,30 +2942,33 @@ sentry__write_minidump( SENTRY_DEBUGF("crashed_pid=%d, crashed_tid=%d, num_threads=%zu", ctx->crashed_pid, ctx->crashed_tid, ctx->platform.num_threads); - minidump_writer_t writer = { 0 }; - writer.crash_ctx = ctx; + minidump_writer_t *writer = SENTRY_MAKE(minidump_writer_t); + if (!writer) { + SENTRY_WARN("failed to allocate minidump writer"); + return -1; + } + writer->crash_ctx = ctx; // Open output file. O_RDWR (not O_WRONLY) because SMART-mode indirect // memory capture pread()'s thread-stack bytes back from the dump after // they're written, so it can scan them for heap pointers. - writer.fd = open(output_path, O_RDWR | O_CREAT | O_TRUNC, 0600); - if (writer.fd < 0) { + writer->fd = open(output_path, O_RDWR | O_CREAT | O_TRUNC, 0600); + if (writer->fd < 0) { SENTRY_WARNF("failed to create minidump: %s", strerror(errno)); + sentry_free(writer); return -1; } // Parse process information - if (parse_proc_maps(&writer) < 0 || enumerate_threads(&writer) < 0) { - close(writer.fd); - unlink(output_path); - return -1; + if (parse_proc_maps(writer) < 0 || enumerate_threads(writer) < 0) { + goto cleanup_error; } // Attach to crashed process via ptrace early so we can: // 1. Read memory using ptrace for memory list stream // 2. Get FPU state for crashed thread via PTRACE_GETFPREGS // 3. Get registers for threads with missing context via PTRACE_GETREGS - if (!ptrace_attach_process(&writer)) { + if (!ptrace_attach_process(writer)) { SENTRY_WARN( "Failed to attach to process via ptrace, continuing without " "it"); @@ -2903,7 +2983,7 @@ sentry__write_minidump( // 1 ThreadList // 2 ModuleList // 3 Exception - // 4 MemoryList + // 4 MemoryList Memory64List in FULL mode // 5 LinuxProcStatus /proc//status // 6 LinuxMaps /proc//maps // 7 ThreadNames @@ -2920,20 +3000,15 @@ sentry__write_minidump( // fails the directory entry stays at type/size/rva = 0 (consumers ignore // it). const uint32_t stream_count = 14; - writer.current_offset = sizeof(minidump_header_t) + writer->current_offset = sizeof(minidump_header_t) + (stream_count * sizeof(minidump_directory_t)); SENTRY_DEBUGF("reserving space for %u streams, offset=%zu", stream_count, - writer.current_offset); + writer->current_offset); - if (lseek(writer.fd, writer.current_offset, SEEK_SET) < 0) { + if (lseek(writer->fd, writer->current_offset, SEEK_SET) < 0) { SENTRY_WARN("lseek failed"); - if (writer.ptrace_attached) { - ptrace(PTRACE_DETACH, ctx->crashed_tid, NULL, NULL); - } - close(writer.fd); - unlink(output_path); - return -1; + goto cleanup_error; } // Write streams @@ -2942,16 +3017,13 @@ sentry__write_minidump( int result = 0; SENTRY_DEBUG("writing system info stream"); - result |= write_system_info_stream(&writer, &directories[0]); + result |= write_system_info_stream(writer, &directories[0]); SENTRY_DEBUG("writing thread list stream"); - result |= write_thread_list_stream(&writer, &directories[1]); + result |= write_thread_list_stream(writer, &directories[1]); SENTRY_DEBUG("writing module list stream"); - result |= write_module_list_stream(&writer, &directories[2]); + result |= write_module_list_stream(writer, &directories[2]); SENTRY_DEBUG("writing exception stream"); - result |= write_exception_stream(&writer, &directories[3]); - - // Write memory list stream (empty for STACK_ONLY, populated for SMART/FULL) - result |= write_memory_list_stream(&writer, &directories[4]); + result |= write_exception_stream(writer, &directories[3]); // Write Linux-specific streams for debugger compatibility. // These are non-fatal: if they fail, the minidump is still valid. The @@ -2966,111 +3038,105 @@ sentry__write_minidump( } while (0) SENTRY_DEBUG("writing linux proc status stream"); - if (write_linux_proc_status_stream(&writer, &directories[5]) < 0) { + if (write_linux_proc_status_stream(writer, &directories[5]) < 0) { SENTRY_WARN("failed to write linux proc status stream"); NULLIFY_DIR_ENTRY(5, MINIDUMP_STREAM_LINUX_PROC_STATUS); } SENTRY_DEBUG("writing linux maps stream"); - if (write_linux_maps_stream(&writer, &directories[6]) < 0) { + if (write_linux_maps_stream(writer, &directories[6]) < 0) { SENTRY_WARN("failed to write linux maps stream"); NULLIFY_DIR_ENTRY(6, MINIDUMP_STREAM_LINUX_MAPS); } // Write thread names stream (matches Crashpad format) SENTRY_DEBUG("writing thread names stream"); - if (write_thread_names_stream(&writer, &directories[7]) < 0) { + if (write_thread_names_stream(writer, &directories[7]) < 0) { SENTRY_WARN("failed to write thread names stream"); NULLIFY_DIR_ENTRY(7, MINIDUMP_STREAM_THREAD_NAMES); } SENTRY_DEBUG("writing linux auxv stream"); - if (write_linux_auxv_stream(&writer, &directories[8]) < 0) { + if (write_linux_auxv_stream(writer, &directories[8]) < 0) { SENTRY_WARN("failed to write linux auxv stream"); NULLIFY_DIR_ENTRY(8, MINIDUMP_STREAM_LINUX_AUXV); } SENTRY_DEBUG("writing linux cpu info stream"); - if (write_linux_cpu_info_stream(&writer, &directories[9]) < 0) { + if (write_linux_cpu_info_stream(writer, &directories[9]) < 0) { SENTRY_DEBUG("linux cpu info stream unavailable"); NULLIFY_DIR_ENTRY(9, MINIDUMP_STREAM_LINUX_CPU_INFO); } SENTRY_DEBUG("writing linux lsb release stream"); - if (write_linux_lsb_release_stream(&writer, &directories[10]) < 0) { + if (write_linux_lsb_release_stream(writer, &directories[10]) < 0) { // Many distros don't ship /etc/lsb-release; this is expected. SENTRY_DEBUG("linux lsb release stream unavailable"); NULLIFY_DIR_ENTRY(10, MINIDUMP_STREAM_LINUX_LSB_RELEASE); } SENTRY_DEBUG("writing linux cmd line stream"); - if (write_linux_cmd_line_stream(&writer, &directories[11]) < 0) { + if (write_linux_cmd_line_stream(writer, &directories[11]) < 0) { SENTRY_DEBUG("linux cmd line stream unavailable"); NULLIFY_DIR_ENTRY(11, MINIDUMP_STREAM_LINUX_CMD_LINE); } SENTRY_DEBUG("writing linux environ stream"); - if (write_linux_environ_stream(&writer, &directories[12]) < 0) { + if (write_linux_environ_stream(writer, &directories[12]) < 0) { SENTRY_DEBUG("linux environ stream unavailable"); NULLIFY_DIR_ENTRY(12, MINIDUMP_STREAM_LINUX_ENVIRON); } SENTRY_DEBUG("writing linux dso debug stream"); - if (write_linux_dso_debug_stream(&writer, &directories[13]) < 0) { + if (write_linux_dso_debug_stream(writer, &directories[13]) < 0) { SENTRY_WARN("failed to write linux dso debug stream"); NULLIFY_DIR_ENTRY(13, MINIDUMP_STREAM_LINUX_DSO_DEBUG); } # undef NULLIFY_DIR_ENTRY + // Write memory list stream (empty for STACK_ONLY, populated for SMART/FULL) + // last, because FULL mode memory can extend past the 4GB RVA limit + result |= write_memory_list_stream(writer, &directories[4]); + if (result < 0) { - if (writer.ptrace_attached) { - ptrace(PTRACE_DETACH, ctx->crashed_tid, NULL, NULL); - } - close(writer.fd); - unlink(output_path); - return -1; + goto cleanup_error; } // Write header and directory at the beginning - if (lseek(writer.fd, 0, SEEK_SET) < 0) { - if (writer.ptrace_attached) { - ptrace(PTRACE_DETACH, ctx->crashed_tid, NULL, NULL); - } - close(writer.fd); - unlink(output_path); - return -1; + if (lseek(writer->fd, 0, SEEK_SET) < 0) { + goto cleanup_error; } - if (write_header(&writer, stream_count) < 0) { - if (writer.ptrace_attached) { - ptrace(PTRACE_DETACH, ctx->crashed_tid, NULL, NULL); - } - close(writer.fd); - unlink(output_path); - return -1; + if (write_header(writer, stream_count) < 0) { + goto cleanup_error; } // Write only the directory entries we actually used size_t dir_size = stream_count * sizeof(minidump_directory_t); - if (write(writer.fd, directories, dir_size) != (ssize_t)dir_size) { - if (writer.ptrace_attached) { - ptrace(PTRACE_DETACH, ctx->crashed_tid, NULL, NULL); - } - close(writer.fd); - unlink(output_path); - return -1; + if (write(writer->fd, directories, dir_size) != (ssize_t)dir_size) { + goto cleanup_error; } - close(writer.fd); + close(writer->fd); // Detach from process if we attached - if (writer.ptrace_attached) { + if (writer->ptrace_attached) { ptrace(PTRACE_DETACH, ctx->crashed_tid, NULL, NULL); SENTRY_DEBUGF("Detached from thread %d", ctx->crashed_tid); } + sentry_free(writer); SENTRY_DEBUG("successfully wrote minidump"); return 0; + +cleanup_error: + if (writer->ptrace_attached) { + ptrace(PTRACE_DETACH, ctx->crashed_tid, NULL, NULL); + } + close(writer->fd); + unlink(output_path); + sentry_free(writer); + return -1; } #endif // SENTRY_PLATFORM_LINUX || SENTRY_PLATFORM_ANDROID diff --git a/src/backends/native/minidump/sentry_minidump_macos.c b/src/backends/native/minidump/sentry_minidump_macos.c index f1456f5f6a..d1b252e1fc 100644 --- a/src/backends/native/minidump/sentry_minidump_macos.c +++ b/src/backends/native/minidump/sentry_minidump_macos.c @@ -9,6 +9,7 @@ # include # include # include +# include # include # include # include @@ -1265,9 +1266,13 @@ should_include_region_macos(const memory_region_t *region, return false; } - // FULL: Include all readable regions + // FULL: Include all readable regions, except for the shared region. That + // holds the dyld shared cache, gigabytes of system libraries shared + // between processes. if (mode == SENTRY_MINIDUMP_MODE_FULL) { - return (region->protection & VM_PROT_READ) != 0; + bool shared = region->address >= SHARED_REGION_BASE + && region->address < SHARED_REGION_BASE + SHARED_REGION_SIZE; + return (region->protection & VM_PROT_READ) != 0 && !shared; } // SMART: Include only regions containing the crash address, matching the @@ -1526,6 +1531,103 @@ capture_indirect_memory_macos( } } +/** + * Clean up the capture file written by the signal handler since we used VM + * regions instead. + */ +static void +remove_module_headers_capture(const minidump_writer_t *writer) +{ + const char *run_path = writer->crash_ctx->run_path; + size_t run_len = strlen(run_path); + char hdr_path[SENTRY_CRASH_MAX_PATH]; + if (run_len + 22 < sizeof(hdr_path)) { + snprintf( + hdr_path, sizeof(hdr_path), "%s/__sentry-modheaders", run_path); + unlink(hdr_path); + } +} + +static ssize_t +read_region( + minidump_writer_base_t *writer, uint64_t addr, void *buf, size_t size) +{ + kern_return_t kr = read_task_memory( + ((minidump_writer_t *)writer)->task, addr, buf, size); + return kr == KERN_SUCCESS ? (ssize_t)size : -1; +} + +// Pages to query at a time +# define PAGE_QUERY_COUNT 1024 + +/** + * Add the pages of a region to the list, except for anonymous pages that were + * never touched. Those have no disposition and read back as zeros, and + * allocators reserve hundreds of megabytes of them. + */ +static bool +add_region_pages(minidump_writer_t *writer, const memory_region_t *region, + minidump_memory64_list_t **list, uint64_t *capacity) +{ + int pages[PAGE_QUERY_COUNT]; + uint64_t address = region->address; + uint64_t end = region->address + region->size; + + while (address < end) { + uint64_t size = PAGE_QUERY_COUNT * vm_page_size; + if (size > end - address) { + size = end - address; + } + + mach_vm_size_t count = PAGE_QUERY_COUNT; + kern_return_t kr = mach_vm_page_range_query(writer->task, address, size, + (mach_vm_address_t)(uintptr_t)pages, &count); + if (kr != KERN_SUCCESS) { + return sentry__minidump_add_range( + list, capacity, region->address, address, end - address); + } + + for (mach_vm_size_t i = 0; i < count; i++) { + if (pages[i] != 0 + && !sentry__minidump_add_range(list, capacity, region->address, + address + i * vm_page_size, vm_page_size)) { + return false; + } + } + address += size; + } + return true; +} + +/** + * Write memory64 list stream with all readable regions. + */ +static int +write_memory64_list_stream(minidump_writer_t *writer, minidump_directory_t *dir) +{ + uint64_t capacity = writer->region_count; + minidump_memory64_list_t *list = sentry_malloc( + sizeof(*list) + capacity * sizeof(minidump_memory64_descriptor_t)); + if (!list) { + return -1; + } + + list->count = 0; + for (size_t i = 0; i < writer->region_count; i++) { + const memory_region_t *region = &writer->regions[i]; + if (should_include_region_macos(region, writer->crash_ctx, 0) + && !add_region_pages(writer, region, &list, &capacity)) { + sentry_free(list); + return -1; + } + } + + int rv = sentry__minidump_write_memory64_list( + (minidump_writer_base_t *)writer, dir, list, read_region); + sentry_free(list); + return rv; +} + /** * Write memory list stream with memory based on minidump mode. * @@ -1551,6 +1653,12 @@ write_memory_list_stream(minidump_writer_t *writer, minidump_directory_t *dir) // When we have VM regions (task_for_pid succeeded), use them if (writer->region_count > 0) { + if (mode == SENTRY_MINIDUMP_MODE_FULL) { + int rv = write_memory64_list_stream(writer, dir); + remove_module_headers_capture(writer); + return rv; + } + // SMART mode: scan registers + stack words for pointers into // writable heap regions and capture a chunk around each. Has to // run before the memory_list allocation below so we know the @@ -1670,16 +1778,7 @@ write_memory_list_stream(minidump_writer_t *writer, minidump_directory_t *dir) sentry_free(memory_list); - // Clean up the capture file written by the signal handler since - // we used VM regions instead. - const char *run_path = writer->crash_ctx->run_path; - size_t run_len = strlen(run_path); - char hdr_path[SENTRY_CRASH_MAX_PATH]; - if (run_len + 22 < sizeof(hdr_path)) { - snprintf( - hdr_path, sizeof(hdr_path), "%s/__sentry-modheaders", run_path); - unlink(hdr_path); - } + remove_module_headers_capture(writer); return dir->rva ? 0 : -1; } @@ -1755,6 +1854,10 @@ sentry__write_minidump( SENTRY_DEBUGF("write_minidump: task_for_pid failed (%d), writing " "minimal minidump", kr); + if (ctx->minidump_mode == SENTRY_MINIDUMP_MODE_FULL) { + SENTRY_WARN("write_minidump: full memory capture requires " + "task_for_pid access"); + } // Without task port, write minimal minidump with all required streams // Matching Crashpad's minimum: SystemInfo, MiscInfo, ThreadList, // Exception, ModuleList, MemoryList. We additionally emit ThreadNames @@ -1867,6 +1970,11 @@ sentry__write_minidump( return -1; } + // Suspend the process during FULL captures, which can outlast the crash + // handler's wait for the daemon + bool suspended = ctx->minidump_mode == SENTRY_MINIDUMP_MODE_FULL + && task_suspend(writer.task) == KERN_SUCCESS; + // Enumerate memory regions enumerate_memory_regions(&writer); @@ -1891,7 +1999,6 @@ sentry__write_minidump( result |= write_thread_list_stream(&writer, &directories[2]); result |= write_exception_stream(&writer, &directories[3]); result |= write_module_list_stream(&writer, &directories[4]); - result |= write_memory_list_stream(&writer, &directories[5]); if (result < 0) { goto cleanup_error; @@ -1904,6 +2011,12 @@ sentry__write_minidump( directories[6].data_size = 0; } + // Write memory list last, because FULL mode memory can extend past the 4GB + // RVA limit + if (write_memory_list_stream(&writer, &directories[5]) < 0) { + goto cleanup_error; + } + // Write header and directory if (lseek(writer.fd, 0, SEEK_SET) < 0) { goto cleanup_error; @@ -1919,6 +2032,9 @@ sentry__write_minidump( } // Cleanup - success path + if (suspended) { + task_resume(writer.task); + } for (mach_msg_type_number_t i = 0; i < writer.thread_count; i++) { mach_port_deallocate(mach_task_self(), writer.threads[i]); } @@ -1933,6 +2049,9 @@ sentry__write_minidump( cleanup_error: // Cleanup - error path (same as success, but delete file and return error) + if (suspended) { + task_resume(writer.task); + } for (mach_msg_type_number_t i = 0; i < writer.thread_count; i++) { mach_port_deallocate(mach_task_self(), writer.threads[i]); } diff --git a/src/backends/native/minidump/sentry_minidump_windows.c b/src/backends/native/minidump/sentry_minidump_windows.c index 6ab23965fa..f32a6307bd 100644 --- a/src/backends/native/minidump/sentry_minidump_windows.c +++ b/src/backends/native/minidump/sentry_minidump_windows.c @@ -15,7 +15,7 @@ * On Xbox, MiniDumpWriteDump is provided by xgameplatform.lib * (linked by the Xbox toolchain), not dbghelp.lib. */ -# if !defined(SENTRY_PLATFORM_XBOX) +# if defined(_MSC_VER) && !defined(SENTRY_PLATFORM_XBOX) # pragma comment(lib, "dbghelp.lib") # endif diff --git a/src/backends/native/sentry_crash_context.h b/src/backends/native/sentry_crash_context.h index b0d5543ef2..8a64cf6a36 100644 --- a/src/backends/native/sentry_crash_context.h +++ b/src/backends/native/sentry_crash_context.h @@ -9,7 +9,10 @@ #include "sentry.h" // For sentry_minidump_mode_t #include "sentry_boot.h" +#include "sentry_os.h" #include "sentry_sync.h" +#include "sentry_utils.h" +#include "sentry_value.h" #include #include @@ -39,6 +42,14 @@ typedef DWORD pid_t; #define SENTRY_CRASH_MAX_THREADS 256 #define SENTRY_CRASH_MAX_MODULES 2048 #define SENTRY_CRASH_MAX_MAPPINGS 4096 +// Max frames for pre-captured backtrace (crash handler -> daemon) +#define SENTRY_CRASH_MAX_BACKTRACE_FRAMES 128 + +typedef struct { + uint32_t count; + uint8_t frame_pointer; + uint64_t ips[SENTRY_CRASH_MAX_BACKTRACE_FRAMES]; +} sentry_crash_capture_t; // Max path length in crash context // Use system PATH_MAX where available (typically 4096 on Linux/macOS, 260 on @@ -144,14 +155,13 @@ typedef struct { uint32_t pdb_age; // PDB age (Windows PE only, appended to debug_id) #if defined(SENTRY_PLATFORM_WINDOWS) char pdb_name[SENTRY_CRASH_MAX_PATH]; // PDB filename (Windows PE only) +#elif defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) + uint64_t elf_offset; // File offset of the ELF image (non-zero in an APK) #endif } sentry_module_info_t; #if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) -// Max frames for pre-captured backtrace (signal handler -> daemon) -# define SENTRY_CRASH_MAX_BACKTRACE_FRAMES 128 - /** * Linux/Android thread context */ @@ -170,12 +180,6 @@ typedef struct { siginfo_t siginfo; ucontext_t context; - // Pre-captured backtrace from signal handler using libunwind (DWARF-based). - // This works without frame pointers, unlike the daemon's FP-based walking. - // The daemon prefers this over FP-walking when backtrace_count > 0. - size_t backtrace_count; - uint64_t backtrace_ips[SENTRY_CRASH_MAX_BACKTRACE_FRAMES]; - // Additional thread contexts (for multi-thread dumps) size_t num_threads; sentry_thread_context_linux_t threads[SENTRY_CRASH_MAX_THREADS]; @@ -324,12 +328,15 @@ typedef struct { sentry_crash_platform_windows_t platform; #endif + // Fault-context capture, callee-first; failed capture may contain the IP. + // On Linux, libunwind captures using DWARF without frame pointers. + // The daemon prefers captures over its own stack walk. + sentry_crash_capture_t capture; + bool event_discarded; + // Sentry-specific metadata paths char database_path[SENTRY_CRASH_MAX_PATH]; // Shared across runs char run_path[SENTRY_CRASH_MAX_PATH]; // For current run - char event_path[SENTRY_CRASH_MAX_PATH]; - char breadcrumb1_path[SENTRY_CRASH_MAX_PATH]; - char breadcrumb2_path[SENTRY_CRASH_MAX_PATH]; char envelope_path[SENTRY_CRASH_MAX_PATH]; char external_reporter_path[SENTRY_CRASH_MAX_PATH]; char dsn[SENTRY_CRASH_MAX_PATH]; // Sentry DSN for uploading crashes @@ -376,4 +383,96 @@ sentry__crash_context_init(sentry_crash_context_t *ctx) // Add 8KB padding for safety and future additions #define SENTRY_CRASH_SHM_SIZE (sizeof(sentry_crash_context_t) + (8 * 1024)) +static inline sentry_value_t +sentry__crash_context_build_stacktrace( + const sentry_crash_context_t *ctx, sentry_value_t registers) +{ + const sentry_crash_capture_t *capture = &ctx->capture; + size_t count = capture->count; + if (count == 0) { + sentry_value_decref(registers); + return sentry_value_new_null(); + } + if (count > SENTRY_CRASH_MAX_BACKTRACE_FRAMES) { + count = SENTRY_CRASH_MAX_BACKTRACE_FRAMES; + } + sentry_value_t stacktrace = sentry_value_new_object(); + sentry_value_t frames = sentry_value_new_list(); + // Sentry expects frames in reverse order (outermost caller first) + for (size_t i = count; i > 0; i--) { + sentry_value_t frame = sentry_value_new_object(); + sentry_value_set_by_key(frame, "instruction_addr", + sentry__value_new_addr(capture->ips[i - 1])); + // Trust describes the unwind source, not the emitted frame index. + sentry_value_set_by_key(frame, "trust", + sentry_value_new_string(i == 1 ? "context" + : capture->frame_pointer ? "fp" + : "cfi")); + sentry_value_append(frames, frame); + } + sentry_value_set_by_key(stacktrace, "frames", frames); + sentry_value_set_by_key(stacktrace, "registers", registers); +#if defined(SENTRY_PLATFORM_MACOS) + // the SDK's macOS unwinder already adjusts return addresses + sentry_value_set_by_key(stacktrace, "instruction_addr_adjustment", + sentry_value_new_string("none")); +#endif + return stacktrace; +} + +static inline sentry_value_t +sentry__crash_context_build_exception(const sentry_crash_context_t *ctx, + const char *mechanism_type, bool handled, sentry_value_t stacktrace) +{ + // Build exception +#if defined(SENTRY_PLATFORM_UNIX) + int signal_number = ctx->platform.signum; + const char *signal_name = sentry__signal_to_string(signal_number); +#elif defined(SENTRY_PLATFORM_WINDOWS) + // Exception code is used directly below as unsigned + const char *signal_name = "EXCEPTION"; +#else +# error Unsupported platform +#endif + + // Avoid snprintf in signal handlers (not async-signal-safe) + char value_buf[128] = "Fatal crash: "; + size_t prefix_len = sizeof("Fatal crash: ") - 1; + size_t len = MIN(strlen(signal_name), sizeof(value_buf) - prefix_len - 1); + memcpy(value_buf + prefix_len, signal_name, len); + value_buf[prefix_len + len] = '\0'; + sentry_value_t exc = sentry_value_new_exception(signal_name, value_buf); + + // Add mechanism + sentry_value_t mechanism = sentry_value_new_object(); + sentry_value_set_by_key( + mechanism, "type", sentry_value_new_string(mechanism_type)); + sentry_value_set_by_key( + mechanism, "synthetic", sentry_value_new_bool(true)); + sentry_value_set_by_key( + mechanism, "handled", sentry_value_new_bool(handled)); + // Add signal metadata + sentry_value_t meta = sentry_value_new_object(); + sentry_value_t signal_info = sentry_value_new_object(); +#if defined(SENTRY_PLATFORM_WINDOWS) + // Windows exception codes are unsigned 32-bit values (e.g., 0xC0000005) + // Use uint64 to preserve the unsigned value for the symbolicator + sentry_value_set_by_key(signal_info, "number", + sentry_value_new_uint64((uint64_t)ctx->platform.exception_code)); +#else + sentry_value_set_by_key( + signal_info, "number", sentry_value_new_int32(signal_number)); +#endif + sentry_value_set_by_key( + signal_info, "name", sentry_value_new_string(signal_name)); + sentry_value_set_by_key(meta, "signal", signal_info); + sentry_value_set_by_key(mechanism, "meta", meta); + sentry_value_set_by_key(exc, "mechanism", mechanism); + // Add stacktrace to exception + if (!sentry_value_is_null(stacktrace)) { + sentry_value_set_by_key(exc, "stacktrace", stacktrace); + } + return exc; +} + #endif diff --git a/src/backends/native/sentry_crash_daemon.c b/src/backends/native/sentry_crash_daemon.c index 83646be50d..fe808c3be0 100644 --- a/src/backends/native/sentry_crash_daemon.c +++ b/src/backends/native/sentry_crash_daemon.c @@ -4,6 +4,7 @@ #include "sentry_alloc.h" #include "sentry_attachment.h" #include "sentry_core.h" +#include "sentry_crash_handler.h" #include "sentry_crash_ipc.h" #include "sentry_database.h" #include "sentry_elf.h" @@ -20,6 +21,7 @@ #include "sentry_symbolizer.h" #include "sentry_sync.h" #include "sentry_transport.h" +#include "sentry_unix_pageallocator.h" #include "sentry_utils.h" #include "sentry_uuid.h" #include "sentry_value.h" @@ -39,6 +41,7 @@ # include # include # include +# include # include # include # include @@ -93,11 +96,12 @@ typedef struct { bool write; bool exec; } vma_range_t; -static vma_range_t *g_vmas = NULL; -static size_t g_vma_count = 0; -static size_t g_vma_capacity = 0; -static bool g_vma_alloc_failed = false; -static bool g_vma_complete = false; +// per daemon thread, the Android crash service hosts several in one process +static __thread vma_range_t *g_vmas = NULL; +static __thread size_t g_vma_count = 0; +static __thread size_t g_vma_capacity = 0; +static __thread bool g_vma_alloc_failed = false; +static __thread bool g_vma_complete = false; static bool vma_record(uint64_t start, uint64_t end, const char *perms) @@ -203,6 +207,90 @@ static size_t walk_stack_with_dbghelp(HANDLE hProcess, DWORD crashed_tid, sentry_frame_info_t *frames, size_t max_frames); #endif +#if defined(SENTRY_PLATFORM_ANDROID) +// matches io.sentry.ndk.SentryNdk.CrashDaemon.SendResult +typedef enum { + SENTRY_ANDROID_SEND_FAILED, + SENTRY_ANDROID_SEND_SENT, + SENTRY_ANDROID_SEND_KEPT, +} sentry_android_send_result_t; + +struct sentry_crash_daemon_s { + sentry_options_t *options; + sentry_crash_ipc_t *ipc; + sentry_transport_t *transport; + FILE *log_file; + char envelope_path[SENTRY_CRASH_MAX_PATH]; + bool transport_shutdown; + sentry_value_t event; +}; + +static void android_cleanup_pending_crash_daemon( + sentry_crash_daemon_t *daemon, bool discard_envelope); + +static pthread_once_t g_android_logcat_once = PTHREAD_ONCE_INIT; + +// daemons in one crash service process share the global logger +static void +android_install_logcat_logger(void) +{ + sentry_logger_t logger = { .logger_func = sentry__logger_defaultlogger, + .logger_data = NULL, + .logger_level = SENTRY_LEVEL_DEBUG }; + sentry__logger_set_global(logger); +} + +__attribute__((visibility("default"))) sentry_crash_daemon_t * +sentry_android_crash_daemon_run(pid_t app_pid, uint64_t app_tid, int notify_fd, + int ready_fd, int message_fd, int shm_fd, sentry_transport_t *transport) +{ + if (!transport || shm_fd < 0) { + goto fail; + } + + // app configuration must be complete before attaching to shm + sentry_crash_ipc_t ipc = { .notify_fd = notify_fd }; + if (!sentry__crash_ipc_wait(&ipc, SENTRY_CRASH_DAEMON_READY_TIMEOUT_MS)) { + goto fail; + } + + sentry_crash_daemon_t *daemon = SENTRY_MAKE(sentry_crash_daemon_t); + if (!daemon) { + goto fail; + } + daemon->transport = transport; + daemon->event = sentry_value_new_null(); + + int rv = sentry__crash_daemon_main( + app_pid, app_tid, notify_fd, ready_fd, shm_fd, message_fd, daemon); + + if (rv != 0 || !daemon->envelope_path[0]) { + android_cleanup_pending_crash_daemon(daemon, true); + return NULL; + } + + return daemon; + +fail: + // the daemon owns the fds, even when it does not start + close(notify_fd); + close(ready_fd); + close(message_fd); + if (shm_fd >= 0) { + close(shm_fd); + } + sentry_transport_free(transport); + return NULL; +} + +__attribute__((visibility("default"))) const char * +sentry_android_crash_daemon_get_envelope_path( + const sentry_crash_daemon_t *daemon) +{ + return daemon->envelope_path; +} +#endif + // Provide default ASAN options for sentry-crash daemon executable // This suppresses false positives from fork() which ASAN doesn't handle well #if defined(__has_feature) @@ -375,7 +463,7 @@ read_legacy_manifest(const sentry_path_t *manifest_path) size_t buf_len = 0; char *buf = sentry__path_read_to_buffer(manifest_path, &buf_len); if (!buf) { - return sentry_value_new_list(); + return sentry_value_new_null(); } const char *start = buf; @@ -445,42 +533,61 @@ read_attachment_manifest(const sentry_path_t *run_folder) return attachments; } -static void -write_attachments_from_manifest( - int fd, const sentry_options_t *options, const sentry_path_t *run_folder) +static sentry_value_t +read_crash_event(const sentry_path_t *run_folder) { - sentry_value_t attachments = read_attachment_manifest(run_folder); - size_t len = sentry_value_get_length(attachments); - for (size_t i = 0; i < len; i++) { - sentry_value_t attachment = sentry_value_get_by_index(attachments, i); - const char *path = sentry__attachment_get_path(attachment); - if (!attachment_is_placeholder(options, path)) { - write_attachment_to_envelope(fd, path, - sentry__attachment_get_filename(attachment), - sentry__attachment_get_type(attachment), - sentry__attachment_get_content_type(attachment)); - } + sentry_path_t *path = sentry__path_join_str(run_folder, "__sentry-event"); + if (!path) { + return sentry_value_new_null(); } - sentry_value_decref(attachments); + size_t len = 0; + char *buf = sentry__path_read_to_buffer(path, &len); + sentry__path_free(path); + if (!buf) { + return sentry_value_new_null(); + } + sentry_value_t event = sentry_value_from_json(buf, len); + sentry_free(buf); + if (sentry_value_get_type(event) != SENTRY_VALUE_TYPE_OBJECT) { + sentry_value_decref(event); + return sentry_value_new_null(); + } + return event; } +#if defined(SENTRY_PLATFORM_ANDROID) +static sentry_path_t * +make_run_envelope_path( + const sentry_run_t *run, const sentry_envelope_t *envelope) +{ + if (!run || !envelope || !run->run_path) { + return NULL; + } + + sentry_uuid_t event_id = sentry__envelope_get_event_id(envelope); + if (sentry_uuid_is_nil(&event_id)) { + return NULL; + } + + char *filename = sentry__uuid_as_filename(&event_id, ".envelope"); + if (!filename) { + return NULL; + } -// For each large attachment listed in `/__sentry-attachments`, -// cache it as an attachment-ref item. Small attachments were already inlined -// during envelope writing. + sentry_path_t *path = sentry__path_join_str(run->run_path, filename); + sentry_free(filename); + return path; +} +#endif + +// cache large staged attachments as attachment-ref items static void add_attachment_refs(sentry_envelope_t *envelope, - const sentry_options_t *options, const sentry_path_t *run_folder) + const sentry_options_t *options, sentry_value_t list) { if (!envelope || !options || !options->run - || !options->enable_large_attachments || !run_folder) { + || !options->enable_large_attachments) { return; } - sentry_value_t list = read_attachment_manifest(run_folder); - if (sentry_value_is_null(list)) { - SENTRY_WARN("Failed to parse attachment manifest"); - return; - } - bool materialized = false; size_t len = sentry_value_get_length(list); for (size_t i = 0; i < len; i++) { @@ -498,36 +605,23 @@ add_attachment_refs(sentry_envelope_t *envelope, SENTRY_WARN("failed to cache attachment-ref"); } } - sentry_value_decref(list); } -#if defined(SENTRY_PLATFORM_UNIX) -/** - * Get signal name from signal number (Unix platforms only) - */ -static const char * -get_signal_name(int signum) +// cache a large minidump as an attachment-ref item +static void +add_minidump_ref(sentry_envelope_t *envelope, const sentry_options_t *options, + const char *path, const sentry_path_t *run_folder) { - switch (signum) { - case SIGABRT: - return "SIGABRT"; - case SIGBUS: - return "SIGBUS"; - case SIGFPE: - return "SIGFPE"; - case SIGILL: - return "SIGILL"; - case SIGSEGV: - return "SIGSEGV"; - case SIGSYS: - return "SIGSYS"; - case SIGTRAP: - return "SIGTRAP"; - default: - return "UNKNOWN"; + sentry_value_t attachment = sentry__attachment_from_file(path); + sentry_attachment_set_filename(attachment, "minidump.dmp"); + sentry_attachment_set_type(attachment, SENTRY_ATTACHMENT_TYPE_MINIDUMP); + if (!sentry__envelope_materialize(envelope) + || !sentry__cache_attachment_ref( + envelope, attachment, options->run->cache_path, run_folder)) { + SENTRY_WARN("failed to cache minidump attachment-ref"); } + sentry_value_decref(attachment); } -#endif /** * Build registers value from crash context for a specific thread. @@ -568,7 +662,8 @@ build_registers_from_ctx(const sentry_crash_context_t *ctx, size_t thread_idx) return sentry__build_registers(&uctx); } -#ifdef SENTRY_WITH_UNWINDER_LIBUNWIND_REMOTE +#if defined(SENTRY_WITH_UNWINDER_LIBUNWIND_REMOTE) \ + || defined(SENTRY_WITH_UNWINDER_LIBUNWINDSTACK_REMOTE) static sentry_value_t build_registers_from_remote_registers( const sentry_remote_registers_t *remote_registers) @@ -718,8 +813,55 @@ enrich_frame_with_module_info( || defined(SENTRY_PLATFORM_MACOS) static void enrich_frame_with_symbol( const sentry_crash_context_t *ctx, sentry_value_t frame, uint64_t addr); +#elif defined(SENTRY_PLATFORM_WINDOWS) +static void +enrich_frame_with_symbol( + const sentry_crash_context_t *ctx, sentry_value_t frame, uint64_t addr) +{ + if (!ctx->symbolize_stacktraces || !g_stack_walk_process) { + return; + } + const size_t size = sizeof(SYMBOL_INFOW) + MAX_SYM_NAME * sizeof(WCHAR); + SYMBOL_INFOW *symbol = sentry_malloc(size); + if (!symbol) { + return; + } + memset(symbol, 0, size); + symbol->SizeOfStruct = sizeof(SYMBOL_INFOW); + symbol->MaxNameLen = MAX_SYM_NAME; + if (SymFromAddrW(g_stack_walk_process, addr, NULL, symbol) + && !(symbol->Flags & SYMFLAG_EXPORT)) { + char *name = sentry__string_from_wstr(symbol->Name); + if (name) { + sentry_value_set_by_key( + frame, "function", sentry_value_new_string(name)); + sentry_free(name); + } + sentry_value_set_by_key( + frame, "symbol_addr", sentry__value_new_addr(symbol->Address)); + } + sentry_free(symbol); +} #endif +static void enrich_stacktrace( + const sentry_crash_context_t *ctx, sentry_value_t stacktrace); + +/** + * Does the handler's capture hold the crashed thread's stack? The fault IP + * alone does not count with libunwindstack, which can unwind the saved context. + */ +static bool +has_captured_stack(const sentry_crash_context_t *ctx) +{ +#ifdef SENTRY_WITH_UNWINDER_LIBUNWINDSTACK_REMOTE + return ctx->capture.count > 1; +#else + return ctx->capture.count > 1 + || (ctx->capture.count == 1 && ctx->capture.ips[0] != 0); +#endif +} + /** * Build stacktrace frames for a specific thread using frame pointer-based * unwinding. Reads the captured stack memory and walks the frame chain. @@ -733,6 +875,13 @@ static sentry_value_t build_stacktrace_for_thread( const sentry_crash_context_t *ctx, size_t thread_idx) { + if (thread_idx == SIZE_MAX && has_captured_stack(ctx)) { + sentry_value_t captured = sentry__crash_context_build_stacktrace( + ctx, build_registers_from_ctx(ctx, SIZE_MAX)); + enrich_stacktrace(ctx, captured); + return captured; + } + sentry_value_t stacktrace = sentry_value_new_object(); sentry_value_t frames = sentry_value_new_list(); @@ -768,6 +917,10 @@ build_stacktrace_for_thread( ip = (uint64_t)thread_context->uc_mcontext.arm_pc; fp = (uint64_t)thread_context->uc_mcontext.arm_fp; sp = (uint64_t)thread_context->uc_mcontext.arm_sp; +# elif defined(__riscv) && __riscv_xlen == 64 + ip = (uint64_t)thread_context->uc_mcontext.__gregs[REG_PC]; + fp = (uint64_t)thread_context->uc_mcontext.__gregs[REG_S0]; + sp = (uint64_t)thread_context->uc_mcontext.__gregs[REG_SP]; # endif #elif defined(SENTRY_PLATFORM_MACOS) # if defined(__x86_64__) @@ -888,7 +1041,8 @@ build_stacktrace_for_thread( } #elif defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) // On Linux, use process_vm_readv to read stack memory from crashed process - if (ctx->platform.num_threads > 0) { + // (threads enumerated from /proc have no registers) + if (ctx->platform.num_threads > 0 && sp != 0) { pid_t pid = ctx->crashed_pid; stack_size = SENTRY_CRASH_MAX_STACK_CAPTURE; stack_start = sp; @@ -899,11 +1053,12 @@ build_stacktrace_for_thread( struct iovec remote_iov = { .iov_base = (void *)(uintptr_t)stack_start, .iov_len = stack_size }; - ssize_t bytes_read - = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0); + ssize_t bytes_read = sentry__process_vm_readv( + pid, &local_iov, 1, &remote_iov, 1, 0); if (bytes_read <= 0) { - SENTRY_DEBUG( - "process_vm_readv failed, falling back to single frame"); + SENTRY_DEBUGF("process_vm_readv failed for %d: %s, falling " + "back to single frame", + pid, strerror(errno)); sentry_free(stack_buf); stack_buf = NULL; } else { @@ -994,10 +1149,11 @@ build_stacktrace_for_thread( int frame_count = 0; #if defined(SENTRY_PLATFORM_LINUX) - // Remote DWARF unwinding via libunwind ptrace accessors. Do not attach to - // the crashed thread from the daemon; use the saved fault context below. + // Remote DWARF unwinding. Do not attach to the crashed thread from the + // daemon. Unwind its saved fault context instead. { -# ifdef SENTRY_WITH_UNWINDER_LIBUNWIND_REMOTE +# if defined(SENTRY_WITH_UNWINDER_LIBUNWIND_REMOTE) \ + || defined(SENTRY_WITH_UNWINDER_LIBUNWINDSTACK_REMOTE) pid_t tid = 0; if (thread_idx == SIZE_MAX) { tid = ctx->crashed_tid; @@ -1008,13 +1164,15 @@ build_stacktrace_for_thread( bool is_crashed_thread = thread_idx == SIZE_MAX || tid == ctx->crashed_tid; - if (tid > 0 && !is_crashed_thread) { + if (tid > 0) { sentry_remote_registers_t registers = { 0 }; sentry_remote_frame_t *remote_frames = sentry_malloc(sizeof(*remote_frames) * MAX_STACK_FRAMES); size_t remote_count = remote_frames - ? sentry__unwind_stack_from_thread(tid, remote_frames, - MAX_STACK_FRAMES, ®isters, ctx->symbolize_stacktraces) + ? sentry__unwind_stack_from_thread(tid, + is_crashed_thread ? &ctx->platform.context : NULL, + remote_frames, MAX_STACK_FRAMES, ®isters, + ctx->symbolize_stacktraces) : 0; if (remote_count > 0) { @@ -1067,6 +1225,12 @@ build_stacktrace_for_thread( sentry_value_set_by_key(stacktrace, "registers", build_registers_from_remote_registers(®isters)); } +# ifdef SENTRY_WITH_UNWINDER_LIBUNWINDSTACK_REMOTE + // libunwindstack already adjusts the caller frames + sentry_value_set_by_key(stacktrace, + "instruction_addr_adjustment", + sentry_value_new_string("none")); +# endif sentry_free(remote_frames); return stacktrace; } @@ -1082,57 +1246,6 @@ build_stacktrace_for_thread( // unwinding failed #endif -#if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) - // Fallback: use pre-captured libunwind backtrace if available - // (DWARF-based, works without frame pointers). - if (ctx->platform.backtrace_count > 0 - && (thread_idx == SIZE_MAX || thread_idx == 0)) { - SENTRY_DEBUGF("Using pre-captured libunwind backtrace (%zu frames)", - ctx->platform.backtrace_count); - - for (size_t i = 0; - i < ctx->platform.backtrace_count && frame_count < MAX_STACK_FRAMES; - i++) { - uint64_t frame_ip = ctx->platform.backtrace_ips[i]; - if (frame_ip == 0 || !is_valid_code_addr(frame_ip)) { - continue; - } - temp_frames[frame_count] = sentry_value_new_object(); - sentry_value_set_by_key(temp_frames[frame_count], - "instruction_addr", sentry__value_new_addr(frame_ip)); - // Trust describes the unwind source, not the emitted frame index. - // If the initial cursor frame is filtered out, the next emitted - // frame was still reached via CFI. - sentry_value_set_by_key(temp_frames[frame_count], "trust", - sentry_value_new_string(i == 0 ? "context" : "cfi")); - enrich_frame_with_module_info( - ctx, temp_frames[frame_count], frame_ip); - enrich_frame_with_symbol(ctx, temp_frames[frame_count], frame_ip); - frame_count++; - } - - if (stack_buf) { - sentry_free(stack_buf); - } - - if (frame_count == 0) { - sentry_value_decref(frames); - sentry_value_decref(stacktrace); - return sentry_value_new_null(); - } - - // Sentry expects frames in reverse order (outermost caller first) - for (int i = frame_count - 1; i >= 0; i--) { - sentry_value_append(frames, temp_frames[i]); - } - - sentry_value_set_by_key(stacktrace, "frames", frames); - sentry_value_set_by_key( - stacktrace, "registers", build_registers_from_ctx(ctx, thread_idx)); - return stacktrace; - } -#endif - // Add the crashing frame (instruction pointer) if (ip != 0 && is_valid_code_addr(ip)) { temp_frames[frame_count] = sentry_value_new_object(); @@ -1213,6 +1326,21 @@ build_stacktrace_for_thread( break; } } +#elif defined(__riscv) && __riscv_xlen == 64 + // RISC-V frame records precede the CFA held in s0 + if (!read_stack_value(stack_buf, stack_start, stack_size, + current_fp - 2 * sizeof(uintptr_t), &saved_fp) + || !read_stack_value(stack_buf, stack_start, stack_size, + current_fp - sizeof(uintptr_t), &return_addr)) { + break; + } + // GCC < 14 leaf frames save only s0, so the caller is in ra + if (walk_count == 0 && return_addr >= stack_start + && return_addr < stack_end) { + saved_fp = return_addr; + return_addr + = (uint64_t)thread_context->uc_mcontext.__gregs[REG_RA]; + } #else // Read saved frame pointer and return address // Frame layout: [FP] = saved FP, [FP + pointer size] = return addr @@ -1315,12 +1443,13 @@ build_stacktrace_for_thread( # include /** - * Extract Build ID from ELF file (for debug_meta) + * Extract Build ID from the ELF image at `elf_offset` in a file + * (for debug_meta) * Returns the Build ID length, or 0 if not found */ static size_t -extract_elf_build_id_for_module( - const char *elf_path, uint8_t *build_id, size_t max_len) +extract_elf_build_id_for_module(const char *elf_path, uint64_t elf_offset, + uint8_t *build_id, size_t max_len) { int fd = sentry__elf_open(elf_path); if (fd < 0) { @@ -1328,13 +1457,14 @@ extract_elf_build_id_for_module( } // Read ELF header -# if defined(__x86_64__) || defined(__aarch64__) +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) Elf64_Ehdr ehdr; # else Elf32_Ehdr ehdr; # endif - if (read(fd, &ehdr, sizeof(ehdr)) != sizeof(ehdr)) { + if (pread(fd, &ehdr, sizeof(ehdr), (off_t)elf_offset) != sizeof(ehdr)) { close(fd); return 0; } @@ -1358,14 +1488,16 @@ extract_elf_build_id_for_module( return 0; } - if (lseek(fd, ehdr.e_shoff, SEEK_SET) != (off_t)ehdr.e_shoff + uint64_t shoff = elf_offset + ehdr.e_shoff; + if (lseek(fd, (off_t)shoff, SEEK_SET) != (off_t)shoff || read(fd, shdr_buf, shdr_size) != (ssize_t)shdr_size) { sentry_free(shdr_buf); close(fd); return 0; } -# if defined(__x86_64__) || defined(__aarch64__) +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) Elf64_Shdr *sections = (Elf64_Shdr *)shdr_buf; # else Elf32_Shdr *sections = (Elf32_Shdr *)shdr_buf; @@ -1388,8 +1520,8 @@ extract_elf_build_id_for_module( continue; } - if (lseek(fd, sections[i].sh_offset, SEEK_SET) - != (off_t)sections[i].sh_offset + uint64_t note_offset = elf_offset + sections[i].sh_offset; + if (lseek(fd, (off_t)note_offset, SEEK_SET) != (off_t)note_offset || read(fd, note_buf, note_size) != (ssize_t)note_size) { sentry_free(note_buf); continue; @@ -1437,7 +1569,13 @@ typedef struct { // Direct-mapped by module index; see get_sym_source. Being BSS, only the // slots touched during resolution are committed to physical memory. +# if defined(SENTRY_PLATFORM_ANDROID) +// Each daemon thread of the Android crash service maps its own instead, which +// is zero-filled on demand the same way. +static __thread sym_source_t *g_sym_sources = NULL; +# else static sym_source_t g_sym_sources[SENTRY_CRASH_MAX_MODULES]; +# endif /** * Parse the ELF file at `path` and record the location of its symbol table @@ -1461,7 +1599,8 @@ elf_locate_symtab(const char *path, int allow_dynsym, sym_source_t *src, return 0; } -# if defined(__x86_64__) || defined(__aarch64__) +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) Elf64_Ehdr ehdr; # else Elf32_Ehdr ehdr; @@ -1492,7 +1631,8 @@ elf_locate_symtab(const char *path, int allow_dynsym, sym_source_t *src, return 0; } -# if defined(__x86_64__) || defined(__aarch64__) +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) Elf64_Shdr *sections = (Elf64_Shdr *)shdr_buf; # else Elf32_Shdr *sections = (Elf32_Shdr *)shdr_buf; @@ -1592,6 +1732,11 @@ get_sym_source(const sentry_module_info_t *mod, uint32_t mod_idx) // most once and reused for every frame in that module. This covers all // modules the context can hold, so no frame is left unsymbolicated for // want of a cache slot. +# if defined(SENTRY_PLATFORM_ANDROID) + if (!g_sym_sources) { + return NULL; + } +# endif sym_source_t *slot = &g_sym_sources[mod_idx]; if (slot->state != 0) { return slot->state > 0 ? slot : NULL; @@ -1614,7 +1759,7 @@ get_sym_source(const sentry_module_info_t *mod, uint32_t mod_idx) if (debuglink[0]) { uint8_t mod_bid[16]; size_t mod_bid_len = extract_elf_build_id_for_module( - mod->name, mod_bid, sizeof(mod_bid)); + mod->name, mod->elf_offset, mod_bid, sizeof(mod_bid)); const char *slash = strrchr(mod->name, '/'); int dir_len = slash ? (int)(slash - mod->name) : 0; @@ -1648,7 +1793,7 @@ get_sym_source(const sentry_module_info_t *mod, uint32_t mod_idx) uint8_t dbg_bid[16]; size_t dbg_bid_len = extract_elf_build_id_for_module( - candidate, dbg_bid, sizeof(dbg_bid)); + candidate, 0, dbg_bid, sizeof(dbg_bid)); if (mod_bid_len && dbg_bid_len && (mod_bid_len != dbg_bid_len || memcmp(mod_bid, dbg_bid, mod_bid_len) != 0)) { @@ -1695,7 +1840,8 @@ sym_source_lookup(const sym_source_t *src, uint64_t sym_target, char *name_out, return 0; } -# if defined(__x86_64__) || defined(__aarch64__) +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) Elf64_Sym chunk[256]; # else Elf32_Sym chunk[256]; @@ -1719,7 +1865,8 @@ sym_source_lookup(const sym_source_t *src, uint64_t sym_target, char *name_out, } for (size_t k = 0; k < n; k++) { -# if defined(__x86_64__) || defined(__aarch64__) +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) unsigned char sym_type = ELF64_ST_TYPE(chunk[k].st_info); # else unsigned char sym_type = ELF32_ST_TYPE(chunk[k].st_info); @@ -1844,6 +1991,11 @@ capture_modules_from_proc_maps(sentry_crash_context_t *ctx) continue; // No pathname or special mapping like [stack] } + // Skip non-readable mappings + if (perms[0] != 'r') { + continue; + } + const char *pathname = line + pathname_offset; // Trim newline size_t len = strlen(pathname); @@ -1855,11 +2007,26 @@ capture_modules_from_proc_maps(sentry_crash_context_t *ctx) } // Check if this file is already captured - if so, extend size if needed + // A mapping at offset 0 starts another load of the file, unless the + // file was captured last (small libraries can map all segments at + // offset 0) sentry_module_info_t *existing_mod = NULL; - for (uint32_t j = 0; j < ctx->module_count; j++) { - if (strncmp(ctx->modules[j].name, pathname, len) == 0 - && ctx->modules[j].name[len] == '\0') { - existing_mod = &ctx->modules[j]; + for (uint32_t j = ctx->module_count; j > 0; j--) { + sentry_module_info_t *other = &ctx->modules[j - 1]; + if (strncmp(other->name, pathname, len) == 0 + && other->name[len] == '\0') { + // An ELF image inside a larger file only owns its load range + if (other->elf_offset != 0) { + if (start >= other->base_address + && start < other->base_address + other->size) { + existing_mod = other; + break; + } + continue; + } + if (offset != 0 || j == ctx->module_count) { + existing_mod = other; + } break; } } @@ -1892,7 +2059,17 @@ capture_modules_from_proc_maps(sentry_crash_context_t *ctx) memcpy(mod->name, pathname, copy_len); mod->name[copy_len] = '\0'; - if (!sentry__elf_is_file(mod->name)) { + // An ELF image can also start inside a larger file, such as a library + // that Android maps straight from an APK. Its load size is known up + // front to group the image's other segments. + mod->elf_offset = 0; + if (offset != 0 && sentry__elf_is_file_at(mod->name, offset)) { + uint64_t elf_size + = sentry__elf_compute_size_from_phdrs(mod->name, offset); + mod->elf_offset = offset; + mod->base_address = start; + mod->size = MAX(end - start, elf_size); + } else if (offset > start || !sentry__elf_is_file(mod->name)) { continue; } @@ -1900,7 +2077,7 @@ capture_modules_from_proc_maps(sentry_crash_context_t *ctx) memset(mod->uuid, 0, sizeof(mod->uuid)); mod->pdb_age = 0; // Not used on Linux, only for Windows PE modules extract_elf_build_id_for_module( - mod->name, mod->uuid, sizeof(mod->uuid)); + mod->name, mod->elf_offset, mod->uuid, sizeof(mod->uuid)); // Convert to little-endian GUID format for Sentry debug_id sentry__uuid_swap_guid_bytes(mod->uuid); @@ -1930,7 +2107,8 @@ enumerate_threads_from_proc(sentry_crash_context_t *ctx) DIR *dir = opendir(task_path); if (!dir) { - SENTRY_WARNF("Failed to open %s for thread enumeration", task_path); + SENTRY_WARNF("Failed to open %s for thread enumeration: %s", task_path, + strerror(errno)); return; } @@ -3127,64 +3305,6 @@ build_stacktrace_from_ctx(const sentry_crash_context_t *ctx) return build_stacktrace_for_thread(ctx, SIZE_MAX); } -/** - * Reads one breadcrumb ring file the crashing process appended on its hot path - * into a breadcrumb list. Returns null if the file is absent or empty. - */ -static sentry_value_t -read_breadcrumb_ring_file(const sentry_path_t *run_folder, const char *name) -{ - if (!run_folder) { - return sentry_value_new_null(); - } - sentry_path_t *path = sentry__path_join_str(run_folder, name); - if (!path) { - return sentry_value_new_null(); - } - size_t size = 0; - char *buf = sentry__path_read_to_buffer(path, &size); - sentry__path_free(path); - if (!buf || size == 0) { - sentry_free(buf); - return sentry_value_new_null(); - } - sentry_value_t list = sentry_value_from_msgpack_stream(buf, size); - sentry_free(buf); - return list; -} - -/** - * Assembles the crash event's breadcrumbs from the two ring files the crashing - * process appended one-at-a-time, merges them in timestamp order, keeps the - * newest `max_breadcrumbs`, and attaches them to `event`. - * Mirrors the crashpad backend's `report_to_envelope`. - */ -static void -apply_breadcrumbs_from_ring_files(sentry_value_t event, - const sentry_path_t *run_folder, const sentry_crash_context_t *ctx) -{ - if (ctx && ctx->max_breadcrumbs == 0) { - return; - } - - sentry_value_t b1 - = read_breadcrumb_ring_file(run_folder, "__sentry-breadcrumb1"); - sentry_value_t b2 - = read_breadcrumb_ring_file(run_folder, "__sentry-breadcrumb2"); - size_t max = ctx && ctx->max_breadcrumbs ? ctx->max_breadcrumbs - : SENTRY_BREADCRUMBS_MAX; - sentry_value_t merged = sentry__value_merge_breadcrumbs(b1, b2, max); - sentry_value_decref(b1); - sentry_value_decref(b2); - // Overwrite any breadcrumbs the base event may carry: the ring files are - // the single source of truth, so this is idempotent and never duplicates. - if (sentry_value_get_type(merged) == SENTRY_VALUE_TYPE_LIST) { - sentry_value_set_by_key(event, "breadcrumbs", merged); - } else { - sentry_value_decref(merged); - } -} - #if defined(SENTRY_PLATFORM_WINDOWS) static bool is_wer_done(const sentry_crash_context_t *ctx) @@ -3217,44 +3337,56 @@ apply_wer_context(sentry_value_t event, const sentry_crash_context_t *ctx) } #endif +static void +enrich_stacktrace(const sentry_crash_context_t *ctx, sentry_value_t stacktrace) +{ + sentry_value_t frames = sentry_value_get_by_key(stacktrace, "frames"); + if (sentry_value_get_type(frames) != SENTRY_VALUE_TYPE_LIST) { + return; + } + for (size_t i = 0; i < sentry_value_get_length(frames); i++) { + sentry_value_t frame = sentry_value_get_by_index(frames, i); + sentry_value_t value + = sentry_value_get_by_key(frame, "instruction_addr"); + uint64_t addr = sentry_value_as_uint64(value); + if (sentry_value_get_type(value) == SENTRY_VALUE_TYPE_STRING) { + const char *text = sentry_value_as_string(value); + char *end = NULL; + addr = strtoull(text, &end, 0); + if (end == text || *end != '\0') { + continue; + } + } + if (!addr) { + continue; + } + if (sentry_value_is_null(sentry_value_get_by_key(frame, "package"))) { + enrich_frame_with_module_info(ctx, frame, addr); + } + if (sentry_value_is_null(sentry_value_get_by_key(frame, "function")) + && sentry_value_is_null( + sentry_value_get_by_key(frame, "symbol_addr"))) { + enrich_frame_with_symbol(ctx, frame, addr); + } + } +} + /** * Build a native event and set the level, mechanism, and handled state * * @param ctx Crash context - * @param event_file_path Path to base event file from parent process - * @param run_folder Run directory holding the breadcrumb ring files + * @param base Staged event received from the parent process * @param level Event level (e.g. "fatal") * @param mechanism_type Exception mechanism type (e.g. "signalhandler") * @param handled Whether the mechanism was handled */ static sentry_value_t -build_native_event(const sentry_crash_context_t *ctx, - const char *event_file_path, const sentry_path_t *run_folder, +build_native_event(const sentry_crash_context_t *ctx, sentry_value_t base, const char *level, const char *mechanism_type, bool handled) { - // Read base event from parent's file - sentry_value_t event = sentry_value_new_null(); - if (!sentry__string_empty(event_file_path)) { - sentry_path_t *ev_path = sentry__path_from_str(event_file_path); - if (ev_path) { - size_t event_size = 0; - char *event_json - = sentry__path_read_to_buffer(ev_path, &event_size); - sentry__path_free(ev_path); - if (event_json && event_size > 0) { - event = sentry_value_from_json(event_json, event_size); - sentry_free(event_json); - } - } - } - - if (sentry_value_is_null(event)) { - event = sentry_value_new_event(); - } else { - sentry__ensure_event_id(event, NULL); - } + sentry_value_t event = sentry__value_clone(base); + sentry__ensure_event_id(event, NULL); - apply_breadcrumbs_from_ring_files(event, run_folder, ctx); #if defined(SENTRY_PLATFORM_WINDOWS) apply_wer_context(event, ctx); #endif @@ -3265,53 +3397,7 @@ build_native_event(const sentry_crash_context_t *ctx, sentry_value_set_by_key(event, "level", sentry_value_new_string(level)); - // Build exception -#if defined(SENTRY_PLATFORM_UNIX) - int signal_number = ctx->platform.signum; - const char *signal_name = get_signal_name(signal_number); -#elif defined(SENTRY_PLATFORM_WINDOWS) - // Exception code is used directly below as unsigned - const char *signal_name = "EXCEPTION"; -#else -# error Unsupported platform -#endif - - sentry_value_t exc = sentry_value_new_object(); - sentry_value_set_by_key(exc, "type", sentry_value_new_string(signal_name)); - - char value_buf[128]; - snprintf(value_buf, sizeof(value_buf), "Fatal crash: %s", signal_name); - sentry_value_set_by_key(exc, "value", sentry_value_new_string(value_buf)); - - // Add mechanism - sentry_value_t mechanism = sentry_value_new_object(); - sentry_value_set_by_key( - mechanism, "type", sentry_value_new_string(mechanism_type)); - sentry_value_set_by_key( - mechanism, "synthetic", sentry_value_new_bool(true)); - sentry_value_set_by_key( - mechanism, "handled", sentry_value_new_bool(handled)); - - // Add signal metadata - sentry_value_t meta = sentry_value_new_object(); - sentry_value_t signal_info = sentry_value_new_object(); -#if defined(SENTRY_PLATFORM_WINDOWS) - // Windows exception codes are unsigned 32-bit values (e.g., 0xC0000005) - // Use uint64 to preserve the unsigned value for the symbolicator - sentry_value_set_by_key(signal_info, "number", - sentry_value_new_uint64((uint64_t)ctx->platform.exception_code)); -#else - sentry_value_set_by_key( - signal_info, "number", sentry_value_new_int32(signal_number)); -#endif - sentry_value_set_by_key( - signal_info, "name", sentry_value_new_string(signal_name)); - sentry_value_set_by_key(meta, "signal", signal_info); - sentry_value_set_by_key(mechanism, "meta", meta); - - sentry_value_set_by_key(exc, "mechanism", mechanism); - - // Add stacktrace to exception + // other threads and missing local captures may still need DbgHelp #if defined(SENTRY_PLATFORM_WINDOWS) g_stack_walk_process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, @@ -3329,14 +3415,31 @@ build_native_event(const sentry_crash_context_t *ctx, ctx->crashed_pid, GetLastError()); } #endif - sentry_value_set_by_key(exc, "stacktrace", build_stacktrace_from_ctx(ctx)); - // Wrap exception in values array - sentry_value_t exceptions = sentry_value_new_object(); - sentry_value_t exc_values = sentry_value_new_list(); - sentry_value_append(exc_values, exc); - sentry_value_set_by_key(exceptions, "values", exc_values); - sentry_value_set_by_key(event, "exception", exceptions); + sentry_value_t exception = sentry_value_get_by_key(event, "exception"); + sentry_value_t values = sentry_value_get_by_key(exception, "values"); + sentry_value_t exc = sentry_value_get_by_index(values, 0); + if (sentry_value_is_null(exc)) { + sentry_value_t stacktrace = build_stacktrace_from_ctx(ctx); + if (sentry_value_is_null(stacktrace)) { + stacktrace = sentry__crash_context_build_stacktrace( + ctx, build_registers_from_ctx(ctx, SIZE_MAX)); + } + exc = sentry__crash_context_build_exception( + ctx, mechanism_type, handled, stacktrace); + // Wrap exception in values array + sentry_event_add_exception(event, exc); + } else { + sentry_value_t stacktrace = sentry_value_get_by_key(exc, "stacktrace"); + sentry_value_t unwound = has_captured_stack(ctx) + ? sentry_value_new_null() + : build_stacktrace_from_ctx(ctx); + if (!sentry_value_is_null(unwound)) { + sentry_value_set_by_key(exc, "stacktrace", unwound); + stacktrace = unwound; + } + enrich_stacktrace(ctx, stacktrace); + } // Always add threads with names to the event JSON { @@ -3625,14 +3728,14 @@ build_native_event(const sentry_crash_context_t *ctx, static bool write_envelope_with_native_stacktrace(const sentry_options_t *options, const char *envelope_path, const sentry_crash_context_t *ctx, - const char *event_file_path, const char *minidump_path, - sentry_path_t *run_folder) + sentry_value_t base, const char *minidump_path, sentry_path_t *run_folder, + sentry_value_t attachments) { // Build native crash event (always include threads with names) SENTRY_DEBUGF("write_envelope_with_native_stacktrace: minidump_path=%s", minidump_path ? minidump_path : "(null)"); - sentry_value_t event = build_native_event( - ctx, event_file_path, run_folder, "fatal", "signalhandler", false); + sentry_value_t event + = build_native_event(ctx, base, "fatal", "signalhandler", false); // Serialize event to JSON size_t event_size = 0; @@ -3788,9 +3891,27 @@ write_envelope_with_native_stacktrace(const sentry_options_t *options, } } - // Add scope attachments using metadata file - if (run_folder) { - write_attachments_from_manifest(fd, options, run_folder); + size_t len = sentry_value_get_length(attachments); + for (size_t i = 0; i < len; i++) { + sentry_value_t attach_info = sentry_value_get_by_index(attachments, i); + sentry_value_t path_val = sentry_value_get_by_key(attach_info, "path"); + sentry_value_t filename_val + = sentry_value_get_by_key(attach_info, "filename"); + sentry_value_t attachment_type_val + = sentry_value_get_by_key(attach_info, "type"); + sentry_value_t content_type_val + = sentry_value_get_by_key(attach_info, "content_type"); + + const char *path = sentry_value_as_string(path_val); + const char *filename = sentry_value_as_string(filename_val); + const char *attachment_type + = sentry_value_as_string(attachment_type_val); + const char *content_type = sentry_value_as_string(content_type_val); + + if (path && filename && !attachment_is_placeholder(options, path)) { + write_attachment_to_envelope( + fd, path, filename, attachment_type, content_type); + } } // Add screenshot attachment if captured by the daemon @@ -3831,48 +3952,23 @@ write_envelope_with_native_stacktrace(const sentry_options_t *options, static bool write_envelope_with_minidump(const sentry_options_t *options, const sentry_crash_context_t *ctx, const char *envelope_path, - const char *event_msgpack_path, const char *minidump_path, - sentry_path_t *run_folder) + sentry_value_t base, const char *minidump_path, sentry_path_t *run_folder, + sentry_value_t attachments) { - // Read the base event, merge in the breadcrumbs from the ring files, - // re-serialize. - size_t event_size = 0; - char *event_json = NULL; - char *event_id = NULL; - sentry_path_t *ev_path = sentry__path_from_str(event_msgpack_path); - if (ev_path) { - size_t base_size = 0; - char *base_json = sentry__path_read_to_buffer(ev_path, &base_size); - sentry__path_free(ev_path); - if (base_json && base_size > 0) { - sentry_value_t event = sentry_value_from_json(base_json, base_size); - if (sentry_value_is_null(event)) { - // Parsing the base event failed (e.g. truncated buffer or - // OOM). Don't serialize the null into "null" and ship an - // invalid payload - fall back to streaming the raw event - // bytes verbatim so the crash report is preserved. - sentry_value_decref(event); - event_json = sentry__string_clone_n(base_json, base_size); - event_size = event_json ? base_size : 0; - } else { - apply_breadcrumbs_from_ring_files(event, run_folder, ctx); + sentry_value_t event = sentry__value_clone(base); + // The minidump holds the exception. Drop the one built for `on_crash`. + sentry_value_remove_by_key(event, "exception"); #if defined(SENTRY_PLATFORM_WINDOWS) - apply_wer_context(event, ctx); + apply_wer_context(event, ctx); #endif - event_id = sentry__string_clone(sentry_value_as_string( - sentry_value_get_by_key(event, "event_id"))); - event_json = sentry__value_to_json(event, &event_size); - sentry_value_decref(event); - if (!event_json) { - // Re-serialization failed (e.g. OOM). Fall back to the raw - // event bytes so the crash report is preserved, losing only - // the merged breadcrumbs rather than the whole event. - event_json = sentry__string_clone_n(base_json, base_size); - event_size = event_json ? base_size : 0; - } - } - } - sentry_free(base_json); + size_t event_size = 0; + char *event_json = sentry__value_to_json(event, &event_size); + char *event_id = sentry__string_clone( + sentry_value_as_string(sentry_value_get_by_key(event, "event_id"))); + sentry_value_decref(event); + if (!event_json) { + sentry_free(event_id); + return false; } // Open envelope file for writing @@ -4017,9 +4113,27 @@ write_envelope_with_minidump(const sentry_options_t *options, #endif } - // Add scope attachments using metadata file - if (run_folder) { - write_attachments_from_manifest(fd, options, run_folder); + size_t len = sentry_value_get_length(attachments); + for (size_t i = 0; i < len; i++) { + sentry_value_t attach_info = sentry_value_get_by_index(attachments, i); + sentry_value_t path_val = sentry_value_get_by_key(attach_info, "path"); + sentry_value_t filename_val + = sentry_value_get_by_key(attach_info, "filename"); + sentry_value_t attachment_type_val + = sentry_value_get_by_key(attach_info, "type"); + sentry_value_t content_type_val + = sentry_value_get_by_key(attach_info, "content_type"); + + const char *path = sentry_value_as_string(path_val); + const char *filename = sentry_value_as_string(filename_val); + const char *attachment_type + = sentry_value_as_string(attachment_type_val); + const char *content_type = sentry_value_as_string(content_type_val); + + if (path && filename && !attachment_is_placeholder(options, path)) { + write_attachment_to_envelope( + fd, path, filename, attachment_type, content_type); + } } // Add screenshot attachment if captured by the daemon @@ -4059,17 +4173,96 @@ write_envelope_with_minidump(const sentry_options_t *options, * * Called by the crash daemon (out-of-process on Linux/macOS). */ +#if defined(SENTRY_PLATFORM_WINDOWS) +// Sentry's symbolicator needs `contexts.device.arch` to process PE modules. If +// the scope already carries a device context with arch (host SDKs like Unity +// provide one), leave it; otherwise synthesize a minimal one so native-only +// consumers still symbolicate. +static void +ensure_device_arch(sentry_value_t event) +{ + sentry_value_t contexts = sentry_value_get_by_key(event, "contexts"); + if (sentry_value_is_null(contexts)) { + contexts = sentry_value_new_object(); + if (sentry_value_set_by_key(event, "contexts", contexts) != 0) { + return; + } + } + sentry_value_t device = sentry_value_get_by_key(contexts, "device"); + if (sentry_value_is_null(device)) { + device = sentry_value_new_object(); + sentry_value_set_by_key( + device, "type", sentry_value_new_string("device")); + if (sentry_value_set_by_key(contexts, "device", device) != 0) { + return; + } + } + if (!sentry_value_is_null(sentry_value_get_by_key(device, "arch"))) { + return; + } +# if defined(_M_AMD64) + sentry_value_set_by_key(device, "arch", sentry_value_new_string("x86_64")); +# elif defined(_M_IX86) + sentry_value_set_by_key(device, "arch", sentry_value_new_string("x86")); +# elif defined(_M_ARM64) + sentry_value_set_by_key(device, "arch", sentry_value_new_string("arm64")); +# endif +} +#endif + +/** + * Removes the crash envelope once the transport has sent or dumped the crash, + * or renames it for a later send. + */ +static void +retain_crash_envelope(const sentry_options_t *options, + const sentry_crash_context_t *ctx, sentry_uuid_t event_id) +{ + if (sentry_uuid_is_nil(&event_id) || !options->run) { + return; + } + char *filename = sentry__uuid_as_filename(&event_id, ".envelope"); + sentry_path_t *run_path = filename + ? sentry__path_join_str(options->run->run_path, filename) + : NULL; + sentry_free(filename); + sentry_path_t *path = sentry__path_from_str(ctx->envelope_path); + sentry_uuid_t last_event_id + = sentry__http_transport_get_last_event_id(options->transport); + if (path && run_path) { + if (sentry__uuid_eq(&last_event_id, &event_id) + || sentry__path_is_file(run_path)) { + // Keep it for the callback on the next launch. + if (!ctx->has_on_crashed_last_run) { + sentry__path_remove(path); + } + } else if (sentry__path_rename(path, run_path) == 0 + && ctx->has_on_crashed_last_run) { + sentry__run_write_crash_marker(options->run, &event_id); + } + } + sentry__path_free(path); + sentry__path_free(run_path); +} + bool -sentry__process_crash(const sentry_options_t *options, sentry_crash_ipc_t *ipc) +sentry__process_crash(const sentry_options_t *options, sentry_crash_ipc_t *ipc, + sentry_crash_daemon_t *daemon, sentry_uuid_t *event_id) { + (void)daemon; SENTRY_DEBUG("Processing crash - START"); bool crash_captured = false; + *event_id = sentry_uuid_nil(); sentry_crash_context_t *ctx = ipc->shmem; // Mark as processing sentry__atomic_store(&ctx->state, SENTRY_CRASH_STATE_PROCESSING); SENTRY_DEBUG("Marked state as PROCESSING"); + if (ctx->event_discarded) { + SENTRY_DEBUG("Crash event discarded by local callback"); + goto done; + } // Check crash reporting mode int mode = ctx->crash_reporting_mode; @@ -4138,38 +4331,28 @@ sentry__process_crash(const sentry_options_t *options, sentry_crash_ipc_t *ipc) goto done; } - // Get event file path from context - const char *event_path = ctx->event_path[0] ? ctx->event_path : NULL; - SENTRY_DEBUGF( - "Event path from context: %s", event_path ? event_path : "(null)"); - if (!event_path) { - SENTRY_WARN("No event file from parent"); - if (minidump_path[0]) { - // Delete the orphaned minidump to prevent disk space leaks -#if defined(SENTRY_PLATFORM_UNIX) - unlink(minidump_path); -#elif defined(SENTRY_PLATFORM_WINDOWS) - wchar_t *wpath = sentry__string_to_wstr(minidump_path); - if (wpath) { - _wunlink(wpath); - sentry_free(wpath); - } -#endif - } - ctx->minidump_path[0] = '\0'; - goto done; + sentry_value_t base = sentry__crash_scope_event(&ipc->scope); + sentry_path_t *run_folder = sentry__path_from_str(ctx->run_path); + sentry_value_t crash_event + = run_folder ? read_crash_event(run_folder) : sentry_value_new_null(); + if (!sentry_value_is_null(crash_event)) { + sentry_value_decref(base); + base = crash_event; } - - // Extract run folder path from event path (event is at - // run_folder/__sentry-event) - SENTRY_DEBUG("Extracting run folder from event path"); - sentry_path_t *ev_path = sentry__path_from_str(event_path); - sentry_path_t *run_folder = ev_path ? sentry__path_dir(ev_path) : NULL; + sentry_value_t attachments = run_folder + ? read_attachment_manifest(run_folder) + : sentry_value_new_null(); + if (sentry_value_is_null(attachments)) { + attachments = sentry_value_incref(ipc->scope.attachments); + } +#if defined(SENTRY_PLATFORM_WINDOWS) + ensure_device_arch(base); +#endif // The crashing process dumps its pending logs, sessions, and transactions // before notifying the daemon. Queue those before writing the crash // envelope so an attachment-ref prewrite is not captured a second time. - if (run_folder && options && options->transport && options->run) { + if (run_folder && options->transport && options->run) { sentry__process_run_envelopes(options, run_folder); } else { SENTRY_DEBUG("No run folder or transport for additional envelopes"); @@ -4182,7 +4365,8 @@ sentry__process_crash(const sentry_options_t *options, sentry_crash_ipc_t *ipc) if (path_len < 0 || path_len >= (int)sizeof(envelope_path)) { SENTRY_WARN("Envelope path truncated or invalid"); - sentry__path_free(ev_path); + sentry_value_decref(base); + sentry_value_decref(attachments); if (run_folder) { sentry__path_free(run_folder); } @@ -4202,8 +4386,9 @@ sentry__process_crash(const sentry_options_t *options, sentry_crash_ipc_t *ipc) if (screenshot_path) { // Pass the crashed app's PID so we capture its windows, not the // daemon's - if (sentry__screenshot_capture( - screenshot_path, (uint32_t)ctx->crashed_pid)) { + if (sentry_screenshot_capture( + screenshot_path->path, (uint32_t)ctx->crashed_pid) + == 0) { SENTRY_DEBUG("Screenshot captured successfully"); } else { SENTRY_DEBUG("Screenshot capture failed"); @@ -4276,6 +4461,11 @@ sentry__process_crash(const sentry_options_t *options, sentry_crash_ipc_t *ipc) } #endif + // Upload large minidumps separately, and keep them out of the envelope + bool minidump_ref = options->run && !sentry__string_empty(minidump_path) + && attachment_is_placeholder(options, minidump_path); + const char *embedded_minidump = minidump_ref ? "" : minidump_path; + // Write envelope based on mode bool envelope_written = false; SENTRY_DEBUGF("Envelope decision: mode=%d, use_native_mode=%d, " @@ -4286,20 +4476,21 @@ sentry__process_crash(const sentry_options_t *options, sentry_crash_ipc_t *ipc) // Mode 1 (NATIVE) or Mode 2 (NATIVE_WITH_MINIDUMP) SENTRY_DEBUGF("Writing envelope with native stacktrace, passing " "minidump_path=%s", - minidump_path[0] ? minidump_path : "NULL"); - envelope_written = write_envelope_with_native_stacktrace(options, - envelope_path, ctx, event_path, - minidump_path[0] ? minidump_path : NULL, run_folder); + embedded_minidump[0] ? embedded_minidump : "NULL"); + envelope_written + = write_envelope_with_native_stacktrace(options, envelope_path, ctx, + base, embedded_minidump, run_folder, attachments); } else { // Mode 0 (MINIDUMP only) SENTRY_DEBUG("Writing envelope with minidump"); - envelope_written = write_envelope_with_minidump( - options, ctx, envelope_path, event_path, minidump_path, run_folder); + envelope_written = write_envelope_with_minidump(options, ctx, + envelope_path, base, embedded_minidump, run_folder, attachments); } if (!envelope_written) { SENTRY_WARN("Failed to write envelope"); - sentry__path_free(ev_path); + sentry_value_decref(base); + sentry_value_decref(attachments); if (run_folder) { sentry__path_free(run_folder); } @@ -4342,6 +4533,14 @@ sentry__process_crash(const sentry_options_t *options, sentry_crash_ipc_t *ipc) } sentry_envelope_t *envelope = sentry__envelope_from_path(env_path); + if (!envelope && embedded_minidump[0]) { + // Report the crash with a native stacktrace, which needs no minidump + SENTRY_WARN("Failed to read envelope file, retrying without minidump"); + if (write_envelope_with_native_stacktrace(options, envelope_path, ctx, + base, NULL, run_folder, attachments)) { + envelope = sentry__envelope_from_path(env_path); + } + } sentry__path_free(env_path); if (!envelope) { @@ -4349,27 +4548,68 @@ sentry__process_crash(const sentry_options_t *options, sentry_crash_ipc_t *ipc) goto cleanup; } - add_attachment_refs(envelope, options, run_folder); + add_attachment_refs(envelope, options, attachments); + if (minidump_ref) { + add_minidump_ref(envelope, options, minidump_path, run_folder); + } + +#if defined(SENTRY_PLATFORM_ANDROID) + sentry_path_t *android_native_envelope_path + = make_run_envelope_path(options->run, envelope); +#endif SENTRY_DEBUG("Envelope loaded, capturing"); // Launch reporter, or fall back to transport (consent/caching in core). if (!sentry__launch_external_crash_reporter(options, envelope)) { - if (options && options->transport && options->run) { - SENTRY_DEBUG("Capturing crash envelope"); - sentry__capture_envelope(options->transport, envelope, options); - crash_captured = true; - SENTRY_DEBUG("Crash envelope captured (queued)"); - } else { - SENTRY_WARN("No transport available for sending envelope"); - sentry_envelope_free(envelope); +#if defined(SENTRY_PLATFORM_ANDROID) + // Tombstone merging needs the sentry-java crash service. The + // standalone daemon is only used in tests and is not supported in + // apps, so it handles the envelope as on Linux. + if (daemon && android_native_envelope_path) { + if (!options->run + || !sentry__run_write_envelope(options->run, envelope)) { + SENTRY_WARN("Failed to dump crash envelope to run folder"); + } else { + SENTRY_DEBUG( + "Crash envelope written for Android tombstone merging"); + sentry__atomic_store(&ctx->state, SENTRY_CRASH_STATE_DONE); + SENTRY_DEBUG("Released crashed process for Android tombstone"); + strncpy(daemon->envelope_path, + android_native_envelope_path->path, + sizeof(daemon->envelope_path) - 1); + daemon->envelope_path[sizeof(daemon->envelope_path) - 1] = '\0'; + daemon->event = sentry_value_incref(base); + sentry_envelope_free(envelope); + envelope = NULL; + } + } +#endif + if (envelope) { + if (options->transport && options->run) { + SENTRY_DEBUG("Capturing crash envelope"); + if (!sentry__run_should_skip_upload(options->run)) { + *event_id = sentry__envelope_get_event_id(envelope); + } + sentry__capture_envelope(options->transport, envelope, options); + crash_captured = true; + SENTRY_DEBUG("Crash envelope captured (queued)"); + } else { + SENTRY_WARN("No transport available for sending envelope"); + sentry_envelope_free(envelope); + } } } else { crash_captured = true; } +#if defined(SENTRY_PLATFORM_ANDROID) + sentry__path_free(android_native_envelope_path); +#endif + // Keep the original crash envelope for the callback on the next launch. - if (!ctx->has_on_crashed_last_run) { + // A crash sent via transport keeps it until the send has finished. + if (!ctx->has_on_crashed_last_run && sentry_uuid_is_nil(event_id)) { #if defined(SENTRY_PLATFORM_UNIX) unlink(envelope_path); #elif defined(SENTRY_PLATFORM_WINDOWS) @@ -4382,36 +4622,15 @@ sentry__process_crash(const sentry_options_t *options, sentry_crash_ipc_t *ipc) } cleanup: - // Send the staged session-replay envelope same-session, enriched from the - // crash event (`/__sentry-event`) so it shares the crash's - // tags/contexts/trace and embeds its breadcrumbs. Only flush when the - // crash itself was delivered: `cleanup` is also reached via `goto` on - // error paths where the crash was never captured, and flushing there - // would consume (and delete) the staged replay for a crash that never - // arrived. - if (crash_captured && options && options->transport + // flush replay only after the crash itself was captured + if (crash_captured && options->transport && sentry__session_replay_has_pending(options)) { - sentry_value_t crash_event = sentry_value_new_null(); - if (ev_path) { - size_t ev_len = 0; - char *ev_json = sentry__path_read_to_buffer(ev_path, &ev_len); - if (ev_json) { - crash_event = sentry_value_from_json(ev_json, ev_len); - sentry_free(ev_json); - } - } - if (!sentry_value_is_null(crash_event)) { - // `__sentry-event` is scope-applied without breadcrumbs; merge - // the ring files so the replay recording can embed them - apply_breadcrumbs_from_ring_files(crash_event, run_folder, ctx); - } - sentry__session_replay_flush_pending( - options, options->transport, crash_event); - sentry_value_decref(crash_event); + sentry__session_replay_flush_pending(options, options->transport, base); } sentry__path_free(run_folder); - sentry__path_free(ev_path); + sentry_value_decref(base); + sentry_value_decref(attachments); SENTRY_DEBUG("Crash processing completed successfully"); @@ -4421,6 +4640,145 @@ sentry__process_crash(const sentry_options_t *options, sentry_crash_ipc_t *ipc) return crash_captured; } +#if defined(SENTRY_PLATFORM_ANDROID) +__attribute__((visibility("default"))) int +sentry_android_crash_daemon_send( + sentry_crash_daemon_t *daemon, const char *path, uint64_t timeout) +{ + if (!path || !path[0]) { + android_cleanup_pending_crash_daemon(daemon, false); + return SENTRY_ANDROID_SEND_FAILED; + } + + sentry_path_t *envelope_path = sentry__path_from_str(path); + sentry_envelope_t *envelope + = envelope_path ? sentry__envelope_from_path(envelope_path) : NULL; + if (envelope_path) { + sentry__path_free(envelope_path); + } + if (!envelope) { + SENTRY_WARN("Failed to read merged Android crash envelope"); + android_cleanup_pending_crash_daemon(daemon, false); + return SENTRY_ANDROID_SEND_FAILED; + } + + sentry_android_send_result_t result = SENTRY_ANDROID_SEND_FAILED; + if (daemon->options->transport && daemon->options->run) { + SENTRY_DEBUG("Capturing merged Android crash envelope"); + // keep a failed upload in the run folder for the next launch + sentry__http_transport_set_dump_failed( + daemon->options->transport, true); + sentry_uuid_t event_id = sentry__envelope_get_event_id(envelope); + + // keep a copy for the next launch until the send has finished + sentry_path_t *raw_path = sentry__path_from_str(daemon->envelope_path); + sentry_path_t *pending_path = sentry__path_join_str( + daemon->options->run->run_path, "__sentry-pending.envelope"); + if (raw_path && strcmp(path, daemon->envelope_path) != 0) { + sentry_path_t *merged_path = sentry__path_from_str(path); + if (merged_path + && sentry__path_rename(merged_path, raw_path) != 0) { + sentry__path_remove(merged_path); + } + sentry__path_free(merged_path); + } + bool pending = raw_path && pending_path + && !sentry__run_should_skip_upload(daemon->options->run) + && sentry__path_rename(raw_path, pending_path) == 0; + if (raw_path && !pending) { + sentry__path_remove(raw_path); + } + + sentry__capture_envelope( + daemon->options->transport, envelope, daemon->options); + + // flush replay only after the crash itself was captured + if (sentry__session_replay_has_pending(daemon->options)) { + sentry__session_replay_flush_pending( + daemon->options, daemon->options->transport, daemon->event); + } + + daemon->options->shutdown_timeout = timeout; + int rv = sentry__transport_shutdown( + daemon->options->transport, daemon->options->shutdown_timeout); + daemon->transport_shutdown = true; + if (rv != 0) { + SENTRY_WARN("transport did not shut down cleanly"); + } + sentry__transport_dump_queue( + daemon->options->transport, daemon->options->run); + sentry__http_transport_set_retry_enabled( + daemon->options->transport, false); + sentry__http_transport_set_dump_failed( + daemon->options->transport, false); + sentry_uuid_t last_event_id = sentry__http_transport_get_last_event_id( + daemon->options->transport); + // the dump and a failed upload both write the raw envelope path + if (raw_path && sentry__path_is_file(raw_path)) { + result = SENTRY_ANDROID_SEND_KEPT; + } else if (!sentry_uuid_is_nil(&event_id) + && sentry__uuid_eq(&last_event_id, &event_id)) { + result = SENTRY_ANDROID_SEND_SENT; + } + if (pending) { + if (result == SENTRY_ANDROID_SEND_FAILED) { + // the next launch sends the pending copy + result = SENTRY_ANDROID_SEND_KEPT; + } else { + sentry__path_remove(pending_path); + } + } + sentry__path_free(pending_path); + sentry__path_free(raw_path); + } else { + SENTRY_WARN( + "No transport available for sending Android crash envelope"); + sentry_envelope_free(envelope); + } + + android_cleanup_pending_crash_daemon(daemon, false); + return result; +} + +__attribute__((visibility("default"))) void +sentry_android_crash_daemon_close(sentry_crash_daemon_t *daemon) +{ + // the next launch sends the unsent envelope + android_cleanup_pending_crash_daemon(daemon, false); +} + +static void +android_cleanup_pending_crash_daemon( + sentry_crash_daemon_t *daemon, bool discard_envelope) +{ + if (discard_envelope && daemon->envelope_path[0]) { + sentry_path_t *path = sentry__path_from_str(daemon->envelope_path); + if (path) { + sentry__path_remove(path); + sentry__path_free(path); + } + } + if (daemon->options) { + if (daemon->options->transport && !daemon->transport_shutdown) { + sentry__transport_shutdown(daemon->options->transport, 0); + } + sentry_options_free(daemon->options); + } + sentry_transport_free(daemon->transport); + if (daemon->ipc) { + sentry__crash_ipc_unlink(daemon->ipc); + sentry__crash_ipc_free(daemon->ipc); + } + if (daemon->log_file) { + sentry__logger_disable(); + fclose(daemon->log_file); + } + + sentry_value_decref(daemon->event); + sentry_free(daemon); +} +#endif + /** * Check if parent process is still alive */ @@ -4454,7 +4812,12 @@ daemon_file_logger( // Get current timestamp time_t now = time(NULL); +#if defined(SENTRY_PLATFORM_WINDOWS) struct tm *tm_info = localtime(&now); +#else + struct tm tm_buf; + struct tm *tm_info = localtime_r(&now, &tm_buf); +#endif char timestamp[SENTRY_CRASH_TIMESTAMP_SIZE]; strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", tm_info); @@ -4468,36 +4831,80 @@ daemon_file_logger( fflush(log_file); // Flush immediately to ensure logs are written } -#if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) +static long g_crash_handling = 0; + +static void +dump_crash_queue(void) +{ + if (!sentry__atomic_compare_swap(&g_crash_handling, 0, 1)) { + return; + } + +#if defined(SENTRY_PLATFORM_UNIX) + (void)!sentry__enter_signal_handler(); + sentry__page_allocator_enable(); +#endif + sentry__logger_disable(); + + SENTRY_WITH_OPTIONS (options) { + if (options->run && options->transport) { + sentry__transport_dump_queue(options->transport, options->run); + sentry__http_transport_set_retry_enabled(options->transport, false); + } + } + +#if defined(SENTRY_PLATFORM_UNIX) + sentry__leave_signal_handler(); +#endif +} + +#if defined(SENTRY_PLATFORM_ANDROID) +int +sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, int notify_eventfd, + int ready_eventfd, int shm_fd, int message_fd, + sentry_crash_daemon_t *daemon) +#elif defined(SENTRY_PLATFORM_LINUX) int -sentry__crash_daemon_main( - pid_t app_pid, uint64_t app_tid, int notify_eventfd, int ready_eventfd) +sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, int notify_eventfd, + int ready_eventfd, int shm_fd, int message_fd) #elif defined(SENTRY_PLATFORM_MACOS) int sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, int notify_pipe_read, - int ready_pipe_write, int shm_fd) + int ready_pipe_write, int shm_fd, int message_fd) #elif defined(SENTRY_PLATFORM_WINDOWS) int sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, - HANDLE ready_event_handle) + HANDLE ready_event_handle, HANDLE message_read_handle) #endif { // Initialize IPC first (attach to shared memory created by parent) // We need this to get the database path for logging #if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) sentry_crash_ipc_t *ipc = sentry__crash_ipc_init_daemon( - app_pid, app_tid, notify_eventfd, ready_eventfd); + app_pid, app_tid, notify_eventfd, ready_eventfd, shm_fd, message_fd); #elif defined(SENTRY_PLATFORM_MACOS) - sentry_crash_ipc_t *ipc = sentry__crash_ipc_init_daemon( - app_pid, app_tid, notify_pipe_read, ready_pipe_write, shm_fd); + sentry_crash_ipc_t *ipc = sentry__crash_ipc_init_daemon(app_pid, app_tid, + notify_pipe_read, ready_pipe_write, shm_fd, message_fd); #elif defined(SENTRY_PLATFORM_WINDOWS) - sentry_crash_ipc_t *ipc = sentry__crash_ipc_init_daemon( - app_pid, app_tid, event_handle, ready_event_handle); + sentry_crash_ipc_t *ipc = sentry__crash_ipc_init_daemon(app_pid, app_tid, + event_handle, ready_event_handle, message_read_handle); #endif if (!ipc) { +#if defined(SENTRY_PLATFORM_ANDROID) + close(notify_eventfd); + close(ready_eventfd); + close(message_fd); +#endif return 1; } +#if defined(SENTRY_PLATFORM_ANDROID) + // the crash service hosts a daemon for each app process + bool shared_process = daemon != NULL; +#else + bool shared_process = false; +#endif + // Set up logging to file for daemon BEFORE redirecting streams char log_path[SENTRY_CRASH_MAX_PATH]; FILE *log_file = NULL; @@ -4519,7 +4926,8 @@ sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, int log_path_len = snprintf(log_path, sizeof(log_path), "%s/sentry-daemon.log", ipc->shmem->run_path); - if (log_path_len > 0 && log_path_len < (int)sizeof(log_path)) { + if (!shared_process && log_path_len > 0 + && log_path_len < (int)sizeof(log_path)) { log_file = fopen(log_path, "w"); } #endif @@ -4544,20 +4952,29 @@ sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, SENTRY_DEBUGF("Database path: %s", ipc->shmem->database_path); } -#if defined(SENTRY_PLATFORM_UNIX) - // Close standard streams to avoid interfering with parent - close(STDIN_FILENO); - close(STDOUT_FILENO); - close(STDERR_FILENO); +#if defined(SENTRY_PLATFORM_ANDROID) + if (shared_process && ipc->shmem->debug_enabled) { + pthread_once(&g_android_logcat_once, android_install_logcat_logger); + } +#endif - // Open /dev/null for std streams - int devnull = open("/dev/null", O_RDWR); - if (devnull >= 0) { - dup2(devnull, STDIN_FILENO); - dup2(devnull, STDOUT_FILENO); - dup2(devnull, STDERR_FILENO); - if (devnull > STDERR_FILENO) { - close(devnull); +#if defined(SENTRY_PLATFORM_UNIX) + // other threads of a shared process own the standard streams + if (!shared_process) { + // Close standard streams to avoid interfering with parent + close(STDIN_FILENO); + close(STDOUT_FILENO); + close(STDERR_FILENO); + + // Open /dev/null for std streams + int devnull = open("/dev/null", O_RDWR); + if (devnull >= 0) { + dup2(devnull, STDIN_FILENO); + dup2(devnull, STDOUT_FILENO); + dup2(devnull, STDERR_FILENO); + if (devnull > STDERR_FILENO) { + close(devnull); + } } } #elif defined(SENTRY_PLATFORM_WINDOWS) @@ -4570,15 +4987,22 @@ sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, #endif // Initialize Sentry options for daemon (reuses all SDK infrastructure) - // Options are passed explicitly to all functions, no global state sentry_options_t *options = sentry_options_new(); if (!options) { SENTRY_ERROR("sentry_options_new() failed"); + sentry__crash_ipc_free(ipc); if (log_file) { + sentry__logger_disable(); fclose(log_file); } return 1; } +#if defined(SENTRY_PLATFORM_ANDROID) + if (daemon) { + sentry_options_set_transport(options, daemon->transport); + daemon->transport = NULL; + } +#endif sentry_options_set_database_path(options, ipc->shmem->database_path); @@ -4591,6 +5015,12 @@ sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, options->enable_large_attachments = ipc->shmem->enable_large_attachments; options->http_retry = false; options->shutdown_timeout = ipc->shmem->shutdown_timeout; + // Use a longer default timeout for async uploads, which run in the + // background after the crashed app exits. + if (!sentry__options_has_shutdown_timeout(options) + && ipc->shmem->crash_upload_mode == SENTRY_CRASH_UPLOAD_MODE_ASYNC) { + options->shutdown_timeout = SENTRY_CRASH_HANDLER_WAIT_TIMEOUT_MS; + } options->transfer_timeout = ipc->shmem->transfer_timeout; // Set custom logger that writes to file @@ -4657,6 +5087,7 @@ sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, // Don't overwrite it with the parent's handle (handles are per-process) (void)event_handle; (void)ready_event_handle; + (void)message_read_handle; #endif #if defined(SENTRY_PLATFORM_WINDOWS) @@ -4671,6 +5102,28 @@ sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, ipc->parent_handle = app_pid; #endif + if (!sentry__crash_scope_init(&ipc->scope, ipc->shmem->max_breadcrumbs)) { + sentry__crash_ipc_free(ipc); + sentry_options_free(options); + if (log_file) { + sentry__logger_disable(); + fclose(log_file); + } + return 1; + } + +#if defined(SENTRY_PLATFORM_ANDROID) + // mapped ahead of the crash, which then goes without symbols on failure + void *sym_sources + = mmap(NULL, SENTRY_CRASH_MAX_MODULES * sizeof(*g_sym_sources), + PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (sym_sources != MAP_FAILED) { + g_sym_sources = sym_sources; + } else { + SENTRY_WARN("Failed to map the symbol cache"); + } +#endif + // Signal to parent that daemon is ready SENTRY_DEBUG("Signaling ready to parent"); sentry__crash_ipc_signal_ready(ipc); @@ -4695,15 +5148,29 @@ sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, SENTRY_WARN("No transport available"); } + // process-wide, not per daemon + bool crash_handler_installed = false; + if (!shared_process) { + sentry__options_set(options); + crash_handler_installed + = sentry__crash_handler_init( + NULL, SENTRY_HANDLER_STRATEGY_DEFAULT, dump_crash_queue) + == 0; + if (!crash_handler_installed) { + SENTRY_WARN("Failed to install daemon crash handler"); + } + } + SENTRY_DEBUG("Entering main loop"); // Daemon main loop bool crash_processed = false; + sentry_uuid_t crash_event_id = sentry_uuid_nil(); uint64_t crash_deadline = 0; while (true) { // Wait for crash notification (with timeout to check parent health) - bool wait_result - = sentry__crash_ipc_wait(ipc, SENTRY_CRASH_DAEMON_WAIT_TIMEOUT_MS); + bool wait_result = sentry__crash_ipc_receive( + ipc, SENTRY_CRASH_DAEMON_WAIT_TIMEOUT_MS); if (wait_result) { SENTRY_DEBUG("Event signaled, checking crash state"); } @@ -4717,7 +5184,13 @@ sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, } if (state == SENTRY_CRASH_STATE_CRASHED) { SENTRY_DEBUG("Crash notification received, processing"); - bool crash_captured = sentry__process_crash(options, ipc); +#if defined(SENTRY_PLATFORM_ANDROID) + bool crash_captured + = sentry__process_crash(options, ipc, daemon, &crash_event_id); +#else + bool crash_captured + = sentry__process_crash(options, ipc, NULL, &crash_event_id); +#endif crash_processed = true; if (crash_captured @@ -4758,8 +5231,17 @@ sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, SENTRY_DEBUG("Spurious notification or already processed"); } + if (ipc->scope.stopped && state != SENTRY_CRASH_STATE_CRASHING) { + break; + } + if (ipc->message_closed && parent_alive) { + // retain legacy WER notifications after the app closes its stream + ipc->notify_pending = sentry__crash_ipc_wait( + ipc, SENTRY_CRASH_DAEMON_WAIT_TIMEOUT_MS); + } + // Check if parent is still alive (only if no crash processed yet) - if (!parent_alive) { + if (!parent_alive && !ipc->notify_pending) { SENTRY_DEBUG("Parent process exited without crash"); break; } @@ -4767,13 +5249,36 @@ sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, SENTRY_DEBUG("Daemon exiting"); +#if defined(SENTRY_PLATFORM_ANDROID) + if (g_sym_sources) { + munmap( + g_sym_sources, SENTRY_CRASH_MAX_MODULES * sizeof(*g_sym_sources)); + g_sym_sources = NULL; + } +#endif +#if defined(SENTRY_PLATFORM_UNIX) && defined(__arm__) + sentry_free(g_vmas); + g_vmas = NULL; + g_vma_count = 0; + g_vma_capacity = 0; +#endif + +#if defined(SENTRY_PLATFORM_ANDROID) + if (daemon && daemon->envelope_path[0]) { + daemon->options = options; + daemon->ipc = ipc; + daemon->log_file = log_file; + return 0; + } +#endif + // Cleanup if (options) { if (options->transport) { // Wait for the configured SDK shutdown timeout to send pending // envelopes (crash envelope + logs envelope, etc.). - int rv = sentry__transport_shutdown( - options->transport, options->shutdown_timeout); + int rv = sentry__transport_shutdown(options->transport, + sentry_options_get_shutdown_timeout(options)); if (rv != 0) { SENTRY_WARN("transport did not shut down cleanly"); } @@ -4784,9 +5289,17 @@ sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, // on. Don't cache it for retry as well if it fails before exit. sentry__http_transport_set_retry_enabled( options->transport, false); + retain_crash_envelope(options, ipc->shmem, crash_event_id); } } } + if (crash_handler_installed) { + sentry__crash_handler_shutdown(); + } + if (!shared_process) { + sentry__options_set(NULL); + } + if (crash_processed) { // Mark as done SENTRY_DEBUG("Marking crash state as DONE"); @@ -4834,20 +5347,23 @@ int main(int argc, char **argv) { // Expected arguments: - // Linux: - // macOS: -# if defined(SENTRY_PLATFORM_MACOS) - if (argc < 6) { + // Linux/macOS/Android: + // + // Windows: + // +# if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_MACOS) \ + || defined(SENTRY_PLATFORM_ANDROID) + if (argc < 7) { fprintf(stderr, - "Usage: sentry-crash " - " \n"); + "Usage: sentry-crash " + " \n"); return 1; } # else - if (argc < 5) { + if (argc < 6) { fprintf(stderr, "Usage: sentry-crash " - "\n"); + " \n"); return 1; } # endif @@ -4856,22 +5372,34 @@ main(int argc, char **argv) pid_t app_pid = (pid_t)strtoul(argv[1], NULL, 10); uint64_t app_tid = strtoull(argv[2], NULL, 16); -# if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) +# if defined(SENTRY_PLATFORM_ANDROID) + int notify_eventfd = atoi(argv[3]); + int ready_eventfd = atoi(argv[4]); + int shm_fd_arg = atoi(argv[5]); + int message_fd = atoi(argv[6]); + return sentry__crash_daemon_main(app_pid, app_tid, notify_eventfd, + ready_eventfd, shm_fd_arg, message_fd, NULL); +# elif defined(SENTRY_PLATFORM_LINUX) int notify_eventfd = atoi(argv[3]); int ready_eventfd = atoi(argv[4]); - return sentry__crash_daemon_main( - app_pid, app_tid, notify_eventfd, ready_eventfd); + int shm_fd_arg = atoi(argv[5]); + int message_fd = atoi(argv[6]); + return sentry__crash_daemon_main(app_pid, app_tid, notify_eventfd, + ready_eventfd, shm_fd_arg, message_fd); # elif defined(SENTRY_PLATFORM_MACOS) int notify_pipe_read = atoi(argv[3]); int ready_pipe_write = atoi(argv[4]); int shm_fd_arg = atoi(argv[5]); - return sentry__crash_daemon_main( - app_pid, app_tid, notify_pipe_read, ready_pipe_write, shm_fd_arg); + int message_fd = atoi(argv[6]); + return sentry__crash_daemon_main(app_pid, app_tid, notify_pipe_read, + ready_pipe_write, shm_fd_arg, message_fd); # elif defined(SENTRY_PLATFORM_WINDOWS) unsigned long long event_handle_val = strtoull(argv[3], NULL, 10); unsigned long long ready_event_val = strtoull(argv[4], NULL, 10); + unsigned long long message_handle_val = strtoull(argv[5], NULL, 10); HANDLE event_handle = (HANDLE)(uintptr_t)event_handle_val; HANDLE ready_event_handle = (HANDLE)(uintptr_t)ready_event_val; + HANDLE message_read_handle = (HANDLE)(uintptr_t)message_handle_val; # if defined(SENTRY_PLATFORM_XBOX) // Required before any XNetworking call the transport makes at @@ -4884,8 +5412,8 @@ main(int argc, char **argv) NULL, 0, sentry__xbox_network_prewarm_thread_proc, NULL, 0, NULL); # endif - int rv = sentry__crash_daemon_main( - app_pid, app_tid, event_handle, ready_event_handle); + int rv = sentry__crash_daemon_main(app_pid, app_tid, event_handle, + ready_event_handle, message_read_handle); # if defined(SENTRY_PLATFORM_XBOX) if (network_prewarm_thread) { diff --git a/src/backends/native/sentry_crash_daemon.h b/src/backends/native/sentry_crash_daemon.h index e689b39f8f..13a593853b 100644 --- a/src/backends/native/sentry_crash_daemon.h +++ b/src/backends/native/sentry_crash_daemon.h @@ -12,6 +12,7 @@ // Forward declaration struct sentry_options_s; +typedef struct sentry_crash_daemon_s sentry_crash_daemon_t; /** * Daemon main loop (runs in forked child on Unix, or separate process on @@ -21,15 +22,19 @@ struct sentry_options_s; * @param notify_handle Notification handle for crash signals * @param ready_handle Ready signal handle to signal parent */ -#if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) -int sentry__crash_daemon_main( - pid_t app_pid, uint64_t app_tid, int notify_eventfd, int ready_eventfd); +#if defined(SENTRY_PLATFORM_ANDROID) +int sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, + int notify_eventfd, int ready_eventfd, int shm_fd, int message_fd, + sentry_crash_daemon_t *daemon); +#elif defined(SENTRY_PLATFORM_LINUX) +int sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, + int notify_eventfd, int ready_eventfd, int shm_fd, int message_fd); #elif defined(SENTRY_PLATFORM_MACOS) int sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, - int notify_pipe_read, int ready_pipe_write, int shm_fd); + int notify_pipe_read, int ready_pipe_write, int shm_fd, int message_fd); #elif defined(SENTRY_PLATFORM_WINDOWS) int sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, - HANDLE event_handle, HANDLE ready_event_handle); + HANDLE event_handle, HANDLE ready_event_handle, HANDLE message_read_handle); #endif /** @@ -42,9 +47,12 @@ int sentry__crash_daemon_main(pid_t app_pid, uint64_t app_tid, * * @param options Sentry options (DSN, transport, etc.) * @param ipc Crash IPC with crash context in shared memory + * @param daemon Android service-hosted daemon to defer the upload to, or NULL + * @param event_id Receives the ID of the crash sent via transport, or nil * @return true if the crash envelope was captured for upload or reporting */ -bool sentry__process_crash( - const struct sentry_options_s *options, sentry_crash_ipc_t *ipc); +bool sentry__process_crash(const struct sentry_options_s *options, + sentry_crash_ipc_t *ipc, sentry_crash_daemon_t *daemon, + sentry_uuid_t *event_id); #endif diff --git a/src/backends/native/sentry_crash_handler.c b/src/backends/native/sentry_crash_handler.c index a9cabf8ba7..898b7244b7 100644 --- a/src/backends/native/sentry_crash_handler.c +++ b/src/backends/native/sentry_crash_handler.c @@ -25,6 +25,12 @@ # include # include # include +# if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) +# include +# endif +# if defined(SENTRY_PLATFORM_ANDROID) +# include +# endif # include #elif defined(SENTRY_PLATFORM_WINDOWS) # include @@ -32,6 +38,28 @@ # include #endif +static void (*g_crash_callback)(void) = NULL; + +#if (defined(SENTRY_PLATFORM_WINDOWS) \ + && !((defined(_MSC_VER) || defined(__clang__)) \ + && (defined(_M_AMD64) || defined(_M_ARM64)))) \ + || ((defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID)) \ + && !defined(__arm__)) +static inline bool +capture_valid_ip(uint64_t ip) +{ + if (ip < 0x1000) { + return false; + } +# if defined(__x86_64__) || defined(_M_AMD64) + if (ip > 0x00007FFFFFFFFFFFULL) { + return false; + } +# endif + return true; +} +#endif + // signal_safe_memcpy and signal_safe_memzero are only used on Unix // (for signal handler context copying) #if defined(SENTRY_PLATFORM_UNIX) @@ -102,6 +130,8 @@ static sentry_handler_strategy_t g_handler_strategy = SENTRY_HANDLER_STRATEGY_DEFAULT; static struct sigaction g_previous_handlers[16]; static stack_t g_signal_stack = { 0 }; +static volatile long g_handlers_installed = 0; +static volatile long g_preloaded = 0; static void reset_signal_handlers(void) @@ -118,7 +148,7 @@ reraise_signal(int signum) raise(signum); } -static void +static bool invoke_previous_signal_handler(int signum, siginfo_t *info, void *context) { for (size_t i = 0; i < g_crash_signal_count; i++) { @@ -127,8 +157,11 @@ invoke_previous_signal_handler(int signum, siginfo_t *info, void *context) } struct sigaction *handler = &g_previous_handlers[i]; - if (handler->sa_handler == SIG_DFL || handler->sa_handler == SIG_IGN) { - return; + if (handler->sa_handler == SIG_DFL) { + return false; + } + if (handler->sa_handler == SIG_IGN) { + return true; } if (handler->sa_flags & SA_SIGINFO) { @@ -137,8 +170,9 @@ invoke_previous_signal_handler(int signum, siginfo_t *info, void *context) handler->sa_handler(signum); } - return; + return true; } + return false; } /** @@ -286,16 +320,108 @@ safe_build_stack_path( } # endif +# if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) +// libunwindstack uses C++ allocation; keep the handler's FP walk bounded +static void +capture_frame_pointer_stack( + sentry_crash_capture_t *capture, const ucontext_t *uctx) +{ +# if defined(SYS_process_vm_readv) && !defined(__arm__) + uintptr_t sp = sentry__ucontext_get_sp(uctx); + uintptr_t fp = 0; +# if defined(__x86_64__) + fp = (uintptr_t)uctx->uc_mcontext.gregs[REG_RBP]; +# elif defined(__i386__) + fp = (uintptr_t)uctx->uc_mcontext.gregs[REG_EBP]; +# elif defined(__aarch64__) + fp = (uintptr_t)uctx->uc_mcontext.regs[29]; +# elif defined(__riscv) && __riscv_xlen == 64 + fp = (uintptr_t)uctx->uc_mcontext.__gregs[REG_S0]; +# endif + capture->frame_pointer = true; + while (fp && fp >= sp && fp - sp <= SENTRY_CRASH_MAX_STACK_CAPTURE + && fp % sizeof(uintptr_t) == 0 + && capture->count < SENTRY_CRASH_MAX_BACKTRACE_FRAMES) { + uintptr_t pair[2]; + struct iovec local = { pair, sizeof(pair) }; + uintptr_t record = fp; +# if defined(__riscv) && __riscv_xlen == 64 + record -= sizeof(pair); + if (record < sp) { + break; + } +# endif + struct iovec remote = { (void *)record, sizeof(pair) }; + if (syscall(SYS_process_vm_readv, getpid(), &local, 1, &remote, 1, 0) + != (ssize_t)sizeof(pair)) { + break; + } + uintptr_t next = pair[0]; + uintptr_t ret = pair[1]; + if (!ret) { + break; + } + if (!capture_valid_ip(ret) + || (next + && (next <= fp || next < sp + || next - sp > SENTRY_CRASH_MAX_STACK_CAPTURE))) { + break; + } + capture->ips[capture->count++] = (uint64_t)ret; + if (!next) { + break; + } + fp = next; + } +# else + (void)capture; + (void)uctx; +# endif +} +# endif + +# if defined(SENTRY_WITH_UNWINDER_LIBUNWIND) \ + || defined(SENTRY_WITH_UNWINDER_LIBUNWIND_MAC) +static void +capture_stack(sentry_crash_capture_t *capture, ucontext_t *uctx) +{ +# if defined(SENTRY_WITH_UNWINDER_LIBUNWIND) + // the libunwind path stops at IP zero; recover callers via FP + if (capture->ips[0] == 0) { + capture_frame_pointer_stack(capture, uctx); + return; + } +# endif + sentry_ucontext_t context = { 0 }; + context.user_context = uctx; + void *ips[SENTRY_CRASH_MAX_BACKTRACE_FRAMES]; + size_t count = sentry_unwind_stack_from_ucontext( + &context, ips, SENTRY_CRASH_MAX_BACKTRACE_FRAMES); +# if defined(SENTRY_WITH_UNWINDER_LIBUNWIND_MAC) + capture->frame_pointer = true; +# endif + for (size_t i = capture->count; i < count; i++) { + capture->ips[i] = (uint64_t)(uintptr_t)ips[i]; + } + if (count > capture->count) { + capture->count = (uint32_t)count; + } +} +# endif + /** * Signal handler (signal-safe) */ static void crash_signal_handler(int signum, siginfo_t *info, void *context) { + if (g_crash_callback) { + g_crash_callback(); + } sentry__enter_crash_handler(); ucontext_t *uctx = (ucontext_t *)context; -# if defined(SENTRY_PLATFORM_LINUX) && !defined(SENTRY_PLATFORM_ANDROID) +# if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) if (g_handler_strategy == SENTRY_HANDLER_STRATEGY_CHAIN_AT_START && signum != SIGABRT && uctx) { uintptr_t ip = sentry__ucontext_get_ip(uctx); @@ -316,15 +442,26 @@ crash_signal_handler(int signum, siginfo_t *info, void *context) # endif sentry_crash_ipc_t *ipc = g_crash_ipc; - if (!ipc || !ipc->shmem) { - // No IPC available, forward to the previous handler - // Re-enable previous signal handlers before re-raising to prevent loops + if (!uctx || !ipc || !ipc->shmem) { + // No context or IPC available, forward to the previous handler + // Re-enable previous signal handlers to prevent loops reset_signal_handlers(); + bool preloaded = sentry__atomic_fetch(&g_preloaded); + if (preloaded) { + // Consume the preload so that a later init reinstalls the handlers + sentry__atomic_store(&g_handlers_installed, 0); + sentry__atomic_store(&g_preloaded, 0); + } + bool handled = false; if (g_handler_strategy != SENTRY_HANDLER_STRATEGY_CHAIN_AT_START) { - invoke_previous_signal_handler(signum, info, context); + handled = invoke_previous_signal_handler(signum, info, context); } - // The previous handler returned, fall back to default termination sentry__exit_crash_handler(); + if (preloaded && handled) { + // Resume wherever the previous handler left off + return; + } + // The previous handler returned, fall back to default termination reraise_signal(signum); return; } @@ -341,9 +478,30 @@ crash_signal_handler(int signum, siginfo_t *info, void *context) sentry_crash_context_t *ctx = ipc->shmem; +# if defined(SENTRY_PLATFORM_ANDROID) + // Let the daemon ptrace and read this process. Non-debuggable apps are not + // dumpable, and Yama requires a declared ptracer (EINVAL without Yama). + // Not restored, since the process terminates after the crash. + prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); + prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0); +# endif + // Fill crash context ctx->crashed_pid = getpid(); ctx->crashed_tid = get_tid(); + ctx->capture.count = 0; + ctx->capture.frame_pointer = false; +# if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) + uintptr_t fault_ip = sentry__ucontext_get_ip(uctx); +# elif defined(SENTRY_PLATFORM_MACOS) && defined(__x86_64__) + uintptr_t fault_ip = uctx->uc_mcontext->__ss.__rip; +# elif defined(SENTRY_PLATFORM_MACOS) && defined(__aarch64__) + uintptr_t fault_ip + = SENTRY__ARM64_GET_PC(uctx->uc_mcontext->__ss) & 0x00007FFFFFFFFFFFULL; +# else + uintptr_t fault_ip = 0; +# endif + ctx->capture.ips[ctx->capture.count++] = (uint64_t)fault_ip; # if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) ctx->platform.signum = signum; @@ -383,29 +541,16 @@ crash_signal_handler(int signum, siginfo_t *info, void *context) // libunwind's core unwinding API (unw_init_local2, unw_step, unw_get_reg) // is async-signal-safe. The daemon will prefer this over FP-based walking. # ifdef SENTRY_WITH_UNWINDER_LIBUNWIND - ctx->platform.backtrace_count = 0; - { - unw_cursor_t cursor; - int ret = unw_init_local2( - &cursor, (unw_context_t *)uctx, UNW_INIT_SIGNAL_FRAME); - if (ret == 0) { - size_t n = 0; - while (n < SENTRY_CRASH_MAX_BACKTRACE_FRAMES) { - unw_word_t ip = 0; - if (unw_get_reg(&cursor, UNW_REG_IP, &ip) < 0 || ip == 0) { - break; - } - ctx->platform.backtrace_ips[n++] = (uint64_t)ip; - if (unw_step(&cursor) <= 0) { - break; - } - } - ctx->platform.backtrace_count = n; - } - } + capture_stack(&ctx->capture, uctx); +# else + capture_frame_pointer_stack(&ctx->capture, uctx); # endif # elif defined(SENTRY_PLATFORM_MACOS) +# if defined(SENTRY_WITH_UNWINDER_LIBUNWIND_MAC) + capture_stack(&ctx->capture, uctx); +# endif + // Capture all threads (signal-safe on macOS) ctx->platform.num_threads = 0; task_t task = mach_task_self(); @@ -778,13 +923,13 @@ crash_signal_handler(int signum, siginfo_t *info, void *context) SENTRY_CRASH_STATE_CRASHED)) { // Successfully claimed crash slot, notify daemon - sentry__crash_ipc_notify(ipc); + bool notified = sentry__crash_ipc_notify(ipc); // Wait for daemon to finish processing (keep process alive for - // minidump) + // minidump), unless no daemon was there to notify bool processing_started = false; int elapsed_ms = 0; - while (elapsed_ms < SENTRY_CRASH_HANDLER_WAIT_TIMEOUT_MS) { + while (notified && elapsed_ms < SENTRY_CRASH_HANDLER_WAIT_TIMEOUT_MS) { long state = sentry__atomic_fetch(&ctx->state); if (state == SENTRY_CRASH_STATE_PROCESSING && !processing_started) { // Daemon started processing (no logging - signal-safe) @@ -811,7 +956,8 @@ crash_signal_handler(int signum, siginfo_t *info, void *context) // Dump daemon log for debugging (uses stdio, safe after page allocator // enabled) if (ctx && ctx->run_path[0] != '\0') { - char log_path[SENTRY_CRASH_MAX_PATH]; + // Static to save signal stack space (guarded by handling_crash) + static char log_path[SENTRY_CRASH_MAX_PATH]; const char suffix[] = "/sentry-daemon.log"; int len = 0; // Manually build path string (signal-safe) @@ -868,31 +1014,30 @@ crash_signal_handler(int signum, siginfo_t *info, void *context) reraise_signal(signum); } -int -sentry__crash_handler_init( - sentry_crash_ipc_t *ipc, sentry_handler_strategy_t strategy) +static int +install_signal_handlers(sentry_crash_ipc_t *ipc, bool preload, + sentry_handler_strategy_t strategy, void (*callback)(void)) { - if (!ipc) { + if (!preload && !ipc && !callback) { return -1; } + if (sentry__atomic_fetch(&g_handlers_installed)) { + if (!preload) { + g_crash_ipc = ipc; + g_handler_strategy = strategy; + } + return 0; + } + g_crash_ipc = ipc; g_handler_strategy = strategy; + g_crash_callback = callback; // Set up signal stack - g_signal_stack.ss_sp = sentry_malloc(SENTRY_CRASH_SIGNAL_STACK_SIZE); - if (!g_signal_stack.ss_sp) { - SENTRY_WARN("failed to allocate signal stack"); - return -1; - } - - g_signal_stack.ss_size = SENTRY_CRASH_SIGNAL_STACK_SIZE; - g_signal_stack.ss_flags = 0; - - if (sigaltstack(&g_signal_stack, NULL) < 0) { - SENTRY_WARNF("failed to set signal stack: %s", strerror(errno)); - sentry_free(g_signal_stack.ss_sp); - g_signal_stack.ss_sp = NULL; + if (sentry__setup_sigaltstack( + &g_signal_stack, SENTRY_CRASH_SIGNAL_STACK_SIZE, "init") + < 0) { return -1; } @@ -902,6 +1047,9 @@ sentry__crash_handler_init( sigemptyset(&sa.sa_mask); sa.sa_sigaction = crash_signal_handler; sa.sa_flags = SA_SIGINFO | SA_ONSTACK; + if (g_crash_callback) { + sa.sa_flags |= SA_NODEFER; + } size_t installed_count = 0; for (size_t i = 0; i < g_crash_signal_count; i++) { @@ -914,15 +1062,18 @@ sentry__crash_handler_init( sigaction(g_crash_signals[j], &g_previous_handlers[j], NULL); } // Clean up signal stack - g_signal_stack.ss_flags = SS_DISABLE; - sigaltstack(&g_signal_stack, NULL); - sentry_free(g_signal_stack.ss_sp); - g_signal_stack.ss_sp = NULL; + sentry__teardown_sigaltstack(&g_signal_stack); return -1; } installed_count++; } + g_crash_ipc = ipc; + sentry__atomic_store(&g_handlers_installed, 1); + if (preload) { + sentry__atomic_store(&g_preloaded, 1); + } + // Prime libunwind's internal cache by performing a short unwind. // This forces dl_iterate_phdr to be called now (while safe) rather than // in the signal handler where it could deadlock if the crash occurs @@ -932,14 +1083,13 @@ sentry__crash_handler_init( { unw_context_t uc; unw_cursor_t cursor; -# ifdef __clang__ -# pragma clang diagnostic push -# pragma clang diagnostic ignored \ - "-Wgnu-statement-expression-from-macro-expansion" +# ifdef __GNUC__ +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wpedantic" # endif if (unw_getcontext(&uc) == 0) { -# ifdef __clang__ -# pragma clang diagnostic pop +# ifdef __GNUC__ +# pragma GCC diagnostic pop # endif if (unw_init_local(&cursor, &uc) == 0) { // Walk a few frames to ensure .eh_frame info is cached @@ -956,10 +1106,24 @@ sentry__crash_handler_init( return 0; } +int +sentry__crash_handler_init(sentry_crash_ipc_t *ipc, + sentry_handler_strategy_t strategy, void (*callback)(void)) +{ + return install_signal_handlers(ipc, false, strategy, callback); +} + +int +sentry__crash_handler_preload(void) +{ + return install_signal_handlers( + NULL, true, SENTRY_HANDLER_STRATEGY_DEFAULT, NULL); +} + int sentry__crash_handler_reinstall(void) { - if (!g_crash_ipc) { + if (!g_crash_ipc && !g_crash_callback) { return -1; } @@ -968,6 +1132,9 @@ sentry__crash_handler_reinstall(void) sigemptyset(&sa.sa_mask); sa.sa_sigaction = crash_signal_handler; sa.sa_flags = SA_SIGINFO | SA_ONSTACK; + if (g_crash_callback) { + sa.sa_flags |= SA_NODEFER; + } for (size_t i = 0; i < g_crash_signal_count; i++) { struct sigaction previous; @@ -988,18 +1155,26 @@ sentry__crash_handler_reinstall(void) void sentry__crash_handler_shutdown(void) { + if (sentry__atomic_fetch(&g_preloaded)) { + g_crash_ipc = NULL; + SENTRY_DEBUG("crash handler deactivated, keeping preloaded handlers"); + return; + } + + if (!sentry__atomic_fetch(&g_handlers_installed)) { + return; + } + // Restore previous signal handlers reset_signal_handlers(); // Clean up signal stack - if (g_signal_stack.ss_sp) { - g_signal_stack.ss_flags = SS_DISABLE; - sigaltstack(&g_signal_stack, NULL); - sentry_free(g_signal_stack.ss_sp); - g_signal_stack.ss_sp = NULL; - } + sentry__teardown_sigaltstack(&g_signal_stack); g_crash_ipc = NULL; + g_crash_callback = NULL; + sentry__atomic_store(&g_handlers_installed, 0); + sentry__atomic_store(&g_preloaded, 0); SENTRY_DEBUG("crash handler shutdown"); } @@ -1012,6 +1187,69 @@ static LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = NULL; static LONG WINAPI crash_exception_filter(EXCEPTION_POINTERS *exception_info); +static void +capture_windows_stack(sentry_crash_capture_t *capture, const CONTEXT *original) +{ + capture->count = 0; + capture->frame_pointer = false; +# if (defined(_MSC_VER) || defined(__clang__)) \ + && (defined(_M_AMD64) || defined(_M_ARM64)) + sentry_ucontext_t uctx = { 0 }; + uctx.exception_ptrs.ContextRecord = (CONTEXT *)original; + void *ips[SENTRY_CRASH_MAX_BACKTRACE_FRAMES]; + capture->count = (uint32_t)sentry_unwind_stack_from_ucontext( + &uctx, ips, SENTRY_CRASH_MAX_BACKTRACE_FRAMES); + for (size_t i = 0; i < capture->count; i++) { + capture->ips[i] = (uint64_t)(uintptr_t)ips[i]; + } +# elif defined(_M_AMD64) || defined(_M_IX86) || defined(_M_ARM64) +# if defined(_M_AMD64) + uintptr_t ip = original->Rip; + uintptr_t fp = original->Rbp; + uintptr_t sp = original->Rsp; +# elif defined(_M_IX86) + uintptr_t ip = original->Eip; + uintptr_t fp = original->Ebp; + uintptr_t sp = original->Esp; +# else + uintptr_t ip = original->Pc; + uintptr_t fp = original->Fp; + uintptr_t sp = original->Sp; +# endif + capture->ips[capture->count++] = ip; + capture->frame_pointer = true; + while (fp && fp >= sp && fp - sp <= SENTRY_CRASH_MAX_STACK_CAPTURE + && fp % sizeof(uintptr_t) == 0 + && capture->count < SENTRY_CRASH_MAX_BACKTRACE_FRAMES) { + uintptr_t pair[2]; + SIZE_T read = 0; + if (!ReadProcessMemory( + GetCurrentProcess(), (void *)fp, pair, sizeof(pair), &read) + || read != sizeof(pair)) { + break; + } + if (!pair[1]) { + break; + } + if (!capture_valid_ip(pair[1]) + || (pair[0] + && (pair[0] <= fp || pair[0] < sp + || pair[0] - sp > SENTRY_CRASH_MAX_STACK_CAPTURE))) { + break; + } + capture->ips[capture->count++] = pair[1]; + if (!pair[0]) { + break; + } + fp = pair[0]; + } +# elif defined(_M_ARM) + capture->ips[capture->count++] = original->Pc; +# else + (void)original; +# endif +} + static void crash_sigabrt_handler(EXCEPTION_POINTERS *exception_pointers) { @@ -1024,6 +1262,16 @@ crash_sigabrt_handler(EXCEPTION_POINTERS *exception_pointers) static LONG WINAPI crash_exception_filter(EXCEPTION_POINTERS *exception_info) { + if (g_crash_callback) { + DWORD code = exception_info->ExceptionRecord->ExceptionCode; + if (code == EXCEPTION_BREAKPOINT || code == EXCEPTION_SINGLE_STEP) { + return EXCEPTION_CONTINUE_SEARCH; + } + g_crash_callback(); + SetUnhandledExceptionFilter(g_previous_filter); + return EXCEPTION_CONTINUE_SEARCH; + } + sentry__enter_crash_handler(); // Only handle crash once static volatile long handling_crash = 0; @@ -1075,6 +1323,8 @@ crash_exception_filter(EXCEPTION_POINTERS *exception_info) sentry__crash_ipc_notify(ipc); } + capture_windows_stack(&ctx->capture, exception_info->ContextRecord); + // Call Sentry's exception handler sentry_ucontext_t sentry_uctx = { 0 }; sentry_uctx.exception_ptrs = *exception_info; @@ -1110,15 +1360,16 @@ crash_exception_filter(EXCEPTION_POINTERS *exception_info) } int -sentry__crash_handler_init( - sentry_crash_ipc_t *ipc, sentry_handler_strategy_t strategy) +sentry__crash_handler_init(sentry_crash_ipc_t *ipc, + sentry_handler_strategy_t strategy, void (*callback)(void)) { - if (!ipc) { + if (!ipc && !callback) { return -1; } (void)strategy; g_crash_ipc = ipc; + g_crash_callback = callback; sentry__crash_handler_reinstall(); @@ -1129,7 +1380,7 @@ sentry__crash_handler_init( int sentry__crash_handler_reinstall(void) { - if (!g_crash_ipc) { + if (!g_crash_ipc && !g_crash_callback) { return -1; } @@ -1147,7 +1398,7 @@ void sentry__crash_handler_shutdown(void) { // Restore previous exception filter (including NULL) - if (g_crash_ipc) { + if (g_crash_ipc || g_crash_callback) { SetUnhandledExceptionFilter(g_previous_filter); g_previous_filter = NULL; } @@ -1155,6 +1406,7 @@ sentry__crash_handler_shutdown(void) sentry__win32_restore_sigabrt_handler(); g_crash_ipc = NULL; + g_crash_callback = NULL; SENTRY_DEBUG("crash handler shutdown"); } diff --git a/src/backends/native/sentry_crash_handler.h b/src/backends/native/sentry_crash_handler.h index bf54eed3df..cf409f9969 100644 --- a/src/backends/native/sentry_crash_handler.h +++ b/src/backends/native/sentry_crash_handler.h @@ -7,14 +7,19 @@ /** * Initialize crash handler (install signal handlers) */ -int sentry__crash_handler_init( - sentry_crash_ipc_t *ipc, sentry_handler_strategy_t strategy); +int sentry__crash_handler_init(sentry_crash_ipc_t *ipc, + sentry_handler_strategy_t strategy, void (*callback)(void)); /** * Reinstalls crash handlers while retaining IPC and the signal stack. */ int sentry__crash_handler_reinstall(void); +/** + * Preload crash handler before full initialization. + */ +int sentry__crash_handler_preload(void); + /** * Shutdown crash handler (restore previous handlers) */ diff --git a/src/backends/native/sentry_crash_ipc.c b/src/backends/native/sentry_crash_ipc.c index deafe3ca51..d3c9269517 100644 --- a/src/backends/native/sentry_crash_ipc.c +++ b/src/backends/native/sentry_crash_ipc.c @@ -1,42 +1,282 @@ #include "sentry_crash_ipc.h" #include "sentry_alloc.h" +#include "sentry_core.h" #include "sentry_logger.h" +#include "sentry_random.h" #include "sentry_sync.h" +#include "sentry_utils.h" +#include "sentry_value.h" #include #include +#if defined(SENTRY_PLATFORM_UNIX) +# include +#endif + +static void +write_u16_le(char *buf, uint16_t value) +{ + buf[0] = (char)(value & 0xffu); + buf[1] = (char)((value >> 8) & 0xffu); +} + +static void +write_u32_le(char *buf, uint32_t value) +{ + buf[0] = (char)(value & 0xffu); + buf[1] = (char)((value >> 8) & 0xffu); + buf[2] = (char)((value >> 16) & 0xffu); + buf[3] = (char)((value >> 24) & 0xffu); +} + +static void +write_u64_le(char *buf, uint64_t value) +{ + for (size_t i = 0; i < 8; i++) { + buf[i] = (char)((value >> (i * 8)) & 0xffu); + } +} + +static uint16_t +read_u16_le(const char *buf) +{ + return (uint16_t)((uint8_t)buf[0] | ((uint16_t)(uint8_t)buf[1] << 8)); +} + +static uint32_t +read_u32_le(const char *buf) +{ + return (uint32_t)(uint8_t)buf[0] | ((uint32_t)(uint8_t)buf[1] << 8) + | ((uint32_t)(uint8_t)buf[2] << 16) | ((uint32_t)(uint8_t)buf[3] << 24); +} + +static uint64_t +read_u64_le(const char *buf) +{ + uint64_t value = 0; + for (size_t i = 0; i < 8; i++) { + value |= (uint64_t)(uint8_t)buf[i] << (i * 8); + } + return value; +} + +bool +sentry__crash_ipc_message_type_is_known(uint16_t type) +{ + return type >= SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT + && type <= SENTRY_CRASH_IPC_MESSAGE_SHUTDOWN; +} + +sentry_crash_ipc_message_result_t +sentry__crash_ipc_message_encode(uint16_t type, uint16_t flags, + uint64_t sequence, const char *payload, size_t payload_len, char **out_buf, + size_t *out_len) +{ + if (!out_buf || !out_len || (payload_len && !payload) + || !sentry__crash_ipc_message_type_is_known(type)) { + return !sentry__crash_ipc_message_type_is_known(type) + ? SENTRY_CRASH_IPC_MESSAGE_UNKNOWN_TYPE + : SENTRY_CRASH_IPC_MESSAGE_INVALID; + } + + if (payload_len > SENTRY_CRASH_IPC_MESSAGE_MAX_LEN + - SENTRY_CRASH_IPC_MESSAGE_MIN_LEN + || payload_len > SIZE_MAX - SENTRY_CRASH_IPC_MESSAGE_HEADER_SIZE) { + return SENTRY_CRASH_IPC_MESSAGE_OVERSIZED; + } + + uint32_t message_len + = (uint32_t)(SENTRY_CRASH_IPC_MESSAGE_MIN_LEN + payload_len); + size_t total_len + = SENTRY_CRASH_IPC_MESSAGE_PREFIX_SIZE + (size_t)message_len; + char *buf = sentry_malloc(total_len); + if (!buf) { + return SENTRY_CRASH_IPC_MESSAGE_OOM; + } + + write_u32_le(buf, message_len); + write_u16_le(buf + 4, type); + write_u16_le(buf + 6, flags); + write_u64_le(buf + 8, sequence); + if (payload_len) { + memcpy( + buf + SENTRY_CRASH_IPC_MESSAGE_HEADER_SIZE, payload, payload_len); + } + + *out_buf = buf; + *out_len = total_len; + return SENTRY_CRASH_IPC_MESSAGE_OK; +} + +sentry_crash_ipc_message_result_t +sentry__crash_ipc_message_decode( + const char *buf, size_t buf_len, sentry_crash_ipc_message_t *message) +{ + if (!buf || !message) { + return SENTRY_CRASH_IPC_MESSAGE_INVALID; + } + if (buf_len < SENTRY_CRASH_IPC_MESSAGE_PREFIX_SIZE) { + return SENTRY_CRASH_IPC_MESSAGE_PARTIAL; + } + + uint32_t message_len = read_u32_le(buf); + if (message_len > SENTRY_CRASH_IPC_MESSAGE_MAX_LEN) { + return SENTRY_CRASH_IPC_MESSAGE_OVERSIZED; + } + if (message_len < SENTRY_CRASH_IPC_MESSAGE_MIN_LEN) { + return SENTRY_CRASH_IPC_MESSAGE_INVALID; + } +#if SIZE_MAX <= UINT32_MAX + if (message_len > SIZE_MAX - SENTRY_CRASH_IPC_MESSAGE_PREFIX_SIZE) { + return SENTRY_CRASH_IPC_MESSAGE_OVERSIZED; + } +#endif + + size_t total_len + = SENTRY_CRASH_IPC_MESSAGE_PREFIX_SIZE + (size_t)message_len; + if (buf_len < total_len) { + return SENTRY_CRASH_IPC_MESSAGE_PARTIAL; + } + if (buf_len > total_len) { + return SENTRY_CRASH_IPC_MESSAGE_INVALID; + } + + uint16_t type = read_u16_le(buf + 4); + if (!sentry__crash_ipc_message_type_is_known(type)) { + return SENTRY_CRASH_IPC_MESSAGE_UNKNOWN_TYPE; + } + + message->type = type; + message->flags = read_u16_le(buf + 6); + message->sequence = read_u64_le(buf + 8); + message->payload = buf + SENTRY_CRASH_IPC_MESSAGE_HEADER_SIZE; + message->payload_len = message_len - SENTRY_CRASH_IPC_MESSAGE_MIN_LEN; + return SENTRY_CRASH_IPC_MESSAGE_OK; +} + #if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) # include # include # include +# include # include +# include # include +# include # include -sentry_crash_ipc_t * -sentry__crash_ipc_init_app(sem_t *init_sem) +# ifndef MFD_CLOEXEC +# define MFD_CLOEXEC 0x0001U +# endif + +int +sentry__crash_ipc_create_memfd(void) { - sentry_crash_ipc_t *ipc = SENTRY_MAKE(sentry_crash_ipc_t); - if (!ipc) { - return NULL; +# ifdef SYS_memfd_create + return (int)syscall(SYS_memfd_create, "sentry-crash", MFD_CLOEXEC); +# else + errno = ENOSYS; + return -1; +# endif +} + +# if defined(SENTRY_PLATFORM_ANDROID) +// Bionic implements neither shm_open() nor sem_open(). Map a file in the +// database directory instead, and lock initialization with a mutex. +static int +shm_create(sentry_crash_ipc_t *ipc) +{ + return open(ipc->shm_name, O_CREAT | O_RDWR | O_EXCL | O_CLOEXEC, 0600); +} + +static int +shm_reopen(sentry_crash_ipc_t *ipc) +{ + return open(ipc->shm_name, O_RDWR | O_CLOEXEC); +} + +static void +shm_remove(sentry_crash_ipc_t *ipc) +{ + unlink(ipc->shm_name); +} + +static bool +init_lock(sentry_crash_ipc_t *ipc) +{ + if (ipc->init_mutex) { + sentry__mutex_lock(ipc->init_mutex); } - ipc->is_daemon = false; - ipc->init_sem = init_sem; // Use provided semaphore (managed by backend) + return true; +} - // Create shared memory with unique name based on PID and thread ID - // macOS has a 31-character limit for POSIX shared memory names (PSEMNAMLEN) - // Format: /s-{8_hex_chars} = 11 chars total (well under 31 limit) - // We mix PID and TID to create a unique 32-bit identifier, allowing - // multiple sentry_init() calls from different threads in the same process. - uint64_t tid = (uint64_t)pthread_self(); - uint32_t id = (uint32_t)((getpid() ^ (tid & 0xFFFFFFFF)) & 0xFFFFFFFF); - snprintf(ipc->shm_name, sizeof(ipc->shm_name), "/s-%08x", id); +static void +init_unlock(sentry_crash_ipc_t *ipc) +{ + if (ipc->init_mutex) { + sentry__mutex_unlock(ipc->init_mutex); + } +} +# else +static int +shm_create(sentry_crash_ipc_t *ipc) +{ + // shm_open() memory raises SIGBUS on write when /dev/shm is full + int fd = sentry__crash_ipc_create_memfd(); + if (fd >= 0) { + ipc->shm_name[0] = '\0'; + return fd; + } + return shm_open(ipc->shm_name, O_CREAT | O_RDWR | O_EXCL, 0600); +} + +static int +shm_reopen(sentry_crash_ipc_t *ipc) +{ + return shm_open(ipc->shm_name, O_RDWR, 0600); +} + +static void +shm_remove(sentry_crash_ipc_t *ipc) +{ + shm_unlink(ipc->shm_name); +} + +static bool +init_lock(sentry_crash_ipc_t *ipc) +{ + return !ipc->init_sem || sem_wait(ipc->init_sem) == 0; +} + +static void +init_unlock(sentry_crash_ipc_t *ipc) +{ + if (ipc->init_sem) { + sem_post(ipc->init_sem); + } +} +# endif + +/** + * Creates what was not handed over (-1): the shared memory, or reuses that + * named by `ipc->shm_name`, and the notification and message fds. + */ +static sentry_crash_ipc_t * +init_app(sentry_crash_ipc_t *ipc, int shm_fd, int notify_fd, int ready_fd, + int message_fd) +{ + ipc->is_daemon = false; + ipc->shm_fd = shm_fd; + ipc->notify_fd = notify_fd; + ipc->ready_fd = ready_fd; + ipc->message_fd[0] = message_fd; + ipc->message_fd[1] = -1; - // Acquire semaphore for exclusive access during initialization - if (ipc->init_sem && sem_wait(ipc->init_sem) < 0) { + // Acquire exclusive access during initialization + if (!init_lock(ipc)) { SENTRY_WARNF( "failed to acquire initialization semaphore: %s", strerror(errno)); sentry_free(ipc); @@ -45,20 +285,18 @@ sentry__crash_ipc_init_app(sem_t *init_sem) // Try to create or open shared memory bool shm_exists = false; - ipc->shm_fd = shm_open(ipc->shm_name, O_CREAT | O_RDWR | O_EXCL, 0600); + if (ipc->shm_fd < 0) { + ipc->shm_fd = shm_create(ipc); + } if (ipc->shm_fd < 0 && errno == EEXIST) { // Shared memory already exists - reuse it shm_exists = true; - ipc->shm_fd = shm_open(ipc->shm_name, O_RDWR, 0600); + ipc->shm_fd = shm_reopen(ipc); } if (ipc->shm_fd < 0) { SENTRY_WARNF("failed to open shared memory: %s", strerror(errno)); - if (ipc->init_sem) { - sem_post(ipc->init_sem); - } - sentry_free(ipc); - return NULL; + goto fail; } // Verify and resize shared memory (both new and existing) @@ -67,37 +305,21 @@ sentry__crash_ipc_init_app(sem_t *init_sem) struct stat st; if (fstat(ipc->shm_fd, &st) < 0) { SENTRY_WARNF("failed to stat shared memory: %s", strerror(errno)); - close(ipc->shm_fd); - if (ipc->init_sem) { - sem_post(ipc->init_sem); - } - sentry_free(ipc); - return NULL; + goto fail; } if (st.st_size != SENTRY_CRASH_SHM_SIZE) { // Existing shm has wrong size, resize it if (ftruncate(ipc->shm_fd, SENTRY_CRASH_SHM_SIZE) < 0) { SENTRY_WARNF("failed to resize existing shared memory: %s", strerror(errno)); - close(ipc->shm_fd); - if (ipc->init_sem) { - sem_post(ipc->init_sem); - } - sentry_free(ipc); - return NULL; + goto fail; } } } else { // New shared memory, set size if (ftruncate(ipc->shm_fd, SENTRY_CRASH_SHM_SIZE) < 0) { SENTRY_WARNF("failed to resize shared memory: %s", strerror(errno)); - close(ipc->shm_fd); - shm_unlink(ipc->shm_name); - if (ipc->init_sem) { - sem_post(ipc->init_sem); - } - sentry_free(ipc); - return NULL; + goto fail; } } @@ -106,88 +328,205 @@ sentry__crash_ipc_init_app(sem_t *init_sem) MAP_SHARED, ipc->shm_fd, 0); if (ipc->shmem == MAP_FAILED) { SENTRY_WARNF("failed to map shared memory: %s", strerror(errno)); - close(ipc->shm_fd); - if (!shm_exists) { - shm_unlink(ipc->shm_name); - } - if (ipc->init_sem) { - sem_post(ipc->init_sem); - } - sentry_free(ipc); - return NULL; + ipc->shmem = NULL; + goto fail; } // Create eventfd for crash notifications - ipc->notify_fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK); if (ipc->notify_fd < 0) { - SENTRY_WARNF("failed to create eventfd: %s", strerror(errno)); - munmap(ipc->shmem, SENTRY_CRASH_SHM_SIZE); - close(ipc->shm_fd); - if (!shm_exists) { - shm_unlink(ipc->shm_name); + ipc->notify_fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK); + if (ipc->notify_fd < 0) { + SENTRY_WARNF("failed to create eventfd: %s", strerror(errno)); + goto fail; } - if (ipc->init_sem) { - sem_post(ipc->init_sem); - } - sentry_free(ipc); - return NULL; } // Create eventfd for daemon ready signal - ipc->ready_fd = eventfd(0, EFD_CLOEXEC); if (ipc->ready_fd < 0) { - SENTRY_WARNF("failed to create ready eventfd: %s", strerror(errno)); - close(ipc->notify_fd); - munmap(ipc->shmem, SENTRY_CRASH_SHM_SIZE); - close(ipc->shm_fd); - if (!shm_exists) { - shm_unlink(ipc->shm_name); + ipc->ready_fd = eventfd(0, EFD_CLOEXEC); + if (ipc->ready_fd < 0) { + SENTRY_WARNF("failed to create ready eventfd: %s", strerror(errno)); + goto fail; } - if (ipc->init_sem) { - sem_post(ipc->init_sem); - } - sentry_free(ipc); - return NULL; } + if (ipc->message_fd[0] < 0 + && socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc->message_fd) + < 0) { + SENTRY_WARNF( + "failed to create message socketpair: %s", strerror(errno)); + goto fail; + } + + struct timeval send_timeout + = { SENTRY_CRASH_IPC_SEND_TIMEOUT_MS / 1000, 0 }; + setsockopt(ipc->message_fd[0], SOL_SOCKET, SO_SNDTIMEO, &send_timeout, + sizeof(send_timeout)); + // Initialize shared memory only if newly created if (!shm_exists) { sentry__crash_context_init(ipc->shmem); } - // Release semaphore after initialization - if (ipc->init_sem) { - sem_post(ipc->init_sem); - } + // Release exclusive access after initialization + init_unlock(ipc); SENTRY_DEBUGF("initialized crash IPC (shm=%s, notify_fd=%d)", ipc->shm_name, ipc->notify_fd); return ipc; + +fail: + if (ipc->message_fd[0] >= 0) { + close(ipc->message_fd[0]); + } + if (ipc->message_fd[1] >= 0) { + close(ipc->message_fd[1]); + } + if (ipc->ready_fd >= 0) { + close(ipc->ready_fd); + } + if (ipc->notify_fd >= 0) { + close(ipc->notify_fd); + } + if (ipc->shmem) { + munmap(ipc->shmem, SENTRY_CRASH_SHM_SIZE); + } + if (ipc->shm_fd >= 0) { + close(ipc->shm_fd); + if (!shm_exists) { + sentry__crash_ipc_unlink(ipc); + } + } + init_unlock(ipc); + sentry_free(ipc); + return NULL; } +# if defined(SENTRY_PLATFORM_ANDROID) sentry_crash_ipc_t * -sentry__crash_ipc_init_daemon( - pid_t app_pid, uint64_t app_tid, int notify_eventfd, int ready_eventfd) +sentry__crash_ipc_init_app( + const char *database_path, sentry_mutex_t *init_mutex) { + if (!database_path || !database_path[0]) { + SENTRY_WARN("Android crash IPC requires a database path"); + return NULL; + } + sentry_crash_ipc_t *ipc = SENTRY_MAKE(sentry_crash_ipc_t); if (!ipc) { return NULL; } - ipc->is_daemon = true; + ipc->init_mutex = init_mutex; - // Open existing shared memory created by app (using PID and thread ID) - // Must match the format in sentry__crash_ipc_init_app - uint32_t id = (uint32_t)((app_pid ^ (app_tid & 0xFFFFFFFF)) & 0xFFFFFFFF); + uint64_t tid = (uint64_t)pthread_self(); + uint32_t id = (uint32_t)((getpid() ^ (tid & 0xFFFFFFFF)) & 0xFFFFFFFF); + snprintf(ipc->shm_name, sizeof(ipc->shm_name), "%s/.sentry-shm-%08x", + database_path, id); + + return init_app(ipc, -1, -1, -1, -1); +} + +sentry_crash_ipc_t * +sentry__crash_ipc_init_app_with_fds(int shm_fd, int notify_fd, int ready_fd, + int message_fd, sentry_mutex_t *init_mutex) +{ + sentry_crash_ipc_t *ipc = SENTRY_MAKE(sentry_crash_ipc_t); + if (!ipc) { + close(shm_fd); + close(notify_fd); + close(ready_fd); + close(message_fd); + return NULL; + } + ipc->init_mutex = init_mutex; + // the crash service attaches after the app has started + ipc->awaiting_ready = 1; + + return init_app(ipc, shm_fd, notify_fd, ready_fd, message_fd); +} + +bool +sentry__crash_ipc_reattach( + sentry_crash_ipc_t *ipc, int notify_fd, int ready_fd, int message_fd) +{ + bool reattached = false; + if (ipc && !ipc->is_daemon + && sentry__atomic_fetch(&ipc->shmem->state) + == SENTRY_CRASH_STATE_READY) { + // stop new frames, and let one in flight finish + sentry__atomic_store(&ipc->message_failed, 1); + while (!sentry__atomic_compare_swap(&ipc->writing, 0, 1)) { + sched_yield(); + } + // in place, so that the crash handler never reads a closed fd + reattached = dup3(notify_fd, ipc->notify_fd, O_CLOEXEC) >= 0 + && dup3(ready_fd, ipc->ready_fd, O_CLOEXEC) >= 0 + && dup3(message_fd, ipc->message_fd[0], O_CLOEXEC) >= 0; + if (reattached) { + struct timeval send_timeout + = { SENTRY_CRASH_IPC_SEND_TIMEOUT_MS / 1000, 0 }; + setsockopt(ipc->message_fd[0], SOL_SOCKET, SO_SNDTIMEO, + &send_timeout, sizeof(send_timeout)); + // a new daemon starts at a snapshot with sequence 1 + ipc->sequence = 0; + sentry_free(ipc->torn_frame); + ipc->torn_frame = NULL; + sentry__atomic_store(&ipc->stalled, 0); + sentry__atomic_store(&ipc->awaiting_ready, 1); + sentry__atomic_store(&ipc->message_failed, 0); + } + sentry__atomic_store(&ipc->writing, 0); + } + close(notify_fd); + close(ready_fd); + close(message_fd); + return reattached; +} +# else +sentry_crash_ipc_t * +sentry__crash_ipc_init_app(sem_t *init_sem) +{ + sentry_crash_ipc_t *ipc = SENTRY_MAKE(sentry_crash_ipc_t); + if (!ipc) { + return NULL; + } + ipc->init_sem = init_sem; // Use provided semaphore (managed by backend) + + // Create shared memory with unique name based on PID and thread ID + // macOS has a 31-character limit for POSIX shared memory names (PSEMNAMLEN) + // Format: /s-{8_hex_chars} = 11 chars total (well under 31 limit) + // We mix PID and TID to create a unique 32-bit identifier, allowing + // multiple sentry_init() calls from different threads in the same process. + uint64_t tid = (uint64_t)pthread_self(); + uint32_t id = (uint32_t)((getpid() ^ (tid & 0xFFFFFFFF)) & 0xFFFFFFFF); snprintf(ipc->shm_name, sizeof(ipc->shm_name), "/s-%08x", id); - ipc->shm_fd = shm_open(ipc->shm_name, O_RDWR, 0600); - if (ipc->shm_fd < 0) { - SENTRY_WARNF( - "daemon: failed to open shared memory: %s", strerror(errno)); - sentry_free(ipc); + return init_app(ipc, -1, -1, -1, -1); +} +# endif + +sentry_crash_ipc_t * +sentry__crash_ipc_init_daemon(pid_t app_pid, uint64_t app_tid, + int notify_eventfd, int ready_eventfd, int shm_fd, int message_fd) +{ + sentry_crash_ipc_t *ipc = SENTRY_MAKE(sentry_crash_ipc_t); + if (!ipc) { + close(shm_fd); return NULL; } + ipc->is_daemon = true; + ipc->message_fd[0] = -1; + ipc->message_fd[1] = message_fd; + fcntl(message_fd, F_SETFD, FD_CLOEXEC); + + // Shared memory is handed over open, its name is only needed to unlink it + // Must match the format in sentry__crash_ipc_init_app + uint32_t id = (uint32_t)((app_pid ^ (app_tid & 0xFFFFFFFF)) & 0xFFFFFFFF); + ipc->shm_fd = shm_fd; +# if !defined(SENTRY_PLATFORM_ANDROID) + snprintf(ipc->shm_name, sizeof(ipc->shm_name), "/s-%08x", id); +# endif // Map shared memory ipc->shmem = mmap(NULL, SENTRY_CRASH_SHM_SIZE, PROT_READ | PROT_WRITE, @@ -209,6 +548,13 @@ sentry__crash_ipc_init_daemon( return NULL; } +# if defined(SENTRY_PLATFORM_ANDROID) + if (ipc->shmem->database_path[0]) { + snprintf(ipc->shm_name, sizeof(ipc->shm_name), "%s/.sentry-shm-%08x", + ipc->shmem->database_path, id); + } +# endif + // Eventfds are inherited from parent after fork - assign them ipc->notify_fd = notify_eventfd; ipc->ready_fd = ready_eventfd; @@ -220,18 +566,24 @@ sentry__crash_ipc_init_daemon( return ipc; } -void -sentry__crash_ipc_notify(sentry_crash_ipc_t *ipc) +static bool +notify_fallback(sentry_crash_ipc_t *ipc) { if (!ipc || ipc->notify_fd < 0) { - return; + return false; + } + + // a pipe without a reader would raise SIGPIPE, the daemon is gone + struct pollfd pfd = { .fd = ipc->notify_fd, .events = POLLOUT }; + if (poll(&pfd, 1, 0) == 1 && (pfd.revents & (POLLERR | POLLHUP))) { + return false; } // Write to eventfd to wake up daemon // This is signal-safe uint64_t val = 1; ssize_t written = write(ipc->notify_fd, &val, sizeof(val)); - (void)written; // Ignore errors in signal handler + return written == (ssize_t)sizeof(val); } bool @@ -268,7 +620,7 @@ void sentry__crash_ipc_unlink(sentry_crash_ipc_t *ipc) { if (ipc && ipc->shm_name[0]) { - shm_unlink(ipc->shm_name); + shm_remove(ipc); } } @@ -279,6 +631,10 @@ sentry__crash_ipc_free(sentry_crash_ipc_t *ipc) return; } + sentry_free(ipc->message_buf); + sentry_free(ipc->torn_frame); + sentry__crash_scope_free(&ipc->scope); + if (ipc->shmem && ipc->shmem != MAP_FAILED) { munmap(ipc->shmem, SENTRY_CRASH_SHM_SIZE); } @@ -299,6 +655,13 @@ sentry__crash_ipc_free(sentry_crash_ipc_t *ipc) close(ipc->ready_fd); } + if (ipc->message_fd[0] >= 0) { + close(ipc->message_fd[0]); + } + if (ipc->message_fd[1] >= 0) { + close(ipc->message_fd[1]); + } + sentry_free(ipc); } @@ -309,6 +672,7 @@ sentry__crash_ipc_free(sentry_crash_ipc_t *ipc) # include # include # include +# include # include # include @@ -321,6 +685,8 @@ sentry__crash_ipc_init_app(sentry_mutex_t *init_mutex) } ipc->is_daemon = false; ipc->init_mutex = init_mutex; + ipc->message_fd[0] = -1; + ipc->message_fd[1] = -1; // Build a file path for shared memory using the system temp directory. // Unlike shm_open(), regular files in $TMPDIR work inside App Sandbox. @@ -445,6 +811,34 @@ sentry__crash_ipc_init_app(sentry_mutex_t *init_mutex) return NULL; } + if (socketpair(AF_UNIX, SOCK_STREAM, 0, ipc->message_fd) < 0) { + SENTRY_WARNF( + "failed to create message socketpair: %s", strerror(errno)); + close(ipc->ready_pipe[0]); + close(ipc->ready_pipe[1]); + close(ipc->notify_pipe[0]); + close(ipc->notify_pipe[1]); + munmap(ipc->shmem, SENTRY_CRASH_SHM_SIZE); + close(ipc->shm_fd); + if (!shm_exists) { + unlink(ipc->shm_path); + } + if (ipc->init_mutex) { + sentry__mutex_unlock(ipc->init_mutex); + } + sentry_free(ipc); + return NULL; + } + int no_sigpipe = 1; + setsockopt(ipc->message_fd[0], SOL_SOCKET, SO_NOSIGPIPE, &no_sigpipe, + sizeof(no_sigpipe)); + struct timeval send_timeout + = { SENTRY_CRASH_IPC_SEND_TIMEOUT_MS / 1000, 0 }; + setsockopt(ipc->message_fd[0], SOL_SOCKET, SO_SNDTIMEO, &send_timeout, + sizeof(send_timeout)); + fcntl(ipc->message_fd[0], F_SETFD, FD_CLOEXEC); + fcntl(ipc->message_fd[1], F_SETFD, FD_CLOEXEC); + if (!shm_exists) { sentry__crash_context_init(ipc->shmem); } @@ -461,7 +855,7 @@ sentry__crash_ipc_init_app(sentry_mutex_t *init_mutex) sentry_crash_ipc_t * sentry__crash_ipc_init_daemon(pid_t app_pid, uint64_t app_tid, - int notify_pipe_read, int ready_pipe_write, int shm_fd) + int notify_pipe_read, int ready_pipe_write, int shm_fd, int message_fd) { (void)app_pid; (void)app_tid; @@ -471,6 +865,9 @@ sentry__crash_ipc_init_daemon(pid_t app_pid, uint64_t app_tid, return NULL; } ipc->is_daemon = true; + ipc->message_fd[0] = -1; + ipc->message_fd[1] = message_fd; + fcntl(message_fd, F_SETFD, FD_CLOEXEC); // Use the inherited shm_fd directly (no shm_open needed, sandbox-safe) ipc->shm_fd = shm_fd; @@ -505,16 +902,16 @@ sentry__crash_ipc_init_daemon(pid_t app_pid, uint64_t app_tid, return ipc; } -void -sentry__crash_ipc_notify(sentry_crash_ipc_t *ipc) +static bool +notify_fallback(sentry_crash_ipc_t *ipc) { if (!ipc) { - return; + return false; } // Write byte to pipe (signal-safe) char byte = 1; - write(ipc->notify_pipe[1], &byte, 1); + return write(ipc->notify_pipe[1], &byte, 1) == 1; } bool @@ -560,6 +957,10 @@ sentry__crash_ipc_free(sentry_crash_ipc_t *ipc) return; } + sentry_free(ipc->message_buf); + sentry_free(ipc->torn_frame); + sentry__crash_scope_free(&ipc->scope); + if (ipc->shmem && ipc->shmem != MAP_FAILED) { munmap(ipc->shmem, SENTRY_CRASH_SHM_SIZE); } @@ -584,6 +985,13 @@ sentry__crash_ipc_free(sentry_crash_ipc_t *ipc) close(ipc->ready_pipe[1]); } + if (ipc->message_fd[0] >= 0) { + close(ipc->message_fd[0]); + } + if (ipc->message_fd[1] >= 0) { + close(ipc->message_fd[1]); + } + if (!ipc->is_daemon) { sentry__crash_ipc_unlink(ipc); } @@ -593,6 +1001,50 @@ sentry__crash_ipc_free(sentry_crash_ipc_t *ipc) #elif defined(SENTRY_PLATFORM_WINDOWS) +// a named pipe, because CreatePipe handles can't be overlapped +static bool +create_message_pipe(sentry_crash_ipc_t *ipc) +{ + uint64_t id = 0; + sentry__getrandom(&id, sizeof(id)); + wchar_t name[SENTRY_CRASH_IPC_NAME_SIZE]; + swprintf(name, SENTRY_CRASH_IPC_NAME_SIZE, + L"\\\\.\\pipe\\sentry-crash-%lu-%llx", GetCurrentProcessId(), id); + HANDLE write_handle = CreateNamedPipeW(name, + PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED + | FILE_FLAG_FIRST_PIPE_INSTANCE, + PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, 1, + SENTRY_CRASH_IPC_PIPE_SIZE, 0, 0, NULL); + if (write_handle == INVALID_HANDLE_VALUE) { + return false; + } + + SECURITY_ATTRIBUTES pipe_attrs; + ZeroMemory(&pipe_attrs, sizeof(pipe_attrs)); + pipe_attrs.nLength = sizeof(pipe_attrs); + pipe_attrs.bInheritHandle = TRUE; + HANDLE read_handle = CreateFileW( + name, GENERIC_READ, 0, &pipe_attrs, OPEN_EXISTING, 0, NULL); + if (read_handle == INVALID_HANDLE_VALUE) { + DWORD error = GetLastError(); + CloseHandle(write_handle); + SetLastError(error); + return false; + } + HANDLE write_event = CreateEventW(NULL, TRUE, FALSE, NULL); + if (!write_event) { + DWORD error = GetLastError(); + CloseHandle(read_handle); + CloseHandle(write_handle); + SetLastError(error); + return false; + } + ipc->message_read_handle = read_handle; + ipc->message_write_handle = write_handle; + ipc->message_write.hEvent = write_event; + return true; +} + sentry_crash_ipc_t * sentry__crash_ipc_init_app(HANDLE init_mutex) { @@ -697,6 +1149,19 @@ sentry__crash_ipc_init_app(HANDLE init_mutex) return NULL; } + if (!create_message_pipe(ipc)) { + SENTRY_WARNF("failed to create message pipe: %lu", GetLastError()); + CloseHandle(ipc->ready_event_handle); + CloseHandle(ipc->event_handle); + UnmapViewOfFile(ipc->shmem); + CloseHandle(ipc->shm_handle); + if (ipc->init_mutex) { + ReleaseMutex(ipc->init_mutex); + } + sentry_free(ipc); + return NULL; + } + // Initialize shared memory only if newly created if (!shm_exists) { sentry__crash_context_init(ipc->shmem); @@ -714,7 +1179,7 @@ sentry__crash_ipc_init_app(HANDLE init_mutex) sentry_crash_ipc_t * sentry__crash_ipc_init_daemon(pid_t app_pid, uint64_t app_tid, - HANDLE event_handle, HANDLE ready_event_handle) + HANDLE event_handle, HANDLE ready_event_handle, HANDLE message_read_handle) { // On Windows, we open events by name, so handles from parent are not used // (handles are per-process and cannot be directly inherited) @@ -726,6 +1191,8 @@ sentry__crash_ipc_init_daemon(pid_t app_pid, uint64_t app_tid, return NULL; } ipc->is_daemon = true; + ipc->message_read_handle = message_read_handle; + SetHandleInformation(message_read_handle, HANDLE_FLAG_INHERIT, 0); // Open existing shared memory (using PID and thread ID) swprintf(ipc->shm_name, SENTRY_CRASH_IPC_NAME_SIZE, @@ -791,17 +1258,18 @@ sentry__crash_ipc_init_daemon(pid_t app_pid, uint64_t app_tid, return ipc; } -void -sentry__crash_ipc_notify(sentry_crash_ipc_t *ipc) +static bool +notify_fallback(sentry_crash_ipc_t *ipc) { if (!ipc || !ipc->event_handle) { // No logging - called from signal handler/exception filter - return; + return false; } // SetEvent is safe to call from exception filter // Ignore errors silently - we're crashing anyway SetEvent(ipc->event_handle); + return true; } bool @@ -839,6 +1307,17 @@ sentry__crash_ipc_free(sentry_crash_ipc_t *ipc) return; } + if (ipc->message_write_pending) { + // the pending write owns the torn frame until it completes + DWORD written = 0; + CancelIoEx(ipc->message_write_handle, &ipc->message_write); + GetOverlappedResult( + ipc->message_write_handle, &ipc->message_write, &written, TRUE); + } + sentry_free(ipc->message_buf); + sentry_free(ipc->torn_frame); + sentry__crash_scope_free(&ipc->scope); + if (ipc->shmem) { UnmapViewOfFile(ipc->shmem); } @@ -855,6 +1334,16 @@ sentry__crash_ipc_free(sentry_crash_ipc_t *ipc) CloseHandle(ipc->ready_event_handle); } + if (ipc->message_read_handle) { + CloseHandle(ipc->message_read_handle); + } + if (ipc->message_write_handle) { + CloseHandle(ipc->message_write_handle); + } + if (ipc->message_write.hEvent) { + CloseHandle(ipc->message_write.hEvent); + } + if (ipc->parent_handle) { CloseHandle(ipc->parent_handle); } @@ -987,3 +1476,584 @@ sentry__crash_ipc_wait_for_ready(sentry_crash_ipc_t *ipc, int timeout_ms) return false; #endif } + +bool +sentry__crash_scope_init(sentry_crash_scope_t *scope, size_t max_breadcrumbs) +{ + memset(scope, 0, sizeof(*scope)); + scope->event = sentry_value_new_null(); + scope->attachments = sentry_value_new_list(); + scope->breadcrumbs = sentry__ringbuffer_new(max_breadcrumbs); + return scope->breadcrumbs && !sentry_value_is_null(scope->attachments); +} + +void +sentry__crash_scope_free(sentry_crash_scope_t *scope) +{ + sentry_value_decref(scope->event); + sentry_value_decref(scope->attachments); + sentry__ringbuffer_free(scope->breadcrumbs); +} + +bool +sentry__crash_scope_apply( + sentry_crash_scope_t *scope, const sentry_crash_ipc_message_t *message) +{ + if (scope->stopped || message->flags + || message->sequence != scope->sequence + 1 + || (!scope->initialized + && message->type != SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT)) { + return false; + } + if (message->type == SENTRY_CRASH_IPC_MESSAGE_CRASH + || message->type == SENTRY_CRASH_IPC_MESSAGE_SHUTDOWN) { + if (message->payload_len) { + return false; + } + scope->sequence = message->sequence; + scope->stopped = true; + return true; + } + + sentry_value_t value + = sentry_value_from_msgpack(message->payload, message->payload_len); + sentry_value_type_t type = sentry_value_get_type(value); + if (sentry_value_is_null(value) + && (message->payload_len != 1 + || (unsigned char)message->payload[0] != 0xc0)) { + return false; + } + bool valid = false; + const char *field = NULL; + switch (message->type) { + case SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT: { + sentry_value_t event = sentry_value_get_by_key(value, "event"); + sentry_value_t attachments + = sentry_value_get_by_key(value, "attachments"); + if (sentry_value_get_type(event) != SENTRY_VALUE_TYPE_OBJECT + || sentry_value_get_type(attachments) != SENTRY_VALUE_TYPE_LIST) { + break; + } + sentry_ringbuffer_t *breadcrumbs + = sentry__ringbuffer_new(scope->breadcrumbs->max_size); + if (!breadcrumbs) { + break; + } + sentry_value_t list = sentry_value_get_by_key(event, "breadcrumbs"); + for (size_t i = 0; i < sentry_value_get_length(list); i++) { + sentry__ringbuffer_append(breadcrumbs, + sentry_value_incref(sentry_value_get_by_index(list, i))); + } + sentry_value_remove_by_key(event, "breadcrumbs"); + sentry__value_replace(&scope->event, sentry_value_incref(event)); + sentry__value_replace( + &scope->attachments, sentry_value_incref(attachments)); + sentry__ringbuffer_free(scope->breadcrumbs); + scope->breadcrumbs = breadcrumbs; + scope->initialized = true; + valid = true; + break; + } + case SENTRY_CRASH_IPC_MESSAGE_SET_RELEASE: + field = "release"; + break; + case SENTRY_CRASH_IPC_MESSAGE_SET_ENVIRONMENT: + field = "environment"; + break; + case SENTRY_CRASH_IPC_MESSAGE_SET_TRANSACTION: + field = "transaction"; + break; + case SENTRY_CRASH_IPC_MESSAGE_SET_FINGERPRINT: + field = "fingerprint"; + break; + case SENTRY_CRASH_IPC_MESSAGE_SET_LEVEL: + field = "level"; + break; + case SENTRY_CRASH_IPC_MESSAGE_SET_USER: + field = "user"; + break; + case SENTRY_CRASH_IPC_MESSAGE_SET_TAG: + case SENTRY_CRASH_IPC_MESSAGE_SET_EXTRA: + case SENTRY_CRASH_IPC_MESSAGE_SET_CONTEXT: { + const char *key + = sentry_value_as_string(sentry_value_get_by_index(value, 0)); + if (type != SENTRY_VALUE_TYPE_LIST + || sentry_value_get_length(value) != 2 + || sentry_value_get_type(sentry_value_get_by_index(value, 0)) + != SENTRY_VALUE_TYPE_STRING) { + break; + } + const char *name = message->type == SENTRY_CRASH_IPC_MESSAGE_SET_TAG + ? "tags" + : message->type == SENTRY_CRASH_IPC_MESSAGE_SET_EXTRA ? "extra" + : "contexts"; + sentry_value_t object = sentry_value_get_by_key(scope->event, name); + if (sentry_value_is_null(object)) { + object = sentry_value_new_object(); + if (sentry_value_set_by_key(scope->event, name, object) != 0) { + break; + } + } + valid + = sentry_value_set_by_key_n(object, key, + sentry_value_get_length(sentry_value_get_by_index(value, 0)), + sentry_value_incref(sentry_value_get_by_index(value, 1))) + == 0; + break; + } + case SENTRY_CRASH_IPC_MESSAGE_REMOVE_TAG: + case SENTRY_CRASH_IPC_MESSAGE_REMOVE_EXTRA: + case SENTRY_CRASH_IPC_MESSAGE_REMOVE_CONTEXT: { + if (type != SENTRY_VALUE_TYPE_STRING) { + break; + } + const char *name = message->type == SENTRY_CRASH_IPC_MESSAGE_REMOVE_TAG + ? "tags" + : message->type == SENTRY_CRASH_IPC_MESSAGE_REMOVE_EXTRA + ? "extra" + : "contexts"; + sentry_value_remove_by_key_n( + sentry_value_get_by_key(scope->event, name), + sentry_value_as_string(value), sentry_value_get_length(value)); + valid = true; + break; + } + case SENTRY_CRASH_IPC_MESSAGE_ADD_BREADCRUMB: + if (type == SENTRY_VALUE_TYPE_OBJECT) { + valid = !scope->breadcrumbs->max_size + || sentry__ringbuffer_append( + scope->breadcrumbs, sentry_value_incref(value)) + == 0; + } + break; + case SENTRY_CRASH_IPC_MESSAGE_SET_ATTACHMENT_LIST: + if (type == SENTRY_VALUE_TYPE_LIST) { + sentry__value_replace( + &scope->attachments, sentry_value_incref(value)); + valid = true; + } + break; + default: + break; + } + if (field) { + sentry_value_type_t expected + = message->type == SENTRY_CRASH_IPC_MESSAGE_SET_USER + ? SENTRY_VALUE_TYPE_OBJECT + : message->type == SENTRY_CRASH_IPC_MESSAGE_SET_FINGERPRINT + ? SENTRY_VALUE_TYPE_LIST + : SENTRY_VALUE_TYPE_STRING; + if (type == expected || sentry_value_is_null(value)) { + if (sentry_value_is_null(value) + || (type == SENTRY_VALUE_TYPE_STRING + && !sentry_value_get_length(value))) { + sentry_value_remove_by_key(scope->event, field); + valid = true; + } else { + valid = sentry_value_set_by_key( + scope->event, field, sentry_value_incref(value)) + == 0; + } + } + } + sentry_value_decref(value); + if (valid) { + scope->sequence = message->sequence; + } + return valid; +} + +sentry_value_t +sentry__crash_scope_event(const sentry_crash_scope_t *scope) +{ + sentry_value_t event = scope->initialized + ? sentry__value_clone(scope->event) + : sentry_value_new_event(); + sentry_value_set_by_key( + event, "breadcrumbs", sentry__ringbuffer_to_list(scope->breadcrumbs)); + sentry_value_set_by_key( + event, "level", sentry__value_new_level(SENTRY_LEVEL_FATAL)); + sentry__ensure_event_id(event, NULL); + return event; +} + +// returns false on a hard error, and `sent < len` if the daemon stopped reading +#if defined(SENTRY_PLATFORM_WINDOWS) +static bool +write_message(sentry_crash_ipc_t *ipc, const char *buf, size_t len, + bool nonblocking, size_t *sent) +{ + *sent = 0; + if (!ipc->message_write_pending) { + HANDLE event = ipc->message_write.hEvent; + memset(&ipc->message_write, 0, sizeof(ipc->message_write)); + ipc->message_write.hEvent = event; + if (!WriteFile(ipc->message_write_handle, buf, (DWORD)len, NULL, + &ipc->message_write) + && GetLastError() != ERROR_IO_PENDING) { + return false; + } + ipc->message_write_pending = true; + } + // a timed out write stays pending, and the next call picks it up + uint64_t deadline + = sentry__monotonic_time() + SENTRY_CRASH_IPC_SEND_TIMEOUT_MS; + DWORD written = 0; + while (!GetOverlappedResult( + ipc->message_write_handle, &ipc->message_write, &written, FALSE)) { + if (GetLastError() != ERROR_IO_INCOMPLETE) { + ipc->message_write_pending = false; + return false; + } + if (nonblocking || sentry__atomic_fetch(&ipc->stopped) + || sentry__monotonic_time() >= deadline) { + return true; + } + WaitForSingleObject(ipc->message_write.hEvent, 10); + } + ipc->message_write_pending = false; + *sent = written; + return true; +} +#else +static bool +write_message(sentry_crash_ipc_t *ipc, const char *buf, size_t len, + bool nonblocking, size_t *sent) +{ + *sent = 0; + int fd = ipc->message_fd[0]; + int flags = 0; +# if defined(MSG_NOSIGNAL) + flags |= MSG_NOSIGNAL; +# endif + int mode = 0; + uint64_t deadline = 0; + if (nonblocking) { + // set O_NONBLOCK, because MSG_DONTWAIT waits for SO_SNDTIMEO on macOS + mode = fcntl(fd, F_GETFL); + fcntl(fd, F_SETFL, mode | O_NONBLOCK); + } else { + deadline = sentry__monotonic_time() + SENTRY_CRASH_IPC_SEND_TIMEOUT_MS; + } + bool failed = false; + while (*sent < len) { + ssize_t written = send(fd, buf + *sent, len - *sent, flags); + if (written < 0 && errno == EINTR) { + continue; + } + if (written < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { + break; + } + if (written <= 0) { + failed = true; + break; + } + *sent += (size_t)written; + // a short send past the deadline has used up SO_SNDTIMEO + if (!nonblocking && *sent < len + && sentry__monotonic_time() >= deadline) { + break; + } + } + if (nonblocking) { + fcntl(fd, F_SETFL, mode); + } + return !failed; +} +#endif + +static bool +acquire_writer(sentry_crash_ipc_t *ipc) +{ + return ipc && !sentry__atomic_fetch(&ipc->stopped) + && !sentry__atomic_fetch(&ipc->message_failed) + && sentry__atomic_compare_swap(&ipc->writing, 0, 1); +} + +static bool +daemon_ready(sentry_crash_ipc_t *ipc) +{ +#if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) + if (sentry__atomic_fetch(&ipc->awaiting_ready)) { + struct pollfd pfd = { ipc->ready_fd, POLLIN, 0 }; + uint64_t val; + if (poll(&pfd, 1, 0) != 1 || !(pfd.revents & POLLIN) + || read(ipc->ready_fd, &val, sizeof(val)) != sizeof(val)) { + return false; + } + sentry__atomic_store(&ipc->awaiting_ready, 0); + } +#else + (void)ipc; +#endif + return true; +} + +static bool +flush_torn_frame(sentry_crash_ipc_t *ipc, bool nonblocking) +{ + if (!ipc->torn_frame) { + return true; + } + size_t sent = 0; + if (!write_message(ipc, ipc->torn_frame + ipc->torn_sent, + ipc->torn_len - ipc->torn_sent, nonblocking, &sent)) { + sentry__atomic_store(&ipc->message_failed, 1); + return false; + } + ipc->torn_sent += sent; + if (ipc->torn_sent < ipc->torn_len) { + return false; + } + sentry_free(ipc->torn_frame); + ipc->torn_frame = NULL; + ipc->sequence++; + return true; +} + +bool +sentry__crash_ipc_flush(sentry_crash_ipc_t *ipc) +{ + if (!acquire_writer(ipc)) { + return false; + } + bool flushed = flush_torn_frame(ipc, true); + sentry__atomic_store(&ipc->writing, 0); + return flushed; +} + +bool +sentry__crash_ipc_send( + sentry_crash_ipc_t *ipc, uint16_t type, sentry_value_t value) +{ + if (!acquire_writer(ipc)) { + return false; + } + bool ready = daemon_ready(ipc); + // wait on shutdown, so that a resumed daemon gets the frame and exits + if (!flush_torn_frame( + ipc, !ready || type != SENTRY_CRASH_IPC_MESSAGE_SHUTDOWN)) { + sentry__atomic_store(&ipc->writing, 0); + return false; + } + size_t payload_len = 0; + char *payload = type == SENTRY_CRASH_IPC_MESSAGE_SHUTDOWN + ? NULL + : sentry_value_to_msgpack(value, &payload_len); + char *buf = NULL; + size_t len = 0; + bool sent = (payload || type == SENTRY_CRASH_IPC_MESSAGE_SHUTDOWN) + && sentry__crash_ipc_message_encode( + type, 0, ipc->sequence + 1, payload, payload_len, &buf, &len) + == SENTRY_CRASH_IPC_MESSAGE_OK; + if (sent) { + size_t written = 0; + sent = write_message(ipc, buf, len, !ready, &written); + if (!sent) { + sentry__atomic_store(&ipc->message_failed, 1); + } else if (written < len) { + ipc->torn_frame = buf; + ipc->torn_len = len; + ipc->torn_sent = written; + buf = NULL; + sentry__atomic_store(&ipc->stalled, 1); + // the daemon reads the tail once it is ready + sent = !ready; + } else { + ipc->sequence++; + if (type == SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT) { + sentry__atomic_store(&ipc->stalled, 0); + } + } + } + sentry_free(buf); + sentry_free(payload); + sentry__atomic_store(&ipc->writing, 0); + return sent; +} + +bool +sentry__crash_ipc_notify(sentry_crash_ipc_t *ipc) +{ + if (!ipc) { + return false; + } + if (sentry__atomic_fetch(&ipc->shmem->state) + == SENTRY_CRASH_STATE_CRASHING) { + return notify_fallback(ipc); + } + sentry__atomic_store(&ipc->stopped, 1); +#if !defined(SENTRY_PLATFORM_WINDOWS) + if (!sentry__atomic_fetch(&ipc->message_failed) + && sentry__atomic_compare_swap(&ipc->writing, 0, 1)) { + bool sent = false; + // a crash frame can't follow a torn frame + if (!sentry__atomic_fetch(&ipc->stalled)) { + char frame[SENTRY_CRASH_IPC_MESSAGE_HEADER_SIZE] = { 0 }; + write_u32_le(frame, SENTRY_CRASH_IPC_MESSAGE_MIN_LEN); + write_u16_le(frame + 4, SENTRY_CRASH_IPC_MESSAGE_CRASH); + write_u64_le(frame + 8, ipc->sequence + 1); + size_t written = 0; + sent = write_message(ipc, frame, sizeof(frame), true, &written) + && written == sizeof(frame); + } + sentry__atomic_store(&ipc->writing, 0); + if (sent) { + return true; + } + } +#endif + // also used by WER; the daemon drains complete frames before freezing + return notify_fallback(ipc); +} + +static void +close_message_stream(sentry_crash_ipc_t *ipc) +{ + ipc->message_closed = true; + sentry_free(ipc->message_buf); + ipc->message_buf = NULL; + ipc->message_len = 0; +#if defined(SENTRY_PLATFORM_WINDOWS) + CloseHandle(ipc->message_read_handle); + ipc->message_read_handle = NULL; +#else + close(ipc->message_fd[1]); + ipc->message_fd[1] = -1; +#endif +} + +bool +sentry__crash_ipc_receive(sentry_crash_ipc_t *ipc, int timeout_ms) +{ + // a bounded poll also checks legacy notifications without blocking a writer + int remaining = timeout_ms; + do { + ipc->notify_pending + = ipc->notify_pending || sentry__crash_ipc_wait(ipc, 0); + bool available = false; + if (!ipc->message_closed) { +#if defined(SENTRY_PLATFORM_WINDOWS) + DWORD bytes = 0; + if (!PeekNamedPipe( + ipc->message_read_handle, NULL, 0, NULL, &bytes, NULL)) { + close_message_stream(ipc); + } + available = bytes > 0; +#else + struct pollfd fd = { ipc->message_fd[1], POLLIN, 0 }; + available = poll(&fd, 1, 0) > 0; +#endif + } + if (!available) { + if (ipc->notify_pending) { + if (sentry__atomic_fetch(&ipc->shmem->state) + == SENTRY_CRASH_STATE_CRASHING) { + ipc->notify_pending = false; + } else { + ipc->scope.stopped = true; + } + return true; + } + if (ipc->message_closed || remaining <= 0) { + return false; + } +#if defined(SENTRY_PLATFORM_WINDOWS) + int delay = remaining < 10 ? remaining : 10; + ipc->notify_pending = sentry__crash_ipc_wait(ipc, delay); + remaining -= delay; +#else +# if defined(SENTRY_PLATFORM_MACOS) + int notify_fd = ipc->notify_pipe[0]; +# else + int notify_fd = ipc->notify_fd; +# endif + struct pollfd fds[] = { + { ipc->message_fd[1], POLLIN, 0 }, + { notify_fd, POLLIN, 0 }, + }; + int rv = poll(fds, 2, remaining); + if (!rv || (rv < 0 && errno != EINTR)) { + return false; + } +#endif + continue; + } + if (!ipc->message_buf) { + ipc->message_size = SENTRY_CRASH_IPC_MESSAGE_HEADER_SIZE; + ipc->message_buf = sentry_malloc(ipc->message_size); + if (!ipc->message_buf) { + close_message_stream(ipc); + continue; + } + } + size_t len = ipc->message_size - ipc->message_len; +#if defined(SENTRY_PLATFORM_WINDOWS) + DWORD bytes = 0, received = 0; + if (!PeekNamedPipe( + ipc->message_read_handle, NULL, 0, NULL, &bytes, NULL) + || !ReadFile(ipc->message_read_handle, + ipc->message_buf + ipc->message_len, + (DWORD)(len < bytes ? len : bytes), &received, NULL) + || !received) { + close_message_stream(ipc); + continue; + } +#else + ssize_t received = recv(ipc->message_fd[1], + ipc->message_buf + ipc->message_len, len, MSG_DONTWAIT); + if (received < 0 && (errno == EINTR || errno == EAGAIN)) { + continue; + } + if (received <= 0) { + close_message_stream(ipc); + continue; + } +#endif + ipc->message_len += (size_t)received; + if (ipc->message_len < ipc->message_size) { + continue; + } + sentry_crash_ipc_message_t message; + sentry_crash_ipc_message_result_t result + = sentry__crash_ipc_message_decode( + ipc->message_buf, ipc->message_len, &message); + if (result == SENTRY_CRASH_IPC_MESSAGE_PARTIAL) { + if (!sentry__crash_ipc_message_type_is_known( + read_u16_le(ipc->message_buf + 4)) + || read_u16_le(ipc->message_buf + 6) + || read_u64_le(ipc->message_buf + 8) + != ipc->scope.sequence + 1) { + close_message_stream(ipc); + continue; + } + ipc->message_size = (size_t)read_u32_le(ipc->message_buf) + + SENTRY_CRASH_IPC_MESSAGE_PREFIX_SIZE; + char *buf = sentry_malloc(ipc->message_size); + if (!buf) { + close_message_stream(ipc); + continue; + } + memcpy(buf, ipc->message_buf, ipc->message_len); + sentry_free(ipc->message_buf); + ipc->message_buf = buf; + continue; + } + if (result != SENTRY_CRASH_IPC_MESSAGE_OK + || !sentry__crash_scope_apply(&ipc->scope, &message)) { + SENTRY_WARN("daemon: invalid scope IPC frame"); + close_message_stream(ipc); + continue; + } + uint16_t type = message.type; + sentry_free(ipc->message_buf); + ipc->message_buf = NULL; + ipc->message_len = 0; + if (type == SENTRY_CRASH_IPC_MESSAGE_CRASH) { + return true; + } + if (type == SENTRY_CRASH_IPC_MESSAGE_SHUTDOWN) { + return false; + } + } while (true); +} diff --git a/src/backends/native/sentry_crash_ipc.h b/src/backends/native/sentry_crash_ipc.h index ad0e4fa6fe..d879345b9f 100644 --- a/src/backends/native/sentry_crash_ipc.h +++ b/src/backends/native/sentry_crash_ipc.h @@ -3,9 +3,17 @@ #include "sentry_boot.h" #include "sentry_crash_context.h" +#include "sentry_ringbuffer.h" + +#include +#include #if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) -# include +# if defined(SENTRY_PLATFORM_ANDROID) +# include "sentry_sync.h" +# else +# include +# endif # include # include #elif defined(SENTRY_PLATFORM_MACOS) @@ -16,6 +24,81 @@ # include #endif +#define SENTRY_CRASH_IPC_MESSAGE_PREFIX_SIZE 4u +#define SENTRY_CRASH_IPC_MESSAGE_HEADER_SIZE 16u +#define SENTRY_CRASH_IPC_MESSAGE_MIN_LEN 12u +#define SENTRY_CRASH_IPC_MESSAGE_MAX_LEN (256u * 1024u * 1024u) +#define SENTRY_CRASH_IPC_SEND_TIMEOUT_MS 1000 +#define SENTRY_CRASH_IPC_PIPE_SIZE (64u * 1024u) + +/** + * Frames use little-endian length/type/flags/sequence, followed by one msgpack + * value. Flags are reserved (zero). Snapshots carry {event, attachments}; keyed + * setters carry [key, value], removals carry the key, and other updates carry + * the new value. Crash and shutdown frames have no payload. + */ +typedef enum { + SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT = 1, + SENTRY_CRASH_IPC_MESSAGE_SET_RELEASE = 2, + SENTRY_CRASH_IPC_MESSAGE_SET_ENVIRONMENT = 3, + SENTRY_CRASH_IPC_MESSAGE_SET_TRANSACTION = 4, + SENTRY_CRASH_IPC_MESSAGE_SET_FINGERPRINT = 5, + SENTRY_CRASH_IPC_MESSAGE_SET_LEVEL = 6, + SENTRY_CRASH_IPC_MESSAGE_SET_USER = 7, + SENTRY_CRASH_IPC_MESSAGE_SET_TAG = 8, + SENTRY_CRASH_IPC_MESSAGE_REMOVE_TAG = 9, + SENTRY_CRASH_IPC_MESSAGE_SET_EXTRA = 10, + SENTRY_CRASH_IPC_MESSAGE_REMOVE_EXTRA = 11, + SENTRY_CRASH_IPC_MESSAGE_SET_CONTEXT = 12, + SENTRY_CRASH_IPC_MESSAGE_REMOVE_CONTEXT = 13, + SENTRY_CRASH_IPC_MESSAGE_ADD_BREADCRUMB = 14, + SENTRY_CRASH_IPC_MESSAGE_SET_ATTACHMENT_LIST = 15, + SENTRY_CRASH_IPC_MESSAGE_CRASH = 16, + SENTRY_CRASH_IPC_MESSAGE_SHUTDOWN = 17, +} sentry_crash_ipc_message_type_t; + +typedef enum { + SENTRY_CRASH_IPC_MESSAGE_OK = 0, + SENTRY_CRASH_IPC_MESSAGE_PARTIAL = 1, + SENTRY_CRASH_IPC_MESSAGE_INVALID = 2, + SENTRY_CRASH_IPC_MESSAGE_OVERSIZED = 3, + SENTRY_CRASH_IPC_MESSAGE_UNKNOWN_TYPE = 4, + SENTRY_CRASH_IPC_MESSAGE_OOM = 5, +} sentry_crash_ipc_message_result_t; + +typedef struct { + uint16_t type; + uint16_t flags; + uint64_t sequence; + const char *payload; + size_t payload_len; +} sentry_crash_ipc_message_t; + +bool sentry__crash_ipc_message_type_is_known(uint16_t type); + +sentry_crash_ipc_message_result_t sentry__crash_ipc_message_encode( + uint16_t type, uint16_t flags, uint64_t sequence, const char *payload, + size_t payload_len, char **out_buf, size_t *out_len); + +sentry_crash_ipc_message_result_t sentry__crash_ipc_message_decode( + const char *buf, size_t buf_len, sentry_crash_ipc_message_t *message); + +typedef struct { + sentry_value_t event; + sentry_value_t attachments; + sentry_ringbuffer_t *breadcrumbs; + uint64_t sequence; + bool initialized; + bool stopped; +} sentry_crash_scope_t; + +bool sentry__crash_scope_init( + sentry_crash_scope_t *scope, size_t max_breadcrumbs); +void sentry__crash_scope_free(sentry_crash_scope_t *scope); +bool sentry__crash_scope_apply( + sentry_crash_scope_t *scope, const sentry_crash_ipc_message_t *message); +sentry_value_t sentry__crash_scope_event(const sentry_crash_scope_t *scope); + #if defined(SENTRY_PLATFORM_WINDOWS) typedef HANDLE sentry_process_handle_t; #else @@ -28,25 +111,59 @@ typedef pid_t sentry_process_handle_t; typedef struct { sentry_crash_context_t *shmem; + // app-only writer guard; crash handling must never wait for its owner + volatile long writing; + volatile long message_failed; + volatile long stopped; + // set from a torn frame until a snapshot reaches the daemon + volatile long stalled; + // set until a daemon that attaches later signals ready + volatile long awaiting_ready; + uint64_t sequence; + // frame with an unsent tail, owned by the writer guard + char *torn_frame; + size_t torn_len; + size_t torn_sent; + + // daemon-only staged state and incremental frame reader + sentry_crash_scope_t scope; + char *message_buf; + size_t message_len; + size_t message_size; + bool message_closed; + bool notify_pending; + #if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) int shm_fd; int notify_fd; // Eventfd for crash notifications int ready_fd; // Eventfd for daemon ready signal + // Anonymous app-to-daemon message stream: app writes, daemon reads. + int message_fd[2]; +# if defined(SENTRY_PLATFORM_ANDROID) + char shm_name[SENTRY_CRASH_MAX_PATH]; // File path, bionic has no shm_open() + sentry_mutex_t *init_mutex; // Process-wide initialization mutex +# else char shm_name[SENTRY_CRASH_IPC_NAME_SIZE]; sem_t *init_sem; // Named semaphore for initialization synchronization char sem_name[SENTRY_CRASH_IPC_NAME_SIZE]; +# endif #elif defined(SENTRY_PLATFORM_MACOS) int shm_fd; int notify_pipe[2]; // Pipe for crash notifications (fork-safe) int ready_pipe[2]; // Pipe for daemon ready signal (fork-safe) + int message_fd[2]; // Anonymous app-to-daemon message stream: app writes, + // daemon reads char shm_path[SENTRY_CRASH_MAX_PATH]; // File-backed shm path (sandbox-safe) sentry_mutex_t *init_mutex; // Process-wide mutex (sandbox-safe, no sem_open) #elif defined(SENTRY_PLATFORM_WINDOWS) HANDLE shm_handle; HANDLE event_handle; // Event for crash notifications (parent -> daemon) - HANDLE - ready_event_handle; // Event for daemon ready signal (daemon -> parent) + HANDLE ready_event_handle; // Event for ready signal (daemon -> parent) + HANDLE message_read_handle; // App-to-daemon message stream read end + HANDLE message_write_handle; // App-to-daemon message stream write end + OVERLAPPED message_write; // Write of the current frame + bool message_write_pending; // Set while that write is in flight wchar_t shm_name[SENTRY_CRASH_IPC_NAME_SIZE]; wchar_t event_name[SENTRY_CRASH_IPC_NAME_SIZE]; wchar_t ready_event_name[SENTRY_CRASH_IPC_NAME_SIZE]; @@ -60,11 +177,24 @@ typedef struct { /** * Initialize IPC for application process. * Creates shared memory and notification mechanism. + * @param database_path Android-only directory for the file-backed mapping * @param init_sem Optional semaphore for synchronizing init (can be NULL) * @param init_mutex Optional mutex for synchronizing init on Windows (can be * NULL) */ -#if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) +#if defined(SENTRY_PLATFORM_ANDROID) +sentry_crash_ipc_t *sentry__crash_ipc_init_app( + const char *database_path, sentry_mutex_t *init_mutex); +sentry_crash_ipc_t *sentry__crash_ipc_init_app_with_fds(int shm_fd, + int notify_fd, int ready_fd, int message_fd, sentry_mutex_t *init_mutex); +/** + * Replaces the app's daemon fds with those of a restarted crash service, and + * takes ownership of the new fds. Fails while a crash is being handled. The + * caller sends a scope snapshot next. + */ +bool sentry__crash_ipc_reattach( + sentry_crash_ipc_t *ipc, int notify_fd, int ready_fd, int message_fd); +#elif defined(SENTRY_PLATFORM_LINUX) sentry_crash_ipc_t *sentry__crash_ipc_init_app(sem_t *init_sem); #elif defined(SENTRY_PLATFORM_MACOS) sentry_crash_ipc_t *sentry__crash_ipc_init_app(sentry_mutex_t *init_mutex); @@ -74,6 +204,14 @@ sentry_crash_ipc_t *sentry__crash_ipc_init_app(HANDLE init_mutex); sentry_crash_ipc_t *sentry__crash_ipc_init_app(void); #endif +#if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) +/** + * Creates anonymous shared memory that depends on neither the disk nor + * /dev/shm. Returns -1 on failure. + */ +int sentry__crash_ipc_create_memfd(void); +#endif + /** * Initialize IPC for daemon process. * Attaches to existing shared memory created by app. @@ -85,14 +223,17 @@ sentry_crash_ipc_t *sentry__crash_ipc_init_app(void); * Linux, pipe fd on macOS, event on Windows) */ #if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) -sentry_crash_ipc_t *sentry__crash_ipc_init_daemon( - pid_t app_pid, uint64_t app_tid, int notify_eventfd, int ready_eventfd); +sentry_crash_ipc_t *sentry__crash_ipc_init_daemon(pid_t app_pid, + uint64_t app_tid, int notify_eventfd, int ready_eventfd, int shm_fd, + int message_fd); #elif defined(SENTRY_PLATFORM_MACOS) sentry_crash_ipc_t *sentry__crash_ipc_init_daemon(pid_t app_pid, - uint64_t app_tid, int notify_pipe_read, int ready_pipe_write, int shm_fd); + uint64_t app_tid, int notify_pipe_read, int ready_pipe_write, int shm_fd, + int message_fd); #elif defined(SENTRY_PLATFORM_WINDOWS) sentry_crash_ipc_t *sentry__crash_ipc_init_daemon(pid_t app_pid, - uint64_t app_tid, HANDLE event_handle, HANDLE ready_event_handle); + uint64_t app_tid, HANDLE event_handle, HANDLE ready_event_handle, + HANDLE message_read_handle); #endif /** @@ -109,8 +250,9 @@ bool sentry__crash_ipc_wait_for_ready(sentry_crash_ipc_t *ipc, int timeout_ms); /** * Notify daemon that a crash occurred (called from signal handler). * This function is signal-safe. + * Returns false if no daemon could be notified, for example because it is gone. */ -void sentry__crash_ipc_notify(sentry_crash_ipc_t *ipc); +bool sentry__crash_ipc_notify(sentry_crash_ipc_t *ipc); /** * Wait for crash notification (called by daemon). @@ -119,6 +261,34 @@ void sentry__crash_ipc_notify(sentry_crash_ipc_t *ipc); */ bool sentry__crash_ipc_wait(sentry_crash_ipc_t *ipc, int timeout_ms); +/** + * Send a borrowed value. Scope updates must hold the scope observer lock. + * Returns false on failure or if a crash interrupted another writer. + * A send that times out keeps the unsent tail of its frame and stalls the + * stream. Later sends first flush the tail, and return false if it stays + * unsent. That flush blocks only for a shutdown frame, up to the send timeout. + * Only a scope snapshot clears the stall. + * Until a daemon that attaches later signals ready, sends never block, and a + * frame that stalls the stream still counts as sent. + */ +bool sentry__crash_ipc_send( + sentry_crash_ipc_t *ipc, uint16_t type, sentry_value_t value); + +/** + * Flush the tail of a stalled stream without blocking. + * Returns true once the tail is through, and the stream is ready for a scope + * snapshot. + */ +bool sentry__crash_ipc_flush(sentry_crash_ipc_t *ipc); + +/** + * Receive and apply ordered frames, returning true on a crash notification. + * Early crash notifications keep the staged scope mutable. + * An out-of-band notification drains complete available frames first; an + * interrupted partial frame is discarded without changing staged state. + */ +bool sentry__crash_ipc_receive(sentry_crash_ipc_t *ipc, int timeout_ms); + /** * Unlink the shared memory. */ diff --git a/src/backends/native/sentry_wer.c b/src/backends/native/sentry_wer.c index 801cda3426..bdfff728c6 100644 --- a/src/backends/native/sentry_wer.c +++ b/src/backends/native/sentry_wer.c @@ -164,6 +164,7 @@ process_wer_exception( == SENTRY_CRASH_STATE_READY) { ctx->crashed_pid = GetProcessId(exception_info->hProcess); ctx->crashed_tid = GetThreadId(exception_info->hThread); + ctx->capture.count = 0; ctx->platform.exception_code = exception_info->exceptionRecord.ExceptionCode; ctx->platform.exception_record = exception_info->exceptionRecord; @@ -176,10 +177,8 @@ process_wer_exception( InterlockedExchange(&ctx->state, SENTRY_CRASH_STATE_CRASHED); if (SetEvent(event)) { claimed = TRUE; - uint64_t timeout_ms = ctx->shutdown_timeout - ? ctx->shutdown_timeout - : SENTRY_CRASH_HANDLER_WAIT_TIMEOUT_MS; - for (uint64_t waited_ms = 0; waited_ms < timeout_ms; + for (uint64_t waited_ms = 0; + waited_ms < SENTRY_CRASH_HANDLER_WAIT_TIMEOUT_MS; waited_ms += SENTRY_CRASH_HANDLER_POLL_INTERVAL_MS) { if (InterlockedCompareExchange(&ctx->state, SENTRY_CRASH_STATE_DONE, SENTRY_CRASH_STATE_DONE) diff --git a/src/backends/sentry_backend_breakpad.cpp b/src/backends/sentry_backend_breakpad.cpp index 86878bafcf..dc9e79b1cf 100644 --- a/src/backends/sentry_backend_breakpad.cpp +++ b/src/backends/sentry_backend_breakpad.cpp @@ -30,6 +30,7 @@ extern "C" { # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wpedantic" # pragma GCC diagnostic ignored "-Wvariadic-macros" +# pragma GCC diagnostic ignored "-Wunknown-pragmas" #endif #ifdef SENTRY_PLATFORM_WINDOWS @@ -238,8 +239,8 @@ breakpad_backend_callback(const google_breakpad::MinidumpDescriptor &descriptor, sentry_path_t *path = sentry__screenshot_get_path(options); sentry_value_t screenshot = sentry_attachment_from_file(path ? path->path : nullptr); - if (!sentry_value_is_null(screenshot) - && sentry__screenshot_capture(path, 0)) { + if (path && !sentry_value_is_null(screenshot) + && sentry_screenshot_capture(path->path, 0) == 0) { sentry__envelope_add_attachment(envelope, screenshot); } sentry_value_decref(screenshot); diff --git a/src/backends/sentry_backend_crashpad.cpp b/src/backends/sentry_backend_crashpad.cpp index a4693f7e4f..b9b6470829 100644 --- a/src/backends/sentry_backend_crashpad.cpp +++ b/src/backends/sentry_backend_crashpad.cpp @@ -954,6 +954,24 @@ remove_attachment(void *state, sentry_value_t attachment) } #endif +static void +clear_scope(void *state) +{ + auto *data = static_cast(state); + if (!data) { + return; + } + + const base::FilePath *paths[] + = { &data->breadcrumb1_path, &data->breadcrumb2_path }; + for (const auto *path : paths) { + if (!path->empty() && write_attachment(data, *path, "", 0) != 0) { + SENTRY_WARN("failed to clear persisted breadcrumbs"); + } + } + data->num_breadcrumbs = 0; +} + static int crashpad_backend_startup( sentry_backend_t *backend, const sentry_options_t *options) @@ -1200,6 +1218,7 @@ crashpad_backend_startup( sentry_scope_observer_t *observer = sentry__scope_observer_new(); if (observer) { observer->data = data; + observer->clear = clear_scope; observer->add_breadcrumb = crashpad_backend_add_breadcrumb; #if defined(SENTRY_PLATFORM_WINDOWS) || defined(SENTRY_PLATFORM_LINUX) \ || defined(SENTRY_PLATFORM_MACOS) diff --git a/src/backends/sentry_backend_inproc.c b/src/backends/sentry_backend_inproc.c index 33a27bd856..9388b37c0f 100644 --- a/src/backends/sentry_backend_inproc.c +++ b/src/backends/sentry_backend_inproc.c @@ -379,51 +379,6 @@ static const struct signal_slot SIGNAL_DEFINITIONS[SIGNAL_COUNT] = { static void handle_signal(int signum, siginfo_t *info, void *user_context); -/** - * Sets up an alternate signal stack for the current thread if one isn't - * already configured. The allocated stack is stored in `out_stack` so it - * can be freed later via `teardown_sigaltstack()`. - */ -static void -setup_sigaltstack(stack_t *out_stack, const char *context) -{ - memset(out_stack, 0, sizeof(*out_stack)); - - stack_t old_sig_stack; - int ret = sigaltstack(NULL, &old_sig_stack); - if (ret == 0 && old_sig_stack.ss_flags == SS_DISABLE) { - SENTRY_DEBUGF( - "installing %s sigaltstack (size: %d)", context, SIGNAL_STACK_SIZE); - out_stack->ss_sp = sentry_malloc(SIGNAL_STACK_SIZE); - if (!out_stack->ss_sp) { - SENTRY_WARN("failed to allocate signal stack"); - return; - } - out_stack->ss_size = SIGNAL_STACK_SIZE; - out_stack->ss_flags = 0; - sigaltstack(out_stack, 0); - } else if (ret == 0) { - SENTRY_DEBUGF("using existing signal stack (size: %d, flags: %d)", - old_sig_stack.ss_size, old_sig_stack.ss_flags); - } else if (ret == -1) { - SENTRY_WARNF("failed to query signal stack: %s", strerror(errno)); - } -} - -/** - * Tears down a signal stack previously set up via `setup_sigaltstack()`. - */ -static void -teardown_sigaltstack(stack_t *sig_stack) -{ - if (sig_stack->ss_sp) { - sig_stack->ss_flags = SS_DISABLE; - sigaltstack(sig_stack, 0); - sentry_free(sig_stack->ss_sp); - sig_stack->ss_sp = NULL; - } -} - static void reset_signal_handlers(void) { @@ -467,7 +422,7 @@ install_signal_handlers(void) } } - setup_sigaltstack(&g_signal_stack, "init"); + sentry__setup_sigaltstack(&g_signal_stack, SIGNAL_STACK_SIZE, "init"); sigemptyset(&g_sigaction.sa_mask); g_sigaction.sa_sigaction = handle_signal; @@ -539,7 +494,7 @@ shutdown_inproc_backend(sentry_backend_t *backend) // signal we still observe will fall through to the previously installed // handler. if (!sentry__atomic_fetch(&g_preloaded)) { - teardown_sigaltstack(&g_signal_stack); + sentry__teardown_sigaltstack(&g_signal_stack); reset_signal_handlers(); } @@ -710,6 +665,8 @@ make_signal_event(const struct signal_slot *sig_slot, sentry_value_set_by_key(exc, "stacktrace", stacktrace); sentry_event_add_exception(event, exc); + sentry__event_ensure_modules(event); + return event; } @@ -813,8 +770,8 @@ process_ucontext_deferred(const sentry_options_t *options, sentry_path_t *path = sentry__screenshot_get_path(options); sentry_value_t screenshot = sentry_attachment_from_file(path ? path->path : NULL); - if (!sentry_value_is_null(screenshot) - && sentry__screenshot_capture(path, 0)) { + if (path && !sentry_value_is_null(screenshot) + && sentry_screenshot_capture(path->path, 0) == 0) { sentry__envelope_add_attachment(envelope, screenshot); } sentry_value_decref(screenshot); @@ -883,7 +840,8 @@ handler_thread_main(void *data) #ifdef SENTRY_PLATFORM_UNIX // Set up an alternate signal stack for the handler thread stack_t handler_thread_stack; - setup_sigaltstack(&handler_thread_stack, "handler"); + sentry__setup_sigaltstack( + &handler_thread_stack, SIGNAL_STACK_SIZE, "handler"); #endif sentry__unwind_init(); @@ -947,7 +905,7 @@ handler_thread_main(void *data) } #ifdef SENTRY_PLATFORM_UNIX - teardown_sigaltstack(&handler_thread_stack); + sentry__teardown_sigaltstack(&handler_thread_stack); #endif sentry_options_free(options); diff --git a/src/backends/sentry_backend_native.c b/src/backends/sentry_backend_native.c index 86acb2de7e..c016003392 100644 --- a/src/backends/sentry_backend_native.c +++ b/src/backends/sentry_backend_native.c @@ -15,6 +15,10 @@ # include # include # endif +# if defined(SENTRY_PLATFORM_ANDROID) +# include +# include +# endif #endif #include @@ -49,9 +53,10 @@ // This lives for the entire backend lifetime and is shared across all threads #if defined(SENTRY_PLATFORM_WINDOWS) static HANDLE g_ipc_mutex = NULL; -#elif defined(SENTRY_PLATFORM_MACOS) -// macOS uses a plain pthread mutex instead of named semaphores (sem_open) -// because App Sandbox blocks POSIX named semaphores. +#elif defined(SENTRY_PLATFORM_MACOS) || defined(SENTRY_PLATFORM_ANDROID) +// macOS/Android use a plain pthread mutex instead of named semaphores +// (sem_open) because App Sandbox blocks POSIX named semaphores and Android has +// no shm_open. static sentry_mutex_t g_ipc_sync_mutex = SENTRY__MUTEX_INIT; #else # include @@ -59,10 +64,140 @@ static sem_t *g_ipc_init_sem = SEM_FAILED; static char g_ipc_sem_name[64] = { 0 }; #endif -// Mutex to protect IPC initialization (Windows and Linux only, not macOS/iOS) -// macOS uses g_ipc_sync_mutex directly; iOS has no out-of-process daemon. +#if defined(SENTRY_PLATFORM_ANDROID) +typedef struct { + bool configured; + int shm_fd; + int notify_fd; + int ready_fd; + int message_fd; +} android_crash_daemon_config_t; + +static android_crash_daemon_config_t g_android_crash_daemon_config + = { false, -1, -1, -1, -1 }; + +__attribute__((visibility("default"))) int +sentry_android_crash_daemon_create_shm(void) +{ + return sentry__crash_ipc_create_memfd(); +} + +__attribute__((visibility("default"))) void +sentry_android_crash_daemon_init( + int shm_fd, int notify_fd, int ready_fd, int message_fd) +{ + if (shm_fd < 0 || notify_fd < 0 || ready_fd < 0 || message_fd < 0) { + // the backend owns the fds, even when it rejects them + close(shm_fd); + close(notify_fd); + close(ready_fd); + close(message_fd); + return; + } + + sentry__mutex_lock(&g_ipc_sync_mutex); + // replaces a configuration that no backend startup took + if (g_android_crash_daemon_config.configured) { + close(g_android_crash_daemon_config.shm_fd); + close(g_android_crash_daemon_config.notify_fd); + close(g_android_crash_daemon_config.ready_fd); + close(g_android_crash_daemon_config.message_fd); + } + g_android_crash_daemon_config.shm_fd = shm_fd; + g_android_crash_daemon_config.notify_fd = notify_fd; + g_android_crash_daemon_config.ready_fd = ready_fd; + g_android_crash_daemon_config.message_fd = message_fd; + g_android_crash_daemon_config.configured = true; + sentry__mutex_unlock(&g_ipc_sync_mutex); +} + +static bool +take_android_crash_daemon_config( + int *shm_fd, int *notify_fd, int *ready_fd, int *message_fd) +{ + bool configured = false; + sentry__mutex_lock(&g_ipc_sync_mutex); + if (g_android_crash_daemon_config.configured) { + *shm_fd = g_android_crash_daemon_config.shm_fd; + *notify_fd = g_android_crash_daemon_config.notify_fd; + *ready_fd = g_android_crash_daemon_config.ready_fd; + *message_fd = g_android_crash_daemon_config.message_fd; + g_android_crash_daemon_config.shm_fd = -1; + g_android_crash_daemon_config.notify_fd = -1; + g_android_crash_daemon_config.ready_fd = -1; + g_android_crash_daemon_config.message_fd = -1; + g_android_crash_daemon_config.configured = false; + configured = true; + } + sentry__mutex_unlock(&g_ipc_sync_mutex); + return configured; +} +#endif + +static char * +resolve_handler_path(const sentry_options_t *options) +{ + if (options->handler_path) { + return sentry__string_clone(options->handler_path->path); + } + +#if defined(SENTRY_PLATFORM_ANDROID) + Dl_info info; + if (dladdr((void *)resolve_handler_path, &info) == 0 || !info.dli_fname) { + SENTRY_WARN("unable to resolve sentry library path for crash daemon"); + return NULL; + } + + sentry_path_t *library_path = sentry__path_from_str(info.dli_fname); + if (!library_path) { + return NULL; + } + + sentry_path_t *library_dir = sentry__path_dir(library_path); + sentry__path_free(library_path); + if (!library_dir) { + return NULL; + } + + sentry_path_t *handler_path + = sentry__path_join_str(library_dir, "libsentry-crash.so"); + sentry__path_free(library_dir); + if (!handler_path) { + return NULL; + } + + if (!sentry__path_is_file(handler_path)) { + // fall back to sentry-crash next to the executable (as in adb runs) + sentry__path_free(handler_path); + sentry_path_t *exe_path = sentry__path_current_exe(); + sentry_path_t *exe_dir = exe_path ? sentry__path_dir(exe_path) : NULL; + handler_path + = exe_dir ? sentry__path_join_str(exe_dir, "sentry-crash") : NULL; + sentry__path_free(exe_dir); + sentry__path_free(exe_path); + } + + if (!handler_path || !sentry__path_is_file(handler_path)) { + SENTRY_WARN("Android crash daemon is missing"); + sentry__path_free(handler_path); + return NULL; + } + + SENTRY_DEBUGF("resolved Android crash daemon path: %s", handler_path->path); + char *handler_path_str = sentry__string_clone(handler_path->path); + sentry__path_free(handler_path); + return handler_path_str; +#else + return NULL; +#endif +} + +// Mutex to protect IPC initialization (Windows and Linux only, not macOS/iOS or +// Android) macOS/Android use g_ipc_sync_mutex directly; iOS has no +// out-of-process daemon. #if defined(SENTRY_PLATFORM_WINDOWS) \ - || (!defined(SENTRY_PLATFORM_MACOS) && !defined(SENTRY_PLATFORM_IOS)) + || (!defined(SENTRY_PLATFORM_MACOS) && !defined(SENTRY_PLATFORM_ANDROID) \ + && !defined(SENTRY_PLATFORM_IOS)) # ifdef SENTRY__MUTEX_INIT_DYN SENTRY__MUTEX_INIT_DYN(g_ipc_init_mutex) # else @@ -237,44 +372,18 @@ typedef struct { sentry_crash_ipc_t *ipc; pid_t daemon_pid; sentry_path_t *run_path; - sentry_path_t *event_path; - sentry_path_t *breadcrumb1_path; - sentry_path_t *breadcrumb2_path; sentry_path_t *envelope_path; - size_t max_breadcrumbs; - size_t num_breadcrumbs; - volatile long crashed; + const sentry_options_t *options; + bool android_service_daemon; sentry_scope_observer_t *scope_observer; + volatile long crashed; } native_backend_state_t; -static void native_backend_flush_scope( - sentry_backend_t *backend, const sentry_options_t *options); -static void native_backend_add_breadcrumb( - void *data, sentry_value_t breadcrumb); -static void add_attachment(void *data, sentry_value_t attachment); - -static void -native_backend_preload_scope(sentry_backend_t *backend) -{ - sentry_value_t breadcrumbs = sentry_value_new_null(); - SENTRY_WITH_SCOPE (scope) { - sentry_value_t attachments = sentry__scope_load_attachments(scope); - size_t attachment_count = sentry_value_get_length(attachments); - for (size_t i = 0; i < attachment_count; i++) { - add_attachment( - backend->data, sentry_value_get_by_index(attachments, i)); - } - sentry_value_decref(attachments); - breadcrumbs = sentry__scope_breadcrumbs_to_list(scope); - } - - size_t breadcrumb_count = sentry_value_get_length(breadcrumbs); - for (size_t i = 0; i < breadcrumb_count; i++) { - native_backend_add_breadcrumb( - backend->data, sentry_value_get_by_index(breadcrumbs, i)); - } - sentry_value_decref(breadcrumbs); -} +static sentry_value_t attachment_list( + native_backend_state_t *state, const sentry_scope_t *scope); +static void sync_attachments(void *data, sentry_value_t attachment); +static bool observe_scope(native_backend_state_t *state); +static void native_backend_shutdown(sentry_backend_t *backend); static void add_attachment(void *data, sentry_value_t attachment) @@ -363,15 +472,16 @@ native_backend_process_old_run(sentry_backend_t *backend, #if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) static pid_t daemon_start(pid_t app_pid, uint64_t app_tid, int notify_eventfd, - int ready_eventfd, const char *handler_path) + int ready_eventfd, int shm_fd, int message_fd, const char *handler_path) #elif defined(SENTRY_PLATFORM_MACOS) static pid_t daemon_start(pid_t app_pid, uint64_t app_tid, int notify_pipe_read, - int ready_pipe_write, int shm_fd, const char *handler_path) + int ready_pipe_write, int shm_fd, int message_fd, const char *handler_path) #elif defined(SENTRY_PLATFORM_WINDOWS) static pid_t daemon_start(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, - HANDLE ready_event_handle, const char *handler_path) + HANDLE ready_event_handle, HANDLE message_read_handle, + const char *handler_path) #endif { #if defined(SENTRY_PLATFORM_MACOS) @@ -404,16 +514,19 @@ daemon_start(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, strcpy(daemon_path + dir_len, "sentry-crash"); } - // Build argument strings (6 args: pid, tid, notify_fd, ready_fd, shm_fd) - char pid_str[32], tid_str[32], notify_str[32], ready_str[32], shm_str[32]; + // Build argument strings (pid, tid, notify_fd, ready_fd, shm_fd, + // message_fd) + char pid_str[32], tid_str[32], notify_str[32], ready_str[32], shm_str[32], + message_str[32]; snprintf(pid_str, sizeof(pid_str), "%d", (int)app_pid); snprintf(tid_str, sizeof(tid_str), "%" PRIx64, app_tid); snprintf(notify_str, sizeof(notify_str), "%d", notify_pipe_read); snprintf(ready_str, sizeof(ready_str), "%d", ready_pipe_write); snprintf(shm_str, sizeof(shm_str), "%d", shm_fd); + snprintf(message_str, sizeof(message_str), "%d", message_fd); char *spawn_argv[] = { "sentry-crash", pid_str, tid_str, notify_str, - ready_str, shm_str, NULL }; + ready_str, shm_str, message_str, NULL }; // Set up posix_spawn attributes posix_spawnattr_t attr; @@ -429,6 +542,7 @@ daemon_start(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, posix_spawn_file_actions_addinherit_np(&file_actions, notify_pipe_read); posix_spawn_file_actions_addinherit_np(&file_actions, ready_pipe_write); posix_spawn_file_actions_addinherit_np(&file_actions, shm_fd); + posix_spawn_file_actions_addinherit_np(&file_actions, message_fd); // Open /dev/null on stdin/stdout/stderr so the daemon starts with valid // standard fds. Without this, POSIX_SPAWN_CLOEXEC_DEFAULT closes them, // and the first fopen() in the daemon would get fd 0, which the daemon's @@ -439,7 +553,7 @@ daemon_start(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, int std_modes[3] = { O_RDONLY, O_WRONLY, O_WRONLY }; for (int i = 0; i < 3; i++) { if (std_fds[i] != notify_pipe_read && std_fds[i] != ready_pipe_write - && std_fds[i] != shm_fd) { + && std_fds[i] != shm_fd && std_fds[i] != message_fd) { posix_spawn_file_actions_addopen( &file_actions, std_fds[i], "/dev/null", std_modes[i], 0); } @@ -480,16 +594,28 @@ daemon_start(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, if (ready_flags != -1) { fcntl(ready_eventfd, F_SETFD, ready_flags & ~FD_CLOEXEC); } + int message_flags = fcntl(message_fd, F_GETFD); + if (message_flags != -1) { + fcntl(message_fd, F_SETFD, message_flags & ~FD_CLOEXEC); + } + + int shm_flags = fcntl(shm_fd, F_GETFD); + if (shm_flags != -1) { + fcntl(shm_fd, F_SETFD, shm_flags & ~FD_CLOEXEC); + } // Convert arguments to strings for exec - char pid_str[32], tid_str[32], notify_str[32], ready_str[32]; + char pid_str[32], tid_str[32], notify_str[32], ready_str[32], + shm_str[32], message_str[32]; snprintf(pid_str, sizeof(pid_str), "%d", (int)app_pid); snprintf(tid_str, sizeof(tid_str), "%" PRIx64, app_tid); snprintf(notify_str, sizeof(notify_str), "%d", notify_eventfd); snprintf(ready_str, sizeof(ready_str), "%d", ready_eventfd); + snprintf(shm_str, sizeof(shm_str), "%d", shm_fd); + snprintf(message_str, sizeof(message_str), "%d", message_fd); - char *argv[] - = { "sentry-crash", pid_str, tid_str, notify_str, ready_str, NULL }; + char *argv[] = { "sentry-crash", pid_str, tid_str, notify_str, + ready_str, shm_str, message_str, NULL }; if (!sentry__string_empty(handler_path)) { execv(handler_path, argv); @@ -572,13 +698,14 @@ daemon_start(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, } // Build command line: sentry-crash.exe - // - wchar_t cmd_line[SENTRY_CRASH_MAX_PATH + 128]; + // + wchar_t cmd_line[SENTRY_CRASH_MAX_PATH + 192]; int cmd_len = _snwprintf(cmd_line, sizeof(cmd_line) / sizeof(wchar_t), - L"\"%s\" %lu %llx %llu %llu", daemon_path_w, (unsigned long)app_pid, - (unsigned long long)app_tid, + L"\"%s\" %lu %llx %llu %llu %llu", daemon_path_w, + (unsigned long)app_pid, (unsigned long long)app_tid, (unsigned long long)(uintptr_t)event_handle, - (unsigned long long)(uintptr_t)ready_event_handle); + (unsigned long long)(uintptr_t)ready_event_handle, + (unsigned long long)(uintptr_t)message_read_handle); if (cmd_len < 0 || cmd_len >= (int)(sizeof(cmd_line) / sizeof(wchar_t))) { SENTRY_WARN("Command line too long for daemon spawn"); @@ -586,27 +713,48 @@ daemon_start(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, } // Prepare process creation structures - STARTUPINFOW si; + STARTUPINFOEXW si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); + si.StartupInfo.cb = sizeof(si); // Hide console window for daemon - si.dwFlags = STARTF_USESHOWWINDOW; - si.wShowWindow = SW_HIDE; + si.StartupInfo.dwFlags = STARTF_USESHOWWINDOW; + si.StartupInfo.wShowWindow = SW_HIDE; ZeroMemory(&pi, sizeof(pi)); + SIZE_T attr_size = 0; + InitializeProcThreadAttributeList(NULL, 1, 0, &attr_size); + si.lpAttributeList = sentry_malloc(attr_size); + if (!si.lpAttributeList) { + return (pid_t)-1; + } + if (!InitializeProcThreadAttributeList( + si.lpAttributeList, 1, 0, &attr_size)) { + sentry_free(si.lpAttributeList); + return (pid_t)-1; + } + if (!UpdateProcThreadAttribute(si.lpAttributeList, 0, + PROC_THREAD_ATTRIBUTE_HANDLE_LIST, &message_read_handle, + sizeof(message_read_handle), NULL, NULL)) { + DeleteProcThreadAttributeList(si.lpAttributeList); + sentry_free(si.lpAttributeList); + return (pid_t)-1; + } + // Create the daemon process if (!CreateProcessW(NULL, // Application name (use command line) cmd_line, // Command line NULL, // Process security attributes NULL, // Thread security attributes - TRUE, // Inherit handles (for event_handle) - CREATE_NO_WINDOW | DETACHED_PROCESS, // Creation flags + TRUE, // inherit the control-stream read handle + CREATE_NO_WINDOW | DETACHED_PROCESS | EXTENDED_STARTUPINFO_PRESENT, NULL, // Environment NULL, // Current directory - &si, // Startup info + &si.StartupInfo, // Startup info &pi)) { // Process information DWORD error = GetLastError(); + DeleteProcThreadAttributeList(si.lpAttributeList); + sentry_free(si.lpAttributeList); char *daemon_path_err = sentry__string_from_wstr(daemon_path_w); if (daemon_path_err) { SENTRY_WARNF("Failed to create daemon process at '%s': Error %lu%s", @@ -621,6 +769,9 @@ daemon_start(pid_t app_pid, uint64_t app_tid, HANDLE event_handle, return (pid_t)-1; } + DeleteProcThreadAttributeList(si.lpAttributeList); + sentry_free(si.lpAttributeList); + // Close thread handle (we don't need it) CloseHandle(pi.hThread); @@ -662,9 +813,10 @@ native_backend_startup( } sentry__mutex_unlock(&g_ipc_init_mutex); -#elif defined(SENTRY_PLATFORM_MACOS) - // macOS uses a plain pthread mutex (no sem_open which is blocked by App - // Sandbox). The mutex is statically initialized - no setup needed. +#elif defined(SENTRY_PLATFORM_MACOS) || defined(SENTRY_PLATFORM_ANDROID) + // macOS/Android use a plain pthread mutex (no sem_open/shm_open which is + // blocked by App Sandbox, or missing on Android). The mutex is statically + // initialized - no setup needed. (void)0; #elif !defined(SENTRY_PLATFORM_IOS) // Create process-wide IPC initialization semaphore (singleton pattern) @@ -695,7 +847,7 @@ native_backend_startup( } backend->data = state; state->run_path = sentry__path_clone(options->run->run_path); - state->max_breadcrumbs = options->max_breadcrumbs; + state->options = options; // Initialize IPC (protected by global synchronization for concurrent // access) @@ -703,6 +855,23 @@ native_backend_startup( state->ipc = sentry__crash_ipc_init_app(g_ipc_mutex); #elif defined(SENTRY_PLATFORM_IOS) state->ipc = sentry__crash_ipc_init_app(NULL); +#elif defined(SENTRY_PLATFORM_ANDROID) + int service_shm_fd = -1; + int service_notify_fd = -1; + int service_ready_fd = -1; + int service_message_fd = -1; + state->android_service_daemon + = take_android_crash_daemon_config(&service_shm_fd, &service_notify_fd, + &service_ready_fd, &service_message_fd); + if (state->android_service_daemon) { + state->ipc = sentry__crash_ipc_init_app_with_fds(service_shm_fd, + service_notify_fd, service_ready_fd, service_message_fd, + &g_ipc_sync_mutex); + } else { + state->ipc = sentry__crash_ipc_init_app( + options->database_path ? options->database_path->path : NULL, + &g_ipc_sync_mutex); + } #elif defined(SENTRY_PLATFORM_MACOS) state->ipc = sentry__crash_ipc_init_app(&g_ipc_sync_mutex); #else @@ -731,7 +900,7 @@ native_backend_startup( return 1; } } -#elif defined(SENTRY_PLATFORM_MACOS) +#elif defined(SENTRY_PLATFORM_MACOS) || defined(SENTRY_PLATFORM_ANDROID) sentry__mutex_lock(&g_ipc_sync_mutex); #elif !defined(SENTRY_PLATFORM_IOS) if (g_ipc_init_sem && sem_wait(g_ipc_init_sem) < 0) { @@ -846,36 +1015,6 @@ native_backend_startup( #endif } - state->event_path = sentry__path_join_str(run_path, "__sentry-event"); - state->breadcrumb1_path - = sentry__path_join_str(run_path, "__sentry-breadcrumb1"); - state->breadcrumb2_path - = sentry__path_join_str(run_path, "__sentry-breadcrumb2"); - - sentry__path_touch(state->event_path); - sentry__path_touch(state->breadcrumb1_path); - sentry__path_touch(state->breadcrumb2_path); - - // Copy paths to crash context -#ifdef _WIN32 - strncpy_s(ctx->event_path, sizeof(ctx->event_path), state->event_path->path, - _TRUNCATE); - strncpy_s(ctx->breadcrumb1_path, sizeof(ctx->breadcrumb1_path), - state->breadcrumb1_path->path, _TRUNCATE); - strncpy_s(ctx->breadcrumb2_path, sizeof(ctx->breadcrumb2_path), - state->breadcrumb2_path->path, _TRUNCATE); -#else - strncpy( - ctx->event_path, state->event_path->path, sizeof(ctx->event_path) - 1); - ctx->event_path[sizeof(ctx->event_path) - 1] = '\0'; - strncpy(ctx->breadcrumb1_path, state->breadcrumb1_path->path, - sizeof(ctx->breadcrumb1_path) - 1); - ctx->breadcrumb1_path[sizeof(ctx->breadcrumb1_path) - 1] = '\0'; - strncpy(ctx->breadcrumb2_path, state->breadcrumb2_path->path, - sizeof(ctx->breadcrumb2_path) - 1); - ctx->breadcrumb2_path[sizeof(ctx->breadcrumb2_path) - 1] = '\0'; -#endif - // Set up crash envelope path state->envelope_path = sentry__path_join_str( options->run->run_path, "__sentry-crash.envelope"); @@ -910,7 +1049,7 @@ native_backend_startup( if (g_ipc_mutex) { ReleaseMutex(g_ipc_mutex); } -#elif defined(SENTRY_PLATFORM_MACOS) +#elif defined(SENTRY_PLATFORM_MACOS) || defined(SENTRY_PLATFORM_ANDROID) sentry__mutex_unlock(&g_ipc_sync_mutex); #elif !defined(SENTRY_PLATFORM_IOS) // Release semaphore after context configuration @@ -919,17 +1058,15 @@ native_backend_startup( } #endif - // Persist the preloaded scope before any crash handler becomes active. - native_backend_preload_scope(backend); - native_backend_flush_scope(backend, options); - // Install crash handlers (signal handlers on Linux/macOS, Mach exception // handler on iOS) #if defined(SENTRY_PLATFORM_IOS) - if (sentry__crash_handler_init(state->ipc, SENTRY_HANDLER_STRATEGY_DEFAULT) + if (sentry__crash_handler_init( + state->ipc, SENTRY_HANDLER_STRATEGY_DEFAULT, NULL) < 0) { SENTRY_WARN("failed to initialize crash handler"); sentry__crash_ipc_free(state->ipc); + sentry__path_free(state->envelope_path); sentry__path_free(state->run_path); sentry_free(state); backend->data = NULL; @@ -938,22 +1075,44 @@ native_backend_startup( #else // Other platforms: Use out-of-process daemon // Pass the notification handles (eventfd/pipe on Unix, events on Windows) - const char *daemon_handler_path - = options->handler_path ? options->handler_path->path : NULL; -# if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) + char *daemon_handler_path = NULL; +# if defined(SENTRY_PLATFORM_ANDROID) + if (state->android_service_daemon) { + // not a child process, so there is no PID to signal or wait for + state->daemon_pid = 0; + SENTRY_DEBUG("using Android service-hosted crash daemon"); + uint64_t ready = 1; + ssize_t written = write(state->ipc->notify_fd, &ready, sizeof(ready)); + (void)written; + } else { + daemon_handler_path = resolve_handler_path(options); + uint64_t tid = (uint64_t)pthread_self(); + state->daemon_pid = daemon_handler_path + ? daemon_start(getpid(), tid, state->ipc->notify_fd, + state->ipc->ready_fd, state->ipc->shm_fd, + state->ipc->message_fd[1], daemon_handler_path) + : -1; + } +# elif defined(SENTRY_PLATFORM_LINUX) + daemon_handler_path = resolve_handler_path(options); uint64_t tid = (uint64_t)pthread_self(); state->daemon_pid = daemon_start(getpid(), tid, state->ipc->notify_fd, - state->ipc->ready_fd, daemon_handler_path); + state->ipc->ready_fd, state->ipc->shm_fd, state->ipc->message_fd[1], + daemon_handler_path); # elif defined(SENTRY_PLATFORM_MACOS) + daemon_handler_path = resolve_handler_path(options); uint64_t tid = (uint64_t)pthread_self(); state->daemon_pid = daemon_start(getpid(), tid, state->ipc->notify_pipe[0], - state->ipc->ready_pipe[1], state->ipc->shm_fd, daemon_handler_path); + state->ipc->ready_pipe[1], state->ipc->shm_fd, + state->ipc->message_fd[1], daemon_handler_path); # elif defined(SENTRY_PLATFORM_WINDOWS) + daemon_handler_path = resolve_handler_path(options); uint64_t tid = (uint64_t)GetCurrentThreadId(); - state->daemon_pid - = daemon_start(GetCurrentProcessId(), tid, state->ipc->event_handle, - state->ipc->ready_event_handle, daemon_handler_path); + state->daemon_pid = daemon_start(GetCurrentProcessId(), tid, + state->ipc->event_handle, state->ipc->ready_event_handle, + state->ipc->message_read_handle, daemon_handler_path); # endif + sentry_free(daemon_handler_path); // On Windows, pid_t is DWORD (unsigned), so (pid_t)-1 == 0xFFFFFFFF. // On Unix, pid_t is signed and fork returns -1 on failure. @@ -964,23 +1123,31 @@ native_backend_startup( # endif SENTRY_WARN("failed to start crash daemon"); sentry__crash_ipc_free(state->ipc); + sentry__path_free(state->envelope_path); sentry__path_free(state->run_path); sentry_free(state); backend->data = NULL; return 1; } - SENTRY_DEBUGF("crash daemon started with PID %d", state->daemon_pid); + if (!state->android_service_daemon) { + SENTRY_DEBUGF("crash daemon started with PID %d", state->daemon_pid); + } # if defined(SENTRY_PLATFORM_MACOS) // Close unused pipe ends in parent process close(state->ipc->notify_pipe[0]); // Daemon reads from this close(state->ipc->ready_pipe[1]); // Daemon writes to this + close(state->ipc->message_fd[1]); // Daemon reads from this state->ipc->notify_pipe[0] = -1; state->ipc->ready_pipe[1] = -1; + state->ipc->message_fd[1] = -1; # endif # if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) + close(state->ipc->message_fd[1]); // Daemon reads from this + state->ipc->message_fd[1] = -1; + // Close unused eventfd ends in parent process // (eventfds are bidirectional, but we only use one direction per fd) // Parent writes to notify_fd, daemon reads from it - parent can close for @@ -990,6 +1157,9 @@ native_backend_startup( // On Linux, allow the daemon to ptrace this process // This is required when Yama LSM ptrace_scope is enabled + // On Android, the crash handler allows any ptracer at crash time instead, + // which also covers the service-hosted daemon +# if !defined(SENTRY_PLATFORM_ANDROID) if (prctl(PR_SET_PTRACER, state->daemon_pid, 0, 0, 0) != 0) { SENTRY_WARNF( "prctl(PR_SET_PTRACER) failed: %s - daemon may not be able to " @@ -998,11 +1168,24 @@ native_backend_startup( } else { SENTRY_DEBUGF("Set daemon PID %d as ptracer", state->daemon_pid); } +# endif # endif +# if defined(SENTRY_PLATFORM_WINDOWS) + CloseHandle(state->ipc->message_read_handle); + state->ipc->message_read_handle = NULL; +# endif + + bool wait_ready = true; +# if defined(SENTRY_PLATFORM_ANDROID) + // the crash service attaches later, the crash handler waits for it + wait_ready = !state->android_service_daemon; +# endif // Wait for daemon to signal it's ready - if (!sentry__crash_ipc_wait_for_ready( - state->ipc, SENTRY_CRASH_DAEMON_READY_TIMEOUT_MS)) { + if (!wait_ready) { + SENTRY_DEBUG("not waiting for the crash service to signal ready"); + } else if (!sentry__crash_ipc_wait_for_ready( + state->ipc, SENTRY_CRASH_DAEMON_READY_TIMEOUT_MS)) { SENTRY_WARN("Daemon did not signal ready in time, proceeding anyway"); } else { SENTRY_DEBUG("Daemon signaled ready"); @@ -1012,15 +1195,37 @@ native_backend_startup( state->ipc->shmem->platform.wer_enabled = wer_register_module(tid, options); # endif + if (!observe_scope(state)) { + SENTRY_WARN("failed to synchronize native crash scope"); + native_backend_shutdown(backend); + return 1; + } + sentry_handler_strategy_t strategy = -# if defined(SENTRY_PLATFORM_LINUX) && !defined(SENTRY_PLATFORM_ANDROID) +# if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) options ? sentry_options_get_handler_strategy(options) : # endif SENTRY_HANDLER_STRATEGY_DEFAULT; - if (sentry__crash_handler_init(state->ipc, strategy) < 0) { +# if defined(SENTRY_PLATFORM_ANDROID) + // CHAIN_AT_START invokes the previous handler and expects to regain + // control. On Android API < 26, the old debuggerd daemon kills the + // crashing process via SIGKILL after the chained handler triggers + // it, so we fall back to DEFAULT which chains at the end instead. + if (strategy == SENTRY_HANDLER_STRATEGY_CHAIN_AT_START + && android_get_device_api_level() < 26) { + strategy = SENTRY_HANDLER_STRATEGY_DEFAULT; + } +# endif + if (sentry__crash_handler_init(state->ipc, strategy, NULL) < 0) { SENTRY_WARN("failed to initialize crash handler"); # if defined(SENTRY_PLATFORM_UNIX) - kill(state->daemon_pid, SIGTERM); + if (state->daemon_pid > 0) { + kill(state->daemon_pid, SIGTERM); + pid_t wait_result; + do { + wait_result = waitpid(state->daemon_pid, NULL, 0); + } while (wait_result < 0 && errno == EINTR); + } # elif defined(SENTRY_PLATFORM_WINDOWS) wer_unregister_module(); // On Windows, terminate the daemon process @@ -1031,7 +1236,12 @@ native_backend_startup( CloseHandle(hDaemon); } # endif + SENTRY_WITH_SCOPE_MUT (scope) { + sentry__scope_remove_observer(scope, state->scope_observer); + } + state->scope_observer = NULL; sentry__crash_ipc_free(state->ipc); + sentry__path_free(state->envelope_path); sentry__path_free(state->run_path); sentry_free(state); backend->data = NULL; @@ -1040,17 +1250,6 @@ native_backend_startup( #endif SENTRY_DEBUG("native backend started successfully"); - sentry_scope_observer_t *observer = sentry__scope_observer_new(); - if (observer) { - observer->data = state; - observer->add_breadcrumb = native_backend_add_breadcrumb; - observer->add_attachment = add_attachment; - SENTRY_WITH_SCOPE_MUT (scope) { - if (sentry__scope_add_observer(scope, observer)) { - state->scope_observer = observer; - } - } - } return 0; } @@ -1066,9 +1265,11 @@ native_backend_shutdown(sentry_backend_t *backend) if (state->scope_observer) { SENTRY_WITH_SCOPE_MUT (scope) { + sentry__mutex_lock(&scope->observers_lock); sentry__scope_remove_observer(scope, state->scope_observer); + state->scope_observer = NULL; + sentry__mutex_unlock(&scope->observers_lock); } - state->scope_observer = NULL; } #if defined(SENTRY_PLATFORM_WINDOWS) @@ -1079,16 +1280,26 @@ native_backend_shutdown(sentry_backend_t *backend) // handler on iOS) sentry__crash_handler_shutdown(); + sentry__crash_ipc_send( + state->ipc, SENTRY_CRASH_IPC_MESSAGE_SHUTDOWN, sentry_value_new_null()); + bool daemon_stopped = false; #if defined(SENTRY_PLATFORM_UNIX) && !defined(SENTRY_PLATFORM_IOS) - // Terminate daemon (Unix) if (state->daemon_pid > 0) { - kill(state->daemon_pid, SIGTERM); - // Wait for daemon to exit - pid_t wait_result; - do { - wait_result = waitpid(state->daemon_pid, NULL, 0); - } while (wait_result < 0 && errno == EINTR); + pid_t wait_result = 0; + for (int i = 0; i < 500; i++) { + wait_result = waitpid(state->daemon_pid, NULL, WNOHANG); + if (wait_result > 0 || (wait_result < 0 && errno != EINTR)) { + break; + } + usleep(10000); + } + if (wait_result == 0) { + kill(state->daemon_pid, SIGTERM); + do { + wait_result = waitpid(state->daemon_pid, NULL, 0); + } while (wait_result < 0 && errno == EINTR); + } daemon_stopped = wait_result == state->daemon_pid; } #elif defined(SENTRY_PLATFORM_WINDOWS) @@ -1097,10 +1308,13 @@ native_backend_shutdown(sentry_backend_t *backend) HANDLE hDaemon = OpenProcess( PROCESS_TERMINATE | SYNCHRONIZE, FALSE, state->daemon_pid); if (hDaemon) { - TerminateProcess(hDaemon, 0); - // Wait for daemon to exit (with timeout) daemon_stopped = WaitForSingleObject(hDaemon, 5000) == WAIT_OBJECT_0; + if (!daemon_stopped) { + TerminateProcess(hDaemon, 0); + daemon_stopped + = WaitForSingleObject(hDaemon, 5000) == WAIT_OBJECT_0; + } CloseHandle(hDaemon); } } @@ -1193,159 +1407,400 @@ native_backend_free(sentry_backend_t *backend) return; } - sentry__path_free(state->event_path); - sentry__path_free(state->breadcrumb1_path); - sentry__path_free(state->breadcrumb2_path); sentry__path_free(state->envelope_path); sentry__path_free(state->run_path); sentry_free(state); } -// Writes the attachment list to /__sentry-attachments so the -// crash daemon can locate and append them to the crash envelope. static void -native_backend_write_attachments( - const sentry_path_t *event_path, const sentry_hint_t *hint) +write_crash_attachments( + native_backend_state_t *state, const sentry_hint_t *hint) { - if (!event_path) { + if (!state || !state->run_path) { return; } - SENTRY_WITH_SCOPE (scope) { - sentry_value_t attachments = hint - ? sentry_value_incref(hint->attachments) - : sentry__scope_load_attachments(scope); - if (sentry_value_get_length(attachments) == 0 && !hint) { - sentry_value_decref(attachments); + sentry_value_t attachments = sentry__hint_resolve_attachments(hint); + size_t len = sentry_value_get_length(attachments); + for (size_t i = 0; i < len; i++) { + add_attachment(state, sentry_value_get_by_index(attachments, i)); + } + sentry_path_t *path + = sentry__path_join_str(state->run_path, "__sentry-attachments"); + if (path) { + sentry__write_attachment_manifest(path, attachments); + sentry__path_free(path); + } + sentry_value_decref(attachments); +} + +static void +write_crash_event(native_backend_state_t *state, sentry_value_t event) +{ + if (!state || !state->run_path) { + return; + } + sentry_path_t *path + = sentry__path_join_str(state->run_path, "__sentry-event"); + if (!path) { + return; + } + size_t len = 0; + char *json = sentry__value_to_json(event, &len); + if (json) { + sentry__path_write_buffer(path, json, len); + sentry_free(json); + } + sentry__path_free(path); +} + +static sentry_value_t +attachment_list(native_backend_state_t *state, const sentry_scope_t *scope) +{ + sentry_value_t attachments = sentry__scope_load_attachments(scope); + sentry_value_t attach_list = sentry_value_new_list(); + size_t len = sentry_value_get_length(attachments); + for (size_t i = 0; i < len; i++) { + sentry_value_t attachment = sentry_value_get_by_index(attachments, i); + sentry_path_t *path + = sentry__attachment_make_run_path(state->run_path, attachment); + if (!path) { continue; } - sentry_path_t *run_path = sentry__path_dir(event_path); - if (!run_path) { - sentry_value_decref(attachments); + // skip missing or partially written attachments + size_t bytes_len = 0; + if (sentry__attachment_get_bytes(attachment, &bytes_len) + && sentry__path_get_size(path) != bytes_len) { + sentry__path_free(path); continue; } - sentry_path_t *attach_list_path - = sentry__path_join_str(run_path, "__sentry-attachments"); - if (attach_list_path) { - sentry__write_attachment_manifest(attach_list_path, attachments); - sentry__path_free(attach_list_path); + sentry_value_t attach_info = sentry_value_new_object(); + sentry_value_set_by_key( + attach_info, "path", sentry_value_new_string(path->path)); + const char *filename = sentry__attachment_get_filename(attachment); + sentry_value_set_by_key( + attach_info, "filename", sentry_value_new_string(filename)); + const char *type = sentry__attachment_get_type(attachment); + if (!sentry__string_empty(type)) { + sentry_value_set_by_key( + attach_info, "type", sentry_value_new_string(type)); + } + const char *content_type + = sentry__attachment_get_content_type(attachment); + if (content_type) { + sentry_value_set_by_key(attach_info, "content_type", + sentry_value_new_string(content_type)); } - sentry__path_free(run_path); - sentry_value_decref(attachments); + sentry_value_append(attach_list, attach_info); + sentry__path_free(path); } + sentry_value_decref(attachments); + return attach_list; } -#if defined(SENTRY_PLATFORM_WINDOWS) -// Sentry's symbolicator needs `contexts.device.arch` to process PE modules. If -// the scope already carries a device context with arch (host SDKs like Unity -// provide one), leave it; otherwise synthesize a minimal one so native-only -// consumers still symbolicate. static void -ensure_device_arch(sentry_value_t event) +sync_attachments(void *data, sentry_value_t attachment) { - sentry_value_t contexts = sentry_value_get_by_key(event, "contexts"); - if (sentry_value_is_null(contexts)) { - contexts = sentry_value_new_object(); - sentry_value_set_by_key(event, "contexts", contexts); - } - sentry_value_t device = sentry_value_get_by_key(contexts, "device"); - if (sentry_value_is_null(device)) { - device = sentry_value_new_object(); - sentry_value_set_by_key( - device, "type", sentry_value_new_string("device")); - sentry_value_set_by_key(contexts, "device", device); - } - if (!sentry_value_is_null(sentry_value_get_by_key(device, "arch"))) { + (void)attachment; + native_backend_state_t *state = data; + if (sentry__atomic_fetch(&state->crashed)) { return; } -# if defined(_M_AMD64) - sentry_value_set_by_key(device, "arch", sentry_value_new_string("x86_64")); -# elif defined(_M_IX86) - sentry_value_set_by_key(device, "arch", sentry_value_new_string("x86")); -# elif defined(_M_ARM64) - sentry_value_set_by_key(device, "arch", sentry_value_new_string("arm64")); -# endif + // send the list directly, because sentry_scope_clear gets here before it + // resets the scope, and a snapshot would restore the cleared data + SENTRY_WITH_SCOPE (scope) { + sentry_value_t list = attachment_list(state, scope); + sentry__crash_ipc_send( + state->ipc, SENTRY_CRASH_IPC_MESSAGE_SET_ATTACHMENT_LIST, list); + sentry_value_decref(list); + } } -#endif static void -native_backend_flush_scope( - sentry_backend_t *backend, const sentry_options_t *options) +observe_attachment(void *data, sentry_value_t attachment) { - native_backend_state_t *state = (native_backend_state_t *)backend->data; - if (!state || !state->event_path || sentry__atomic_fetch(&state->crashed)) { + native_backend_state_t *state = data; + if (sentry__atomic_fetch(&state->crashed)) { return; } + add_attachment(data, attachment); + sync_attachments(data, attachment); +} - native_backend_write_attachments(state->event_path, NULL); +static bool +send_snapshot(native_backend_state_t *state, const sentry_scope_t *scope, + sentry_value_t event) +{ + sentry_value_t snapshot = sentry_value_new_object(); + sentry_value_set_by_key(snapshot, "event", sentry_value_incref(event)); + sentry_value_set_by_key( + snapshot, "attachments", attachment_list(state, scope)); + bool sent = sentry__crash_ipc_send( + state->ipc, SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT, snapshot); + sentry_value_decref(snapshot); + return sent; +} - // Create event with current scope +static bool +snapshot_scope(native_backend_state_t *state, const sentry_scope_t *scope) +{ + if (sentry__atomic_fetch(&state->crashed)) { + return false; + } sentry_value_t event = sentry_value_new_object(); - sentry_value_set_by_key( - event, "level", sentry__value_new_level(SENTRY_LEVEL_FATAL)); + sentry__scope_apply_to_event( + scope, state->options, event, SENTRY_SCOPE_BREADCRUMBS); + bool sent = send_snapshot(state, scope, event); + sentry_value_decref(event); + return sent; +} - // Apply scope with contexts +static void +clear_scope(void *data) +{ + native_backend_state_t *state = data; + if (sentry__atomic_fetch(&state->crashed)) { + return; + } + // clear observers run before the source scope is reset SENTRY_WITH_SCOPE (scope) { - sentry__scope_apply_to_event(scope, options, event, SENTRY_SCOPE_NONE); + sentry_scope_t *empty = sentry_scope_clone(scope); + if (empty) { + sentry_scope_clear(empty); + snapshot_scope(state, empty); + sentry_scope_free(empty); + } } -#if defined(SENTRY_PLATFORM_WINDOWS) - ensure_device_arch(event); -#endif +} - size_t json_len = 0; - char *json_str = sentry__value_to_json(event, &json_len); - sentry_value_decref(event); +static void +send_update(native_backend_state_t *state, uint16_t type, sentry_value_t value) +{ + if (!sentry__atomic_fetch(&state->ipc->stalled)) { + sentry__crash_ipc_send(state->ipc, type, value); + } else if (sentry__crash_ipc_flush(state->ipc)) { + // the snapshot includes this update + SENTRY_WITH_SCOPE (scope) { + snapshot_scope(state, scope); + } + } +} - if (json_str) { - sentry__path_write_buffer(state->event_path, json_str, json_len); - sentry_free(json_str); +#define VALUE_OBSERVER(Name, Type) \ + static void Name(void *data, sentry_value_t value) \ + { \ + send_update(data, Type, value); \ } + +VALUE_OBSERVER(set_release, SENTRY_CRASH_IPC_MESSAGE_SET_RELEASE) +VALUE_OBSERVER(set_environment, SENTRY_CRASH_IPC_MESSAGE_SET_ENVIRONMENT) +VALUE_OBSERVER(set_transaction, SENTRY_CRASH_IPC_MESSAGE_SET_TRANSACTION) +VALUE_OBSERVER(set_fingerprint, SENTRY_CRASH_IPC_MESSAGE_SET_FINGERPRINT) +VALUE_OBSERVER(add_breadcrumb, SENTRY_CRASH_IPC_MESSAGE_ADD_BREADCRUMB) +#undef VALUE_OBSERVER + +static void +set_user(void *data, sentry_value_t user) +{ + native_backend_state_t *state = data; + sentry_value_t value = sentry__value_clone(user); + if (sentry_value_get_type(value) == SENTRY_VALUE_TYPE_OBJECT + && sentry_value_is_null(sentry_value_get_by_key(value, "id")) + && state->options->run->installation_id) { + sentry_value_set_by_key(value, "id", + sentry_value_new_string(state->options->run->installation_id)); + } + send_update(state, SENTRY_CRASH_IPC_MESSAGE_SET_USER, value); + sentry_value_decref(value); } static void -native_backend_add_breadcrumb(void *data, sentry_value_t breadcrumb) +set_level(void *data, sentry_level_t level) { - native_backend_state_t *state = (native_backend_state_t *)data; - if (!state) { - return; + native_backend_state_t *state = data; + sentry_value_t value = sentry__value_new_level(level); + send_update(state, SENTRY_CRASH_IPC_MESSAGE_SET_LEVEL, value); + sentry_value_decref(value); +} + +static void +send_key(void *data, uint16_t type, const char *key, sentry_value_t value) +{ + sentry_value_t pair = sentry_value_new_list(); + sentry_value_append(pair, sentry_value_new_string(key)); + sentry_value_append(pair, sentry_value_incref(value)); + send_update(data, type, pair); + sentry_value_decref(pair); +} + +static void +set_tag(void *data, const char *key, sentry_value_t value) +{ + send_key(data, SENTRY_CRASH_IPC_MESSAGE_SET_TAG, key, value); +} + +static void +set_extra(void *data, const char *key, sentry_value_t value) +{ + send_key(data, SENTRY_CRASH_IPC_MESSAGE_SET_EXTRA, key, value); +} + +static void +set_context(void *data, const char *key, sentry_value_t value) +{ + if (!sentry__string_eq(key, "trace")) { + send_key(data, SENTRY_CRASH_IPC_MESSAGE_SET_CONTEXT, key, value); } +} - size_t max_breadcrumbs = state->max_breadcrumbs; - if (!max_breadcrumbs) { - return; +#define REMOVE_OBSERVER(Name, Type) \ + static void Name(void *data, const char *key) \ + { \ + sentry_value_t value = sentry_value_new_string(key); \ + send_update(data, Type, value); \ + sentry_value_decref(value); \ } - bool first_breadcrumb = state->num_breadcrumbs % max_breadcrumbs == 0; +REMOVE_OBSERVER(remove_tag, SENTRY_CRASH_IPC_MESSAGE_REMOVE_TAG) +REMOVE_OBSERVER(remove_extra, SENTRY_CRASH_IPC_MESSAGE_REMOVE_EXTRA) +REMOVE_OBSERVER(remove_context_key, SENTRY_CRASH_IPC_MESSAGE_REMOVE_CONTEXT) +#undef REMOVE_OBSERVER - const sentry_path_t *breadcrumb_file - = state->num_breadcrumbs % (max_breadcrumbs * 2) < max_breadcrumbs - ? state->breadcrumb1_path - : state->breadcrumb2_path; +static void +remove_context(void *data, const char *key) +{ + if (!sentry__string_eq(key, "trace")) { + remove_context_key(data, key); + } +} - state->num_breadcrumbs++; +static void +set_trace(void *data, sentry_value_t trace) +{ + if (sentry_value_is_null(trace)) { + remove_context_key(data, "trace"); + } else { + send_key(data, SENTRY_CRASH_IPC_MESSAGE_SET_CONTEXT, "trace", trace); + } +} - if (!breadcrumb_file) { - return; +static bool +init_scope_observer(void *data, const sentry_scope_t *scope) +{ + native_backend_state_t *state = data; + sentry_value_t attachments = sentry__scope_load_attachments(scope); + for (size_t i = 0; i < sentry_value_get_length(attachments); i++) { + add_attachment(state, sentry_value_get_by_index(attachments, i)); } + sentry_value_decref(attachments); + return snapshot_scope(state, scope); +} - // Append as msgpack, matching the crashpad backend. msgpack values are - // self-delimiting, so the daemon can read the concatenated ring file back - // into a list via `sentry_value_from_msgpack`. - size_t mpack_size = 0; - char *mpack = sentry_value_to_msgpack(breadcrumb, &mpack_size); - if (!mpack) { - return; +#if defined(SENTRY_PLATFORM_ANDROID) +// shutdown clears scope_observer under observers_lock before freeing the IPC +static native_backend_state_t * +android_service_backend_state(const sentry_options_t *options) +{ + native_backend_state_t *state + = options->backend ? options->backend->data : NULL; + if (!state || !state->android_service_daemon || !state->scope_observer + || sentry__atomic_fetch(&state->crashed)) { + return NULL; } + return state; +} - int rv = first_breadcrumb - ? sentry__path_write_buffer(breadcrumb_file, mpack, mpack_size) - : sentry__path_append_buffer(breadcrumb_file, mpack, mpack_size); +__attribute__((visibility("default"))) int +sentry_android_crash_daemon_dup_shm_fd(void) +{ + int fd = -1; + SENTRY_WITH_OPTIONS (options) { + // prevent the IPC lookup from racing with backend shutdown or reinstall + sentry_scope_t *scope = sentry_scope_acquire(); + if (!scope) { + continue; + } + sentry__mutex_lock(&scope->observers_lock); + native_backend_state_t *state = android_service_backend_state(options); + if (state) { + fd = fcntl(state->ipc->shm_fd, F_DUPFD_CLOEXEC, 0); + } + sentry__mutex_unlock(&scope->observers_lock); + sentry_scope_release(scope); + } + return fd; +} - sentry_free(mpack); +__attribute__((visibility("default"))) bool +sentry_android_crash_daemon_reattach( + int notify_fd, int ready_fd, int message_fd) +{ + bool reattached = false; + bool taken = false; + SENTRY_WITH_OPTIONS (options) { + // scope changes notify under this lock, so none lands before the + // snapshot + SENTRY_WITH_SCOPE_MUT (scope) { + sentry__mutex_lock(&scope->observers_lock); + native_backend_state_t *state + = android_service_backend_state(options); + taken = state != NULL; + if (taken + && sentry__crash_ipc_reattach( + state->ipc, notify_fd, ready_fd, message_fd)) { + // as at startup, the new daemon waits for the configured app + uint64_t ready = 1; + ssize_t written + = write(state->ipc->notify_fd, &ready, sizeof(ready)); + (void)written; + reattached = snapshot_scope(state, scope); + } + sentry__mutex_unlock(&scope->observers_lock); + } + } + if (!taken) { + close(notify_fd); + close(ready_fd); + close(message_fd); + } + return reattached; +} +#endif - if (rv != 0) { - SENTRY_WARN("failed to write breadcrumb"); +static bool +observe_scope(native_backend_state_t *state) +{ + sentry_scope_observer_t *observer = sentry__scope_observer_new(); + if (!observer) { + return false; } + observer->data = state; + observer->clear = clear_scope; + observer->set_release = set_release; + observer->set_environment = set_environment; + observer->set_transaction = set_transaction; + observer->set_fingerprint = set_fingerprint; + observer->set_level = set_level; + observer->set_user = set_user; + observer->set_tag = set_tag; + observer->remove_tag = remove_tag; + observer->set_extra = set_extra; + observer->remove_extra = remove_extra; + observer->set_context = set_context; + observer->remove_context = remove_context; + observer->set_trace = set_trace; + observer->add_breadcrumb = add_breadcrumb; + observer->add_attachment = observe_attachment; + observer->remove_attachment = sync_attachments; + bool sent = false; + SENTRY_WITH_SCOPE_MUT (scope) { + if (sentry__scope_add_observer_with_init( + scope, observer, init_scope_observer)) { + state->scope_observer = observer; + sent = true; + } + } + return sent; } /** @@ -1358,6 +1813,9 @@ native_backend_except(sentry_backend_t *backend, const sentry_ucontext_t *uctx) native_backend_state_t *state = (native_backend_state_t *)backend->data; if (state) { sentry__atomic_store(&state->crashed, 1); + if (state->ipc) { + sentry__atomic_store(&state->ipc->stopped, 1); + } } SENTRY_WITH_OPTIONS (options) { @@ -1383,6 +1841,16 @@ native_backend_except(sentry_backend_t *backend, const sentry_ucontext_t *uctx) sentry_value_t event = sentry_value_new_event(); sentry_value_set_by_key( event, "level", sentry__value_new_level(SENTRY_LEVEL_FATAL)); + sentry_crash_context_t *ctx + = state && state->ipc ? state->ipc->shmem : NULL; + if (ctx) { + sentry_value_t exc = sentry__crash_context_build_exception(ctx, + "signalhandler", false, + sentry__crash_context_build_stacktrace( + ctx, sentry__build_registers(uctx))); + sentry_event_add_exception(event, exc); + } + sentry__event_ensure_modules(event); sentry_hint_t hint; sentry__hint_init(&hint); @@ -1404,26 +1872,12 @@ native_backend_except(sentry_backend_t *backend, const sentry_ucontext_t *uctx) } if (should_handle) { - bool modified = sentry__hint_is_modified(&hint); - if (modified) { - size_t len = sentry_value_get_length(hint.attachments); - for (size_t i = 0; i < len; i++) { - add_attachment(state, - sentry_value_get_by_index(hint.attachments, i)); - } - } - // Write modified hint attachments or reload the current scope - native_backend_write_attachments( - state ? state->event_path : NULL, modified ? &hint : NULL); - // Apply scope to the event. The daemon assembles breadcrumbs - // from the ring files + write_crash_attachments(state, &hint); SENTRY_WITH_SCOPE (scope) { sentry__scope_apply_to_event( - scope, options, event, SENTRY_SCOPE_NONE); + scope, options, event, SENTRY_SCOPE_BREADCRUMBS); } -#if defined(SENTRY_PLATFORM_WINDOWS) - ensure_device_arch(event); -#endif + write_crash_event(state, event); #ifndef SENTRY_SCREENSHOT_NONE // The screenshot is captured by the daemon out-of-process, so @@ -1445,24 +1899,6 @@ native_backend_except(sentry_backend_t *backend, const sentry_ucontext_t *uctx) } #endif - // Write event as JSON file - // Daemon will read this and create envelope with minidump - if (state && state->event_path) { - size_t event_json_len = 0; - char *event_json - = sentry__value_to_json(event, &event_json_len); - if (event_json) { - int rv = sentry__path_write_buffer( - state->event_path, event_json, event_json_len); - sentry_free(event_json); - if (rv == 0) { - SENTRY_DEBUG("Wrote crash event JSON for daemon"); - } else { - SENTRY_WARN("Failed to write event JSON"); - } - } - } - sentry_value_decref(event); // End session with crashed status and write session envelope to @@ -1506,6 +1942,9 @@ native_backend_except(sentry_backend_t *backend, const sentry_ucontext_t *uctx) sentry_value_decref(event); sentry_value_decref(transaction); } + if (!should_handle && ctx) { + ctx->event_discarded = true; + } sentry__hint_deinit(&hint); } } @@ -1520,6 +1959,11 @@ native_backend_reinstall(sentry_backend_t *backend) void sentry__backend_preload(void) { +#ifdef SENTRY_PLATFORM_UNIX + if (sentry__crash_handler_preload() < 0) { + SENTRY_WARN("failed to preload native crash handler"); + } +#endif } /** @@ -1537,7 +1981,6 @@ sentry__backend_new(void) backend->shutdown_func = native_backend_shutdown; backend->free_func = native_backend_free; backend->except_func = native_backend_except; - backend->flush_scope_func = native_backend_flush_scope; backend->user_consent_changed_func = native_backend_user_consent_changed; backend->process_old_run_func = native_backend_process_old_run; backend->reinstall_func = native_backend_reinstall; diff --git a/src/integrations/sentry_integration_wer.c b/src/integrations/sentry_integration_wer.c index f59e14c8fc..11be4031f8 100644 --- a/src/integrations/sentry_integration_wer.c +++ b/src/integrations/sentry_integration_wer.c @@ -62,8 +62,9 @@ sentry_integration_wer_free(void *data) } static void -wer_set_tag(void *data, const char *key, const char *value) +wer_set_tag(void *data, const char *key, sentry_value_t tag) { + const char *value = sentry_value_as_string(tag); sentry_integration_wer_data_t *wer_data = (sentry_integration_wer_data_t *)data; if (!wer_data->WerRegisterCustomMetadata) { @@ -135,7 +136,7 @@ static int wer_sync_tag(const char *key, sentry_value_t value, void *data) { if (sentry_value_get_type(value) == SENTRY_VALUE_TYPE_STRING) { - wer_set_tag(data, key, sentry_value_as_string(value)); + wer_set_tag(data, key, value); } return 0; } @@ -232,8 +233,6 @@ wer_clear(void *data) sentry_value_t tags = sentry__scope_load_tags(scope); sentry_value_foreach_key_value(tags, wer_cleanup_tag, wer_data); sentry_value_decref(tags); - - wer_for_each_attachment(scope, wer_data, wer_remove_attachment); } static void diff --git a/src/modulefinder/sentry_modulefinder_linux.c b/src/modulefinder/sentry_modulefinder_linux.c index df1cacff5f..646fa4e184 100644 --- a/src/modulefinder/sentry_modulefinder_linux.c +++ b/src/modulefinder/sentry_modulefinder_linux.c @@ -5,6 +5,7 @@ #include "sentry_core.h" #include "sentry_elf.h" +#include "sentry_os.h" #include "sentry_path.h" #include "sentry_string.h" #include "sentry_sync.h" @@ -16,22 +17,10 @@ #include #include #include -#include #include #include #include -#if defined(__ANDROID_API__) && __ANDROID_API__ < 23 -static ssize_t -process_vm_readv(pid_t __pid, const struct iovec *__local_iov, - unsigned long __local_iov_count, const struct iovec *__remote_iov, - unsigned long __remote_iov_count, unsigned long __flags) -{ - return syscall(__NR_process_vm_readv, __pid, __local_iov, __local_iov_count, - __remote_iov, __remote_iov_count, __flags); -} -#endif - #define ENSURE(Ptr) \ if (!Ptr) \ goto fail @@ -137,7 +126,7 @@ read_safely(void *dst, void *src, size_t size) remote[0].iov_len = size; errno = 0; - ssize_t nread = process_vm_readv(pid, local, 1, remote, 1, 0); + ssize_t nread = sentry__process_vm_readv(pid, local, 1, remote, 1, 0); bool rv = nread == (ssize_t)size; // The syscall can fail with `EPERM` if we lack permissions for this syscall diff --git a/src/modulefinder/sentry_modulefinder_windows.c b/src/modulefinder/sentry_modulefinder_windows.c index 60722c797a..fe0bec1d82 100644 --- a/src/modulefinder/sentry_modulefinder_windows.c +++ b/src/modulefinder/sentry_modulefinder_windows.c @@ -204,7 +204,8 @@ load_modules(void) # endif sentry_value_set_by_key(rv, "image_addr", - sentry__value_new_addr((uint64_t)module.modBaseAddr)); + sentry__value_new_addr( + (uint64_t)(uintptr_t)module.modBaseAddr)); sentry_value_set_by_key(rv, "image_size", sentry_value_new_int32((int32_t)module.modBaseSize)); sentry_value_set_by_key(rv, "code_file", diff --git a/src/path/sentry_path_unix.c b/src/path/sentry_path_unix.c index 28540a6f54..df9f4cc331 100644 --- a/src/path/sentry_path_unix.c +++ b/src/path/sentry_path_unix.c @@ -440,6 +440,9 @@ sentry__path_create_dir_all(const sentry_path_t *path) } while (0) p = sentry__string_clone(path->path); + if (!p) { + return 1; + } for (ptr = p; *ptr; ptr++) { if (*ptr == '/' && ptr != p) { *ptr = 0; @@ -704,3 +707,28 @@ sentry__filewriter_byte_count(const sentry_filewriter_t *filewriter) { return filewriter ? filewriter->byte_count : 0; } + +FILE * +sentry__path_open(const sentry_path_t *path, const char *mode, size_t offset) +{ + if (!path || !mode) { + return NULL; + } + FILE *file = fopen(path->path, mode); + if (!file) { + return NULL; + } +#if defined(SENTRY_PLATFORM_NX) || defined(SENTRY_PLATFORM_PS) + int result = offset > LONG_MAX ? -1 : fseek(file, (long)offset, SEEK_SET); +#else + off_t file_offset = (off_t)offset; + int result = file_offset < 0 || (size_t)file_offset != offset + ? -1 + : fseeko(file, file_offset, SEEK_SET); +#endif + if (result != 0) { + fclose(file); + return NULL; + } + return file; +} diff --git a/src/path/sentry_path_windows.c b/src/path/sentry_path_windows.c index 7169a89afd..4350b32923 100644 --- a/src/path/sentry_path_windows.c +++ b/src/path/sentry_path_windows.c @@ -870,3 +870,24 @@ sentry__filewriter_byte_count(const sentry_filewriter_t *filewriter) { return filewriter ? filewriter->byte_count : 0; } + +FILE * +sentry__path_open(const sentry_path_t *path, const char *mode, size_t offset) +{ + if (!path || !mode) { + return NULL; + } + wchar_t *mode_w = sentry__string_to_wstr(mode); + FILE *file = mode_w ? _wfopen(path->path_w, mode_w) : NULL; + sentry_free(mode_w); + if (!file) { + return NULL; + } + int result + = offset > INT64_MAX ? -1 : _fseeki64(file, (int64_t)offset, SEEK_SET); + if (result != 0) { + fclose(file); + return NULL; + } + return file; +} diff --git a/src/screenshot/sentry_screenshot_none.c b/src/screenshot/sentry_screenshot_none.c index 01d3887087..538f33cd83 100644 --- a/src/screenshot/sentry_screenshot_none.c +++ b/src/screenshot/sentry_screenshot_none.c @@ -2,9 +2,8 @@ #include "sentry_core.h" -bool -sentry__screenshot_capture( - const sentry_path_t *UNUSED(path), uint32_t UNUSED(pid)) +int +sentry_screenshot_capture(const char *UNUSED(path), uint32_t UNUSED(pid)) { - return false; + return 1; } diff --git a/src/screenshot/sentry_screenshot_windows.c b/src/screenshot/sentry_screenshot_windows.c index 7064662265..a0eb3263ee 100644 --- a/src/screenshot/sentry_screenshot_windows.c +++ b/src/screenshot/sentry_screenshot_windows.c @@ -147,9 +147,13 @@ calculate_region(DWORD pid, HRGN region) } } -bool -sentry__screenshot_capture(const sentry_path_t *path, uint32_t pid) +int +sentry_screenshot_capture(const char *path, uint32_t pid) { + sentry_path_t *screenshot_path = sentry__path_from_str(path); + if (!screenshot_path) { + return 1; + } // Use provided PID, or current process if 0 DWORD target_pid = pid ? pid : GetCurrentProcessId(); HRGN region = CreateRectRgn(0, 0, 0, 0); @@ -162,7 +166,8 @@ sentry__screenshot_capture(const sentry_path_t *path, uint32_t pid) if (width <= 0 || height <= 0) { SENTRY_INFO("no visible windows to capture"); DeleteObject(region); - return false; + sentry__path_free(screenshot_path); + return 1; } HDC src = GetDC(NULL); @@ -173,16 +178,17 @@ sentry__screenshot_capture(const sentry_path_t *path, uint32_t pid) SelectClipRgn(hdc, region); BitBlt(hdc, 0, 0, width, height, src, box.left, box.top, SRCCOPY); - bool rv = save_bitmap(bitmap, path->path_w); + bool rv = save_bitmap(bitmap, screenshot_path->path_w); if (!rv) { - SENTRY_WARNF("Failed to save screenshot: \"%s\"", path->path); + SENTRY_WARNF("Failed to save screenshot: \"%s\"", path); } else { - SENTRY_DEBUGF("Saved screenshot: \"%s\"", path->path); + SENTRY_DEBUGF("Saved screenshot: \"%s\"", path); } DeleteObject(bitmap); DeleteDC(hdc); ReleaseDC(NULL, src); DeleteObject(region); - return rv; + sentry__path_free(screenshot_path); + return rv ? 0 : 1; } diff --git a/src/sentry_app_hang_latch.c b/src/sentry_app_hang_latch.c index 75d8dd8b66..08f1f6bc5f 100644 --- a/src/sentry_app_hang_latch.c +++ b/src/sentry_app_hang_latch.c @@ -51,8 +51,8 @@ sentry__app_hang_should_capture( // here: the access is off any signal handler (both writer and worker run in // normal thread context) and the heartbeat cadence dwarfs the few-ns lock, so // the lock only delivers the tear-free guarantee we already need. -static uint64_t g_target_tid = 0; -static uint64_t g_last_heartbeat_ms = 0; +static sentry_atomic_u64_t g_target_tid = 0; +static sentry_atomic_u64_t g_last_heartbeat_ms = 0; static volatile long g_app_hang_active = 0; static volatile long g_app_hang_paused = 0; diff --git a/src/sentry_core.c b/src/sentry_core.c index db1deaccf6..7df44b2ad7 100644 --- a/src/sentry_core.c +++ b/src/sentry_core.c @@ -37,6 +37,7 @@ #endif static sentry_options_t *g_options = NULL; +static sentry_scope_observer_t *g_scope_observer = NULL; #ifdef SENTRY__MUTEX_INIT_DYN SENTRY__MUTEX_INIT_DYN(g_options_lock) #else @@ -59,6 +60,17 @@ sentry__options_getref(void) return options; } +void +sentry__options_set(sentry_options_t *options) +{ + SENTRY__MUTEX_INIT_DYN_ONCE(g_options_lock); + sentry__mutex_lock(&g_options_lock); + sentry_options_t *previous = g_options; + g_options = sentry__options_incref(options); + sentry__mutex_unlock(&g_options_lock); + sentry_options_free(previous); +} + sentry_options_t * sentry__options_lock(void) { @@ -85,7 +97,7 @@ sentry__should_skip_upload(void) } static void -flush_global_scope(sentry_scope_t *scope) +flush_scope(sentry_scope_t *scope) { sentry_options_t *options = sentry__options_incref(scope->state); if (options && options->backend && options->backend->flush_scope_func) { @@ -94,6 +106,65 @@ flush_global_scope(sentry_scope_t *scope) sentry_options_free(options); } +static void +update_session_user(void *data, sentry_value_t user) +{ + sentry_scope_t *scope = data; + sentry_options_t *options = sentry__options_incref(scope->state); + sentry__mutex_lock(&options->session_lock); + if (options->session) { + sentry__session_sync_user(options->session, user, + options->run ? options->run->installation_id : NULL); + sentry__run_write_session(options->run, options->session); + sentry__session_notify_changed(options); + } + sentry__mutex_unlock(&options->session_lock); + sentry_options_free(options); +} + +static void +clear_session_user(void *data) +{ + update_session_user(data, sentry_value_new_null()); +} + +static bool +register_scope_observer(sentry_scope_t *scope, sentry_options_t *options) +{ + sentry_scope_observer_t *observer = sentry__scope_observer_new(); + if (!observer) { + return false; + } + observer->data = scope; + observer->clear = clear_session_user; + observer->set_user = update_session_user; + sentry__mutex_lock(&scope->observers_lock); + if (!sentry__scope_add_observer(scope, observer)) { + sentry__mutex_unlock(&scope->observers_lock); + return false; + } + sentry__scope_set_state(scope, sentry__options_incref(options)); + g_scope_observer = observer; + sentry__mutex_unlock(&scope->observers_lock); + return true; +} + +static void +unregister_scope_observer(sentry_scope_t *scope) +{ + if (!g_scope_observer) { + return; + } + sentry__mutex_lock(&scope->observers_lock); + sentry_options_t *options = scope->state; + sentry__scope_set_flush_func(scope, NULL); + sentry__scope_remove_observer(scope, g_scope_observer); + g_scope_observer = NULL; + sentry__scope_set_state(scope, NULL); + sentry__mutex_unlock(&scope->observers_lock); + sentry_options_free(options); +} + static void register_integrations(sentry_scope_t *scope, const sentry_options_t *options) { @@ -169,6 +240,12 @@ sentry_init(sentry_options_t *options) sentry_close(); + if (!sentry__scope_init(options)) { + SENTRY_WARN("failed to initialize scopes"); + goto fail; + } + initial_scope_prepared = true; + sentry__client_report_reset(); sentry_logger_t logger = { NULL, NULL, SENTRY_LEVEL_DEBUG }; @@ -250,9 +327,14 @@ sentry_init(sentry_options_t *options) #endif SENTRY_WITH_SCOPE_MUT (scope) { - sentry__scope_apply_options(scope, options); + if (register_scope_observer(scope, options)) { + sentry__scope_apply_options(scope, options); + } + } + if (!g_scope_observer) { + SENTRY_WARN("failed to register scope observer"); + goto fail; } - initial_scope_prepared = true; sentry__crash_reserve_alloc(options->crash_memory_reserve); @@ -278,8 +360,7 @@ sentry_init(sentry_options_t *options) // *after* setting the global options, register integrations and trigger a // scope and consent flush, since at least crashpad needs that. SENTRY_WITH_SCOPE_MUT (scope) { - sentry__scope_set_state(scope, sentry__options_incref(options)); - sentry__scope_set_flush_func(scope, flush_global_scope); + sentry__scope_set_flush_func(scope, flush_scope); register_integrations(scope, options); sentry__scope_flush(scope); } @@ -316,6 +397,11 @@ sentry_init(sentry_options_t *options) fail: SENTRY_WARN("`sentry_init` failed"); + if (initial_scope_prepared) { + SENTRY_WITH_SCOPE_MUT (scope) { + unregister_scope_observer(scope); + } + } sentry__crash_reserve_release(); if (transport) { sentry__transport_shutdown(transport, 0); @@ -378,10 +464,7 @@ sentry_close(void) size_t dumped_envelopes = 0; if (options) { SENTRY_WITH_SCOPE_MUT (scope) { - sentry_options_t *scope_options = scope->state; - sentry__scope_set_flush_func(scope, NULL); - sentry__scope_set_state(scope, NULL); - sentry_options_free(scope_options); + unregister_scope_observer(scope); } sentry_end_session(); if (options->backend && options->backend->shutdown_func) { @@ -391,8 +474,8 @@ sentry_close(void) sentry__crash_reserve_release(); if (options->transport) { - if (sentry__transport_shutdown( - options->transport, options->shutdown_timeout) + if (sentry__transport_shutdown(options->transport, + sentry_options_get_shutdown_timeout(options)) != 0) { SENTRY_WARN("transport did not shut down cleanly"); } @@ -417,19 +500,17 @@ sentry_close(void) return (int)dumped_envelopes; } -int -sentry_shutdown(void) -{ - return sentry_close(); -} - int sentry_reinstall_backend(void) { int rv = 0; SENTRY_WITH_OPTIONS (options) { // prevent scope observers from racing with backend reinstall - sentry_scope_t *scope = sentry__scope_getref(); + sentry_scope_t *scope = sentry_scope_acquire(); + if (!scope) { + rv = 1; + continue; + } sentry__mutex_lock(&scope->observers_lock); sentry_backend_t *backend = options->backend; if (backend) { @@ -451,7 +532,7 @@ sentry_reinstall_backend(void) } } sentry__mutex_unlock(&scope->observers_lock); - sentry__scope_finish(scope); + sentry_scope_release(scope); } return rv; } @@ -637,12 +718,6 @@ sentry_scope_capture_event( } } -sentry_uuid_t -sentry_capture_event_with_scope(sentry_value_t event, sentry_scope_t *scope) -{ - return sentry_scope_capture_event(scope, event, NULL); -} - static sentry_value_t prepare_attachments( sentry_hint_t *hint, sentry_scope_t *local_scope); @@ -793,17 +868,12 @@ prepare_attachments(sentry_hint_t *hint, sentry_scope_t *local_scope) if (hint) { sentry__attachments_extend(&attachments, hint->attachments); } - if (local_scope) { - sentry_value_t local_attachments - = sentry__scope_load_attachments(local_scope); - sentry__attachments_extend(&attachments, local_attachments); - sentry_value_decref(local_attachments); - } - SENTRY_WITH_SCOPE (scope) { - sentry_value_t global_attachments - = sentry__scope_load_attachments(scope); - sentry__attachments_extend(&attachments, global_attachments); - sentry_value_decref(global_attachments); + sentry_scope_t *scope = local_scope ? local_scope : sentry_scope_acquire(); + sentry_value_t scope_attachments = sentry__scope_load_attachments(scope); + sentry__attachments_extend(&attachments, scope_attachments); + sentry_value_decref(scope_attachments); + if (!local_scope) { + sentry_scope_release(scope); } if (hint) { sentry__hint_set_attachments(hint, sentry_value_incref(attachments)); @@ -811,6 +881,28 @@ prepare_attachments(sentry_hint_t *hint, sentry_scope_t *local_scope) return attachments; } +void +sentry__event_ensure_modules(sentry_value_t event) +{ + sentry_value_t debug_meta = sentry_value_get_by_key(event, "debug_meta"); + sentry_value_t images = sentry_value_get_by_key(debug_meta, "images"); + if (!sentry_value_is_null(images)) { + return; + } + + sentry_value_t modules = sentry_get_modules_list(); + if (!sentry_value_is_null(modules)) { + bool had_debug_meta = !sentry_value_is_null(debug_meta); + if (!had_debug_meta) { + debug_meta = sentry_value_new_object(); + } + sentry_value_set_by_key(debug_meta, "images", modules); + if (!had_debug_meta) { + sentry_value_set_by_key(event, "debug_meta", debug_meta); + } + } +} + sentry_value_t sentry__invoke_on_crash(const sentry_options_t *options, const sentry_ucontext_t *uctx, sentry_value_t event, sentry_hint_t *hint) @@ -839,6 +931,23 @@ sentry__invoke_before_send( return event; } +sentry_value_t +sentry__invoke_before_breadcrumb( + const sentry_options_t *options, sentry_value_t breadcrumb) +{ + if (!options || !options->before_breadcrumb_func) { + return breadcrumb; + } + SENTRY_DEBUG("invoking `before_breadcrumb` hook"); + breadcrumb = options->before_breadcrumb_func( + breadcrumb, options->before_breadcrumb_data); + if (sentry_value_is_null(breadcrumb)) { + SENTRY_DEBUG( + "breadcrumb was discarded by the `before_breadcrumb` hook"); + } + return breadcrumb; +} + sentry_value_t sentry__prepare_event(const sentry_options_t *options, sentry_value_t event, sentry_scope_t *local_scope) @@ -847,19 +956,18 @@ sentry__prepare_event(const sentry_options_t *options, sentry_value_t event, sentry__record_errors_on_current_session(options, 1); } + sentry__event_ensure_modules(event); + + sentry_scope_mode_t mode = SENTRY_SCOPE_ALL; + if (!options->symbolize_stacktraces) { + mode &= ~SENTRY_SCOPE_STACKTRACES; + } if (local_scope) { - SENTRY_DEBUG("merging local scope into event"); - sentry_scope_mode_t mode = SENTRY_SCOPE_BREADCRUMBS; sentry__scope_apply_to_event(local_scope, options, event, mode); - } - - SENTRY_WITH_SCOPE (scope) { - SENTRY_DEBUG("merging global scope into event"); - sentry_scope_mode_t mode = SENTRY_SCOPE_ALL; - if (!options->symbolize_stacktraces) { - mode &= ~SENTRY_SCOPE_STACKTRACES; + } else { + SENTRY_WITH_SCOPE (scope) { + sentry__scope_apply_to_event(scope, options, event, mode); } - sentry__scope_apply_to_event(scope, options, event, mode); } return event; } @@ -902,8 +1010,7 @@ sentry__prepare_transaction(const sentry_options_t *options, SENTRY_WITH_SCOPE (scope) { SENTRY_DEBUG("merging scope into transaction"); // Don't include debugging info - sentry_scope_mode_t mode = SENTRY_SCOPE_ALL & ~SENTRY_SCOPE_MODULES - & ~SENTRY_SCOPE_STACKTRACES; + sentry_scope_mode_t mode = SENTRY_SCOPE_ALL & ~SENTRY_SCOPE_STACKTRACES; sentry__scope_apply_to_event(scope, options, transaction, mode); } @@ -937,24 +1044,6 @@ sentry__prepare_transaction(const sentry_options_t *options, return NULL; } -static sentry_envelope_t * -prepare_user_report(const sentry_options_t *options, sentry_value_t user_report) -{ - sentry_envelope_t *envelope = NULL; - - envelope = sentry__envelope_new(options); - if (!envelope || !sentry__envelope_add_user_report(envelope, user_report)) { - goto fail; - } - - return envelope; - -fail: - SENTRY_WARN("dropping user report"); - sentry_envelope_free(envelope); - return NULL; -} - static sentry_envelope_t * prepare_user_feedback(const sentry_options_t *options, sentry_value_t user_feedback, sentry_hint_t *hint, @@ -969,13 +1058,13 @@ prepare_user_feedback(const sentry_options_t *options, event, "level", sentry__value_new_level(SENTRY_LEVEL_INFO)); if (local_scope) { - SENTRY_DEBUG("merging local scope into feedback event"); sentry__scope_apply_to_event( - local_scope, options, event, SENTRY_SCOPE_NONE); - } - SENTRY_WITH_SCOPE (scope) { - SENTRY_DEBUG("merging global scope into feedback event"); - sentry__scope_apply_to_event(scope, options, event, SENTRY_SCOPE_NONE); + local_scope, options, event, SENTRY_SCOPE_DSC); + } else { + SENTRY_WITH_SCOPE (scope) { + sentry__scope_apply_to_event( + scope, options, event, SENTRY_SCOPE_DSC); + } } sentry_value_t all_attachments = prepare_attachments(hint, local_scope); @@ -1120,21 +1209,6 @@ sentry__ensure_event_id(sentry_value_t event, sentry_uuid_t *uuid_out) void sentry_set_user(sentry_value_t user) { - if (!sentry_value_is_null(user)) { - sentry_options_t *options = sentry__options_lock(); - if (options) { - sentry__mutex_lock(&options->session_lock); - if (options->session) { - sentry__session_sync_user(options->session, user, - options->run ? options->run->installation_id : NULL); - sentry__run_write_session(options->run, options->session); - sentry__session_notify_changed(options); - } - sentry__mutex_unlock(&options->session_lock); - } - sentry__options_unlock(); - } - SENTRY_WITH_SCOPE_MUT (scope) { sentry_scope_set_user(scope, user); } @@ -1177,24 +1251,6 @@ sentry_set_environment(const char *environment) void sentry_add_breadcrumb(sentry_value_t breadcrumb) { - bool discarded = false; - SENTRY_WITH_OPTIONS (options) { - if (options->before_breadcrumb_func) { - SENTRY_DEBUG("invoking `before_breadcrumb` hook"); - breadcrumb = options->before_breadcrumb_func( - breadcrumb, options->before_breadcrumb_data); - if (sentry_value_is_null(breadcrumb)) { - SENTRY_DEBUG("breadcrumb was discarded by the " - "`before_breadcrumb` hook"); - discarded = true; - } - } - } - - if (discarded) { - return; - } - // backend observers persist breadcrumbs without a scope flush SENTRY_WITH_SCOPE_MUT (scope) { sentry_scope_add_breadcrumb(scope, breadcrumb); @@ -1339,14 +1395,6 @@ sentry_update_context_n(const char *key, size_t key_len, sentry_value_t value) } } -void -sentry__set_propagation_context(const char *key, sentry_value_t value) -{ - SENTRY_WITH_SCOPE_MUT (scope) { - sentry__scope_set_propagation_context(scope, key, value); - } -} - void sentry__apply_to_telemetry(const sentry_scope_t *scope, const sentry_options_t *options, sentry_value_t telemetry, @@ -1354,9 +1402,11 @@ sentry__apply_to_telemetry(const sentry_scope_t *scope, { if (scope) { sentry__scope_apply_to_telemetry(scope, telemetry, attributes); - } - SENTRY_WITH_SCOPE (global_scope) { - sentry__scope_apply_to_telemetry(global_scope, telemetry, attributes); + } else { + SENTRY_WITH_SCOPE (global_scope) { + sentry__scope_apply_to_telemetry( + global_scope, telemetry, attributes); + } } sentry__value_add_attribute(attributes, sentry_value_new_string(sentry_options_get_sdk_name(options)), "string", @@ -1428,39 +1478,35 @@ void sentry_set_trace_n(const char *trace_id, size_t trace_id_len, const char *parent_span_id, size_t parent_span_id_len) { - sentry_value_t context = sentry_value_new_null(); - SENTRY_WITH_SCOPE_MUT (scope) { - context = sentry_value_new_object(); - - sentry_value_set_by_key( - context, "type", sentry_value_new_string("trace")); - - sentry_value_set_by_key(context, "trace_id", - sentry_value_new_string_n(trace_id, trace_id_len)); - if (parent_span_id && parent_span_id_len) { - sentry_value_set_by_key(context, "parent_span_id", - sentry_value_new_string_n(parent_span_id, parent_span_id_len)); - } - - sentry_uuid_t span_id = sentry_uuid_new_v4(); - sentry_value_set_by_key( - context, "span_id", sentry__value_new_span_uuid(&span_id)); - sentry__scope_set_trace_managed(scope, false); - sentry__scope_flush(scope); + sentry_scope_set_trace_n( + scope, trace_id, trace_id_len, parent_span_id, parent_span_id_len); } +} - if (!sentry_value_is_null(context)) { - sentry__generate_sample_rand(context); +void +sentry_continue_trace(const char *sentry_trace, const char *baggage) +{ + sentry_continue_trace_n(sentry_trace, sentry__guarded_strlen(sentry_trace), + baggage, sentry__guarded_strlen(baggage)); +} - sentry__set_propagation_context("trace", context); +void +sentry_continue_trace_n(const char *sentry_trace, size_t sentry_trace_len, + const char *baggage, size_t baggage_len) +{ + SENTRY_WITH_SCOPE_MUT (scope) { + sentry_scope_continue_trace_n( + scope, sentry_trace, sentry_trace_len, baggage, baggage_len); + } +} - SENTRY_WITH_OPTIONS (options) { - SENTRY_WITH_SCOPE_MUT (scope) { - sentry__scope_update_dsc(scope, options); - sentry__scope_flush(scope); - } - } +void +sentry_iter_trace_propagation_headers( + sentry_iter_headers_function_t callback, void *userdata) +{ + SENTRY_WITH_SCOPE (scope) { + sentry_scope_iter_trace_propagation_headers(scope, callback, userdata); } } @@ -1477,12 +1523,6 @@ sentry_start_new_trace(void) } } -void -sentry_regenerate_trace(void) -{ - sentry_start_new_trace(); -} - void sentry_set_transaction(const char *transaction) { @@ -1936,20 +1976,6 @@ sentry_span_discard(sentry_span_t *opaque_span) sentry__span_decref(opaque_span); } -void -sentry_capture_user_feedback(sentry_value_t user_report) -{ - sentry_envelope_t *envelope = NULL; - - SENTRY_WITH_OPTIONS (options) { - envelope = prepare_user_report(options, user_report); - if (envelope) { - sentry__capture_envelope(options->transport, envelope, options); - } - } - sentry_value_decref(user_report); -} - static sentry_uuid_t capture_feedback(sentry_value_t user_feedback, sentry_hint_t *hint, sentry_scope_t *local_scope) @@ -2079,18 +2105,6 @@ sentry_get_crashed_last_run(void) return g_last_crash; } -int -sentry_clear_crashed_last_run(void) -{ - bool success = false; - sentry_options_t *options = sentry__options_lock(); - if (options) { - success = sentry__clear_crash_marker(options); - } - sentry__options_unlock(); - return success ? 0 : 1; -} - sentry_uuid_t sentry_capture_minidump(const char *path) { diff --git a/src/sentry_core.h b/src/sentry_core.h index b3aa24c027..19924ab956 100644 --- a/src/sentry_core.h +++ b/src/sentry_core.h @@ -47,6 +47,11 @@ bool sentry__should_skip_upload(void); */ bool sentry__event_is_transaction(sentry_value_t event); +/** + * Populates missing `debug_meta.images` with cached modules when available. + */ +void sentry__event_ensure_modules(sentry_value_t event); + /** * Invokes the configured `on_crash` callback, if any. * @@ -65,9 +70,15 @@ sentry_value_t sentry__invoke_on_crash(const sentry_options_t *options, sentry_value_t sentry__invoke_before_send( const sentry_options_t *options, sentry_value_t event, sentry_hint_t *hint); +/** + * Invokes the configured `before_breadcrumb` callback, if any. + */ +sentry_value_t sentry__invoke_before_breadcrumb( + const sentry_options_t *options, sentry_value_t breadcrumb); + /** * Prepares an event by recording errors on the current session and applying - * the local and global scopes. + * the local, isolation, and global scopes. * * Returns `event` without transferring ownership. */ @@ -123,7 +134,7 @@ void sentry__submit_envelope(sentry_transport_t *transport, sentry_envelope_t *envelope, const sentry_options_t *options); /** - * Captures the `envelope` on the global scope, recording the last sent event + * Captures the `envelope` on the isolation scope, recording the last sent event * ID. * * Note: This is not safe to call from crash handlers; use @@ -150,6 +161,12 @@ sentry_value_t sentry__ensure_event_id( */ const sentry_options_t *sentry__options_getref(void); +/** + * Replaces the global options with a retained reference, or clears them if + * NULL. + */ +void sentry__options_set(sentry_options_t *options); + /** * This will acquire a lock on the global options. */ @@ -160,13 +177,12 @@ sentry_options_t *sentry__options_lock(void); */ void sentry__options_unlock(void); -void sentry__set_propagation_context(const char *key, sentry_value_t value); - /* * Populates a telemetry item (a log or metric) with attributes and scope data * from all available sources. Values are applied in precedence order, where the * first write wins: per-call attributes already present in `attributes`, then - * the passed `scope`, then the global scope, and finally the options. + * the passed `scope`, then its isolation and global scopes, and finally the + * options. */ void sentry__apply_to_telemetry(const sentry_scope_t *scope, const sentry_options_t *options, sentry_value_t telemetry, diff --git a/src/sentry_elf.h b/src/sentry_elf.h index bb80d3f019..7a50b37534 100644 --- a/src/sentry_elf.h +++ b/src/sentry_elf.h @@ -37,9 +37,11 @@ sentry__elf_open(const char *path) * Used to filter out non-ELF mappings (e.g. files under /dev/shm, deleted * files, sentry-native's own IPC shared memory) from the module list — LLDB and * other consumers can choke on entries that look like modules but aren't. + * A non-zero offset checks for an ELF image inside a larger file, such as a + * library that Android maps straight from an APK. */ static inline bool -sentry__elf_is_file(const char *path) +sentry__elf_is_file_at(const char *path, uint64_t offset) { int fd = sentry__elf_open(path); if (fd < 0) { @@ -47,16 +49,23 @@ sentry__elf_is_file(const char *path) } unsigned char magic[SELFMAG]; - bool is_elf = read(fd, magic, SELFMAG) == (ssize_t)SELFMAG + bool is_elf = pread(fd, magic, SELFMAG, (off_t)offset) == (ssize_t)SELFMAG && memcmp(magic, ELFMAG, SELFMAG) == 0; close(fd); return is_elf; } +static inline bool +sentry__elf_is_file(const char *path) +{ + return sentry__elf_is_file_at(path, 0); +} + static inline bool sentry__elf_is_native_class(const unsigned char e_ident[EI_NIDENT]) { -# if defined(__x86_64__) || defined(__aarch64__) +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) return e_ident[EI_CLASS] == ELFCLASS64; # else return e_ident[EI_CLASS] == ELFCLASS32; @@ -71,7 +80,8 @@ sentry__elf_has_shdr_size( return false; } -# if defined(__x86_64__) || defined(__aarch64__) +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) return e_shentsize == sizeof(Elf64_Shdr); # else return e_shentsize == sizeof(Elf32_Shdr); @@ -86,7 +96,8 @@ sentry__elf_has_sym_entsize( return false; } -# if defined(__x86_64__) || defined(__aarch64__) +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) return sh_entsize == sizeof(Elf64_Sym); # else return sh_entsize == sizeof(Elf32_Sym); @@ -101,7 +112,8 @@ sentry__elf_has_phdr_size( return false; } -# if defined(__x86_64__) || defined(__aarch64__) +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) return e_phentsize == sizeof(Elf64_Phdr); # else return e_phentsize == sizeof(Elf32_Phdr); @@ -203,6 +215,90 @@ sentry__elf_find_note(const void *buf, size_t buf_size, size_t alignment, return NULL; } +/** + * Compute the virtual memory size of an ELF file from its PT_LOAD segments. + * This matches Crashpad's behavior: size = max(p_vaddr + p_memsz) - + * min(p_vaddr) across all PT_LOAD segments, rather than using page-aligned + * /proc/maps sizes. + * Returns the computed size, or 0 on failure (caller should fall back to + * /proc/maps size). + */ +static inline uint64_t +sentry__elf_compute_size_from_phdrs(const char *elf_path, uint64_t elf_offset) +{ + int fd = sentry__elf_open(elf_path); + if (fd < 0) { + return 0; + } + +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) + Elf64_Ehdr ehdr; +# else + Elf32_Ehdr ehdr; +# endif + + if (pread(fd, &ehdr, sizeof(ehdr), (off_t)elf_offset) != sizeof(ehdr) + || memcmp(ehdr.e_ident, ELFMAG, SELFMAG) != 0 || ehdr.e_phnum == 0) { + close(fd); + return 0; + } + + if (!sentry__elf_has_phdr_size(ehdr.e_ident, ehdr.e_phentsize)) { + close(fd); + return 0; + } + + // Read program headers + size_t phdr_size = (size_t)ehdr.e_phentsize * ehdr.e_phnum; + void *phdr_buf = sentry_malloc(phdr_size); + if (!phdr_buf) { + close(fd); + return 0; + } + + uint64_t phoff = elf_offset + ehdr.e_phoff; + if (lseek(fd, (off_t)phoff, SEEK_SET) != (off_t)phoff + || read(fd, phdr_buf, phdr_size) != (ssize_t)phdr_size) { + sentry_free(phdr_buf); + close(fd); + return 0; + } + +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) + Elf64_Phdr *phdrs = (Elf64_Phdr *)phdr_buf; +# else + Elf32_Phdr *phdrs = (Elf32_Phdr *)phdr_buf; +# endif + + uint64_t min_vaddr = UINT64_MAX; + uint64_t max_vaddr = 0; + bool found_load = false; + + for (int i = 0; i < ehdr.e_phnum; i++) { + if (phdrs[i].p_type == PT_LOAD) { + found_load = true; + if (phdrs[i].p_vaddr < min_vaddr) { + min_vaddr = phdrs[i].p_vaddr; + } + uint64_t end = (uint64_t)phdrs[i].p_vaddr + phdrs[i].p_memsz; + if (end > max_vaddr) { + max_vaddr = end; + } + } + } + + sentry_free(phdr_buf); + close(fd); + + if (!found_load || max_vaddr <= min_vaddr) { + return 0; + } + + return max_vaddr - min_vaddr; +} + #endif #endif diff --git a/src/sentry_envelope.c b/src/sentry_envelope.c index ac0eeb3e4f..9a00174c73 100644 --- a/src/sentry_envelope.c +++ b/src/sentry_envelope.c @@ -13,7 +13,6 @@ #include "sentry_value.h" #include #include -#include #include struct sentry_envelope_item_s { @@ -421,6 +420,7 @@ sentry_envelope_item_t * sentry__envelope_add_event(sentry_envelope_t *envelope, sentry_value_t event, const sentry_options_t *options) { + (void)options; sentry_envelope_item_t *item = envelope_add_item(envelope); if (!item) { return NULL; @@ -434,9 +434,12 @@ sentry__envelope_add_event(sentry_envelope_t *envelope, sentry_value_t event, sentry_uuid_t event_id; sentry__ensure_event_id(event, &event_id); + sentry_value_t dsc = sentry__value_take_by_key(event, "dsc"); + sentry__jsonwriter_write_value(jw, event); item->payload = sentry__jsonwriter_into_string(jw, &item->payload_len); if (!item->payload) { + sentry_value_decref(dsc); return NULL; } item->event = event; @@ -448,16 +451,6 @@ sentry__envelope_add_event(sentry_envelope_t *envelope, sentry_value_t event, sentry__envelope_set_event_id(envelope, &event_id); - double traces_sample_rate = options ? options->traces_sample_rate : 0.0; - sentry_value_t dsc = sentry_value_new_null(); - double sample_rand = (double)NAN; - SENTRY_WITH_SCOPE (scope) { - dsc = sentry__scope_load_dsc(scope); - sentry_value_t trace_context = sentry__scope_load_trace_context(scope); - sample_rand = sentry_value_as_double( - sentry_value_get_by_key(trace_context, "sample_rand")); - sentry_value_decref(trace_context); - } if (!sentry_value_is_null(dsc)) { sentry_value_t trace_id = sentry_value_get_by_key( sentry_value_get_by_key( @@ -470,20 +463,6 @@ sentry__envelope_add_event(sentry_envelope_t *envelope, sentry_value_t event, SENTRY_WARN("couldn't retrieve trace_id from scope to apply to the " "dynamic sampling context"); } - if (!isnan(sample_rand)) { - if (sample_rand >= traces_sample_rate) { - sentry_value_set_by_key( - dsc, "sampled", sentry_value_new_string("false")); - } else { - sentry_value_set_by_key( - dsc, "sampled", sentry_value_new_string("true")); - } - } else { - // only for testing; in production, the SDK should always have a - // non-null sample_rand. We don't set "sampled" to keep dsc empty - SENTRY_WARN("couldn't retrieve sample_rand from scope to apply to " - "the dynamic sampling context"); - } // only add dsc if it has values if (sentry_value_is_true(dsc)) { #ifdef SENTRY_UNITTEST @@ -624,39 +603,6 @@ sentry__envelope_add_metrics( "application/vnd.sentry.items.trace-metric+json"); } -sentry_envelope_item_t * -sentry__envelope_add_user_report( - sentry_envelope_t *envelope, sentry_value_t user_report) -{ - sentry_envelope_item_t *item = envelope_add_item(envelope); - if (!item) { - return NULL; - } - - sentry_jsonwriter_t *jw = sentry__jsonwriter_new_sb(NULL); - if (!jw) { - return NULL; - } - - sentry_uuid_t event_id; - sentry__ensure_event_id(user_report, &event_id); - - sentry__jsonwriter_write_value(jw, user_report); - item->payload = sentry__jsonwriter_into_string(jw, &item->payload_len); - if (!item->payload) { - return NULL; - } - - sentry__envelope_item_set_header( - item, "type", sentry_value_new_string("user_report")); - sentry_value_t length = sentry_value_new_int32((int32_t)item->payload_len); - sentry__envelope_item_set_header(item, "length", length); - - sentry__envelope_set_event_id(envelope, &event_id); - - return item; -} - sentry_envelope_item_t * sentry__envelope_add_feedback_event(sentry_envelope_t *envelope, sentry_value_t feedback_event, const sentry_options_t *options) @@ -722,6 +668,10 @@ attachment_ref_payload_to_string( sentry_value_set_by_key( obj, "content_type", sentry_value_new_string(ref->content_type)); } + if (ref->chunk_size) { + sentry_value_set_by_key(obj, "chunk_size", + sentry_value_new_uint64((uint64_t)ref->chunk_size)); + } sentry__jsonwriter_write_value(jw, obj); sentry_value_decref(obj); return sentry__jsonwriter_into_string(jw, payload_len); @@ -1100,6 +1050,67 @@ sentry_envelope_deserialize(const char *buf, size_t buf_len) return envelope; } +/** + * Parses the serialized item at `*ptr` into its headers and the location of its + * payload, without copying or parsing the payload, and advances `*ptr` to the + * next item. Returns false if the item is malformed. + */ +static bool +parse_item(const char **ptr, const char *end, sentry_value_t *headers, + const char **payload, size_t *len) +{ + *headers = sentry_value_new_null(); + + // item headers + const char *item_headers_end = memchr(*ptr, '\n', (size_t)(end - *ptr)); + if (!item_headers_end) { + return false; + } + size_t item_headers_len = (size_t)(item_headers_end - *ptr); + *headers = sentry_value_from_json(*ptr, item_headers_len); + if (sentry_value_get_type(*headers) != SENTRY_VALUE_TYPE_OBJECT) { + return false; + } + *ptr = item_headers_end + 1; // skip newline + + if (*ptr > end) { + return false; + } + + // item payload + sentry_value_t length = sentry_value_get_by_key(*headers, "length"); + if (sentry_value_is_null(length)) { + // length omitted -> find newline or end of buffer + const char *payload_end = memchr(*ptr, '\n', (size_t)(end - *ptr)); + if (!payload_end) { + payload_end = end; + } + *len = (size_t)(payload_end - *ptr); + } else if (sentry_value_get_type(length) == SENTRY_VALUE_TYPE_UINT64) { + uint64_t payload_len = sentry_value_as_uint64(length); + if (payload_len >= SIZE_MAX) { + return false; + } + *len = (size_t)payload_len; + } else { + int64_t payload_len = sentry_value_as_int64(length); + if (payload_len < 0 || (uint64_t)payload_len >= SIZE_MAX) { + return false; + } + *len = (size_t)payload_len; + } + if (*len > 0 && (*len >= SIZE_MAX || *len > (size_t)(end - *ptr))) { + return false; + } + *payload = *ptr; + *ptr += *len; + + while (*ptr < end && **ptr == '\n') { + (*ptr)++; + } + return true; +} + // https://develop.sentry.dev/sdk/data-model/envelopes/ static bool deserialize_into(sentry_envelope_t *envelope, const char *buf, size_t buf_len) @@ -1136,56 +1147,18 @@ deserialize_into(sentry_envelope_t *envelope, const char *buf, size_t buf_len) return false; } - // item headers - const char *item_headers_end = memchr(ptr, '\n', (size_t)(end - ptr)); - if (!item_headers_end) { - return false; - } - size_t item_headers_len = (size_t)(item_headers_end - ptr); + const char *payload = NULL; sentry_value_decref(item->headers); - item->headers = sentry_value_from_json(ptr, item_headers_len); - if (sentry_value_get_type(item->headers) != SENTRY_VALUE_TYPE_OBJECT) { + if (!parse_item( + &ptr, end, &item->headers, &payload, &item->payload_len)) { return false; } - ptr = item_headers_end + 1; // skip newline - - if (ptr > end) { - return false; - } - - // item payload - sentry_value_t length - = sentry_value_get_by_key(item->headers, "length"); - if (sentry_value_is_null(length)) { - // length omitted -> find newline or end of buffer - const char *payload_end = memchr(ptr, '\n', (size_t)(end - ptr)); - if (!payload_end) { - payload_end = end; - } - item->payload_len = (size_t)(payload_end - ptr); - } else if (sentry_value_get_type(length) == SENTRY_VALUE_TYPE_UINT64) { - uint64_t payload_len = sentry_value_as_uint64(length); - if (payload_len >= SIZE_MAX) { - return false; - } - item->payload_len = (size_t)payload_len; - } else { - int64_t payload_len = sentry_value_as_int64(length); - if (payload_len < 0 || (uint64_t)payload_len >= SIZE_MAX) { - return false; - } - item->payload_len = (size_t)payload_len; - } if (item->payload_len > 0) { - if (item->payload_len >= SIZE_MAX - || item->payload_len > (size_t)(end - ptr)) { - return false; - } item->payload = sentry_malloc(item->payload_len + 1); if (!item->payload) { return false; } - memcpy(item->payload, ptr, item->payload_len); + memcpy(item->payload, payload, item->payload_len); item->payload[item->payload_len] = '\0'; // item event/transaction @@ -1197,12 +1170,6 @@ deserialize_into(sentry_envelope_t *envelope, const char *buf, size_t buf_len) item->event = sentry_value_from_json(item->payload, item->payload_len); } - - ptr += item->payload_len; - } - - while (ptr < end && *ptr == '\n') { - ptr++; } } @@ -1641,6 +1608,19 @@ sentry__envelope_item_get_attachment_ref( sentry_value_get_by_key(ref->_owner, "content_type")); ref->attachment_type = sentry_value_as_string( sentry_value_get_by_key(item->headers, "attachment_type")); + sentry_value_t value = sentry_value_get_by_key(ref->_owner, "chunk_size"); + uint64_t chunk_size = 0; + if (sentry_value_get_type(value) == SENTRY_VALUE_TYPE_UINT64) { + chunk_size = sentry_value_as_uint64(value); + } else { + int64_t size = sentry_value_as_int64(value); + if (size > 0) { + chunk_size = (uint64_t)size; + } + } + if (chunk_size <= SIZE_MAX) { + ref->chunk_size = (size_t)chunk_size; + } return true; } @@ -1675,8 +1655,8 @@ set_attachment_ref_payload( } bool -sentry__envelope_item_resolve_attachment_ref( - sentry_envelope_item_t *item, const char *location) +sentry__envelope_item_resolve_attachment_ref(sentry_envelope_item_t *item, + const char *path, const char *location, size_t chunk_size) { if (sentry__string_empty(location)) { return false; @@ -1686,13 +1666,14 @@ sentry__envelope_item_resolve_attachment_ref( return false; } sentry_attachment_ref_t resolved = { 0 }; - if (!sentry__string_empty(ref.path)) { - resolved.path = ref.path; + if (!sentry__string_empty(path)) { + resolved.path = path; } if (!sentry__string_empty(ref.attachment_type)) { resolved.attachment_type = ref.attachment_type; } resolved.location = location; + resolved.chunk_size = chunk_size; if (!sentry__string_empty(ref.content_type)) { resolved.content_type = ref.content_type; } @@ -1735,3 +1716,43 @@ sentry__envelope_has_content_type( } return false; } + +bool +sentry__envelope_has_item_type( + const sentry_envelope_t *envelope, const char *type) +{ + if (!envelope || !type) { + return false; + } + if (!envelope->is_raw) { + for (const sentry_envelope_item_t *item + = envelope->contents.items.first_item; + item; item = item->next) { + const char *item_type = sentry_value_as_string( + sentry_value_get_by_key(item->headers, "type")); + if (sentry__string_eq(item_type, type)) { + return true; + } + } + return false; + } + + const char *ptr = envelope->contents.raw.payload; + const char *end = ptr + envelope->contents.raw.payload_len; + const char *headers_end = memchr(ptr, '\n', (size_t)(end - ptr)); + ptr = headers_end ? headers_end + 1 : end; + while (ptr < end) { + sentry_value_t headers; + const char *payload; + size_t len; + bool ok = parse_item(&ptr, end, &headers, &payload, &len); + const char *item_type + = sentry_value_as_string(sentry_value_get_by_key(headers, "type")); + bool found = ok && sentry__string_eq(item_type, type); + sentry_value_decref(headers); + if (!ok || found) { + return found; + } + } + return false; +} diff --git a/src/sentry_envelope.h b/src/sentry_envelope.h index ab20c3a67c..17fc805a3e 100644 --- a/src/sentry_envelope.h +++ b/src/sentry_envelope.h @@ -23,6 +23,7 @@ typedef struct { const char *location; const char *content_type; const char *attachment_type; + size_t chunk_size; sentry_value_t _owner; } sentry_attachment_ref_t; @@ -67,12 +68,6 @@ sentry_envelope_item_t *sentry__envelope_add_event(sentry_envelope_t *envelope, sentry_envelope_item_t *sentry__envelope_add_transaction( sentry_envelope_t *envelope, sentry_value_t transaction); -/** - * Add a deprecated user report to this envelope. - */ -sentry_envelope_item_t *sentry__envelope_add_user_report( - sentry_envelope_t *envelope, sentry_value_t user_report); - /** * Add a list of logs to this envelope. */ @@ -229,8 +224,8 @@ void sentry__attachment_ref_cleanup(sentry_attachment_ref_t *ref); /** * Resolves an attachment-ref item with a remote TUS location. */ -bool sentry__envelope_item_resolve_attachment_ref( - sentry_envelope_item_t *item, const char *location); +bool sentry__envelope_item_resolve_attachment_ref(sentry_envelope_item_t *item, + const char *path, const char *location, size_t chunk_size); /** * If `envelope` is raw, parse it in place into a structured envelope. @@ -246,4 +241,11 @@ bool sentry__envelope_materialize(sentry_envelope_t *envelope); bool sentry__envelope_has_content_type( const sentry_envelope_t *envelope, const char *content_type); +/** + * True if `envelope` contains at least one item with the given `type` header + * value. For raw envelopes this parses only the item headers. + */ +bool sentry__envelope_has_item_type( + const sentry_envelope_t *envelope, const char *type); + #endif diff --git a/src/sentry_info.c b/src/sentry_info.c index ca2f6387a4..12cdb7a046 100644 --- a/src/sentry_info.c +++ b/src/sentry_info.c @@ -5,15 +5,3 @@ sentry_sdk_version(void) { return SENTRY_SDK_VERSION; } - -const char * -sentry_sdk_name(void) -{ - return SENTRY_SDK_NAME; -} - -const char * -sentry_sdk_user_agent(void) -{ - return SENTRY_SDK_USER_AGENT; -} diff --git a/src/sentry_options.c b/src/sentry_options.c index 9fff22277a..33d8c01bd5 100644 --- a/src/sentry_options.c +++ b/src/sentry_options.c @@ -110,9 +110,9 @@ sentry_options_new(void) false; #endif opts->backend = sentry__backend_new(); - opts->transport = sentry__transport_new_default(); + opts->transport = sentry_transport_new_default(); opts->refcount = 1; - opts->shutdown_timeout = SENTRY_DEFAULT_SHUTDOWN_TIMEOUT; + opts->shutdown_timeout = UINT64_MAX; opts->transfer_timeout = SENTRY_DEFAULT_TRANSFER_TIMEOUT; sentry_options_set_sample_rate( opts, sentry__getenv_double("SENTRY_SAMPLE_RATE", 1.0)); @@ -436,19 +436,6 @@ sentry_options_get_proxy(const sentry_options_t *opts) return opts->proxy; } -void -sentry_options_set_http_proxy_n( - sentry_options_t *opts, const char *proxy, size_t proxy_len) -{ - sentry_options_set_proxy_n(opts, proxy, proxy_len); -} - -void -sentry_options_set_http_proxy(sentry_options_t *opts, const char *proxy) -{ - sentry_options_set_proxy(opts, proxy); -} - const char * sentry_options_get_http_proxy(const sentry_options_t *opts) { @@ -782,9 +769,17 @@ sentry_options_set_shutdown_timeout( } uint64_t -sentry_options_get_shutdown_timeout(sentry_options_t *opts) +sentry_options_get_shutdown_timeout(const sentry_options_t *opts) { - return opts->shutdown_timeout; + return sentry__options_has_shutdown_timeout(opts) + ? opts->shutdown_timeout + : SENTRY_DEFAULT_SHUTDOWN_TIMEOUT; +} + +bool +sentry__options_has_shutdown_timeout(const sentry_options_t *opts) +{ + return opts->shutdown_timeout != UINT64_MAX; } void @@ -795,7 +790,7 @@ sentry_options_set_transfer_timeout( } uint64_t -sentry_options_get_transfer_timeout(sentry_options_t *opts) +sentry_options_get_transfer_timeout(const sentry_options_t *opts) { return opts->transfer_timeout; } @@ -815,21 +810,6 @@ sentry_options_add_attachment_n( &opts->attachments, path, path_len, NULL, NULL)); } -void -sentry_options_add_view_hierarchy(sentry_options_t *opts, const char *path) -{ - sentry_value_decref(sentry__attachments_add_path(&opts->attachments, path, - SENTRY_ATTACHMENT_TYPE_VIEW_HIERARCHY, "application/json")); -} - -void -sentry_options_add_view_hierarchy_n( - sentry_options_t *opts, const char *path, size_t path_len) -{ - sentry_value_decref(sentry__attachments_add_path_n(&opts->attachments, path, - path_len, SENTRY_ATTACHMENT_TYPE_VIEW_HIERARCHY, "application/json")); -} - void sentry_options_set_attach_screenshot(sentry_options_t *opts, int val) { @@ -919,24 +899,6 @@ sentry_options_add_attachmentw(sentry_options_t *opts, const wchar_t *path) sentry_options_add_attachmentw_n(opts, path, path_len); } -void -sentry_options_add_view_hierarchyw(sentry_options_t *opts, const wchar_t *path) -{ - size_t path_len = path ? wcslen(path) : 0; - sentry_value_decref( - sentry__attachments_add_wpath_n(&opts->attachments, path, path_len, - SENTRY_ATTACHMENT_TYPE_VIEW_HIERARCHY, "application/json")); -} - -void -sentry_options_add_view_hierarchyw_n( - sentry_options_t *opts, const wchar_t *path, size_t path_len) -{ - sentry_value_decref( - sentry__attachments_add_wpath_n(&opts->attachments, path, path_len, - SENTRY_ATTACHMENT_TYPE_VIEW_HIERARCHY, "application/json")); -} - void sentry_options_set_handler_pathw_n( sentry_options_t *opts, const wchar_t *path, size_t path_len) @@ -999,7 +961,7 @@ sentry_options_set_max_spans(sentry_options_t *opts, size_t max_spans) * transaction. */ size_t -sentry_options_get_max_spans(sentry_options_t *opts) +sentry_options_get_max_spans(const sentry_options_t *opts) { return opts->max_spans; } @@ -1020,7 +982,7 @@ sentry_options_set_traces_sample_rate( * Returns the sample rate for transactions. */ double -sentry_options_get_traces_sample_rate(sentry_options_t *opts) +sentry_options_get_traces_sample_rate(const sentry_options_t *opts) { return opts->traces_sample_rate; } diff --git a/src/sentry_options.h b/src/sentry_options.h index 405f43e77d..1ab095620c 100644 --- a/src/sentry_options.h +++ b/src/sentry_options.h @@ -159,4 +159,9 @@ bool sentry__options_add_integration( bool sentry__options_has_integration( const sentry_options_t *opts, const char *name); +/** + * Returns whether the `shutdown_timeout` option has been set. + */ +bool sentry__options_has_shutdown_timeout(const sentry_options_t *opts); + #endif diff --git a/src/sentry_os.c b/src/sentry_os.c index 47c2ffe835..d5afc49ab0 100644 --- a/src/sentry_os.c +++ b/src/sentry_os.c @@ -1,19 +1,198 @@ #include "sentry_os.h" +#include "sentry_logger.h" #include "sentry_path.h" #include "sentry_slice.h" #include "sentry_string.h" #include "sentry_value.h" #include +#include #if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_WINDOWS) # include "sentry_core.h" -# include "sentry_logger.h" # include "sentry_utils.h" #endif +#if defined(SENTRY_PLATFORM_UNIX) && !defined(SENTRY_PLATFORM_PS) +# include +# include +#endif #ifdef SENTRY_PLATFORM_LINUX +# include +# include # include #endif +#if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) +ssize_t +sentry__process_vm_readv(pid_t pid, const struct iovec *local_iov, + unsigned long local_iov_count, const struct iovec *remote_iov, + unsigned long remote_iov_count, unsigned long flags) +{ +# if defined(SENTRY_PLATFORM_ANDROID) && defined(__ANDROID_API__) \ + && __ANDROID_API__ < 23 + return syscall(__NR_process_vm_readv, pid, local_iov, local_iov_count, + remote_iov, remote_iov_count, flags); +# else + return process_vm_readv( + pid, local_iov, local_iov_count, remote_iov, remote_iov_count, flags); +# endif +} +#endif + +#if (defined(SENTRY_PLATFORM_WINDOWS) && !defined(SENTRY_PLATFORM_XBOX)) \ + || (defined(SENTRY_PLATFORM_UNIX) && !defined(SENTRY_PLATFORM_MACOS) \ + && !defined(SENTRY_PLATFORM_PS)) +static bool +set_os_uname(sentry_value_t os, const char *sysname, const char *release) +{ + char *version = sentry__string_clone(release); + if (!version) { + return false; + } + + char *build = version; + size_t num_dots = 0; + for (; build[0] != '\0'; build++) { + char c = build[0]; + if (c == '.') { + num_dots += 1; + } + if (!(c >= '0' && c <= '9') && (c != '.' || num_dots > 2)) { + break; + } + } + char *build_start = build; + if (build[0] == '-' || build[0] == '.') { + build_start++; + } + + if (build_start[0] != '\0') { + sentry_value_set_by_key( + os, "build", sentry_value_new_string(build_start)); + } + + build[0] = '\0'; + + sentry_value_set_by_key(os, "name", sentry_value_new_string(sysname)); + sentry_value_set_by_key(os, "version", sentry_value_new_string(version)); + sentry_free(version); + return true; +} +#endif + +#if defined(SENTRY_PLATFORM_LINUX) \ + || (defined(SENTRY_PLATFORM_WINDOWS) && !defined(SENTRY_PLATFORM_XBOX)) +# define OS_RELEASE_MAX_LINE_SIZE 256 +# define OS_RELEASE_MAX_KEY_SIZE 64 +# define OS_RELEASE_MAX_VALUE_SIZE 128 + +// Prefer the host over the Steam Runtime or Flatpak container. +static const char *const os_release_paths[] = { + "/run/host/etc/os-release", + "/run/host/usr/lib/os-release", + "/run/host/os-release", + "/etc/os-release", + "/usr/lib/os-release", +}; + +static int +parse_os_release_line(const char *line, char *key, char *value) +{ + const char *equals = strchr(line, '='); + if (equals == NULL) + return 1; + + size_t key_length + = MIN((size_t)(equals - line), OS_RELEASE_MAX_KEY_SIZE - 1); + strncpy(key, line, key_length); + key[key_length] = '\0'; + + sentry_slice_t value_slice + = { .ptr = equals + 1, .len = strlen(equals + 1) }; + + // some values are wrapped in double quotes + if (value_slice.len >= 2 && value_slice.ptr[0] == '\"' + && value_slice.ptr[value_slice.len - 1] == '\"') { + value_slice.ptr++; + value_slice.len -= 2; + } + + sentry__slice_to_buffer(value_slice, value, OS_RELEASE_MAX_VALUE_SIZE); + + return 0; +} + +static void +parse_line_into_object(const char *line, sentry_value_t os_dist) +{ + char value[OS_RELEASE_MAX_VALUE_SIZE]; + char key[OS_RELEASE_MAX_KEY_SIZE]; + + if (parse_os_release_line(line, key, value) == 0) { + if (strcmp(key, "ID") == 0) { + sentry_value_set_by_key( + os_dist, "name", sentry_value_new_string(value)); + } + + if (strcmp(key, "VERSION_ID") == 0) { + sentry_value_set_by_key( + os_dist, "version", sentry_value_new_string(value)); + } + + if (strcmp(key, "PRETTY_NAME") == 0) { + sentry_value_set_by_key( + os_dist, "pretty_name", sentry_value_new_string(value)); + } + + if (strcmp(key, "NAME") == 0) { + sentry_value_set_by_key( + os_dist, "display_name", sentry_value_new_string(value)); + } + + if (strcmp(key, "BUILD_ID") == 0) { + sentry_value_set_by_key( + os_dist, "build", sentry_value_new_string(value)); + } + } +} + +# ifndef SENTRY_UNITTEST +static +# endif + void + set_os_distribution( + sentry_value_t os, sentry_value_t os_dist, const char *release) +{ + sentry_value_t id = sentry_value_get_by_key(os_dist, "name"); + const char *id_str = sentry_value_as_string(id); + + // SteamOS and Bazzite are reported as the OS itself, not as a distribution. + if (strcmp(id_str, "steamos") == 0 || strcmp(id_str, "bazzite") == 0) { + sentry_value_t name = sentry_value_get_by_key(os_dist, "display_name"); + if (sentry_value_is_null(name)) { + name = id; + } + sentry_value_t version = sentry_value_get_by_key(os_dist, "version"); + if (!sentry_value_is_null(version)) { + sentry_value_incref(version); + sentry_value_set_by_key(os, "version", version); + } + sentry_value_set_by_key(os, "name", sentry_value_incref(name)); + sentry_value_set_by_key( + os, "build", sentry_value_get_by_key_owned(os_dist, "build")); + sentry_value_set_by_key( + os, "kernel_version", sentry_value_new_string(release)); + return; + } + + sentry_value_set_by_key(os, "distribution_name", + sentry_value_get_by_key_owned(os_dist, "name")); + sentry_value_set_by_key(os, "distribution_version", + sentry_value_get_by_key_owned(os_dist, "version")); + sentry_value_set_by_key(os, "distribution_pretty_name", + sentry_value_get_by_key_owned(os_dist, "pretty_name")); +} +#endif + #ifdef SENTRY_PLATFORM_WINDOWS # include @@ -379,11 +558,96 @@ sentry__get_wine_context(void) return context; } +static sentry_value_t +get_wine_os_release(const char *path) +{ + sentry_path_t *wine_path = make_wine_path(path, ""); + char *buf = read_wine_file(wine_path); + sentry__path_free(wine_path); + if (!buf) { + return sentry_value_new_null(); + } + + sentry_value_t os_dist = sentry_value_new_object(); + for (char *line = buf; line && *line;) { + char *next = strchr(line, '\n'); + if (next) { + *next++ = '\0'; + } + size_t len = strlen(line); + if (len > 0 && line[len - 1] == '\r') { + line[len - 1] = '\0'; + } + parse_line_into_object(line, os_dist); + line = next; + } + sentry_free(buf); + return os_dist; +} + +typedef void(CDECL *sentry__wine_get_host_version_t)( + const char **sysname, const char **release); + +/** + * Under Wine, reports the host OS instead of the Windows version that Wine + * emulates, in the same shape as the native Linux and macOS OS contexts. + */ +static sentry_value_t +get_wine_host_os_context(void) +{ + const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); + if (!ntdll) { + return sentry_value_new_null(); + } + + const sentry__wine_get_host_version_t wine_get_host_version + = (sentry__wine_get_host_version_t)GetProcAddress( + ntdll, "wine_get_host_version"); + if (!wine_get_host_version) { + return sentry_value_new_null(); + } + + const char *sysname = NULL; + const char *release = NULL; + wine_get_host_version(&sysname, &release); + if (sentry__string_empty(sysname) || sentry__string_empty(release)) { + return sentry_value_new_null(); + } + + sentry_value_t os = sentry_value_new_object(); + if (sentry_value_is_null(os) || !set_os_uname(os, sysname, release)) { + sentry_value_decref(os); + return sentry_value_new_null(); + } + + if (strcmp(sysname, "Linux") == 0) { + for (size_t i = 0; + i < sizeof(os_release_paths) / sizeof(os_release_paths[0]); i++) { + sentry_value_t os_dist = get_wine_os_release(os_release_paths[i]); + if (!sentry_value_is_null(os_dist)) { + set_os_distribution(os, os_dist, release); + sentry_value_decref(os_dist); + break; + } + } + } + + sentry_value_freeze(os); + return os; +} + # endif // !defined(SENTRY_PLATFORM_XBOX) sentry_value_t sentry__get_os_context(void) { +# if !defined(SENTRY_PLATFORM_XBOX) + sentry_value_t wine_os = get_wine_host_os_context(); + if (!sentry_value_is_null(wine_os)) { + return wine_os; + } +# endif + const sentry_value_t os = sentry_value_new_object(); if (sentry_value_is_null(os)) { return os; @@ -699,60 +963,6 @@ sentry__get_os_context(void) # include # if defined(SENTRY_PLATFORM_LINUX) -# define OS_RELEASE_MAX_LINE_SIZE 256 -# define OS_RELEASE_MAX_KEY_SIZE 64 -# define OS_RELEASE_MAX_VALUE_SIZE 128 - -static int -parse_os_release_line(const char *line, char *key, char *value) -{ - const char *equals = strchr(line, '='); - if (equals == NULL) - return 1; - - unsigned long key_length = MIN(equals - line, OS_RELEASE_MAX_KEY_SIZE - 1); - strncpy(key, line, key_length); - key[key_length] = '\0'; - - sentry_slice_t value_slice - = { .ptr = equals + 1, .len = strlen(equals + 1) }; - - // some values are wrapped in double quotes - if (value_slice.len >= 2 && value_slice.ptr[0] == '\"' - && value_slice.ptr[value_slice.len - 1] == '\"') { - value_slice.ptr++; - value_slice.len -= 2; - } - - sentry__slice_to_buffer(value_slice, value, OS_RELEASE_MAX_VALUE_SIZE); - - return 0; -} - -static void -parse_line_into_object(const char *line, sentry_value_t os_dist) -{ - char value[OS_RELEASE_MAX_VALUE_SIZE]; - char key[OS_RELEASE_MAX_KEY_SIZE]; - - if (parse_os_release_line(line, key, value) == 0) { - if (strcmp(key, "ID") == 0) { - sentry_value_set_by_key( - os_dist, "name", sentry_value_new_string(value)); - } - - if (strcmp(key, "VERSION_ID") == 0) { - sentry_value_set_by_key( - os_dist, "version", sentry_value_new_string(value)); - } - - if (strcmp(key, "PRETTY_NAME") == 0) { - sentry_value_set_by_key( - os_dist, "pretty_name", sentry_value_new_string(value)); - } - } -} - # ifndef SENTRY_UNITTEST static # endif @@ -826,60 +1036,20 @@ sentry__get_os_context(void) goto fail; } - char *build = uts.release; - size_t num_dots = 0; - for (; build[0] != '\0'; build++) { - char c = build[0]; - if (c == '.') { - num_dots += 1; - } - if (!(c >= '0' && c <= '9') && (c != '.' || num_dots > 2)) { - break; - } - } - char *build_start = build; - if (build[0] == '-' || build[0] == '.') { - build_start++; - } - - if (build_start[0] != '\0') { - sentry_value_set_by_key( - os, "build", sentry_value_new_string(build_start)); + if (!set_os_uname(os, uts.sysname, uts.release)) { + goto fail; } - build[0] = '\0'; - - sentry_value_set_by_key(os, "name", sentry_value_new_string(uts.sysname)); - sentry_value_set_by_key( - os, "version", sentry_value_new_string(uts.release)); - # if defined(SENTRY_PLATFORM_LINUX) - /** - * The file /etc/os-release takes precedence over /usr/lib/os-release. - * Applications should check for the former, and exclusively use its data if - * it exists, and only fall back to /usr/lib/os-release if it is missing. - * Applications should not read data from both files at the same time. - * - * From: - * https://www.freedesktop.org/software/systemd/man/latest/os-release.html#Description - */ - sentry_value_t os_dist = get_linux_os_release("/etc/os-release"); - if (sentry_value_is_null(os_dist)) { - os_dist = get_linux_os_release("/usr/lib/os-release"); - if (sentry_value_is_null(os_dist)) { - return os; + for (size_t i = 0; + i < sizeof(os_release_paths) / sizeof(os_release_paths[0]); i++) { + sentry_value_t os_dist = get_linux_os_release(os_release_paths[i]); + if (!sentry_value_is_null(os_dist)) { + set_os_distribution(os, os_dist, uts.release); + sentry_value_decref(os_dist); + break; } } - sentry_value_set_by_key( - os, "distribution_name", sentry_value_get_by_key(os_dist, "name")); - sentry_value_set_by_key(os, "distribution_version", - sentry_value_get_by_key(os_dist, "version")); - sentry_value_set_by_key(os, "distribution_pretty_name", - sentry_value_get_by_key(os_dist, "pretty_name")); - sentry_value_incref(sentry_value_get_by_key(os_dist, "name")); - sentry_value_incref(sentry_value_get_by_key(os_dist, "version")); - sentry_value_incref(sentry_value_get_by_key(os_dist, "pretty_name")); - sentry_value_decref(os_dist); # endif // defined(SENTRY_PLATFORM_LINUX) return os; @@ -1012,6 +1182,17 @@ sentry__build_registers(const sentry_ucontext_t *uctx) sentry_value_set_by_key(registers, "cpsr", sentry__value_new_addr(uctx->user_context->uc_mcontext.arm_cpsr)); +# elif defined(__riscv) && __riscv_xlen == 64 + + static const char *names[] + = { "pc", "ra", "sp", "gp", "tp", "t0", "t1", "t2", "s0", "s1", "a0", + "a1", "a2", "a3", "a4", "a5", "a6", "a7", "s2", "s3", "s4", "s5", + "s6", "s7", "s8", "s9", "s10", "s11", "t3", "t4", "t5", "t6" }; + for (size_t i = 0; i < sizeof(names) / sizeof(names[0]); i++) { + sentry_value_set_by_key(registers, names[i], + sentry__value_new_addr(uctx->user_context->uc_mcontext.__gregs[i])); + } + # endif # undef SET_REG @@ -1235,3 +1416,76 @@ sentry__build_registers(const sentry_ucontext_t *uctx) return registers; } + +#if defined(SENTRY_PLATFORM_UNIX) +/** + * Get signal name from signal number (Unix platforms only) + */ +const char * +sentry__signal_to_string(int signum) +{ + switch (signum) { + case SIGABRT: + return "SIGABRT"; + case SIGBUS: + return "SIGBUS"; + case SIGFPE: + return "SIGFPE"; + case SIGILL: + return "SIGILL"; + case SIGSEGV: + return "SIGSEGV"; + case SIGSYS: + return "SIGSYS"; + case SIGTRAP: + return "SIGTRAP"; + default: + return "UNKNOWN"; + } +} +#endif + +#if defined(SENTRY_PLATFORM_UNIX) && !defined(SENTRY_PLATFORM_PS) +int +sentry__setup_sigaltstack(stack_t *out_stack, size_t size, const char *context) +{ + memset(out_stack, 0, sizeof(*out_stack)); + + stack_t old_sig_stack; + int ret = sigaltstack(NULL, &old_sig_stack); + if (ret == 0 && old_sig_stack.ss_flags == SS_DISABLE) { + SENTRY_DEBUGF("installing %s sigaltstack (size: %zu)", context, size); + out_stack->ss_sp = sentry_malloc(size); + if (!out_stack->ss_sp) { + SENTRY_WARN("failed to allocate signal stack"); + return -1; + } + out_stack->ss_size = size; + out_stack->ss_flags = 0; + if (sigaltstack(out_stack, 0) < 0) { + SENTRY_WARNF("failed to set signal stack: %s", strerror(errno)); + sentry_free(out_stack->ss_sp); + out_stack->ss_sp = NULL; + return -1; + } + } else if (ret == 0) { + SENTRY_DEBUGF("using existing signal stack (size: %d, flags: %d)", + old_sig_stack.ss_size, old_sig_stack.ss_flags); + } else if (ret == -1) { + SENTRY_WARNF("failed to query signal stack: %s", strerror(errno)); + return -1; + } + return 0; +} + +void +sentry__teardown_sigaltstack(stack_t *sig_stack) +{ + if (sig_stack->ss_sp) { + sig_stack->ss_flags = SS_DISABLE; + sigaltstack(sig_stack, 0); + sentry_free(sig_stack->ss_sp); + sig_stack->ss_sp = NULL; + } +} +#endif diff --git a/src/sentry_os.h b/src/sentry_os.h index 3dd68fcedc..aa5fe55fe0 100644 --- a/src/sentry_os.h +++ b/src/sentry_os.h @@ -3,6 +3,15 @@ #include "sentry_boot.h" +#if defined(SENTRY_PLATFORM_UNIX) && !defined(SENTRY_PLATFORM_PS) +# include +#endif + +#if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) +# include +# include +#endif + #ifdef SENTRY_PLATFORM_LINUX # include @@ -17,6 +26,8 @@ sentry__ucontext_get_ip(const ucontext_t *uctx) return (uintptr_t)uctx->uc_mcontext.arm_pc; # elif defined(__aarch64__) return (uintptr_t)uctx->uc_mcontext.pc; +# elif defined(__riscv) && __riscv_xlen == 64 + return (uintptr_t)uctx->uc_mcontext.__gregs[REG_PC]; # else (void)uctx; return 0; @@ -34,6 +45,8 @@ sentry__ucontext_get_sp(const ucontext_t *uctx) return (uintptr_t)uctx->uc_mcontext.arm_sp; # elif defined(__aarch64__) return (uintptr_t)uctx->uc_mcontext.sp; +# elif defined(__riscv) && __riscv_xlen == 64 + return (uintptr_t)uctx->uc_mcontext.__gregs[REG_SP]; # else (void)uctx; return 0; @@ -68,8 +81,35 @@ void sentry__win32_restore_sigabrt_handler(void); #endif +#if defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) +ssize_t sentry__process_vm_readv(pid_t pid, const struct iovec *local_iov, + unsigned long local_iov_count, const struct iovec *remote_iov, + unsigned long remote_iov_count, unsigned long flags); +#endif + sentry_value_t sentry__get_os_context(void); sentry_value_t sentry__build_registers(const sentry_ucontext_t *uctx); +#if defined(SENTRY_PLATFORM_UNIX) +const char *sentry__signal_to_string(int signum); +#endif + +#if defined(SENTRY_PLATFORM_UNIX) && !defined(SENTRY_PLATFORM_PS) +/** + * Sets up an alternate signal stack for the current thread if one isn't + * already configured. The allocated stack is stored in `out_stack` so it + * can be freed later via `sentry__teardown_sigaltstack()`. + * Returns 0 on success or -1 on failure. + */ +int sentry__setup_sigaltstack( + stack_t *out_stack, size_t size, const char *context); + +/** + * Tears down a signal stack previously set up via + * `sentry__setup_sigaltstack()`. + */ +void sentry__teardown_sigaltstack(stack_t *sig_stack); +#endif + #endif diff --git a/src/sentry_path.h b/src/sentry_path.h index 2dd2cf2d25..d6a638b644 100644 --- a/src/sentry_path.h +++ b/src/sentry_path.h @@ -4,6 +4,7 @@ #include "sentry_boot.h" #include "sentry_string.h" +#include #include struct sentry_path_s { @@ -220,6 +221,12 @@ int sentry__path_touch(const sentry_path_t *path); */ size_t sentry__path_get_size(const sentry_path_t *path); +/** + * Opens `path` with `mode` and seeks to `offset`, or returns NULL on failure. + */ +FILE *sentry__path_open( + const sentry_path_t *path, const char *mode, size_t offset); + /** * This will return the last modification time of the file at `path`, or 0 on * failure. diff --git a/src/sentry_scope.c b/src/sentry_scope.c index 3f568fcb88..8b55724743 100644 --- a/src/sentry_scope.c +++ b/src/sentry_scope.c @@ -16,6 +16,7 @@ #include "sentry_uuid.h" #include "sentry_value.h" +#include #include #ifdef SENTRY_BACKEND_CRASHPAD @@ -28,6 +29,8 @@ # define SENTRY_BACKEND "native" #endif +static const sentry_level_t SENTRY_LEVEL_NONE = SENTRY_LEVEL_TRACE - 1; + struct sentry_scope_data_s { sentry_rwlock_t rwlock; @@ -61,15 +64,32 @@ struct sentry_scope_data_s { bool trace_managed; }; -static bool g_scope_initialized = false; -static sentry_scope_t g_scope = { 0 }; +typedef struct scope_access_s { + sentry_scope_data_t *data; + size_t depth; + bool write; + bool pooled; + struct scope_access_s *next; +} scope_access_t; + +static long g_scope_initialized = 0; static sentry_scope_data_t g_scope_data = { 0 }; -static bool g_scope_idle_initialized = false; -static sentry_cond_t g_scope_idle; +static sentry_scope_t g_scope = { .refcount = -1, .data = &g_scope_data }; +static sentry_scope_t *g_isolation_scope = NULL; +// keep common scope access off the heap during capture: +// 1. global scope +// 2. isolation scope +// 3. local or user scope +// 4. a nested user scope, e.g. a clone batched inside its source's batch +// deeper nesting falls back to the heap +#define SCOPE_ACCESS_POOL_SIZE 4 #ifdef _MSC_VER -static __declspec(thread) size_t g_scope_depth; +static __declspec(thread) scope_access_t *g_scope_access; +static __declspec(thread) scope_access_t + g_scope_access_pool[SCOPE_ACCESS_POOL_SIZE]; #else -static __thread size_t g_scope_depth; +static __thread scope_access_t *g_scope_access; +static __thread scope_access_t g_scope_access_pool[SCOPE_ACCESS_POOL_SIZE]; #endif #ifdef SENTRY__MUTEX_INIT_DYN SENTRY__MUTEX_INIT_DYN(g_lock) @@ -77,26 +97,83 @@ SENTRY__MUTEX_INIT_DYN(g_lock) static sentry_mutex_t g_lock = SENTRY__MUTEX_INIT; #endif +static scope_access_t * +scope_data_get_access(const sentry_scope_data_t *data) +{ +#ifndef SENTRY_PLATFORM_WINDOWS + // avoid dynamic TLS access during signal handling + if (!sentry__block_for_signal_handler()) { + return NULL; + } +#endif + for (scope_access_t *access = g_scope_access; access; + access = access->next) { + if (access->data == data) { + return access; + } + } + return NULL; +} + +static bool +scope_data_read_lock(const sentry_scope_data_t *data) +{ + if (scope_data_get_access(data)) { + return false; + } + sentry__rwlock_read_lock((sentry_rwlock_t *)&data->rwlock); + return true; +} + +static void +scope_data_read_unlock(const sentry_scope_data_t *data, bool locked) +{ + if (locked) { + sentry__rwlock_read_unlock((sentry_rwlock_t *)&data->rwlock); + } +} + +static bool +scope_data_write_lock(sentry_scope_data_t *data) +{ + scope_access_t *access = scope_data_get_access(data); + assert(!access || access->write); + if (access && access->write) { + return false; + } + sentry__rwlock_write_lock(&data->rwlock); + return true; +} + +static void +scope_data_write_unlock(sentry_scope_data_t *data, bool locked) +{ + if (locked) { + sentry__rwlock_write_unlock(&data->rwlock); + } +} + #define SENTRY_SCOPE_READ_LOCK(Data) \ for (const sentry_scope_data_t *_locked_data = (Data); _locked_data; \ - sentry__rwlock_read_unlock((sentry_rwlock_t *)&_locked_data->rwlock), \ - _locked_data = NULL) \ - for (bool _locked_once \ - = (sentry__rwlock_read_lock( \ - (sentry_rwlock_t *)&_locked_data->rwlock), \ - true); \ - _locked_once; _locked_once = false) + _locked_data = NULL) \ + for (bool _lock_acquired = scope_data_read_lock(_locked_data), \ + _locked_once = true; \ + _locked_once; \ + scope_data_read_unlock(_locked_data, _lock_acquired), \ + _locked_once = false) #define SENTRY_SCOPE_WRITE_LOCK(Data) \ for (sentry_scope_data_t *_locked_data = (Data); _locked_data; \ - sentry__rwlock_write_unlock(&_locked_data->rwlock), \ - _locked_data = NULL) \ - for (bool _locked_once \ - = (sentry__rwlock_write_lock(&_locked_data->rwlock), true); \ - _locked_once; _locked_once = false) + _locked_data = NULL) \ + for (bool _lock_acquired = scope_data_write_lock(_locked_data), \ + _locked_once = true; \ + _locked_once; \ + scope_data_write_unlock(_locked_data, _lock_acquired), \ + _locked_once = false) static size_t begin_scope_notify(sentry_scope_t *scope); static void end_scope_notify(sentry_scope_t *scope); +static sentry_options_t *ref_options(const sentry_scope_t *scope); // notify observers registered before this notification started #define SENTRY_SCOPE_NOTIFY(scope, callback, ...) \ @@ -153,7 +230,7 @@ get_client_sdk(void) } static void -init_scope_data(sentry_scope_data_t *data) +init_scope_data(sentry_scope_data_t *data, size_t max_breadcrumbs) { data->release = sentry_value_new_null(); data->environment = sentry_value_new_null(); @@ -165,9 +242,9 @@ init_scope_data(sentry_scope_data_t *data) data->attributes = sentry_value_new_object(); data->contexts = sentry_value_new_object(); data->propagation_context = sentry_value_new_object(); - data->breadcrumbs = sentry__ringbuffer_new(SENTRY_BREADCRUMBS_MAX); + data->breadcrumbs = sentry__ringbuffer_new(max_breadcrumbs); data->dynamic_sampling_context = sentry_value_new_object(); - data->level = SENTRY_LEVEL_ERROR; + data->level = SENTRY_LEVEL_NONE; data->last_event_id = sentry_uuid_nil(); data->client_sdk = sentry_value_new_null(); data->attachments = sentry_value_new_list(); @@ -203,7 +280,7 @@ new_scope_data(void) sentry_scope_data_t *data = SENTRY_MAKE(sentry_scope_data_t); if (data) { sentry__rwlock_init(&data->rwlock); - init_scope_data(data); + init_scope_data(data, SENTRY_BREADCRUMBS_MAX); } return data; } @@ -219,29 +296,6 @@ free_scope_data(sentry_scope_data_t *data) sentry_free(data); } -static void -cleanup_global_data(sentry_scope_data_t *data) -{ - cleanup_scope_data(data); - sentry__rwlock_free(&data->rwlock); -} - -static void -init_global_data(sentry_scope_data_t *data) -{ - sentry__value_replace(&data->user, sentry_value_new_object()); - sentry_value_set_by_key(data->contexts, "os", sentry__get_os_context()); -#if defined(SENTRY_PLATFORM_WINDOWS) && !defined(SENTRY_PLATFORM_XBOX) - sentry_value_t wine_context = sentry__get_wine_context(); - if (!sentry_value_is_null(wine_context)) { - sentry_value_set_by_key(data->contexts, "wine", wine_context); - } else { - sentry_value_decref(wine_context); - } -#endif - sentry__value_replace(&data->client_sdk, get_client_sdk()); -} - static void clear_scope_data(sentry_scope_data_t *data) { @@ -254,8 +308,10 @@ clear_scope_data(sentry_scope_data_t *data) sentry_value_t dynamic_sampling_context = sentry_value_incref(data->dynamic_sampling_context); + size_t max_breadcrumbs = data->breadcrumbs ? data->breadcrumbs->max_size + : SENTRY_BREADCRUMBS_MAX; cleanup_scope_data(data); - init_scope_data(data); + init_scope_data(data, max_breadcrumbs); sentry_value_decref(data->propagation_context); sentry_value_decref(data->dynamic_sampling_context); @@ -344,18 +400,22 @@ sentry__scope_update_dsc(sentry_scope_t *scope, const sentry_options_t *options) dsc, "sample_rate", sentry_value_new_double(1.0)); } + sentry_value_t parent_trace = scope->parent + ? sentry__scope_load_trace_context(scope->parent) + : sentry_value_new_null(); SENTRY_SCOPE_WRITE_LOCK (data) { - sentry_value_t sample_rand = sentry_value_get_by_key( - sentry_value_get_by_key(data->propagation_context, "trace"), - "sample_rand"); - sentry_value_set_by_key( - dsc, "sample_rand", sentry_value_incref(sample_rand)); - sentry_value_set_by_key( - dsc, "release", sentry_value_incref(data->release)); - sentry_value_set_by_key( - dsc, "environment", sentry_value_incref(data->environment)); + sentry_value_t trace + = sentry_value_get_by_key(data->propagation_context, "trace"); + sentry_value_t sample_rand + = sentry_value_get_by_key_owned(trace, "sample_rand"); + if (sentry_value_is_null(trace) && scope->parent) { + sample_rand + = sentry_value_get_by_key_owned(parent_trace, "sample_rand"); + } + sentry_value_set_by_key(dsc, "sample_rand", sample_rand); sentry__value_replace(&data->dynamic_sampling_context, dsc); } + sentry_value_decref(parent_trace); } static bool @@ -380,31 +440,166 @@ init_scope(sentry_scope_t *scope, sentry_scope_data_t *data) scope->pending_flush = false; scope->flush_func = NULL; scope->state = NULL; + scope->parent = NULL; sentry__mutex_init(&scope->observers_lock); scope->one_shot = false; return true; } -static sentry_scope_t * -get_scope(void) +static const sentry_scope_t * +get_global_scope(void) { - // cleanup clears g_scope_initialized before existing references finish - if (g_scope.data) { + if (sentry__atomic_fetch(&g_scope_initialized)) { return &g_scope; } +#ifndef SENTRY_PLATFORM_WINDOWS + if (!sentry__block_for_signal_handler()) { + return NULL; + } +#endif + SENTRY__MUTEX_INIT_DYN_ONCE(g_lock); + sentry__mutex_lock(&g_lock); + if (!sentry__atomic_fetch(&g_scope_initialized)) { + sentry_scope_data_t *data = &g_scope_data; + sentry__rwlock_init(&data->rwlock); + init_scope_data(data, 0); + data->level = SENTRY_LEVEL_ERROR; + data->trace_managed = false; + sentry_value_t contexts = data->contexts; + sentry_value_t sdk = get_client_sdk(); + if (sentry_value_is_null(contexts) || sentry_value_is_null(sdk)) { + cleanup_scope_data(data); + sentry__rwlock_free(&data->rwlock); + sentry_value_decref(sdk); + sentry__mutex_unlock(&g_lock); + return NULL; + } + sentry_value_set_by_key(contexts, "os", sentry__get_os_context()); +#if defined(SENTRY_PLATFORM_WINDOWS) && !defined(SENTRY_PLATFORM_XBOX) + sentry_value_t wine_context = sentry__get_wine_context(); + if (!sentry_value_is_null(wine_context)) { + sentry_value_set_by_key(contexts, "wine", wine_context); + } else { + sentry_value_decref(wine_context); + } +#endif + sentry_value_freeze(contexts); + sentry_value_freeze(sdk); + sentry__value_replace(&data->client_sdk, sdk); + sentry__mutex_init(&g_scope.observers_lock); + sentry__atomic_store(&g_scope_initialized, 1); + } + sentry__mutex_unlock(&g_lock); + return &g_scope; +} - memset(&g_scope, 0, sizeof(sentry_scope_t)); - memset(&g_scope_data, 0, sizeof(sentry_scope_data_t)); - sentry__rwlock_init(&g_scope_data.rwlock); - init_scope_data(&g_scope_data); - if (!init_scope(&g_scope, &g_scope_data)) { - return &g_scope; +static bool +init_global_scope(const sentry_options_t *options) +{ + const sentry_scope_t *scope = get_global_scope(); + if (!scope) { + return false; + } + sentry_value_t sdk = get_client_sdk(); + if (sentry_value_is_null(sdk)) { + return false; + } + if (options->sdk_name) { + sentry_value_set_by_key( + sdk, "name", sentry_value_new_string(options->sdk_name)); + } + sentry_value_t integrations = sentry_value_get_by_key(sdk, "integrations"); + for (size_t i = 0; i < options->num_integrations; i++) { + const char *name = options->integrations[i]->name; + if (!name) { + continue; + } + if (sentry_value_is_null(integrations)) { + integrations = sentry_value_new_list(); + sentry_value_set_by_key(sdk, "integrations", integrations); + } + sentry_value_append(integrations, sentry_value_new_string(name)); + } + sentry_value_freeze(sdk); + sentry_value_t attachments + = sentry__attachments_clone(options->attachments); + sentry_value_freeze(attachments); + SENTRY_SCOPE_WRITE_LOCK (scope->data) { + sentry__value_replace(&scope->data->client_sdk, sdk); + sentry__value_replace(&scope->data->attachments, attachments); + sentry__value_replace( + &scope->data->release, sentry_value_new_string(options->release)); + sentry__value_replace(&scope->data->environment, + sentry_value_new_string(options->environment)); + } + return true; +} + +static void +reset_global_scope(void) +{ + if (!sentry__atomic_fetch(&g_scope_initialized)) { + return; + } + sentry_value_t sdk = get_client_sdk(); + sentry_value_freeze(sdk); + sentry_scope_data_t *data = &g_scope_data; + SENTRY_SCOPE_WRITE_LOCK (data) { + sentry__value_replace(&data->client_sdk, sdk); + sentry__value_replace(&data->attachments, sentry_value_new_list()); + sentry__value_replace(&data->release, sentry_value_new_null()); + sentry__value_replace(&data->environment, sentry_value_new_null()); } - init_global_data(g_scope.data); +} - g_scope_initialized = true; +static sentry_scope_t * +alloc_scope(void) +{ + sentry_scope_t *scope = SENTRY_MAKE(sentry_scope_t); + if (!scope) { + return NULL; + } - return &g_scope; + if (!init_scope(scope, NULL)) { + sentry_free(scope); + return NULL; + } + return scope; +} + +static sentry_scope_t * +new_isolation_scope(void) +{ + const sentry_scope_t *global = get_global_scope(); + if (!global) { + return NULL; + } + sentry_scope_t *scope = alloc_scope(); + if (scope) { + scope->parent = sentry__scope_incref(global); + } + return scope; +} + +bool +sentry__scope_init(const sentry_options_t *options) +{ + if (!init_global_scope(options)) { + return false; + } + sentry_scope_t *scope = new_isolation_scope(); + if (!scope) { + reset_global_scope(); + return false; + } + + SENTRY__MUTEX_INIT_DYN_ONCE(g_lock); + sentry__mutex_lock(&g_lock); + sentry_scope_t *old_scope = g_isolation_scope; + g_isolation_scope = scope; + sentry__mutex_unlock(&g_lock); + sentry__scope_decref(old_scope); + return true; } static void @@ -427,33 +622,22 @@ cleanup_scope(sentry_scope_t *scope) scope->data = NULL; cleanup_observers(scope); sentry__mutex_free(&scope->observers_lock); + sentry__scope_decref((sentry_scope_t *)scope->parent); } sentry_scope_t * -sentry__scope_incref(sentry_scope_t *scope) +sentry__scope_incref(const sentry_scope_t *scope) { - if (scope) { - sentry__atomic_fetch_and_add(&scope->refcount, 1); + if (scope && sentry__atomic_fetch((long *)&scope->refcount) >= 0) { + sentry__atomic_fetch_and_add((long *)&scope->refcount, 1); } - return scope; + return (sentry_scope_t *)scope; } void sentry__scope_decref(sentry_scope_t *scope) { - if (!scope) { - return; - } - - if (scope == &g_scope) { - SENTRY__MUTEX_INIT_DYN_ONCE(g_lock); - sentry__mutex_lock(&g_lock); - long refcount = sentry__atomic_fetch_and_add(&scope->refcount, -1); - assert(refcount > 1); - if (refcount == 2 && g_scope_idle_initialized) { - sentry__cond_wake_all(&g_scope_idle); - } - sentry__mutex_unlock(&g_lock); + if (!scope || sentry__atomic_fetch(&scope->refcount) < 0) { return; } @@ -472,69 +656,35 @@ sentry__scope_cleanup(void) sentry__options_unlock(); return; } + reset_global_scope(); SENTRY__MUTEX_INIT_DYN_ONCE(g_lock); sentry__mutex_lock(&g_lock); sentry__options_unlock(); - if (!g_scope_idle_initialized) { - sentry__cond_init(&g_scope_idle); - g_scope_idle_initialized = true; - } - if (g_scope_initialized) { - g_scope_initialized = false; - while (sentry__atomic_fetch(&g_scope.refcount) > 1) { - sentry__cond_wait(&g_scope_idle, &g_lock); - } - cleanup_global_data(g_scope.data); - g_scope.data = NULL; - cleanup_observers(&g_scope); - sentry__mutex_free(&g_scope.observers_lock); - } - sentry__cond_wake_all(&g_scope_idle); + sentry_scope_t *scope = g_isolation_scope; + g_isolation_scope = NULL; sentry__mutex_unlock(&g_lock); + sentry__scope_decref(scope); } sentry_scope_t * -sentry__scope_getref(void) +sentry_scope_acquire(void) { #ifndef SENTRY_PLATFORM_WINDOWS - // avoid dynamic TLS access in the signal handler + // avoid dynamic mutex initialization in the signal handler if (!sentry__block_for_signal_handler()) { - return sentry__scope_incref(get_scope()); + return sentry__scope_incref(g_isolation_scope); } #endif SENTRY__MUTEX_INIT_DYN_ONCE(g_lock); sentry__mutex_lock(&g_lock); - if (!g_scope_idle_initialized) { - sentry__cond_init(&g_scope_idle); - g_scope_idle_initialized = true; - } - // let existing callers finish reentrant scope access during cleanup - while (!g_scope_initialized && g_scope.data && !g_scope_depth) { - sentry__cond_wait(&g_scope_idle, &g_lock); + if (!g_isolation_scope) { + g_isolation_scope = new_isolation_scope(); } - sentry_scope_t *scope = sentry__scope_incref(get_scope()); - g_scope_depth++; + sentry_scope_t *scope = sentry__scope_incref(g_isolation_scope); sentry__mutex_unlock(&g_lock); return scope; } -void -sentry__scope_finish(sentry_scope_t *scope) -{ - if (!scope) { - return; - } - - if (scope == &g_scope -#ifndef SENTRY_PLATFORM_WINDOWS - && sentry__block_for_signal_handler() -#endif - ) { - g_scope_depth--; - } - sentry__scope_decref(scope); -} - static void flush_scope(sentry_scope_t *scope) { @@ -543,7 +693,9 @@ flush_scope(sentry_scope_t *scope) } sentry__mutex_lock(&scope->observers_lock); - if (scope->pending_flush && !scope->is_notifying) { + scope_access_t *access = scope_data_get_access(scope->data); + if (scope->pending_flush && !scope->is_notifying + && (!access || !access->write)) { scope->pending_flush = false; if (scope->flush_func) { scope->flush_func(scope); @@ -552,13 +704,6 @@ flush_scope(sentry_scope_t *scope) sentry__mutex_unlock(&scope->observers_lock); } -void -sentry__scope_finish_mut(sentry_scope_t *scope) -{ - flush_scope(scope); - sentry__scope_finish(scope); -} - void sentry__scope_set_flush_func( sentry_scope_t *scope, void (*func)(sentry_scope_t *scope)) @@ -593,6 +738,14 @@ sentry__scope_observer_new(void) bool sentry__scope_add_observer( sentry_scope_t *scope, sentry_scope_observer_t *observer) +{ + return sentry__scope_add_observer_with_init(scope, observer, NULL); +} + +bool +sentry__scope_add_observer_with_init(sentry_scope_t *scope, + sentry_scope_observer_t *observer, + bool (*init)(void *data, const sentry_scope_t *scope)) { if (!observer) { return false; @@ -615,6 +768,11 @@ sentry__scope_add_observer( new_array[scope->num_observers] = observer; scope->observers = new_array; scope->num_observers = new_count; + if (init && !init(observer->data, scope)) { + sentry__scope_remove_observer(scope, observer); + sentry__mutex_unlock(&scope->observers_lock); + return false; + } sentry__mutex_unlock(&scope->observers_lock); return true; } @@ -703,24 +861,176 @@ end_scope_notify(sentry_scope_t *scope) sentry_scope_t * sentry_scope_new(void) { - sentry_scope_t *scope = SENTRY_MAKE(sentry_scope_t); + sentry_scope_t *scope = alloc_scope(); if (!scope) { return NULL; } - - if (!init_scope(scope, NULL)) { - sentry_free(scope); + scope->parent = sentry_scope_acquire(); + if (!scope->parent) { + sentry_scope_free(scope); return NULL; } return scope; } +static int +scope_begin(const sentry_scope_t *scope, bool write) +{ + if (!scope) { + return 1; + } +#ifndef SENTRY_PLATFORM_WINDOWS + if (!sentry__block_for_signal_handler()) { + return 0; + } +#endif + + sentry_scope_data_t *data = scope->data; + scope_access_t *access = scope_data_get_access(data); + if (access) { + if (write && !access->write) { + return 1; + } + access->depth++; + return 0; + } + + // depth == 0 marks a free slot + for (size_t i = 0; i < SCOPE_ACCESS_POOL_SIZE; i++) { + if (g_scope_access_pool[i].depth == 0) { + access = &g_scope_access_pool[i]; + access->pooled = true; + break; + } + } + if (!access) { + access = SENTRY_MAKE(scope_access_t); + } + if (!access) { + return 1; + } + + if (write) { + lock_scope_notify((sentry_scope_t *)scope); + sentry__rwlock_write_lock(&data->rwlock); + } else { + sentry__rwlock_read_lock(&data->rwlock); + } + access->data = data; + access->depth = 1; + access->write = write; + access->next = g_scope_access; + g_scope_access = access; + return 0; +} + +int +sentry_scope_begin_read(const sentry_scope_t *scope) +{ + if (!scope) { + return 1; + } + if (scope->parent && sentry_scope_begin_read(scope->parent)) { + return 1; + } + if (!scope_begin(scope, false)) { + return 0; + } + if (scope->parent) { + sentry_scope_end_read(scope->parent); + } + return 1; +} + +int +sentry_scope_begin_write(sentry_scope_t *scope) +{ + if (!scope) { + return 1; + } + if (scope->parent && sentry_scope_begin_read(scope->parent)) { + return 1; + } + if (!scope_begin(scope, true)) { + return 0; + } + if (scope->parent) { + sentry_scope_end_read(scope->parent); + } + return 1; +} + +static void +scope_end(const sentry_scope_t *scope) +{ + if (!scope) { + return; + } +#ifndef SENTRY_PLATFORM_WINDOWS + if (!sentry__block_for_signal_handler()) { + return; + } +#endif + + scope_access_t **link = &g_scope_access; + while (*link && (*link)->data != scope->data) { + link = &(*link)->next; + } + scope_access_t *access = *link; + if (!access) { + assert(false); + return; + } + if (--access->depth > 0) { + return; + } + + *link = access->next; + bool write = access->write; + if (!access->pooled) { + sentry_free(access); + } + if (!write) { + sentry__rwlock_read_unlock(&scope->data->rwlock); + return; + } + sentry__rwlock_write_unlock(&scope->data->rwlock); + + flush_scope((sentry_scope_t *)scope); + unlock_scope_notify((sentry_scope_t *)scope); +} + +void +sentry_scope_end_read(const sentry_scope_t *scope) +{ + if (!scope) { + return; + } + scope_end(scope); + if (scope->parent) { + sentry_scope_end_read(scope->parent); + } +} + +void +sentry_scope_end_write(sentry_scope_t *scope) +{ + sentry_scope_end_read(scope); +} + void sentry_scope_free(sentry_scope_t *scope) { + flush_scope(scope); sentry__scope_decref(scope); } +void +sentry_scope_release(sentry_scope_t *scope) +{ + sentry_scope_free(scope); +} + bool sentry__scope_is_one_shot(const sentry_scope_t *scope) { @@ -759,42 +1069,15 @@ sentry__scope_apply_options(sentry_scope_t *scope, sentry_options_t *options) { sentry_scope_data_t *data = scope->data; SENTRY_SCOPE_WRITE_LOCK (data) { - if (options->sdk_name) { - sentry_value_t sdk_name - = sentry_value_new_string(options->sdk_name); - sentry_value_set_by_key(data->client_sdk, "name", sdk_name); - } - sentry_value_t integrations - = sentry_value_get_by_key(data->client_sdk, "integrations"); - for (size_t i = 0; i < options->num_integrations; i++) { - const char *name = options->integrations[i]->name; - if (!name) { - continue; - } - if (sentry_value_is_null(integrations)) { - integrations = sentry_value_new_list(); - sentry_value_set_by_key( - data->client_sdk, "integrations", integrations); - } - sentry_value_append(integrations, sentry_value_new_string(name)); - } - sentry_value_freeze(data->client_sdk); generate_propagation_context(data->propagation_context); - sentry_value_decref(data->attachments); - data->attachments = options->attachments; - options->attachments = sentry_value_new_null(); sentry__ringbuffer_set_max_size( data->breadcrumbs, options->max_breadcrumbs); } - sentry_scope_set_release_n( - scope, options->release, sentry__guarded_strlen(options->release)); - sentry_scope_set_environment_n(scope, options->environment, - sentry__guarded_strlen(options->environment)); + sentry__scope_update_dsc(scope, options); if (options->initial_scope_func) { options->initial_scope_func(scope, options->initial_scope_data); } - sentry__scope_update_dsc(scope, options); } void @@ -812,9 +1095,10 @@ sentry_scope_clear(sentry_scope_t *scope) observer->clear(observer->data); } } - end_scope_notify(scope); + sentry__scope_clear_attachments(scope); clear_scope_data(scope->data); + end_scope_notify(scope); unlock_scope_notify(scope); sentry__scope_flush(scope); } @@ -841,6 +1125,7 @@ sentry_scope_clone(const sentry_scope_t *scope) sentry_free(clone); return NULL; } + clone->parent = sentry__scope_incref(scope->parent); return clone; } @@ -849,12 +1134,64 @@ sentry__scope_load_propagation_context(const sentry_scope_t *scope) { sentry_value_t propagation_context = sentry_value_new_null(); SENTRY_SCOPE_READ_LOCK (scope->data) { - propagation_context - = sentry__value_clone(scope->data->propagation_context); + if (!scope->parent + || sentry_value_get_length(scope->data->propagation_context)) { + propagation_context + = sentry__value_clone(scope->data->propagation_context); + } + } + if (scope->parent) { + sentry_value_t parent + = sentry__scope_load_propagation_context(scope->parent); + if (sentry_value_is_null(propagation_context)) { + return parent; + } + sentry__value_merge_objects_shallow(propagation_context, parent); + sentry_value_decref(parent); } return propagation_context; } +static void +notify_trace(sentry_scope_t *scope) +{ + lock_scope_notify(scope); + bool observed = false; + for (size_t i = 0; i < scope->num_observers; i++) { + if (scope->observers[i] && scope->observers[i]->set_trace) { + observed = true; + break; + } + } + if (!observed) { + unlock_scope_notify(scope); + return; + } + sentry_value_t span = sentry__scope_load_span_or_transaction(scope); + sentry_value_t trace = sentry__value_get_trace_context(span); + if (!sentry_value_is_null(trace)) { + sentry_value_t data = sentry_value_get_by_key(span, "data"); + if (!sentry_value_is_null(data)) { + sentry_value_set_by_key(trace, "data", sentry_value_incref(data)); + } + } else { + sentry_value_t contexts = sentry__scope_load_contexts(scope); + trace = sentry__value_clone(sentry_value_get_by_key(contexts, "trace")); + sentry_value_decref(contexts); + sentry_value_t propagation = sentry__scope_load_trace_context(scope); + if (sentry_value_is_null(trace)) { + trace = propagation; + } else { + sentry__value_merge_objects(trace, propagation); + sentry_value_decref(propagation); + } + } + SENTRY_SCOPE_NOTIFY(scope, set_trace, trace); + sentry_value_decref(trace); + sentry_value_decref(span); + unlock_scope_notify(scope); +} + void sentry__scope_set_propagation_context( sentry_scope_t *scope, const char *key, sentry_value_t value) @@ -862,6 +1199,7 @@ sentry__scope_set_propagation_context( SENTRY_SCOPE_WRITE_LOCK (scope->data) { sentry_value_set_by_key(scope->data->propagation_context, key, value); } + notify_trace(scope); sentry__scope_flush(scope); } @@ -871,6 +1209,7 @@ sentry__scope_regenerate_propagation_context(sentry_scope_t *scope) SENTRY_SCOPE_WRITE_LOCK (scope->data) { generate_propagation_context(scope->data->propagation_context); } + notify_trace(scope); } sentry_value_t @@ -881,6 +1220,9 @@ sentry__scope_load_trace_context(const sentry_scope_t *scope) trace_context = sentry__value_clone( sentry_value_get_by_key(scope->data->propagation_context, "trace")); } + if (sentry_value_is_null(trace_context) && scope->parent) { + return sentry__scope_load_trace_context(scope->parent); + } return trace_context; } @@ -893,14 +1235,21 @@ sentry__scope_set_trace_context( sentry_value_get_by_key(scope->data->propagation_context, "trace"), key, value); } + notify_trace(scope); } bool sentry__scope_is_trace_managed(const sentry_scope_t *scope) { bool managed = false; + bool has_trace = false; SENTRY_SCOPE_READ_LOCK (scope->data) { managed = scope->data->trace_managed; + has_trace = !sentry_value_is_null( + sentry_value_get_by_key(scope->data->propagation_context, "trace")); + } + if (!has_trace && scope->parent) { + return sentry__scope_is_trace_managed(scope->parent); } return managed; } @@ -917,9 +1266,72 @@ sentry_value_t sentry__scope_load_dsc(const sentry_scope_t *scope) { sentry_value_t dsc = sentry_value_new_null(); - SENTRY_SCOPE_READ_LOCK (scope->data) { - dsc = sentry__value_clone(scope->data->dynamic_sampling_context); + bool frozen = false; + for (const sentry_scope_t *cur = scope; cur; cur = cur->parent) { + bool inherit = false; + SENTRY_SCOPE_READ_LOCK (cur->data) { + frozen + = sentry_value_is_frozen(cur->data->dynamic_sampling_context); + inherit = !frozen && cur->parent + && !sentry_value_get_length( + cur->data->dynamic_sampling_context); + if (!inherit) { + dsc = sentry__value_clone(cur->data->dynamic_sampling_context); + } + } + if (!inherit) { + break; + } + } + if (!frozen && sentry_value_get_type(dsc) == SENTRY_VALUE_TYPE_OBJECT) { + sentry_value_t release = sentry__scope_ref_release(scope); + if (sentry_value_is_null(release)) { + sentry_value_remove_by_key(dsc, "release"); + } else { + sentry_value_set_by_key(dsc, "release", release); + } + sentry_value_t environment = sentry__scope_ref_environment(scope); + if (sentry_value_is_null(environment)) { + sentry_value_remove_by_key(dsc, "environment"); + } else { + sentry_value_set_by_key(dsc, "environment", environment); + } + } + return dsc; +} + +static sentry_value_t +make_dsc(const sentry_scope_t *scope, const sentry_options_t *options) +{ + sentry_value_t dsc = sentry__scope_load_dsc(scope); + sentry_value_t trace_context = sentry__scope_load_trace_context(scope); + double sample_rand = sentry_value_as_double( + sentry_value_get_by_key(trace_context, "sample_rand")); + sentry_value_t sampled + = sentry_value_get_by_key_owned(trace_context, "sampled"); + sentry_value_decref(trace_context); + if (!sentry_value_is_null(dsc)) { + if (!sentry_value_is_null(sampled)) { + // inherit the incoming sampling decision + sentry_value_set_by_key(dsc, "sampled", + sentry_value_new_string( + sentry_value_is_true(sampled) ? "true" : "false")); + } else if (!isnan(sample_rand)) { + if (sample_rand >= options->traces_sample_rate) { + sentry_value_set_by_key( + dsc, "sampled", sentry_value_new_string("false")); + } else { + sentry_value_set_by_key( + dsc, "sampled", sentry_value_new_string("true")); + } + } else { + // only for testing; in production, the SDK should always have a + // non-null sample_rand. We don't set "sampled" to keep dsc empty + SENTRY_WARN("couldn't retrieve sample_rand from scope to apply to " + "the dynamic sampling context"); + } } + sentry_value_decref(sampled); return dsc; } @@ -927,10 +1339,13 @@ void sentry__scope_foreach_dsc(const sentry_scope_t *scope, sentry_value_foreach_key_value_function_t callback, void *userdata) { - SENTRY_SCOPE_READ_LOCK (scope->data) { - sentry_value_foreach_key_value( - scope->data->dynamic_sampling_context, callback, userdata); + if (sentry_scope_begin_read(scope)) { + return; } + sentry_value_t dsc = sentry__scope_load_dsc(scope); + sentry_value_foreach_key_value(dsc, callback, userdata); + sentry_value_decref(dsc); + sentry_scope_end_read(scope); } void @@ -1048,15 +1463,20 @@ sentry__symbolize_stacktrace(sentry_value_t stacktrace) #endif static sentry_value_t -load_span_or_transaction_trace_context(const sentry_scope_data_t *scope_data) +load_span_or_transaction_trace_context(const sentry_scope_t *scope) { // prep contexts sourced from scope; data about transaction on scope needs // to be extracted and inserted sentry_value_t value = sentry_value_new_null(); - if (scope_data->span) { - value = scope_data->span->inner; - } else if (scope_data->transaction_object) { - value = scope_data->transaction_object->inner; + sentry_span_t *span = sentry__scope_ref_span(scope); + sentry_transaction_t *transaction = NULL; + if (span) { + value = span->inner; + } else { + transaction = sentry__scope_ref_transaction_object(scope); + if (transaction) { + value = transaction->inner; + } } sentry_value_t trace = sentry__value_get_trace_context(value); @@ -1066,6 +1486,8 @@ load_span_or_transaction_trace_context(const sentry_scope_data_t *scope_data) sentry_value_set_by_key(trace, "data", sentry__value_clone(data)); } } + sentry__span_decref(span); + sentry__transaction_decref(transaction); return trace; } @@ -1085,6 +1507,10 @@ sentry__scope_apply_to_event(const sentry_scope_t *scope, const sentry_options_t *options, sentry_value_t event, sentry_scope_mode_t mode) { + if (sentry_scope_begin_read(scope)) { + return; + } + #define IS_NULL(Key) sentry_value_is_null(sentry_value_get_by_key(event, Key)) #define SET(Key, Value) sentry_value_set_by_key(event, Key, Value) #define PLACE_STRING(Key, Source) \ @@ -1113,63 +1539,53 @@ sentry__scope_apply_to_event(const sentry_scope_t *scope, } \ } while (0) - const sentry_scope_data_t *data = scope->data; bool is_transaction = sentry__event_is_transaction(event); sentry_value_t event_contexts = sentry_value_get_by_key(event, "contexts"); - sentry_value_t release = sentry_value_new_null(); - sentry_value_t environment = sentry_value_new_null(); - sentry_level_t level = SENTRY_LEVEL_ERROR; - sentry_value_t user = sentry_value_new_null(); - sentry_value_t fingerprint = sentry_value_new_null(); - sentry_value_t transaction = sentry_value_new_null(); - sentry_value_t client_sdk = sentry_value_new_null(); - sentry_value_t contexts = sentry_value_new_null(); + sentry_value_t release = sentry__scope_ref_release(scope); + sentry_value_t environment = sentry__scope_ref_environment(scope); + sentry_level_t level = sentry__scope_get_level(scope); + sentry_value_t user = sentry__scope_ref_user(scope); + sentry_value_t fingerprint = sentry__scope_ref_fingerprint(scope); + sentry_value_t transaction = sentry__scope_ref_transaction(scope); + sentry_value_t client_sdk = sentry__scope_ref_client_sdk(scope); + sentry_value_t tags = sentry__scope_load_tags(scope); + sentry_value_t extra = sentry__scope_load_extra(scope); + sentry_value_t contexts = sentry__scope_load_contexts(scope); sentry_value_t scope_trace = sentry_value_new_null(); sentry_value_t propagation_context = sentry_value_new_null(); sentry_value_t scope_breadcrumbs = sentry_value_new_null(); + sentry_value_t dsc = sentry_value_new_null(); - SENTRY_SCOPE_READ_LOCK (data) { - release = sentry_value_incref(data->release); - environment = sentry_value_incref(data->environment); - level = data->level; - user = sentry_value_incref(data->user); - fingerprint = sentry_value_incref(data->fingerprint); - transaction = sentry_value_incref(data->transaction); - client_sdk = sentry_value_incref(data->client_sdk); - - sentry_value_t event_tags = sentry_value_get_by_key(event, "tags"); - if (sentry_value_is_null(event_tags)) { - if (!sentry_value_is_null(scope->data->tags)) { - sentry_value_set_by_key( - event, "tags", sentry__value_clone(scope->data->tags)); - } - } else { - sentry__value_merge_objects(event_tags, scope->data->tags); + if (!is_transaction) { + scope_trace = load_span_or_transaction_trace_context(scope); + if (sentry_value_is_null(scope_trace) + && sentry_value_is_null( + sentry_value_get_by_key(event_contexts, "trace"))) { + propagation_context = sentry__scope_load_propagation_context(scope); } - - sentry_value_t event_extra = sentry_value_get_by_key(event, "extra"); - if (sentry_value_is_null(event_extra)) { - if (!sentry_value_is_null(scope->data->extra)) { - sentry_value_set_by_key( - event, "extra", sentry__value_clone(scope->data->extra)); - } - } else { - sentry__value_merge_objects(event_extra, scope->data->extra); + if (mode & SENTRY_SCOPE_DSC) { + dsc = make_dsc(scope, options); } + } + if (mode & SENTRY_SCOPE_BREADCRUMBS) { + scope_breadcrumbs = sentry__scope_breadcrumbs_to_list(scope); + } + sentry_scope_end_read(scope); - contexts = sentry__value_clone(data->contexts); - if (!is_transaction) { - scope_trace = load_span_or_transaction_trace_context(data); - if (sentry_value_is_null(scope_trace) - && sentry_value_is_null( - sentry_value_get_by_key(event_contexts, "trace"))) { - propagation_context - = sentry__value_clone(data->propagation_context); - } - } - if (mode & SENTRY_SCOPE_BREADCRUMBS) { - scope_breadcrumbs = sentry__ringbuffer_to_list(data->breadcrumbs); - } + sentry_value_t event_tags = sentry_value_get_by_key(event, "tags"); + if (sentry_value_is_null(event_tags)) { + sentry_value_set_by_key(event, "tags", tags); + } else { + sentry__value_merge_objects(event_tags, tags); + sentry_value_decref(tags); + } + + sentry_value_t event_extra = sentry_value_get_by_key(event, "extra"); + if (sentry_value_is_null(event_extra)) { + sentry_value_set_by_key(event, "extra", extra); + } else { + sentry__value_merge_objects(event_extra, extra); + sentry_value_decref(extra); } PLACE_STRING("platform", "native"); @@ -1216,6 +1632,9 @@ sentry__scope_apply_to_event(const sentry_scope_t *scope, PLACE_VALUE("sdk", client_sdk); sentry_value_decref(client_sdk); + PLACE_VALUE("dsc", dsc); + sentry_value_decref(dsc); + if (is_transaction && !sentry_value_is_null(contexts)) { sentry_value_remove_by_key(contexts, "trace"); } @@ -1252,15 +1671,6 @@ sentry__scope_apply_to_event(const sentry_scope_t *scope, } #if !defined(SENTRY_PLATFORM_NX) - if (mode & SENTRY_SCOPE_MODULES) { - sentry_value_t modules = sentry_get_modules_list(); - if (!sentry_value_is_null(modules)) { - sentry_value_t debug_meta = sentry_value_new_object(); - sentry_value_set_by_key(debug_meta, "images", modules); - sentry_value_set_by_key(event, "debug_meta", debug_meta); - } - } - if (mode & SENTRY_SCOPE_STACKTRACES) { sentry__foreach_stacktrace(event, sentry__symbolize_stacktrace); } @@ -1272,11 +1682,31 @@ sentry__scope_apply_to_event(const sentry_scope_t *scope, #undef PLACE_STRING #undef SET #undef IS_NULL + + if (options->run && options->run->installation_id) { + sentry_value_t usr = sentry_value_get_by_key(event, "user"); + if (sentry_value_is_null(usr)) { + sentry_value_set_by_key(event, "user", sentry_value_new_object()); + usr = sentry_value_get_by_key(event, "user"); + } + if (sentry_value_get_type(usr) == SENTRY_VALUE_TYPE_OBJECT + && sentry_value_is_null(sentry_value_get_by_key(usr, "id"))) { + sentry_value_set_by_key(usr, "id", + sentry_value_new_string(options->run->installation_id)); + } + } } void sentry_scope_add_breadcrumb(sentry_scope_t *scope, sentry_value_t breadcrumb) { + sentry_options_t *options = ref_options(scope); + breadcrumb = sentry__invoke_before_breadcrumb(options, breadcrumb); + sentry_options_free(options); + if (sentry_value_is_null(breadcrumb)) { + return; + } + bool added = false; lock_scope_notify(scope); SENTRY_SCOPE_WRITE_LOCK (scope->data) { @@ -1299,6 +1729,15 @@ sentry__scope_breadcrumbs_to_list(const sentry_scope_t *scope) SENTRY_SCOPE_READ_LOCK (scope->data) { breadcrumbs = sentry__ringbuffer_to_list(scope->data->breadcrumbs); } + if (scope->parent) { + sentry_value_t parent + = sentry__scope_breadcrumbs_to_list(scope->parent); + if (sentry_value_get_length(parent)) { + sentry__value_replace(&breadcrumbs, + sentry__value_merge_breadcrumbs(breadcrumbs, parent, SIZE_MAX)); + } + sentry_value_decref(parent); + } return breadcrumbs; } @@ -1309,6 +1748,9 @@ sentry__scope_ref_user(const sentry_scope_t *scope) SENTRY_SCOPE_READ_LOCK (scope->data) { user = sentry_value_incref(scope->data->user); } + if (sentry_value_is_null(user) && scope->parent) { + return sentry__scope_ref_user(scope->parent); + } return user; } @@ -1329,7 +1771,17 @@ sentry__scope_load_tags(const sentry_scope_t *scope) { sentry_value_t tags = sentry_value_new_null(); SENTRY_SCOPE_READ_LOCK (scope->data) { - tags = sentry__value_clone(scope->data->tags); + if (!scope->parent || sentry_value_get_length(scope->data->tags)) { + tags = sentry__value_clone(scope->data->tags); + } + } + if (scope->parent) { + sentry_value_t parent = sentry__scope_load_tags(scope->parent); + if (sentry_value_is_null(tags)) { + return parent; + } + sentry__value_merge_objects(tags, parent); + sentry_value_decref(parent); } return tags; } @@ -1338,17 +1790,19 @@ void sentry_scope_set_tag(sentry_scope_t *scope, const char *key, const char *value) { sentry_value_t tag_value = sentry_value_new_string(value); + sentry_value_t stored_value = sentry_value_incref(tag_value); bool did_set = false; lock_scope_notify(scope); SENTRY_SCOPE_WRITE_LOCK (scope->data) { - did_set - = sentry_value_set_by_key(scope->data->tags, key, tag_value) == 0; + did_set = sentry_value_set_by_key(scope->data->tags, key, stored_value) + == 0; } if (did_set) { - SENTRY_SCOPE_NOTIFY(scope, set_tag, key, value); + SENTRY_SCOPE_NOTIFY(scope, set_tag, key, tag_value); } unlock_scope_notify(scope); sentry__scope_flush(scope); + sentry_value_decref(tag_value); } void @@ -1371,8 +1825,7 @@ sentry_scope_set_tag_n(sentry_scope_t *scope, const char *key, size_t key_len, == 0; } if (did_set) { - SENTRY_SCOPE_NOTIFY( - scope, set_tag, notify_key, sentry_value_as_string(tag_value)); + SENTRY_SCOPE_NOTIFY(scope, set_tag, notify_key, tag_value); } unlock_scope_notify(scope); sentry__scope_flush(scope); @@ -1387,8 +1840,9 @@ set_tag_value(const char *key, sentry_value_t value, void *userdata) SENTRY_WARNF("set_tags: ignoring non-string value for tag `%s`", key); return 0; } - sentry_scope_set_tag( - (sentry_scope_t *)userdata, key, sentry_value_as_string(value)); + sentry_scope_set_tag_n((sentry_scope_t *)userdata, key, + sentry__guarded_strlen(key), sentry_value_as_string(value), + sentry_value_get_length(value)); return 0; } @@ -1448,7 +1902,17 @@ sentry__scope_load_extra(const sentry_scope_t *scope) { sentry_value_t extra = sentry_value_new_null(); SENTRY_SCOPE_READ_LOCK (scope->data) { - extra = sentry__value_clone(scope->data->extra); + if (!scope->parent || sentry_value_get_length(scope->data->extra)) { + extra = sentry__value_clone(scope->data->extra); + } + } + if (scope->parent) { + sentry_value_t parent = sentry__scope_load_extra(scope->parent); + if (sentry_value_is_null(extra)) { + return parent; + } + sentry__value_merge_objects(extra, parent); + sentry_value_decref(parent); } return extra; } @@ -1562,7 +2026,18 @@ sentry__scope_load_attributes(const sentry_scope_t *scope) { sentry_value_t attributes = sentry_value_new_null(); SENTRY_SCOPE_READ_LOCK (scope->data) { - attributes = sentry__value_clone(scope->data->attributes); + if (!scope->parent + || sentry_value_get_length(scope->data->attributes)) { + attributes = sentry__value_clone(scope->data->attributes); + } + } + if (scope->parent) { + sentry_value_t parent = sentry__scope_load_attributes(scope->parent); + if (sentry_value_is_null(attributes)) { + return parent; + } + sentry__value_merge_objects_shallow(attributes, parent); + sentry_value_decref(parent); } return attributes; } @@ -1591,7 +2066,17 @@ sentry__scope_load_contexts(const sentry_scope_t *scope) { sentry_value_t contexts = sentry_value_new_null(); SENTRY_SCOPE_READ_LOCK (scope->data) { - contexts = sentry__value_clone(scope->data->contexts); + if (!scope->parent || sentry_value_get_length(scope->data->contexts)) { + contexts = sentry__value_clone(scope->data->contexts); + } + } + if (scope->parent) { + sentry_value_t parent = sentry__scope_load_contexts(scope->parent); + if (sentry_value_is_null(contexts)) { + return parent; + } + sentry__value_merge_objects(contexts, parent); + sentry_value_decref(parent); } return contexts; } @@ -1610,6 +2095,9 @@ sentry_scope_set_context( } if (did_set) { SENTRY_SCOPE_NOTIFY(scope, set_context, key, value); + if (sentry__string_eq(key, "trace")) { + notify_trace(scope); + } } unlock_scope_notify(scope); sentry__scope_flush(scope); @@ -1636,6 +2124,9 @@ sentry_scope_set_context_n(sentry_scope_t *scope, const char *key, } if (did_set) { SENTRY_SCOPE_NOTIFY(scope, set_context, notify_key, value); + if (key_len == 5 && memcmp(key, "trace", 5) == 0) { + notify_trace(scope); + } } unlock_scope_notify(scope); sentry__scope_flush(scope); @@ -1653,6 +2144,9 @@ sentry_scope_remove_context(sentry_scope_t *scope, const char *key) } if (removed) { SENTRY_SCOPE_NOTIFY(scope, remove_context, key); + if (sentry__string_eq(key, "trace")) { + notify_trace(scope); + } } unlock_scope_notify(scope); sentry__scope_flush(scope); @@ -1670,6 +2164,9 @@ sentry_scope_remove_context_n( } if (removed_key) { SENTRY_SCOPE_NOTIFY(scope, remove_context, removed_key); + if (key_len == 5 && memcmp(removed_key, "trace", 5) == 0) { + notify_trace(scope); + } } unlock_scope_notify(scope); sentry__scope_flush(scope); @@ -1709,6 +2206,9 @@ sentry_scope_update_context_n(sentry_scope_t *scope, const char *key, } if (did_set) { SENTRY_SCOPE_NOTIFY(scope, set_context, notify_key, value); + if (key_len == 5 && memcmp(key, "trace", 5) == 0) { + notify_trace(scope); + } } unlock_scope_notify(scope); sentry__scope_flush(scope); @@ -1725,8 +2225,6 @@ sentry_scope_set_release_n( SENTRY_SCOPE_WRITE_LOCK (scope->data) { sentry__value_replace( &scope->data->release, sentry_value_incref(value)); - sentry_value_set_by_key(scope->data->dynamic_sampling_context, - "release", sentry_value_incref(value)); } SENTRY_SCOPE_NOTIFY_OWNED(scope, set_release, value); unlock_scope_notify(scope); @@ -1749,8 +2247,6 @@ sentry_scope_set_environment_n( SENTRY_SCOPE_WRITE_LOCK (scope->data) { sentry__value_replace( &scope->data->environment, sentry_value_incref(value)); - sentry_value_set_by_key(scope->data->dynamic_sampling_context, - "environment", sentry_value_incref(value)); } SENTRY_SCOPE_NOTIFY_OWNED(scope, set_environment, value); unlock_scope_notify(scope); @@ -1798,6 +2294,9 @@ sentry__scope_ref_fingerprint(const sentry_scope_t *scope) SENTRY_SCOPE_READ_LOCK (scope->data) { fingerprint = sentry_value_incref(scope->data->fingerprint); } + if (sentry_value_is_null(fingerprint) && scope->parent) { + return sentry__scope_ref_fingerprint(scope->parent); + } return fingerprint; } @@ -1888,13 +2387,129 @@ sentry_scope_remove_fingerprint(sentry_scope_t *scope) sentry__scope_flush(scope); } +// the options attached to the isolation scope, available already while +// `sentry_init` applies the initial scope, or the global options +static sentry_options_t * +ref_options(const sentry_scope_t *scope) +{ + sentry_options_t *options = NULL; + for (; scope && !options; scope = scope->parent) { + sentry__mutex_lock((sentry_mutex_t *)&scope->observers_lock); + options = sentry__options_incref(scope->state); + sentry__mutex_unlock((sentry_mutex_t *)&scope->observers_lock); + } + return options ? options : (sentry_options_t *)sentry__options_getref(); +} + +void +sentry_scope_set_trace( + sentry_scope_t *scope, const char *trace_id, const char *parent_span_id) +{ + sentry_scope_set_trace_n(scope, trace_id, sentry__guarded_strlen(trace_id), + parent_span_id, sentry__guarded_strlen(parent_span_id)); +} + +void +sentry_scope_set_trace_n(sentry_scope_t *scope, const char *trace_id, + size_t trace_id_len, const char *parent_span_id, size_t parent_span_id_len) +{ + sentry_value_t context = sentry_value_new_object(); + + sentry_value_set_by_key(context, "type", sentry_value_new_string("trace")); + + sentry_value_set_by_key( + context, "trace_id", sentry_value_new_string_n(trace_id, trace_id_len)); + if (parent_span_id && parent_span_id_len) { + sentry_value_set_by_key(context, "parent_span_id", + sentry_value_new_string_n(parent_span_id, parent_span_id_len)); + } + + sentry_uuid_t span_id = sentry_uuid_new_v4(); + sentry_value_set_by_key( + context, "span_id", sentry__value_new_span_uuid(&span_id)); + sentry__scope_set_trace_managed(scope, false); + + sentry__generate_sample_rand(context); + + sentry__scope_set_propagation_context(scope, "trace", context); + + sentry_options_t *options = ref_options(scope); + if (options) { + sentry__scope_update_dsc(scope, options); + sentry__scope_flush(scope); + } + sentry_options_free(options); +} + +void +sentry_scope_continue_trace( + sentry_scope_t *scope, const char *sentry_trace, const char *baggage) +{ + sentry_scope_continue_trace_n(scope, sentry_trace, + sentry__guarded_strlen(sentry_trace), baggage, + sentry__guarded_strlen(baggage)); +} + +void +sentry_scope_continue_trace_n(sentry_scope_t *scope, const char *sentry_trace, + size_t sentry_trace_len, const char *baggage, size_t baggage_len) +{ + sentry_value_t context = sentry__parse_trace_headers( + sentry_trace, sentry_trace_len, baggage, baggage_len); + sentry_value_t dsc = sentry__value_take_by_key(context, "incoming_dsc"); + + sentry_options_t *options = ref_options(scope); + if (options) { + if (!sentry_value_is_null(sentry_value_get_by_key(context, "trace_id")) + && sentry__trace_can_continue(dsc, options)) { + sentry_value_set_by_key( + context, "type", sentry_value_new_string("trace")); + sentry_uuid_t span_id = sentry_uuid_new_v4(); + sentry_value_set_by_key( + context, "span_id", sentry__value_new_span_uuid(&span_id)); + sentry__scope_set_propagation_context( + scope, "trace", sentry_value_incref(context)); + if (sentry_value_get_length(dsc) > 0) { + sentry__scope_freeze_dsc(scope, dsc); + } else { + sentry__scope_update_dsc(scope, options); + } + } else { + // start a new trace if the incoming one cannot be continued + sentry__scope_regenerate_propagation_context(scope); + sentry__scope_update_dsc(scope, options); + } + sentry__scope_set_trace_managed(scope, false); + sentry__scope_flush(scope); + } + sentry_options_free(options); + sentry_value_decref(dsc); + sentry_value_decref(context); +} + +void +sentry_scope_iter_trace_propagation_headers(const sentry_scope_t *scope, + sentry_iter_headers_function_t callback, void *userdata) +{ + sentry_value_t span = sentry__scope_load_span_or_transaction(scope); + if (sentry_value_is_null(span)) { + span = sentry__scope_load_trace_context(scope); + } + sentry__span_iter_headers(scope, span, callback, userdata); + sentry_value_decref(span); +} + sentry_level_t sentry__scope_get_level(const sentry_scope_t *scope) { - sentry_level_t level = SENTRY_LEVEL_ERROR; + sentry_level_t level = SENTRY_LEVEL_NONE; SENTRY_SCOPE_READ_LOCK (scope->data) { level = scope->data->level; } + if (level == SENTRY_LEVEL_NONE) { + return scope->parent ? sentry__scope_get_level(scope->parent) + : SENTRY_LEVEL_ERROR; + } return level; } @@ -1905,6 +2520,9 @@ sentry__scope_ref_client_sdk(const sentry_scope_t *scope) SENTRY_SCOPE_READ_LOCK (scope->data) { client_sdk = sentry_value_incref(scope->data->client_sdk); } + if (sentry_value_is_null(client_sdk) && scope->parent) { + return sentry__scope_ref_client_sdk(scope->parent); + } return client_sdk; } @@ -1937,23 +2555,43 @@ sentry_value_t sentry__scope_load_attachments(const sentry_scope_t *scope) { sentry_value_t attachments = sentry_value_new_null(); + if (!scope) { + return attachments; + } SENTRY_SCOPE_READ_LOCK (scope->data) { attachments = sentry__attachments_clone(scope->data->attachments); } + if (scope->parent) { + sentry_value_t parent = sentry__scope_load_attachments(scope->parent); + sentry__attachments_extend(&attachments, parent); + sentry_value_decref(parent); + } return attachments; } sentry_value_t sentry__scope_add_attachment(sentry_scope_t *scope, sentry_value_t attachment) { + if (!sentry__attachment_validate(attachment)) { + sentry_value_decref(attachment); + return sentry_value_new_null(); + } bool did_add = false; - sentry_value_t added = sentry_value_new_null(); lock_scope_notify(scope); - SENTRY_SCOPE_WRITE_LOCK (scope->data) { - size_t len = sentry_value_get_length(scope->data->attachments); - added = sentry__attachments_add(&scope->data->attachments, attachment); - did_add = !sentry_value_is_null(added) - && sentry_value_get_length(scope->data->attachments) > len; + sentry_value_t attachments = sentry__scope_load_attachments(scope); + sentry_value_t added = sentry__attachments_find(attachments, attachment); + sentry_value_decref(attachments); + if (sentry_value_is_null(added)) { + SENTRY_SCOPE_WRITE_LOCK (scope->data) { + size_t len = sentry_value_get_length(scope->data->attachments); + added = sentry__attachments_add( + &scope->data->attachments, attachment); + did_add = !sentry_value_is_null(added) + && sentry_value_get_length(scope->data->attachments) > len; + } + } else { + sentry_value_freeze(attachment); + sentry_value_decref(attachment); } if (did_add) { SENTRY_SCOPE_NOTIFY(scope, add_attachment, added); @@ -2022,9 +2660,14 @@ sentry_transaction_t * sentry__scope_ref_transaction_object(const sentry_scope_t *scope) { sentry_transaction_t *transaction = NULL; + bool has_binding = false; SENTRY_SCOPE_READ_LOCK (scope->data) { transaction = scope->data->transaction_object; sentry__transaction_incref(transaction); + has_binding = scope->data->span || scope->data->transaction_object; + } + if (!has_binding && scope->parent) { + return sentry__scope_ref_transaction_object(scope->parent); } return transaction; } @@ -2040,6 +2683,7 @@ sentry__scope_set_transaction_object( sentry__transaction_decref(scope->data->transaction_object); scope->data->transaction_object = transaction; } + notify_trace(scope); sentry__scope_flush(scope); } @@ -2056,6 +2700,7 @@ sentry__scope_remove_transaction_object( } if (removed) { sentry__transaction_decref(transaction); + notify_trace(scope); } if (removed) { sentry__scope_flush(scope); @@ -2079,6 +2724,9 @@ sentry__scope_remove_transaction_value( } } sentry__transaction_decref(transaction_object); + if (transaction_object) { + notify_trace(scope); + } return transaction_object != NULL; } @@ -2095,6 +2743,7 @@ sentry__scope_restore_transaction_object( } } if (restored) { + notify_trace(scope); sentry__scope_flush(scope); } return restored; @@ -2104,9 +2753,14 @@ sentry_span_t * sentry__scope_ref_span(const sentry_scope_t *scope) { sentry_span_t *span = NULL; + bool has_binding = false; SENTRY_SCOPE_READ_LOCK (scope->data) { span = scope->data->span; sentry__span_incref(span); + has_binding = scope->data->span || scope->data->transaction_object; + } + if (!has_binding && scope->parent) { + return sentry__scope_ref_span(scope->parent); } return span; } @@ -2115,13 +2769,18 @@ sentry_value_t sentry__scope_load_span_or_transaction(const sentry_scope_t *scope) { sentry_value_t value = sentry_value_new_null(); + bool has_binding = false; SENTRY_SCOPE_READ_LOCK (scope->data) { + has_binding = scope->data->span || scope->data->transaction_object; if (scope->data->span) { value = sentry__value_clone(scope->data->span->inner); } else if (scope->data->transaction_object) { value = sentry__value_clone(scope->data->transaction_object->inner); } } + if (!has_binding && scope->parent) { + return sentry__scope_load_span_or_transaction(scope->parent); + } return value; } @@ -2135,6 +2794,7 @@ sentry__scope_set_span(sentry_scope_t *scope, sentry_span_t *span) sentry__span_decref(scope->data->span); scope->data->span = span; } + notify_trace(scope); sentry__scope_flush(scope); } @@ -2150,6 +2810,7 @@ sentry__scope_remove_span(sentry_scope_t *scope, sentry_span_t *span) } if (removed) { sentry__span_decref(span); + notify_trace(scope); } if (removed) { sentry__scope_flush(scope); @@ -2172,6 +2833,7 @@ sentry__scope_remove_span_value(sentry_scope_t *scope, sentry_value_t span) } sentry__span_decref(scope_span); if (scope_span != NULL) { + notify_trace(scope); sentry__scope_flush(scope); } return scope_span != NULL; @@ -2188,6 +2850,7 @@ sentry__scope_restore_span(sentry_scope_t *scope, sentry_span_t *span) } } if (restored) { + notify_trace(scope); sentry__scope_flush(scope); } return restored; @@ -2243,6 +2906,9 @@ sentry__scope_ref_release(const sentry_scope_t *scope) SENTRY_SCOPE_READ_LOCK (scope->data) { release = sentry_value_incref(scope->data->release); } + if (sentry_value_is_null(release) && scope->parent) { + return sentry__scope_ref_release(scope->parent); + } return release; } @@ -2253,6 +2919,9 @@ sentry__scope_ref_environment(const sentry_scope_t *scope) SENTRY_SCOPE_READ_LOCK (scope->data) { environment = sentry_value_incref(scope->data->environment); } + if (sentry_value_is_null(environment) && scope->parent) { + return sentry__scope_ref_environment(scope->parent); + } return environment; } @@ -2263,6 +2932,9 @@ sentry__scope_ref_transaction(const sentry_scope_t *scope) SENTRY_SCOPE_READ_LOCK (scope->data) { transaction = sentry_value_incref(scope->data->transaction); } + if (sentry_value_is_null(transaction) && scope->parent) { + return sentry__scope_ref_transaction(scope->parent); + } return transaction; } @@ -2331,72 +3003,77 @@ sentry_scope_attach_bytesw_n(sentry_scope_t *scope, const char *buf, } #endif +static sentry_value_t +load_context(const sentry_scope_t *scope, const char *key) +{ + sentry_value_t context = sentry_value_new_null(); + SENTRY_SCOPE_READ_LOCK (scope->data) { + context = sentry__value_clone( + sentry_value_get_by_key(scope->data->contexts, key)); + } + if (scope->parent) { + sentry_value_t parent = load_context(scope->parent, key); + if (sentry_value_is_null(context)) { + return parent; + } + sentry__value_merge_objects(context, parent); + sentry_value_decref(parent); + } + return context; +} + void sentry__scope_apply_to_telemetry(const sentry_scope_t *scope, sentry_value_t telemetry, sentry_value_t attributes) { - const sentry_scope_data_t *data = scope->data; - sentry_value_t os_name = sentry_value_new_null(); - sentry_value_t os_version = sentry_value_new_null(); - sentry_value_t user = sentry_value_new_null(); - sentry_value_t environment = sentry_value_new_null(); - sentry_value_t release = sentry_value_new_null(); - - SENTRY_SCOPE_READ_LOCK (data) { - sentry__value_merge_objects_shallow(attributes, data->attributes); - - sentry_value_t trace_id = sentry_value_get_by_key( - sentry_value_get_by_key(data->propagation_context, "trace"), - "trace_id"); + if (sentry_scope_begin_read(scope)) { + return; + } - sentry_value_t parent_span_id = sentry_value_new_object(); - bool has_parent_span = false; - if (data->transaction_object) { - sentry_value_t span_id = sentry_value_get_by_key( - data->transaction_object->inner, "span_id"); - sentry_value_set_by_key( - parent_span_id, "value", sentry_value_incref(span_id)); - trace_id = sentry_value_get_by_key( - data->transaction_object->inner, "trace_id"); - has_parent_span = true; - } else if (data->span) { - sentry_value_t span_id - = sentry_value_get_by_key(data->span->inner, "span_id"); - sentry_value_set_by_key( - parent_span_id, "value", sentry_value_incref(span_id)); - trace_id = sentry_value_get_by_key(data->span->inner, "trace_id"); - has_parent_span = true; - } + for (const sentry_scope_t *cur = scope; cur; cur = cur->parent) { + sentry__value_merge_objects_shallow(attributes, cur->data->attributes); + } + sentry_span_t *span = sentry__scope_ref_span(scope); + sentry_transaction_t *transaction + = sentry__scope_ref_transaction_object(scope); + sentry_value_t trace; + if (span) { + trace = span->inner; + } else if (transaction) { + trace = transaction->inner; + } else { + trace = sentry__scope_load_trace_context(scope); + } + sentry_value_t parent_span_id = sentry_value_new_null(); + sentry_value_t trace_id = sentry_value_get_by_key_owned(trace, "trace_id"); + if (span || transaction) { + parent_span_id = sentry_value_get_by_key_owned(trace, "span_id"); + } else { + sentry_value_decref(trace); + } + sentry__span_decref(span); + sentry__transaction_decref(transaction); + sentry_value_t os_context = load_context(scope, "os"); + sentry_value_t os_name = sentry_value_get_by_key_owned(os_context, "name"); + sentry_value_t os_version + = sentry_value_get_by_key_owned(os_context, "version"); + sentry_value_t user = sentry__scope_ref_user(scope); + sentry_value_t environment = sentry__scope_ref_environment(scope); + sentry_value_t release = sentry__scope_ref_release(scope); + sentry_scope_end_read(scope); + sentry_value_decref(os_context); + + if (!sentry_value_is_null(parent_span_id)) { + sentry__value_add_attribute(attributes, parent_span_id, "string", + "sentry.trace.parent_span_id"); + } + if (!sentry_value_is_null(trace_id) + && sentry_value_is_null( + sentry_value_get_by_key(telemetry, "trace_id"))) { sentry_value_set_by_key( - parent_span_id, "type", sentry_value_new_string("string")); - if (has_parent_span - && sentry_value_is_null(sentry_value_get_by_key( - attributes, "sentry.trace.parent_span_id"))) { - sentry_value_set_by_key( - attributes, "sentry.trace.parent_span_id", parent_span_id); - } else { - sentry_value_decref(parent_span_id); - } - if (!sentry_value_is_null(trace_id) - && sentry_value_is_null( - sentry_value_get_by_key(telemetry, "trace_id"))) { - sentry_value_set_by_key( - telemetry, "trace_id", sentry_value_incref(trace_id)); - } - - sentry_value_t os_context - = sentry_value_get_by_key(data->contexts, "os"); - if (!sentry_value_is_null(os_context)) { - os_name = sentry_value_incref( - sentry_value_get_by_key(os_context, "name")); - os_version = sentry_value_incref( - sentry_value_get_by_key(os_context, "version")); - } - - user = sentry_value_incref(data->user); - environment = sentry_value_incref(data->environment); - release = sentry_value_incref(data->release); + telemetry, "trace_id", sentry_value_incref(trace_id)); } + sentry_value_decref(trace_id); if (!sentry_value_is_null(os_name)) { sentry__value_add_attribute(attributes, os_name, "string", "os.name"); diff --git a/src/sentry_scope.h b/src/sentry_scope.h index 090c64e45c..c6e63fe4d6 100644 --- a/src/sentry_scope.h +++ b/src/sentry_scope.h @@ -37,7 +37,7 @@ typedef struct sentry_scope_observer_s { void (*add_breadcrumb)(void *data, sentry_value_t breadcrumb); - void (*set_tag)(void *data, const char *key, const char *value); + void (*set_tag)(void *data, const char *key, sentry_value_t value); void (*remove_tag)(void *data, const char *key); void (*set_extra)(void *data, const char *key, sentry_value_t value); @@ -48,6 +48,8 @@ typedef struct sentry_scope_observer_s { void (*add_attachment)(void *data, sentry_value_t attachment); void (*remove_attachment)(void *data, sentry_value_t attachment); + + void (*set_trace)(void *data, sentry_value_t trace); } sentry_scope_observer_t; typedef struct sentry_scope_data_s sentry_scope_data_t; @@ -56,6 +58,7 @@ typedef struct sentry_scope_data_s sentry_scope_data_t; * This represents the current scope. */ struct sentry_scope_s { + // negative for static scopes long refcount; sentry_scope_data_t *data; @@ -66,6 +69,8 @@ struct sentry_scope_s { bool pending_flush; void (*flush_func)(sentry_scope_t *scope); void *state; + // immutable after construction + const sentry_scope_t *parent; // Whether this scope is single-use. A capture function frees a one-shot // scope after applying it. @@ -80,24 +85,25 @@ typedef enum { SENTRY_SCOPE_NONE = 0x0, // Add all the breadcrumbs from the scope to the event. SENTRY_SCOPE_BREADCRUMBS = 0x1, - // Add the module list to the event. + // TODO: remove SENTRY_SCOPE_MODULES = 0x2, // Symbolize all the stacktraces on-device which are found in the event. SENTRY_SCOPE_STACKTRACES = 0x4, + // Add the dynamic sampling context for the envelope trace header. + SENTRY_SCOPE_DSC = 0x8, // All of the above. SENTRY_SCOPE_ALL = ~0, } sentry_scope_mode_t; /** - * This will return a new reference to the global scope, initializing it if - * needed. + * Replaces the isolation scope for SDK initialization. */ -sentry_scope_t *sentry__scope_getref(void); +bool sentry__scope_init(const sentry_options_t *options); /** * Increment the refcount and return the scope pointer. */ -sentry_scope_t *sentry__scope_incref(sentry_scope_t *scope); +sentry_scope_t *sentry__scope_incref(const sentry_scope_t *scope); /** * Decrement the refcount and free the scope when the last reference is @@ -106,7 +112,7 @@ sentry_scope_t *sentry__scope_incref(sentry_scope_t *scope); void sentry__scope_decref(sentry_scope_t *scope); /** - * This will free all the data attached to the global scope + * Releases the isolation scope after SDK shutdown. */ void sentry__scope_cleanup(void); @@ -121,21 +127,9 @@ void sentry__scope_set_one_shot(sentry_scope_t *scope, bool one_shot); */ void sentry__scope_free_one_shot(sentry_scope_t *scope); -/** - * Finish a read-only global scope access. - * This consumes the caller's scope reference. - */ -void sentry__scope_finish(sentry_scope_t *scope); - -/** - * Finish a mutable global scope access, flushing pending changes. - * This consumes the caller's scope reference. - */ -void sentry__scope_finish_mut(sentry_scope_t *scope); - /** * Flush scope changes. The flush is deferred until mutable access finishes. - * No-op for non-global scopes without a flush callback. + * No-op for scopes without a flush callback. */ void sentry__scope_flush(sentry_scope_t *scope); void sentry__scope_set_flush_func( @@ -143,8 +137,8 @@ void sentry__scope_set_flush_func( void sentry__scope_set_state(sentry_scope_t *scope, void *state); /** - * This will merge the requested data which is in the given `scope` to the given - * `event`. + * This will merge the requested data from `scope` and its parents to the given + * `event`, most specific first. * See `sentry_scope_mode_t` for the different types of data that can be * attached. */ @@ -169,7 +163,7 @@ sentry_level_t sentry__scope_get_level(const sentry_scope_t *scope); sentry_value_t sentry__scope_ref_client_sdk(const sentry_scope_t *scope); /** - * Returns an owned reference to the scope attachment list. + * Returns an owned list of attachments from the scope and its parents. * The caller must release it with `sentry_value_decref`. */ sentry_value_t sentry__scope_load_attachments(const sentry_scope_t *scope); @@ -228,14 +222,15 @@ bool sentry__scope_is_trace_managed(const sentry_scope_t *scope); void sentry__scope_set_trace_managed(sentry_scope_t *scope, bool managed); /** - * These are convenience macros to access the global scope inside a code block. + * These are convenience macros to access the isolation scope inside a code + * block. */ #define SENTRY_WITH_SCOPE(Scope) \ - for (const sentry_scope_t *Scope = sentry__scope_getref(); Scope; \ - sentry__scope_finish((sentry_scope_t *)Scope), Scope = NULL) + for (const sentry_scope_t *Scope = sentry_scope_acquire(); Scope; \ + sentry__scope_decref((sentry_scope_t *)Scope), Scope = NULL) #define SENTRY_WITH_SCOPE_MUT(Scope) \ - for (sentry_scope_t *Scope = sentry__scope_getref(); Scope; \ - sentry__scope_finish_mut(Scope), Scope = NULL) + for (sentry_scope_t *Scope = sentry_scope_acquire(); Scope; \ + sentry_scope_release(Scope), Scope = NULL) // TODO: adapt console SDKs to SENTRY_WITH_SCOPE_MUT and remove the alias #define SENTRY_WITH_SCOPE_MUT_NO_FLUSH(Scope) SENTRY_WITH_SCOPE_MUT (Scope) @@ -258,6 +253,18 @@ sentry_scope_observer_t *sentry__scope_observer_new(void); bool sentry__scope_add_observer( sentry_scope_t *scope, sentry_scope_observer_t *observer); +/** + * Register and initialize a scope observer. + * + * Calls `init` with the observer's data and the scope after registration, + * while scope notifications are locked. The callback must only read the scope. + * Returning false removes the observer. Takes ownership of `observer`, + * freeing it if registration or initialization fails. + */ +bool sentry__scope_add_observer_with_init(sentry_scope_t *scope, + sentry_scope_observer_t *observer, + bool (*init)(void *data, const sentry_scope_t *scope)); + /** * Remove a scope observer. * @@ -287,9 +294,8 @@ void sentry__scope_update_dsc( void sentry__scope_freeze_dsc(sentry_scope_t *scope, sentry_value_t incoming); /** - * Merges the given scope data into a telemetry item (a log or metric): its - * attributes, trace, user, etc. Existing values are kept, so this can be called - * for each scope in a precedence chain, most specific first (first write wins). + * Merges the scope and its parent scopes into a log or metric, most specific + * first. Existing values are kept. */ void sentry__scope_apply_to_telemetry(const sentry_scope_t *scope, sentry_value_t telemetry, sentry_value_t attributes); diff --git a/src/sentry_screenshot.h b/src/sentry_screenshot.h index b0ee209217..c372d34b6e 100644 --- a/src/sentry_screenshot.h +++ b/src/sentry_screenshot.h @@ -13,9 +13,9 @@ * @param pid The process ID whose windows should be captured (0 = current * process). * - * Returns true if the screenshot was successfully captured and saved. + * Returns 0 if the screenshot was successfully captured and saved. */ -bool sentry__screenshot_capture(const sentry_path_t *path, uint32_t pid); +int sentry_screenshot_capture(const char *path, uint32_t pid); /** * Returns the path where a screenshot should be saved. diff --git a/src/sentry_session.c b/src/sentry_session.c index 76bef8d046..885b55bd6b 100644 --- a/src/sentry_session.c +++ b/src/sentry_session.c @@ -249,18 +249,19 @@ sentry_start_session(void) sentry_envelope_t *envelope = NULL; sentry_options_t *options = sentry__options_lock(); SENTRY_WITH_SCOPE (scope) { - if (options) { + if (options && !sentry_scope_begin_read(scope)) { sentry__mutex_lock(&options->session_lock); options->session = sentry__session_new(scope); + sentry_value_t user = sentry__scope_ref_user(scope); + sentry_scope_end_read(scope); if (options->session) { - sentry_value_t user = sentry__scope_ref_user(scope); sentry__session_sync_user(options->session, user, options->run ? options->run->installation_id : NULL); - sentry_value_decref(user); envelope = take_session_start_update(options); sentry__session_notify_changed(options); sentry__run_write_session(options->run, options->session); } + sentry_value_decref(user); sentry__mutex_unlock(&options->session_lock); } } diff --git a/src/sentry_session.h b/src/sentry_session.h index b2caefde62..d5af9af3bb 100644 --- a/src/sentry_session.h +++ b/src/sentry_session.h @@ -78,7 +78,7 @@ void sentry__session_send_start_update(const sentry_options_t *options); /** * This notifies the backend that the current session of `options` started, - * changed or ended. Must be called with the options lock held. + * changed or ended. Must be called with the session lock held. */ void sentry__session_notify_changed(const sentry_options_t *options); diff --git a/src/sentry_sync.h b/src/sentry_sync.h index d96b5d58ca..63f407b175 100644 --- a/src/sentry_sync.h +++ b/src/sentry_sync.h @@ -676,9 +676,18 @@ sentry__atomic_compare_swap(volatile long *val, long expected, long desired) * only 32 bits wide on Windows and 32-bit POSIX targets, so callers that need * a full 64-bit atomic (e.g. a monotonic timestamp that must not tear on a * 32-bit platform) use these instead. + * + * `uint64_t` is only 4-byte aligned on 32-bit x86, so POSIX targets declare the + * operands as `sentry_atomic_u64_t` to keep the accesses lock-free. */ +#ifdef SENTRY_PLATFORM_WINDOWS +typedef uint64_t sentry_atomic_u64_t; +#else +typedef uint64_t sentry_atomic_u64_t __attribute__((aligned(8))); +#endif + static inline void -sentry__atomic_store_u64(uint64_t *val, uint64_t value) +sentry__atomic_store_u64(sentry_atomic_u64_t *val, uint64_t value) { #ifdef SENTRY_PLATFORM_WINDOWS InterlockedExchange64((volatile LONG64 *)val, (LONG64)value); @@ -688,7 +697,7 @@ sentry__atomic_store_u64(uint64_t *val, uint64_t value) } static inline uint64_t -sentry__atomic_fetch_u64(uint64_t *val) +sentry__atomic_fetch_u64(sentry_atomic_u64_t *val) { #ifdef SENTRY_PLATFORM_WINDOWS return (uint64_t)InterlockedCompareExchange64((volatile LONG64 *)val, 0, 0); diff --git a/src/sentry_telemetry.c b/src/sentry_telemetry.c index 2bcecedd6a..9eafb9821f 100644 --- a/src/sentry_telemetry.c +++ b/src/sentry_telemetry.c @@ -41,8 +41,9 @@ sentry__telemetry_shutdown(const sentry_options_t *options) sentry__mutex_lock(&g_telemetry_lock); SENTRY_DEBUG("shutting down telemetry"); - sentry__logs_shutdown(options->shutdown_timeout); - sentry__metrics_shutdown(options->shutdown_timeout); + uint64_t timeout = sentry_options_get_shutdown_timeout(options); + sentry__logs_shutdown(timeout); + sentry__metrics_shutdown(timeout); sentry__threadpool_flush(g_telemetry_pool); sentry__threadpool_shutdown(g_telemetry_pool); sentry__threadpool_free(g_telemetry_pool); @@ -69,8 +70,6 @@ sentry__telemetry_force_flush(void) void sentry__telemetry_flush_crash_safe(void) { - SENTRY_SIGNAL_SAFE_LOG("DEBUG crash-safe telemetry flush"); sentry__logs_flush_crash_safe(); sentry__metrics_flush_crash_safe(); - SENTRY_SIGNAL_SAFE_LOG("DEBUG crash-safe telemetry flush complete"); } diff --git a/src/sentry_thread_stackwalk_posix.c b/src/sentry_thread_stackwalk_posix.c index 7824ee35ed..fff989cb7e 100644 --- a/src/sentry_thread_stackwalk_posix.c +++ b/src/sentry_thread_stackwalk_posix.c @@ -28,7 +28,6 @@ static sem_t g_done; static volatile sig_atomic_t g_active = 0; -static void *g_ips[SENTRY_APP_HANG_MAX_FRAMES]; static volatile sig_atomic_t g_count = 0; static volatile sig_atomic_t g_want = 0; @@ -38,6 +37,8 @@ static sem_t g_unwind_done; // watchdog -> handler: unwind complete, you may return static volatile sig_atomic_t g_abort_park = 0; static ucontext_t *volatile g_park_uctx = NULL; +# else +static void *g_ips[SENTRY_APP_HANG_MAX_FRAMES]; # endif static void @@ -89,7 +90,7 @@ handler(int sig, siginfo_t *info, void *ucontext) } } g_park_uctx = NULL; - // watchdog wrote g_ips/g_count before releasing us + // watchdog wrote g_count before releasing us n = (size_t)__atomic_load_n(&g_count, __ATOMIC_RELAXED); # else (void)ucontext; @@ -147,15 +148,14 @@ ensure_installed(void) // dl_iterate_phdr for the first time inside the signal handler. unw_context_t uc; unw_cursor_t cur; -# ifdef __clang__ +# ifdef __GNUC__ // This pragma is required to build with Werror on ARM64 Ubuntu -# pragma clang diagnostic push -# pragma clang diagnostic ignored \ - "-Wgnu-statement-expression-from-macro-expansion" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wpedantic" # endif int got_context = unw_getcontext(&uc); -# ifdef __clang__ -# pragma clang diagnostic pop +# ifdef __GNUC__ +# pragma GCC diagnostic pop # endif if (got_context == 0 && unw_init_local(&cur, &uc) == 0) { for (int i = 0; i < 5 && unw_step(&cur) > 0; i++) { } diff --git a/src/sentry_tracing.c b/src/sentry_tracing.c index ec0967aef5..2d539f23ff 100644 --- a/src/sentry_tracing.c +++ b/src/sentry_tracing.c @@ -10,6 +10,7 @@ #include "sentry_utils.h" #include "sentry_value.h" #include +#include #include static inline bool @@ -109,6 +110,12 @@ transaction_context_new_n(sentry_slice_t name, sentry_slice_t operation) sentry_value_set_by_key(transaction_context, "parent_span_id", sentry__value_clone( sentry_value_get_by_key(trace_context, "parent_span_id"))); + sentry_value_t sampled + = sentry_value_get_by_key(trace_context, "sampled"); + if (!sentry_value_is_null(sampled)) { + sentry_value_set_by_key(transaction_context, "sampled", + sentry__value_clone(sampled)); + } } sentry_value_decref(trace_context); } @@ -287,8 +294,7 @@ compare_header_key( } static void -parse_sentry_trace( - sentry_transaction_context_t *tx_ctx, const char *value, size_t value_len) +parse_sentry_trace(sentry_value_t inner, const char *value, size_t value_len) { // Parse sentry-trace header: traceid-spanid(-sampled)? const char *trace_id_start = value; @@ -298,8 +304,6 @@ parse_sentry_trace( return; } - sentry_value_t inner = tx_ctx->inner; - char *s = sentry__string_clone_n( trace_id_start, (size_t)(trace_id_end - trace_id_start)); if (!is_valid_trace_id(s)) { @@ -350,15 +354,13 @@ parse_sentry_trace( } static void -parse_baggage( - sentry_transaction_context_t *tx_ctx, const char *value, size_t value_len) +parse_baggage(sentry_value_t inner, const char *value, size_t value_len) { // https://www.w3.org/TR/baggage/ — Sentry-prefixed members are kept and // percent-decoded; non-sentry members are ignored. static const char sentry_prefix[] = "sentry-"; static const size_t sentry_prefix_len = sizeof(sentry_prefix) - 1; - sentry_value_t inner = tx_ctx->inner; sentry_value_t incoming = sentry_value_get_by_key(inner, "incoming_dsc"); if (sentry_value_is_null(incoming)) { incoming = sentry_value_new_object(); @@ -405,6 +407,58 @@ sentry__trace_can_continue( return true; } +static double +parse_double(sentry_value_t value) +{ + const char *str = sentry_value_as_string(value); + char *end = NULL; + double d = sentry__strtod_c(str, &end); + return end != str && *end == '\0' ? d : (double)NAN; +} + +sentry_value_t +sentry__parse_trace_headers(const char *sentry_trace, size_t sentry_trace_len, + const char *baggage, size_t baggage_len) +{ + sentry_value_t trace = sentry_value_new_object(); + if (sentry_trace && sentry_trace_len) { + parse_sentry_trace(trace, sentry_trace, sentry_trace_len); + } + if (baggage && baggage_len) { + parse_baggage(trace, baggage, baggage_len); + } + + sentry_value_t dsc = sentry_value_get_by_key(trace, "incoming_dsc"); + double sample_rand + = parse_double(sentry_value_get_by_key(dsc, "sample_rand")); + if (sample_rand >= 0.0 && sample_rand < 1.0) { + sentry_value_set_by_key( + trace, "sample_rand", sentry_value_new_double(sample_rand)); + return trace; + } + + sentry__generate_sample_rand(trace); + sentry_value_t sampled = sentry_value_get_by_key(trace, "sampled"); + double sample_rate + = parse_double(sentry_value_get_by_key(dsc, "sample_rate")); + if (!sentry_value_is_null(sampled) && sample_rate >= 0.0 + && sample_rate <= 1.0) { + // keep the incoming sampling decision when compared to `sample_rate` + sample_rand = sentry_value_as_double( + sentry_value_get_by_key(trace, "sample_rand")); + sample_rand = sentry_value_is_true(sampled) + ? sample_rand * sample_rate + : sample_rate + sample_rand * (1.0 - sample_rate); + sentry_value_set_by_key( + trace, "sample_rand", sentry_value_new_double(sample_rand)); + } + if (sentry_value_get_length(dsc) > 0) { + sentry_value_set_by_key(dsc, "sample_rand", + sentry_value_incref(sentry_value_get_by_key(trace, "sample_rand"))); + } + return trace; +} + void sentry_transaction_context_update_from_header_n( sentry_transaction_context_t *tx_ctx, const char *key, size_t key_len, @@ -418,14 +472,14 @@ sentry_transaction_context_update_from_header_n( const char sentry_trace[] = "sentry-trace"; const size_t sentry_trace_len = sizeof(sentry_trace) - 1; if (compare_header_key(key, key_len, sentry_trace, sentry_trace_len)) { - parse_sentry_trace(tx_ctx, value, value_len); + parse_sentry_trace(tx_ctx->inner, value, value_len); return; } const char baggage[] = "baggage"; const size_t baggage_len = sizeof(baggage) - 1; if (compare_header_key(key, key_len, baggage, baggage_len)) { - parse_baggage(tx_ctx, value, value_len); + parse_baggage(tx_ctx->inner, value, value_len); return; } } @@ -931,8 +985,8 @@ sentry_transaction_set_status( } } -static void -sentry__span_iter_headers(sentry_value_t span, +void +sentry__span_iter_headers(const sentry_scope_t *scope, sentry_value_t span, sentry_iter_headers_function_t callback, void *userdata) { sentry_value_t trace_id = sentry_value_get_by_key(span, "trace_id"); @@ -945,9 +999,15 @@ sentry__span_iter_headers(sentry_value_t span, // (32 char trace_id)-(16-char span_id)-(0|1) + null terminator char buf[SENTRY_TRACE_LEN + 1]; - snprintf(buf, sizeof(buf), "%s-%s-%s", sentry_value_as_string(trace_id), - sentry_value_as_string(span_id), - sentry_value_is_true(sampled) ? "1" : "0"); + if (sentry_value_is_null(sampled)) { + // deferred sampling decision + snprintf(buf, sizeof(buf), "%s-%s", sentry_value_as_string(trace_id), + sentry_value_as_string(span_id)); + } else { + snprintf(buf, sizeof(buf), "%s-%s-%s", sentry_value_as_string(trace_id), + sentry_value_as_string(span_id), + sentry_value_is_true(sampled) ? "1" : "0"); + } callback("sentry-trace", buf, userdata); // Outgoing baggage: build from the scope DSC (frozen from upstream when @@ -961,9 +1021,7 @@ sentry__span_iter_headers(sentry_value_t span, sentry__stringbuilder_append(&sb, "sentry-trace_id="); sentry__stringbuilder_append(&sb, sentry_value_as_string(trace_id)); - SENTRY_WITH_SCOPE (scope) { - sentry__scope_foreach_dsc(scope, append_baggage_member, &sb); - } + sentry__scope_foreach_dsc(scope, append_baggage_member, &sb); char *baggage = sentry__stringbuilder_into_string(&sb); if (baggage) { @@ -988,20 +1046,24 @@ sentry__span_iter_headers(sentry_value_t span, } void -sentry_span_iter_headers(sentry_span_t *span, +sentry_span_iter_headers(const sentry_span_t *span, sentry_iter_headers_function_t callback, void *userdata) { if (span) { - sentry__span_iter_headers(span->inner, callback, userdata); + SENTRY_WITH_SCOPE (scope) { + sentry__span_iter_headers(scope, span->inner, callback, userdata); + } } } void -sentry_transaction_iter_headers(sentry_transaction_t *tx, +sentry_transaction_iter_headers(const sentry_transaction_t *tx, sentry_iter_headers_function_t callback, void *userdata) { if (tx) { - sentry__span_iter_headers(tx->inner, callback, userdata); + SENTRY_WITH_SCOPE (scope) { + sentry__span_iter_headers(scope, tx->inner, callback, userdata); + } } } diff --git a/src/sentry_tracing.h b/src/sentry_tracing.h index 2c9907794a..c3fd4d051e 100644 --- a/src/sentry_tracing.h +++ b/src/sentry_tracing.h @@ -93,4 +93,21 @@ sentry_value_t sentry__value_get_trace_context(sentry_value_t span); bool sentry__trace_can_continue( sentry_value_t incoming, const sentry_options_t *options); +/** + * Parses incoming `sentry-trace` and `baggage` headers into an object with + * `trace_id`, `parent_span_id`, `sampled`, `sample_rand` and `incoming_dsc`. + * Missing or invalid values are left out, except `sample_rand`, which is + * derived from the incoming sampling decision or generated when missing. + */ +sentry_value_t sentry__parse_trace_headers(const char *sentry_trace, + size_t sentry_trace_len, const char *baggage, size_t baggage_len); + +/** + * Iterates the distributed tracing headers of the given span, or of a + * propagation trace context, with the baggage built from the dynamic sampling + * context of `scope`. The sampled flag is omitted if `span` has none. + */ +void sentry__span_iter_headers(const sentry_scope_t *scope, sentry_value_t span, + sentry_iter_headers_function_t callback, void *userdata); + #endif diff --git a/src/sentry_transport.h b/src/sentry_transport.h index 4c4dd0ef01..afe7fdb463 100644 --- a/src/sentry_transport.h +++ b/src/sentry_transport.h @@ -46,7 +46,7 @@ int sentry__transport_shutdown(sentry_transport_t *transport, uint64_t timeout); /** * This will create a new platform specific HTTP transport. */ -sentry_transport_t *sentry__transport_new_default(void); +sentry_transport_t *sentry_transport_new_default(void); /** * This function will instruct the platform specific transport to dump all the diff --git a/src/sentry_utils.c b/src/sentry_utils.c index 46c76bee20..2df98ed095 100644 --- a/src/sentry_utils.c +++ b/src/sentry_utils.c @@ -143,6 +143,9 @@ sentry__url_parse(sentry_url_t *url_out, const char *url, bool requires_path) tmp = ptr; SKIP_WHILE_NOT(tmp, '/'); aux_buf = sentry__string_clone_n_unchecked(ptr, (size_t)(tmp - ptr)); + if (!aux_buf) { + goto error; + } char *end; url_out->port = (int)strtol(aux_buf, &end, 10); if (end != aux_buf + strlen(aux_buf)) { diff --git a/src/sentry_uuid.c b/src/sentry_uuid.c index ae87a60d09..061552135d 100644 --- a/src/sentry_uuid.c +++ b/src/sentry_uuid.c @@ -192,3 +192,9 @@ sentry__uuid_is_valid(const char *id, size_t len) } return true; } + +bool +sentry__uuid_eq(const sentry_uuid_t *a, const sentry_uuid_t *b) +{ + return memcmp(a->bytes, b->bytes, sizeof(a->bytes)) == 0; +} diff --git a/src/sentry_uuid.h b/src/sentry_uuid.h index 7fe37a6625..c51e7bbec1 100644 --- a/src/sentry_uuid.h +++ b/src/sentry_uuid.h @@ -34,4 +34,9 @@ sentry_uuid_t sentry__uuid_from_native(const GUID *guid); */ bool sentry__uuid_is_valid(const char *id, size_t len); +/** + * True if `a` and `b` are the same UUID. + */ +bool sentry__uuid_eq(const sentry_uuid_t *a, const sentry_uuid_t *b); + #endif diff --git a/src/sentry_value.c b/src/sentry_value.c index b5c7710a10..8333cdc824 100644 --- a/src/sentry_value.c +++ b/src/sentry_value.c @@ -849,32 +849,53 @@ sentry_value_set_by_key(sentry_value_t value, const char *k, sentry_value_t v) return 1; } -char * -sentry__value_remove_and_take_key_n( - sentry_value_t value, const char *k, size_t k_len) +static bool +take_pair(sentry_value_t value, const char *k, size_t k_len, obj_pair_t *out) { if (!k) { - return NULL; + return false; } sentry_slice_t k_slice = { k, k_len }; thing_t *thing = value_as_unfrozen_thing(value); if (!thing || thing_get_type(thing) != THING_TYPE_OBJECT || !thing_detach(thing)) { - return NULL; + return false; } obj_t *o = thing->payload._ptr; for (size_t i = 0; i < o->len; i++) { obj_pair_t *pair = &o->pairs[i]; if (sentry__slice_eqs(k_slice, pair->k)) { - char *key = pair->k; - sentry_value_decref(pair->v); + *out = *pair; memmove(o->pairs + i, o->pairs + i + 1, (o->len - i - 1) * sizeof(o->pairs[0])); o->len--; - return key; + return true; } } - return NULL; + return false; +} + +char * +sentry__value_remove_and_take_key_n( + sentry_value_t value, const char *k, size_t k_len) +{ + obj_pair_t pair; + if (!take_pair(value, k, k_len, &pair)) { + return NULL; + } + sentry_value_decref(pair.v); + return pair.k; +} + +sentry_value_t +sentry__value_take_by_key(sentry_value_t value, const char *k) +{ + obj_pair_t pair; + if (!k || !take_pair(value, k, strlen(k), &pair)) { + return sentry_value_new_null(); + } + sentry_free(pair.k); + return pair.v; } int @@ -1821,42 +1842,6 @@ sentry_value_new_stacktrace(void **ips, size_t len) return stacktrace; } -sentry_value_t -sentry_value_new_user_feedback(const sentry_uuid_t *uuid, const char *name, - const char *email, const char *comments) -{ - SENTRY_SUPPRESS_DEPRECATED - return sentry_value_new_user_feedback_n(uuid, name, - sentry__guarded_strlen(name), email, sentry__guarded_strlen(email), - comments, sentry__guarded_strlen(comments)); - SENTRY_RESTORE_DEPRECATED -} - -sentry_value_t -sentry_value_new_user_feedback_n(const sentry_uuid_t *uuid, const char *name, - size_t name_len, const char *email, size_t email_len, const char *comments, - size_t comments_len) -{ - sentry_value_t rv = sentry_value_new_object(); - - sentry_value_set_by_key(rv, "event_id", sentry__value_new_uuid(uuid)); - - if (name) { - sentry_value_set_by_key( - rv, "name", sentry_value_new_string_n(name, name_len)); - } - if (email) { - sentry_value_set_by_key( - rv, "email", sentry_value_new_string_n(email, email_len)); - } - if (comments) { - sentry_value_set_by_key( - rv, "comments", sentry_value_new_string_n(comments, comments_len)); - } - - return rv; -} - sentry_value_t sentry_value_new_feedback(const char *message, const char *contact_email, const char *name, const sentry_uuid_t *associated_event_id) @@ -1946,14 +1931,6 @@ sentry_value_set_stacktrace(sentry_value_t value, void **ips, size_t len) sentry_value_set_by_key(value, "stacktrace", stacktrace); } -void -sentry_event_value_add_stacktrace(sentry_value_t event, void **ips, size_t len) -{ - sentry_value_t thread = sentry_value_new_object(); - sentry_value_set_stacktrace(thread, ips, len); - sentry_event_add_thread(event, thread); -} - #define SENTRY_MPACK_MAX_DEPTH 64 static sentry_value_t diff --git a/src/sentry_value.h b/src/sentry_value.h index 0ec6830b10..edaf42dead 100644 --- a/src/sentry_value.h +++ b/src/sentry_value.h @@ -92,6 +92,12 @@ void sentry__value_replace(sentry_value_t *target, sentry_value_t value); char *sentry__value_remove_and_take_key_n( sentry_value_t value, const char *key, size_t key_len); +/** + * Removes a value by key and returns it, transferring ownership to the + * caller. Returns a null value if the key does not exist. + */ +sentry_value_t sentry__value_take_by_key(sentry_value_t value, const char *key); + /** * This will parse the Value into a UUID, or return a `nil` UUID on error. * See also `sentry_uuid_from_string`. diff --git a/src/transports/sentry_function_transport.c b/src/transports/sentry_function_transport.c deleted file mode 100644 index 5d801bf257..0000000000 --- a/src/transports/sentry_function_transport.c +++ /dev/null @@ -1,42 +0,0 @@ -#include "sentry_alloc.h" -#include "sentry_core.h" -#include "sentry_envelope.h" -#include "sentry_string.h" -#include "sentry_sync.h" - -struct transport_state { - void (*func)(const sentry_envelope_t *envelope, void *data); - void *data; -}; - -static void -send_envelope_function_transport(sentry_envelope_t *envelope, void *_state) -{ - struct transport_state *state = _state; - state->func(envelope, state->data); - sentry_envelope_free(envelope); -} - -sentry_transport_t * -sentry_new_function_transport( - void (*func)(const sentry_envelope_t *envelope, void *data), void *data) -{ - SENTRY_INFO("initializing function transport"); - struct transport_state *state = SENTRY_MAKE(struct transport_state); - if (!state) { - return NULL; - } - state->func = func; - state->data = data; - - sentry_transport_t *transport - = sentry_transport_new(send_envelope_function_transport); - if (!transport) { - sentry_free(state); - return NULL; - } - sentry_transport_set_state(transport, state); - sentry_transport_set_free_func(transport, sentry_free); - - return transport; -} diff --git a/src/transports/sentry_http_transport.c b/src/transports/sentry_http_transport.c index 99ab08d1fa..dd4c9c8628 100644 --- a/src/transports/sentry_http_transport.c +++ b/src/transports/sentry_http_transport.c @@ -21,11 +21,13 @@ #define ENVELOPE_MIME "application/x-sentry-envelope" #define TUS_MIME "application/offset+octet-stream" -#define TUS_MAX_HTTP_HEADERS 4 +#define TUS_CHUNK_SIZE (32 * 1024 * 1024) // 32 MiB #ifdef SENTRY_TRANSPORT_COMPRESSION # define MAX_HTTP_HEADERS 4 +# define TUS_MAX_HTTP_HEADERS 6 #else # define MAX_HTTP_HEADERS 3 +# define TUS_MAX_HTTP_HEADERS 4 #endif typedef struct { @@ -43,6 +45,9 @@ typedef struct { volatile long shutting_down; sentry_retry_t *retry; volatile long retry_enabled; + volatile long dump_failed; + sentry_mutex_t last_event_lock; + sentry_uuid_t last_event_id; sentry_cache_keep_t cache_keep; sentry_run_t *run; bool send_client_reports; @@ -96,6 +101,23 @@ gzipped_with_compression(const char *body, const size_t body_len, deflateEnd(&stream); return true; } + +static bool +gzipped_file_chunk(const sentry_path_t *path, size_t offset, size_t len, + char **compressed_body, size_t *compressed_body_len) +{ + FILE *file = sentry__path_open(path, "rb", offset); + if (!file) { + return false; + } + char *chunk = sentry_malloc(len); + bool compressed = chunk && fread(chunk, 1, len, file) == len + && gzipped_with_compression( + chunk, len, compressed_body, compressed_body_len); + sentry_free(chunk); + fclose(file); + return compressed; +} #endif sentry_prepared_http_request_t * @@ -270,20 +292,22 @@ prepare_tus_request_common(size_t upload_size, const char *attachment_type, h->key = "upload-length"; h->value = sentry__uint64_to_string((uint64_t)upload_size); - if (!sentry__string_empty(attachment_type)) { - h = &req->headers[req->headers_len++]; - h->key = "upload-metadata"; - h->value = tus_build_upload_metadata(attachment_type); - } + h = &req->headers[req->headers_len++]; + h->key = "upload-metadata"; + h->value = tus_build_upload_metadata(sentry__string_empty(attachment_type) + ? SENTRY_ATTACHMENT_TYPE_GENERIC + : attachment_type); return req; } static sentry_prepared_http_request_t * prepare_tus_upload_request(const char *location, const sentry_path_t *path, - size_t file_size, const sentry_dsn_t *dsn, const char *user_agent) + size_t file_size, size_t upload_offset, size_t body_len, + const sentry_dsn_t *dsn, const char *user_agent) { - if (!location || !path) { + if (!location || !path || upload_offset > file_size + || body_len > file_size - upload_offset) { return NULL; } @@ -304,8 +328,22 @@ prepare_tus_upload_request(const char *location, const sentry_path_t *path, req->method = "PATCH"; req->url = sentry__string_clone(location); - req->body_path = sentry__path_clone(path); - req->body_len = file_size; + + bool compressed = false; +#ifdef SENTRY_TRANSPORT_COMPRESSION + // Compression buffers the chunk in memory, so skip oversized chunks such + // as unchunked uploads. + if (body_len <= TUS_CHUNK_SIZE) { + compressed = gzipped_file_chunk( + path, upload_offset, body_len, &req->body, &req->body_len); + req->body_owned = compressed; + } +#endif + if (!compressed) { + req->body_path = sentry__path_clone(path); + req->body_len = body_len; + req->body_offset = upload_offset; + } sentry_prepared_http_header_t *h; h = &req->headers[req->headers_len++]; @@ -322,7 +360,55 @@ prepare_tus_upload_request(const char *location, const sentry_path_t *path, h = &req->headers[req->headers_len++]; h->key = "upload-offset"; - h->value = sentry__string_clone("0"); + h->value = sentry__uint64_to_string((uint64_t)upload_offset); + +#ifdef SENTRY_TRANSPORT_COMPRESSION + if (compressed) { + h = &req->headers[req->headers_len++]; + h->key = "content-encoding"; + h->value = sentry__string_clone("gzip"); + + h = &req->headers[req->headers_len++]; + h->key = "x-decoded-content-length"; + h->value = sentry__uint64_to_string((uint64_t)body_len); + } +#endif + + return req; +} + +static sentry_prepared_http_request_t * +prepare_tus_offset_request( + const char *location, const sentry_dsn_t *dsn, const char *user_agent) +{ + if (!location) { + return NULL; + } + + sentry_prepared_http_request_t *req + = SENTRY_MAKE(sentry_prepared_http_request_t); + if (!req) { + return NULL; + } + memset(req, 0, sizeof(*req)); + + req->headers = sentry_malloc(sizeof(sentry_prepared_http_header_t) * 2); + if (!req->headers) { + sentry_free(req); + return NULL; + } + + req->method = "HEAD"; + req->url = sentry__string_clone(location); + + sentry_prepared_http_header_t *h; + h = &req->headers[req->headers_len++]; + h->key = "x-sentry-auth"; + h->value = sentry__dsn_get_auth_header(dsn, user_agent); + + h = &req->headers[req->headers_len++]; + h->key = "tus-resumable"; + h->value = sentry__string_clone("1.0.0"); return req; } @@ -333,6 +419,10 @@ http_response_cleanup(sentry_http_response_t *resp) sentry_free(resp->retry_after); sentry_free(resp->x_sentry_rate_limits); sentry_free(resp->location); + sentry_free(resp->upload_offset); + sentry_free(resp->upload_chunk_granularity); + sentry_free(resp->upload_min_chunk_size); + sentry_free(resp->upload_max_chunk_size); } void @@ -357,6 +447,18 @@ sentry_http_response_set_header( } else if (sentry__string_eq(lower_key, "location")) { sentry_free(resp->location); resp->location = sentry__string_clone(value); + } else if (sentry__string_eq(lower_key, "upload-offset")) { + sentry_free(resp->upload_offset); + resp->upload_offset = sentry__string_clone(value); + } else if (sentry__string_eq(lower_key, "upload-chunk-granularity")) { + sentry_free(resp->upload_chunk_granularity); + resp->upload_chunk_granularity = sentry__string_clone(value); + } else if (sentry__string_eq(lower_key, "upload-min-chunk-size")) { + sentry_free(resp->upload_min_chunk_size); + resp->upload_min_chunk_size = sentry__string_clone(value); + } else if (sentry__string_eq(lower_key, "upload-max-chunk-size")) { + sentry_free(resp->upload_max_chunk_size); + resp->upload_max_chunk_size = sentry__string_clone(value); } sentry_free(lower_key); } @@ -436,6 +538,12 @@ sentry_http_request_get_body_file_path( return req->body_path->path; } +size_t +sentry_http_request_get_body_file_offset(const sentry_http_request_t *req) +{ + return req && req->body_path ? req->body_offset : 0; +} + #ifdef SENTRY_PLATFORM_WINDOWS const wchar_t * sentry_http_request_get_body_file_pathw( @@ -458,23 +566,9 @@ enum { RESULT_OK = 0, RESULT_ERROR = -1, RESULT_SHUTDOWN = -2, + RESULT_DISCARD = -3, }; -static int -http_send_request(http_transport_state_t *state, - sentry_prepared_http_request_t *req, sentry_http_response_t *resp) -{ - memset(resp, 0, sizeof(*resp)); - if (!state->send_func(state->client, req, resp)) { - int result = sentry__atomic_fetch(&state->shutting_down) - ? RESULT_SHUTDOWN - : RESULT_ERROR; - http_response_cleanup(resp); - return result; - } - return resp->status_code; -} - static bool http_handle_error(int status_code) { @@ -502,88 +596,244 @@ http_update_ratelimiter( } else if (resp->status_code == 429) { sentry__rate_limiter_update_from_429(state->ratelimiter); } - http_response_cleanup(resp); +} + +static int +http_send_request(http_transport_state_t *state, + sentry_prepared_http_request_t *req, sentry_http_response_t *resp) +{ + memset(resp, 0, sizeof(*resp)); + if (!state->send_func(state->client, req, resp)) { + int result = sentry__atomic_fetch(&state->shutting_down) + ? RESULT_SHUTDOWN + : RESULT_ERROR; + http_response_cleanup(resp); + return result; + } + http_update_ratelimiter(state, resp); + return resp->status_code; +} + +static bool +tus_parse_size(const char *value, size_t max, size_t *size) +{ + if (sentry__string_empty(value) || !size) { + return false; + } + + size_t parsed = 0; + for (const char *p = value; *p; p++) { + if (*p < '0' || *p > '9') { + return false; + } + size_t digit = (size_t)(*p - '0'); + if (parsed > max / 10 || (parsed == max / 10 && digit > max % 10)) { + return false; + } + parsed = parsed * 10 + digit; + } + + *size = parsed; + return true; +} + +static bool +tus_choose_chunk_size(const sentry_http_response_t *resp, size_t *chunk_size) +{ + *chunk_size = 0; + if (!resp->upload_chunk_granularity || !resp->upload_min_chunk_size + || !resp->upload_max_chunk_size) { + return true; + } + + size_t granularity, min, max; + if (!tus_parse_size(resp->upload_chunk_granularity, SIZE_MAX, &granularity) + || !tus_parse_size(resp->upload_min_chunk_size, SIZE_MAX, &min) + || !tus_parse_size(resp->upload_max_chunk_size, SIZE_MAX, &max) + || !granularity || !min || min > max) { + return false; + } + + size_t size = TUS_CHUNK_SIZE; + if (size > max) { + size = max; + } + size -= size % granularity; + if (size < min) { + size_t rem = min % granularity; + if (rem && granularity - rem > max - min) { + return false; + } + size = rem ? min + granularity - rem : min; + } + *chunk_size = size; + return true; +} + +// The upload spec marks 503 and 504 as retryable. +static int +tus_status_result(int status) +{ + if (status == 503 || status == 504) { + return RESULT_ERROR; + } + return status ? status : RESULT_ERROR; } // Perform a TUS upload for the file at / and put the -// resulting remote location URL (caller frees) in `location_out`. +// resulting remote location into the attachment-ref item. static int tus_upload_file(http_transport_state_t *state, const sentry_path_t *cache_path, - const sentry_attachment_ref_t *ref, char **location_out) + sentry_envelope_item_t *item, const sentry_attachment_ref_t *ref) { - *location_out = NULL; sentry_path_t *att_file = sentry__path_join_filename(cache_path, ref->path); if (!att_file || !sentry__path_is_file(att_file) || sentry__path_is_symlink(att_file)) { sentry__path_free(att_file); - return RESULT_ERROR; + return RESULT_DISCARD; } size_t file_size = sentry__path_get_size(att_file); if (file_size == 0) { sentry__path_free(att_file); - return RESULT_ERROR; - } - - // Step 1: TUS creation (POST, no body) - sentry_prepared_http_request_t *req = prepare_tus_request_common( - file_size, ref->attachment_type, state->dsn, state->user_agent); - if (!req) { - sentry__path_free(att_file); - return RESULT_ERROR; + return RESULT_DISCARD; } + size_t upload_offset = 0; + size_t chunk_size = ref->chunk_size; + char *location = NULL; + sentry_prepared_http_request_t *req; sentry_http_response_t resp; - int status_code = http_send_request(state, req, &resp); - sentry__prepared_http_request_free(req); - if (status_code < 0) { - sentry__path_free(att_file); - return status_code; + bool create = sentry__string_empty(ref->location); + if (!create) { + // Step 1a: TUS upload offset (HEAD, no body) + char *upload_url = sentry__dsn_resolve_url(state->dsn, ref->location); + req = prepare_tus_offset_request( + upload_url, state->dsn, state->user_agent); + sentry_free(upload_url); + if (!req) { + sentry__path_free(att_file); + return RESULT_DISCARD; + } + + int status_code = http_send_request(state, req, &resp); + sentry__prepared_http_request_free(req); + if (status_code < 0) { + sentry__path_free(att_file); + return status_code; + } + + bool valid_offset = (resp.status_code == 200 || resp.status_code == 204) + && tus_parse_size(resp.upload_offset, file_size, &upload_offset); + int status = resp.status_code; + http_response_cleanup(&resp); + create = status == 404 || status == 410; + if (!create && !valid_offset) { + sentry__path_free(att_file); + return tus_status_result(status); + } + + if (!create) { + location = sentry__string_clone(ref->location); + } + if (!create && !location) { + sentry__path_free(att_file); + return RESULT_DISCARD; + } } + if (create) { + // Step 1b: TUS creation (POST, no body) + req = prepare_tus_request_common( + file_size, ref->attachment_type, state->dsn, state->user_agent); + if (!req) { + sentry__path_free(att_file); + return RESULT_DISCARD; + } - if (resp.status_code != 201 || !resp.location) { - sentry__path_free(att_file); + int status_code = http_send_request(state, req, &resp); + sentry__prepared_http_request_free(req); + if (status_code < 0) { + sentry__path_free(att_file); + return status_code; + } + + if (resp.status_code != 201 || sentry__string_empty(resp.location)) { + int status = resp.status_code; + sentry__path_free(att_file); + http_response_cleanup(&resp); + return tus_status_result(status); + } + + if (!tus_choose_chunk_size(&resp, &chunk_size)) { + sentry__path_free(att_file); + http_response_cleanup(&resp); + return RESULT_ERROR; + } + + // Record the upload URL so an interrupted PATCH can be resumed. + location = sentry__string_clone(resp.location); http_response_cleanup(&resp); - return RESULT_ERROR; + if (!location + || !sentry__envelope_item_resolve_attachment_ref( + item, ref->path, location, chunk_size)) { + sentry_free(location); + sentry__path_free(att_file); + return RESULT_DISCARD; + } } // Step 2: TUS upload (PATCH with file body). The placeholder needs the // raw `Location` value the TUS endpoint returned (relative path); only the // PATCH itself needs an absolute URL. - char *patch_url = sentry__dsn_resolve_url(state->dsn, resp.location); - char *location = sentry__string_clone(resp.location); - http_response_cleanup(&resp); - if (!location) { - sentry_free(patch_url); - sentry__path_free(att_file); - return RESULT_ERROR; - } - req = prepare_tus_upload_request( - patch_url, att_file, file_size, state->dsn, state->user_agent); - sentry_free(patch_url); - sentry__path_free(att_file); - if (!req) { - sentry_free(location); - return RESULT_ERROR; - } - - status_code = http_send_request(state, req, &resp); - sentry__prepared_http_request_free(req); - if (status_code < 0) { - sentry_free(location); - return status_code; - } - - int status = resp.status_code; - http_response_cleanup(&resp); + char *patch_url = sentry__dsn_resolve_url(state->dsn, location); + sentry_free(location); + int result = RESULT_OK; + // When resuming at the end of the file, an empty PATCH retrieves the + // final attachment Location for the placeholder. + do { + size_t len = file_size - upload_offset; + if (chunk_size && len > chunk_size) { + len = chunk_size; + } + req = prepare_tus_upload_request(patch_url, att_file, file_size, + upload_offset, len, state->dsn, state->user_agent); + if (!req) { + result = RESULT_DISCARD; + break; + } - if (status != 204) { - sentry_free(location); - return RESULT_ERROR; - } + int status = http_send_request(state, req, &resp); + sentry__prepared_http_request_free(req); + if (status < 0) { + result = status; + break; + } - *location_out = location; - return status; + size_t offset; + if (status == 409) { + result = RESULT_ERROR; + } else if (status != 204) { + result = tus_status_result(status); + } else if (!tus_parse_size(resp.upload_offset, file_size, &offset) + || offset < upload_offset || (offset == upload_offset && len) + || (offset == file_size && sentry__string_empty(resp.location))) { + result = RESULT_ERROR; + } else { + upload_offset = offset; + if (upload_offset == file_size + && !sentry__envelope_item_resolve_attachment_ref( + item, NULL, resp.location, 0)) { + result = RESULT_ERROR; + } + } + http_response_cleanup(&resp); + if (result != RESULT_OK) { + break; + } + } while (upload_offset < file_size); + sentry_free(patch_url); + sentry__path_free(att_file); + return result; } // Collect the non-NULL `path` values from every attachment-ref item in the @@ -672,9 +922,10 @@ prune_attachment_refs(const sentry_run_t *run, sentry_value_t paths, } } -// Walk attachment-ref items: for each one with `path` and no `location`, try -// TUS upload and set `location`. If TUS is unavailable or fails for a given -// item, drop it and send the event without the large attachment. +// Walk attachment-ref items: upload new ones and resume previously interrupted +// ones. Local and HTTP errors drop the affected item; recoverable network +// errors and resumable uploads keep the envelope intact for transport retry, +// caching, or shutdown persistence. static int resolve_attachment_refs( http_transport_state_t *state, sentry_envelope_t *envelope) @@ -705,7 +956,8 @@ resolve_attachment_refs( continue; } - if (!sentry__string_empty(ref.location)) { + if (!sentry__string_empty(ref.location) + && sentry__string_empty(ref.path)) { // Crash-resume: TUS already done on a prior attempt. Nothing to do. sentry__attachment_ref_cleanup(&ref); i++; @@ -719,28 +971,26 @@ resolve_attachment_refs( continue; } - char *new_location = NULL; - int result = tus_upload_file(state, cache_path, &ref, &new_location); - if (new_location) { - bool resolved = sentry__envelope_item_resolve_attachment_ref( - item, new_location); - sentry_free(new_location); - if (resolved) { - sentry__attachment_ref_cleanup(&ref); - i++; - continue; - } + int result = tus_upload_file(state, cache_path, item, &ref); + if (result == RESULT_OK) { sentry__attachment_ref_cleanup(&ref); - return RESULT_ERROR; + i++; + continue; } - if (result == RESULT_SHUTDOWN) { + if (result == RESULT_SHUTDOWN + || (result == RESULT_ERROR + && (sentry__atomic_fetch(&state->retry_enabled) + || state->cache_keep))) { sentry__attachment_ref_cleanup(&ref); return result; } sentry__attachment_ref_cleanup(&ref); - sentry__client_report_discard(SENTRY_DISCARD_REASON_SEND_ERROR, - SENTRY_DATA_CATEGORY_ATTACHMENT, 1); + // Relay records outcomes for 429 responses. + if (result != 429) { + sentry__client_report_discard(SENTRY_DISCARD_REASON_SEND_ERROR, + SENTRY_DATA_CATEGORY_ATTACHMENT, 1); + } if (!sentry__envelope_remove_item(envelope, item)) { return RESULT_ERROR; } @@ -785,7 +1035,7 @@ http_send_envelope(sentry_envelope_t *envelope, void *_state) int status_code = http_send_request(state, req, &resp); sentry__prepared_http_request_free(req); if (status_code >= 0) { - http_update_ratelimiter(state, &resp); + http_response_cleanup(&resp); } return status_code; } @@ -831,6 +1081,7 @@ http_transport_state_free(void *_state) sentry__rate_limiter_free(state->ratelimiter); sentry__retry_free(state->retry); sentry__run_free(state->run); + sentry__mutex_free(&state->last_event_lock); sentry_free(state); } @@ -865,6 +1116,10 @@ http_send_task(void *_envelope, void *_state) && sentry__run_write_envelope(state->run, envelope)) { // Keep attachment-ref cache siblings for the persisted envelope. ref_owner = envelope; + } else if (sentry__atomic_fetch(&state->dump_failed) + && sentry__run_write_envelope(state->run, envelope)) { + // Keep attachment-ref cache siblings for the dumped envelope. + ref_owner = envelope; } else if (state->retry && sentry__retry_enqueue(state->retry, envelope)) { // Keep attachment-ref cache siblings for the queued retry envelope. @@ -889,6 +1144,13 @@ http_send_task(void *_envelope, void *_state) } sentry_value_decref(ref_paths); + if (status_code != RESULT_OK && !sentry_uuid_is_nil(&event_id) + && sentry__envelope_has_item_type(envelope, "event")) { + sentry__mutex_lock(&state->last_event_lock); + state->last_event_id = event_id; + sentry__mutex_unlock(&state->last_event_lock); + } + if (status_code == 0 && reported) { sentry__client_report_restore(&report); } else if (status_code >= 0 && http_handle_error(status_code)) { @@ -1055,6 +1317,7 @@ sentry__http_transport_new( state->ratelimiter = sentry__rate_limiter_new(); state->client = client; state->send_func = send_func; + sentry__mutex_init(&state->last_event_lock); sentry_bgworker_t *bgworker = sentry__bgworker_new(state, http_transport_state_free); @@ -1115,6 +1378,29 @@ sentry__http_transport_set_retry_enabled( } } +void +sentry__http_transport_set_dump_failed( + sentry_transport_t *transport, bool enabled) +{ + if (sentry__transport_get_state(transport)) { + sentry__atomic_store( + &http_transport_get_state(transport)->dump_failed, enabled); + } +} + +sentry_uuid_t +sentry__http_transport_get_last_event_id(sentry_transport_t *transport) +{ + sentry_uuid_t event_id = sentry_uuid_nil(); + if (sentry__transport_get_state(transport)) { + http_transport_state_t *state = http_transport_get_state(transport); + sentry__mutex_lock(&state->last_event_lock); + event_id = state->last_event_id; + sentry__mutex_unlock(&state->last_event_lock); + } + return event_id; +} + sentry_transport_t * sentry_http_transport_new(sentry_http_client_factory_func_t factory, void *factory_data, sentry_http_client_send_func_t send_func, @@ -1173,9 +1459,16 @@ sentry__prepare_tus_create_request(size_t file_size, sentry_prepared_http_request_t * sentry__prepare_tus_upload_request(const char *location, - const sentry_path_t *path, size_t file_size, const sentry_dsn_t *dsn, - const char *user_agent) + const sentry_path_t *path, size_t file_size, size_t upload_offset, + size_t body_len, const sentry_dsn_t *dsn, const char *user_agent) { return prepare_tus_upload_request( - location, path, file_size, dsn, user_agent); + location, path, file_size, upload_offset, body_len, dsn, user_agent); +} + +bool +sentry__tus_choose_chunk_size( + const sentry_http_response_t *resp, size_t *chunk_size) +{ + return tus_choose_chunk_size(resp, chunk_size); } diff --git a/src/transports/sentry_http_transport.h b/src/transports/sentry_http_transport.h index 0f2d11c66a..de4dd322e8 100644 --- a/src/transports/sentry_http_transport.h +++ b/src/transports/sentry_http_transport.h @@ -19,6 +19,7 @@ typedef struct sentry_http_request_s { size_t headers_len; char *body; size_t body_len; + size_t body_offset; bool body_owned; sentry_path_t *body_path; } sentry_prepared_http_request_t; @@ -31,7 +32,8 @@ sentry_prepared_http_request_t *sentry__prepare_tus_create_request( const char *user_agent); sentry_prepared_http_request_t *sentry__prepare_tus_upload_request( const char *location, const sentry_path_t *path, size_t file_size, - const sentry_dsn_t *dsn, const char *user_agent); + size_t upload_offset, size_t body_len, const sentry_dsn_t *dsn, + const char *user_agent); void sentry__prepared_http_request_free(sentry_prepared_http_request_t *req); @@ -40,8 +42,15 @@ struct sentry_http_response_s { char *retry_after; char *x_sentry_rate_limits; char *location; + char *upload_offset; + char *upload_chunk_granularity; + char *upload_min_chunk_size; + char *upload_max_chunk_size; }; +bool sentry__tus_choose_chunk_size( + const sentry_http_response_t *resp, size_t *chunk_size); + /** * Creates a new HTTP transport with the given client and send function. * Use the setter functions below to configure optional client callbacks. @@ -62,6 +71,15 @@ void sentry__http_transport_set_shutdown_client( sentry_transport_t *transport, void (*shutdown_client)(void *)); void sentry__http_transport_set_retry_enabled( sentry_transport_t *transport, bool enabled); +void sentry__http_transport_set_dump_failed( + sentry_transport_t *transport, bool enabled); + +/** + * Returns the ID of the last event that the transport sent, successfully or + * not. + */ +sentry_uuid_t sentry__http_transport_get_last_event_id( + sentry_transport_t *transport); #ifdef SENTRY_UNITTEST void *sentry__http_transport_get_bgworker(sentry_transport_t *transport); diff --git a/src/transports/sentry_http_transport_curl.c b/src/transports/sentry_http_transport_curl.c index 32296facb8..fcef16302f 100644 --- a/src/transports/sentry_http_transport_curl.c +++ b/src/transports/sentry_http_transport_curl.c @@ -202,6 +202,7 @@ typedef struct { typedef struct { FILE *file; const sentry_path_t *path; + size_t remaining; } file_body_t; static curl_client_t * @@ -411,10 +412,14 @@ file_read_callback(char *buffer, size_t size, size_t nitems, void *userdata) goto fail; } size_t capacity = size * nitems; + if (capacity > body->remaining) { + capacity = body->remaining; + } size_t read = fread(buffer, 1, capacity, body->file); if (read < capacity && ferror(body->file)) { goto fail; } + body->remaining -= read; return read; fail: @@ -470,19 +475,17 @@ curl_send_task(void *_client, sentry_prepared_http_request_t *req, FILE *body_file = NULL; file_body_t file_body = { 0 }; if (req->body_path) { -#ifdef SENTRY_PLATFORM_WINDOWS - body_file = _wfopen(req->body_path->path_w, L"rb"); -#else - body_file = fopen(req->body_path->path, "rb"); -#endif + body_file = sentry__path_open(req->body_path, "rb", req->body_offset); if (!body_file) { - SENTRY_WARNF("failed to open request body file \"%s\"", - sentry__path_filename(req->body_path)); + SENTRY_WARNF("failed to open request body file \"%s\" at offset " + "%zu", + sentry__path_filename(req->body_path), req->body_offset); g_curl.slist_free_all(headers); return false; } file_body.file = body_file; file_body.path = req->body_path; + file_body.remaining = req->body_len; g_curl.easy_setopt(curl, CURLOPT_UPLOAD, 1L); g_curl.easy_setopt(curl, CURLOPT_CUSTOMREQUEST, req->method); g_curl.easy_setopt(curl, CURLOPT_READFUNCTION, file_read_callback); @@ -491,8 +494,11 @@ curl_send_task(void *_client, sentry_prepared_http_request_t *req, curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)req->body_len); } else if (req->body) { g_curl.easy_setopt(curl, CURLOPT_POST, (long)1); + g_curl.easy_setopt(curl, CURLOPT_CUSTOMREQUEST, req->method); g_curl.easy_setopt(curl, CURLOPT_POSTFIELDS, req->body); g_curl.easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)req->body_len); + } else if (sentry__string_eq(req->method, "HEAD")) { + g_curl.easy_setopt(curl, CURLOPT_NOBODY, 1L); } else { g_curl.easy_setopt(curl, CURLOPT_CUSTOMREQUEST, req->method); } @@ -547,7 +553,7 @@ curl_send_task(void *_client, sentry_prepared_http_request_t *req, } sentry_transport_t * -sentry__transport_new_default(void) +sentry_transport_new_default(void) { SENTRY_INFO("initializing curl transport"); curl_client_t *client = curl_client_new(); diff --git a/src/transports/sentry_http_transport_winhttp.c b/src/transports/sentry_http_transport_winhttp.c index 7562585f18..26b61cc173 100644 --- a/src/transports/sentry_http_transport_winhttp.c +++ b/src/transports/sentry_http_transport_winhttp.c @@ -204,18 +204,22 @@ winhttp_send_task(void *_client, sentry_prepared_http_request_t *req, wchar_t *url = sentry__string_to_wstr(req->url); wchar_t *headers = NULL; + size_t url_len = url ? wcslen(url) : 0; + wchar_t *url_path = sentry_malloc((url_len + 1) * sizeof(wchar_t)); URL_COMPONENTS url_components; wchar_t hostname[128]; - wchar_t url_path[4096]; memset(&url_components, 0, sizeof(URL_COMPONENTS)); url_components.dwStructSize = sizeof(URL_COMPONENTS); url_components.lpszHostName = hostname; url_components.dwHostNameLength = 128; url_components.lpszUrlPath = url_path; - url_components.dwUrlPathLength = 1024; + url_components.dwUrlPathLength = (DWORD)(url_len + 1); - WinHttpCrackUrl(url, 0, 0, &url_components); + if (!url || !url_path || !WinHttpCrackUrl(url, 0, 0, &url_components)) { + SENTRY_WARNF("`WinHttpCrackUrl` failed with code `%d`", GetLastError()); + goto exit; + } #ifdef SENTRY_PLATFORM_XBOX // Ensure Xbox network connectivity is initialized before HTTP requests @@ -285,6 +289,22 @@ winhttp_send_task(void *_client, sentry_prepared_http_request_t *req, goto exit; } + LARGE_INTEGER file_offset; + if (req->body_offset > INT64_MAX) { + SENTRY_WARNF("failed to seek request body file \"%s\"", + sentry__path_filename(req->body_path)); + CloseHandle(hFile); + goto exit; + } + file_offset.QuadPart = (LONGLONG)req->body_offset; + if (!SetFilePointerEx(hFile, file_offset, NULL, FILE_BEGIN)) { + SENTRY_WARNF( + "failed to seek request body file \"%s\" with code `%d`", + sentry__path_filename(req->body_path), GetLastError()); + CloseHandle(hFile); + goto exit; + } + // https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpsendrequest#support-for-greater-than-4-gb-upload DWORD total_length = req->body_len > (size_t)(DWORD)-1 ? WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH @@ -294,8 +314,11 @@ winhttp_send_task(void *_client, sentry_prepared_http_request_t *req, if (result) { char chunk[65536]; DWORD bytes_read = 0; - while (true) { - if (!ReadFile(hFile, chunk, sizeof(chunk), &bytes_read, NULL)) { + size_t remaining = req->body_len; + while (remaining) { + DWORD len = remaining < sizeof(chunk) ? (DWORD)remaining + : sizeof(chunk); + if (!ReadFile(hFile, chunk, len, &bytes_read, NULL)) { SENTRY_WARNF("failed to read request body file \"%s\" " "with code `%d`", sentry__path_filename(req->body_path), GetLastError()); @@ -303,6 +326,7 @@ winhttp_send_task(void *_client, sentry_prepared_http_request_t *req, break; } if (bytes_read == 0) { + result = false; break; } @@ -321,6 +345,7 @@ winhttp_send_task(void *_client, sentry_prepared_http_request_t *req, result = false; break; } + remaining -= bytes_written; } } else { SENTRY_WARNF( @@ -398,6 +423,37 @@ winhttp_send_task(void *_client, sentry_prepared_http_request_t *req, sentry_http_response_set_header(resp, "location", location); sentry_free(location); } + + char *upload_offset = query_header(client->request, L"upload-offset"); + if (upload_offset) { + sentry_http_response_set_header( + resp, "upload-offset", upload_offset); + sentry_free(upload_offset); + } + + char *upload_chunk_granularity + = query_header(client->request, L"upload-chunk-granularity"); + if (upload_chunk_granularity) { + sentry_http_response_set_header( + resp, "upload-chunk-granularity", upload_chunk_granularity); + sentry_free(upload_chunk_granularity); + } + + char *upload_min_chunk_size + = query_header(client->request, L"upload-min-chunk-size"); + if (upload_min_chunk_size) { + sentry_http_response_set_header( + resp, "upload-min-chunk-size", upload_min_chunk_size); + sentry_free(upload_min_chunk_size); + } + + char *upload_max_chunk_size + = query_header(client->request, L"upload-max-chunk-size"); + if (upload_max_chunk_size) { + sentry_http_response_set_header( + resp, "upload-max-chunk-size", upload_max_chunk_size); + sentry_free(upload_max_chunk_size); + } } uint64_t now = sentry__monotonic_time(); @@ -409,12 +465,13 @@ exit:; WinHttpCloseHandle(request); } sentry_free(url); + sentry_free(url_path); sentry_free(headers); return result; } sentry_transport_t * -sentry__transport_new_default(void) +sentry_transport_new_default(void) { SENTRY_INFO("initializing winhttp transport"); winhttp_client_t *client = winhttp_client_new(); diff --git a/src/transports/sentry_transport_none.c b/src/transports/sentry_transport_none.c index 361a947e76..e9553e4cda 100644 --- a/src/transports/sentry_transport_none.c +++ b/src/transports/sentry_transport_none.c @@ -2,7 +2,7 @@ #include "sentry_transport.h" sentry_transport_t * -sentry__transport_new_default(void) +sentry_transport_new_default(void) { return NULL; } diff --git a/src/transports/sentry_transport_stdout.c b/src/transports/sentry_transport_stdout.c new file mode 100644 index 0000000000..530bb10f6a --- /dev/null +++ b/src/transports/sentry_transport_stdout.c @@ -0,0 +1,33 @@ +#include "sentry_core.h" +#include "sentry_transport.h" + +#include + +#ifdef SENTRY_PLATFORM_WINDOWS +# include +# include +#endif + +static void +print_envelope(sentry_envelope_t *envelope, void *unused_state) +{ + (void)unused_state; + size_t size_out = 0; + char *serialized = sentry_envelope_serialize(envelope, &size_out); + if (serialized) { + fwrite(serialized, 1, size_out, stdout); + fflush(stdout); + } + sentry_free(serialized); + sentry_envelope_free(envelope); +} + +sentry_transport_t * +sentry_transport_new_default(void) +{ +#ifdef SENTRY_PLATFORM_WINDOWS + fflush(stdout); + _setmode(_fileno(stdout), _O_BINARY); +#endif + return sentry_transport_new(print_envelope); +} diff --git a/src/unwinder/sentry_unwinder.c b/src/unwinder/sentry_unwinder.c index 420dd1f26e..1d1e5dca51 100644 --- a/src/unwinder/sentry_unwinder.c +++ b/src/unwinder/sentry_unwinder.c @@ -1,6 +1,17 @@ #include "sentry_unwinder.h" #include "sentry_boot.h" +#if defined(SENTRY_WITH_UNWINDER_LIBUNWIND_REMOTE) \ + || defined(SENTRY_WITH_UNWINDER_LIBUNWINDSTACK_REMOTE) +# include "sentry_logger.h" + +# include +# include +# include +# include +# include +#endif + #define DEFINE_UNWINDER(Func) \ size_t sentry__unwind_stack_##Func(void *addr, \ const sentry_ucontext_t *uctx, void **ptrs, size_t max_frames) @@ -25,19 +36,21 @@ void sentry__unwind_init_libunwindstack(void); #if defined(SENTRY_PLATFORM_LINUX) # define DEFINE_THREAD_UNWINDER(Func) \ size_t sentry__unwind_stack_from_thread_##Func(pid_t tid, \ - sentry_remote_frame_t *frames, size_t max_frames, \ - sentry_remote_registers_t *registers, bool symbolize) + const ucontext_t *context, sentry_remote_frame_t *frames, \ + size_t max_frames, sentry_remote_registers_t *registers, \ + bool symbolize) # define TRY_THREAD_UNWINDER(Func) \ do { \ size_t rv = sentry__unwind_stack_from_thread_##Func( \ - tid, frames, max_frames, registers, symbolize); \ + tid, context, frames, max_frames, registers, symbolize); \ if (rv > 0) { \ return rv; \ } \ } while (0) DEFINE_THREAD_UNWINDER(libunwind_remote); +DEFINE_THREAD_UNWINDER(libunwindstack_remote); #endif static size_t @@ -80,19 +93,75 @@ sentry_unwind_stack_from_ucontext( #if defined(SENTRY_PLATFORM_LINUX) size_t -sentry__unwind_stack_from_thread(pid_t tid, sentry_remote_frame_t *frames, - size_t max_frames, sentry_remote_registers_t *registers, bool symbolize) +sentry__unwind_stack_from_thread(pid_t tid, const ucontext_t *context, + sentry_remote_frame_t *frames, size_t max_frames, + sentry_remote_registers_t *registers, bool symbolize) { (void)tid; + (void)context; (void)frames; (void)max_frames; (void)registers; (void)symbolize; # ifdef SENTRY_WITH_UNWINDER_LIBUNWIND_REMOTE TRY_THREAD_UNWINDER(libunwind_remote); +# endif +# ifdef SENTRY_WITH_UNWINDER_LIBUNWINDSTACK_REMOTE + TRY_THREAD_UNWINDER(libunwindstack_remote); # endif return 0; } + +# if defined(SENTRY_WITH_UNWINDER_LIBUNWIND_REMOTE) \ + || defined(SENTRY_WITH_UNWINDER_LIBUNWINDSTACK_REMOTE) +/** + * Attach to a thread of another process and wait until it stops. + * Returns false, leaving the thread detached, if either fails. + */ +bool +sentry__ptrace_attach_thread(pid_t tid) +{ + if (ptrace(PTRACE_ATTACH, tid, NULL, NULL) != 0) { + SENTRY_WARNF("remote_unwind: ptrace attach failed for %d: %s", tid, + strerror(errno)); + return false; + } + + // Poll with WNOHANG to avoid hanging on threads in D state. PTRACE_ATTACH + // sends SIGSTOP but the thread won't stop until it leaves uninterruptible + // sleep, which may never happen. + int status = 0; + int retries = 20; + for (;;) { + pid_t waited = waitpid(tid, &status, __WALL | WNOHANG); + if (waited == tid) { + break; + } + if (waited < 0) { + SENTRY_WARNF("remote_unwind: waitpid failed for %d: %s", tid, + strerror(errno)); + ptrace(PTRACE_DETACH, tid, NULL, NULL); + return false; + } + if (--retries <= 0) { + SENTRY_WARNF("remote_unwind: waitpid timed out for %d", tid); + ptrace(PTRACE_DETACH, tid, NULL, NULL); + return false; + } + usleep(100000); + } + + if (!WIFSTOPPED(status)) { + SENTRY_WARNF( + "remote_unwind: thread %d did not stop after attach: status=%d", + tid, status); + ptrace(PTRACE_DETACH, tid, NULL, NULL); + return false; + } + + return true; +} +# endif #endif void diff --git a/src/unwinder/sentry_unwinder.h b/src/unwinder/sentry_unwinder.h index 047ab6fc10..9249010a24 100644 --- a/src/unwinder/sentry_unwinder.h +++ b/src/unwinder/sentry_unwinder.h @@ -34,10 +34,16 @@ typedef struct { sentry_remote_register_t values[SENTRY_REMOTE_UNWIND_MAX_REGISTERS]; } sentry_remote_registers_t; -size_t sentry__unwind_stack_from_thread(pid_t tid, +/** + * Unwinds a thread of another process. Attaches to the thread, or unwinds its + * saved `context` if given. Returns 0 if no unwinder supports `context`. + */ +size_t sentry__unwind_stack_from_thread(pid_t tid, const ucontext_t *context, sentry_remote_frame_t *frames, size_t max_frames, sentry_remote_registers_t *registers, bool symbolize); +bool sentry__ptrace_attach_thread(pid_t tid); + #endif /** diff --git a/src/unwinder/sentry_unwinder_dbghelp.c b/src/unwinder/sentry_unwinder_dbghelp.c index 82c344e3bf..ff28727de8 100644 --- a/src/unwinder/sentry_unwinder_dbghelp.c +++ b/src/unwinder/sentry_unwinder_dbghelp.c @@ -10,6 +10,7 @@ typedef WORD(NTAPI *RtlCaptureStackBackTraceProc)(DWORD FramesToSkip, #ifdef __clang__ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wmissing-prototypes" +# pragma clang diagnostic ignored "-Wlanguage-extension-token" #endif size_t @@ -41,6 +42,90 @@ sentry__unwind_stack_dbghelp( #endif } +#if (defined(_MSC_VER) || defined(__clang__)) \ + && (defined(_M_AMD64) || defined(_M_ARM64)) + if (!addr) { + // unwind tables without DbgHelp or symbol loading + CONTEXT walk = *uctx->exception_ptrs.ContextRecord; +# if defined(_M_ARM64) + DWORD64 *ip = &walk.Pc; + DWORD64 *sp = &walk.Sp; +# else + DWORD64 *ip = &walk.Rip; + DWORD64 *sp = &walk.Rsp; +# endif + size_t size = 0; + if (size < max_frames) { + ptrs[size++] = (void *)(uintptr_t)*ip; + } else { + return 0; + } + while (size < max_frames) { + DWORD64 control_pc = *ip; +# if defined(_M_ARM64) + // use the call instruction for lookup, keeping frame PCs unadjusted + if (walk.ContextFlags & CONTEXT_UNWOUND_TO_CALL) { + control_pc -= 4; + } + DWORD64 previous_ip = *ip; +# endif + DWORD64 image_base = 0; + PRUNTIME_FUNCTION entry = NULL; + __try { + entry = RtlLookupFunctionEntry(control_pc, &image_base, NULL); + } __except (EXCEPTION_EXECUTE_HANDLER) { + break; + } + DWORD64 previous_sp = *sp; + if (entry) { + PVOID handler_data = NULL; + DWORD64 establisher = 0; + __try { + RtlVirtualUnwind(UNW_FLAG_NHANDLER, image_base, control_pc, + entry, &walk, &handler_data, &establisher, NULL); + } __except (EXCEPTION_EXECUTE_HANDLER) { + break; + } + } else { +# if defined(_M_ARM64) + walk.Pc = walk.Lr; + walk.ContextFlags |= CONTEXT_UNWOUND_TO_CALL; +# else + DWORD64 ret = 0; + SIZE_T read = 0; + if (!ReadProcessMemory(GetCurrentProcess(), (void *)walk.Rsp, + &ret, sizeof(ret), &read) + || read != sizeof(ret)) { + break; + } + walk.Rip = ret; + walk.Rsp += sizeof(ret); +# endif + } + if (!*ip) { + break; + } + if (*ip < 0x1000 +# if defined(_M_AMD64) + || *ip > 0x00007FFFFFFFFFFFULL +# endif + ) { + break; + } +# if defined(_M_ARM64) + if (*sp < previous_sp + || (*sp == previous_sp && *ip == previous_ip)) { +# else + if (*sp <= previous_sp) { +# endif + break; + } + ptrs[size++] = (void *)(uintptr_t)*ip; + } + return size; + } +#endif + sentry__init_dbghelp(); CONTEXT ctx = *uctx->exception_ptrs.ContextRecord; @@ -80,7 +165,7 @@ sentry__unwind_stack_dbghelp( stack_frame.AddrStack.Mode = AddrModeFlat; if (addr) { - stack_frame.AddrPC.Offset = (DWORD64)addr; + stack_frame.AddrPC.Offset = (DWORD64)(uintptr_t)addr; } while (StackWalk64(machine_type, GetCurrentProcess(), GetCurrentThread(), diff --git a/src/unwinder/sentry_unwinder_libunwind.c b/src/unwinder/sentry_unwinder_libunwind.c index 9a154608c8..0217325e8d 100644 --- a/src/unwinder/sentry_unwinder_libunwind.c +++ b/src/unwinder/sentry_unwinder_libunwind.c @@ -1,5 +1,4 @@ #include "sentry_boot.h" -#include "sentry_logger.h" #include "sentry_unwinder.h" #define UNW_LOCAL_ONLY #include @@ -65,7 +64,7 @@ static bool find_mem_range_from_fd(int fd, uintptr_t ptr, mem_range_t *range) { - char buf[4096]; + char buf[512]; size_t carry = 0; bool skip_to_nl = false; // true while discarding an oversized line's tail @@ -156,28 +155,24 @@ sentry__unwind_stack_libunwind( int ret = unw_init_local2(&cursor, (unw_context_t *)uctx->user_context, UNW_INIT_SIGNAL_FRAME); if (ret != 0) { - SENTRY_WARN("Failed to initialize libunwind with ucontext"); return 0; } } else { -#ifdef __clang__ +#ifdef __GNUC__ // This pragma is required to build with Werror on ARM64 Ubuntu -# pragma clang diagnostic push -# pragma clang diagnostic ignored \ - "-Wgnu-statement-expression-from-macro-expansion" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wpedantic" #endif int ret = unw_getcontext(&uc); -#ifdef __clang__ -# pragma clang diagnostic pop +#ifdef __GNUC__ +# pragma GCC diagnostic pop #endif if (ret != 0) { - SENTRY_WARN("Failed to retrieve context with libunwind"); return 0; } ret = unw_init_local(&cursor, &uc); if (ret != 0) { - SENTRY_WARN("Failed to initialize libunwind with local context"); return 0; } } @@ -203,9 +198,6 @@ sentry__unwind_stack_libunwind( // ensure we have a valid stack pointer otherwise we only send the top frame mem_range_t stack = { 0, 0 }; if (uctx && !find_mem_range((uintptr_t)sp, &stack)) { - SENTRY_WARNF("unwinder: SP (%p) is in unmapped memory likely due to " - "stack overflow", - (void *)sp); return n; } diff --git a/src/unwinder/sentry_unwinder_libunwind_mac.c b/src/unwinder/sentry_unwinder_libunwind_mac.c index 668a0bda20..a3c74bcb41 100644 --- a/src/unwinder/sentry_unwinder_libunwind_mac.c +++ b/src/unwinder/sentry_unwinder_libunwind_mac.c @@ -98,6 +98,26 @@ valid_ptr(uintptr_t p, mem_range_t *cache) #endif } +static bool +read_frame(uintptr_t p, uintptr_t record[2], mem_range_t *cache) +{ + if (!valid_ptr(p, cache)) { + return false; + } +#if defined(SENTRY_PLATFORM_MACOS) + mach_vm_size_t size = 0; + return mach_vm_read_overwrite(mach_task_self(), p, 2 * sizeof(uintptr_t), + (mach_vm_address_t)record, &size) + == KERN_SUCCESS + && size == 2 * sizeof(uintptr_t); +#else + const uintptr_t *frame = (uintptr_t *)p; + record[0] = frame[0]; + record[1] = frame[1]; + return true; +#endif +} + /** * This does the same frame-pointer walk for arm64 and x86_64, with the only * difference being which registers value is used as frame-pointer (fp vs rbp) @@ -107,14 +127,14 @@ fp_walk( uintptr_t fp, size_t *n, void **ptrs, size_t max_frames, mem_range_t *cache) { while (*n < max_frames) { - if (!valid_ptr(fp, cache)) { + uintptr_t record[2]; + if (!read_frame(fp, record, cache)) { break; } // arm64 frame record layout: [prev_fp, saved_lr] at fp and fp+8 // x86_64 frame record layout: [prev_rbp, saved_retaddr] at bp and bp+8 - const uintptr_t *record = (uintptr_t *)fp; - const uintptr_t next_fp = record[0]; + const uintptr_t next_fp = STRIP_PAC(record[0]); uintptr_t ret_addr = record[1]; if (!valid_ptr(next_fp, cache) || !ret_addr) { break; @@ -138,20 +158,20 @@ fp_walk_from_uctx(const sentry_ucontext_t *uctx, void **ptrs, size_t max_frames) #if defined(__arm64__) uintptr_t pc, fp, lr; -# if defined(__arm64e__) - // arm64e uses opaque accessors that handle PAC authentication +# if __DARWIN_OPAQUE_ARM_THREAD_STATE64 + // opaque state uses accessors that handle PAC authentication pc = __darwin_arm_thread_state64_get_pc(mctx->__ss); fp = __darwin_arm_thread_state64_get_fp(mctx->__ss); lr = __darwin_arm_thread_state64_get_lr(mctx->__ss); # else // arm64 can access members directly, strip PAC defensively pc = STRIP_PAC((uintptr_t)mctx->__ss.__pc); - fp = (uintptr_t)mctx->__ss.__fp; + fp = STRIP_PAC((uintptr_t)mctx->__ss.__fp); lr = STRIP_PAC((uintptr_t)mctx->__ss.__lr); # endif // top frame: crash PC points to the faulting instruction, no adjustment - if (pc && n < max_frames) { + if (n < max_frames) { ptrs[n++] = (void *)pc; } @@ -174,11 +194,11 @@ fp_walk_from_uctx(const sentry_ucontext_t *uctx, void **ptrs, size_t max_frames) // it sub-calls (LR is a stale return within the crashing function). // // In both cases, walking from fp captures the correct remaining frames. - if (valid_ptr(fp, &cache)) { - const uintptr_t *record = (uintptr_t *)fp; + uintptr_t record[2]; + if (read_frame(fp, record, &cache)) { uintptr_t saved_lr = STRIP_PAC(record[1]); if (lr == saved_lr) { - fp_walk(record[0], &n, ptrs, max_frames, &cache); + fp_walk(STRIP_PAC(record[0]), &n, ptrs, max_frames, &cache); } else { fp_walk(fp, &n, ptrs, max_frames, &cache); } @@ -188,7 +208,7 @@ fp_walk_from_uctx(const sentry_ucontext_t *uctx, void **ptrs, size_t max_frames) uintptr_t bp = (uintptr_t)mctx->__ss.__rbp; // top frame: no adjustment - if (ip && n < max_frames) { + if (n < max_frames) { ptrs[n++] = (void *)ip; } diff --git a/src/unwinder/sentry_unwinder_libunwind_remote.c b/src/unwinder/sentry_unwinder_libunwind_remote.c index ca99aa7d53..3991d1d284 100644 --- a/src/unwinder/sentry_unwinder_libunwind_remote.c +++ b/src/unwinder/sentry_unwinder_libunwind_remote.c @@ -15,11 +15,8 @@ # include "sentry_logger.h" -# include # include # include -# include -# include # include # include @@ -71,48 +68,15 @@ capture_registers(unw_cursor_t *cursor, sentry_remote_registers_t *registers) size_t sentry__unwind_stack_from_thread_libunwind_remote(pid_t tid, - sentry_remote_frame_t *frames, size_t max_frames, + const ucontext_t *context, sentry_remote_frame_t *frames, size_t max_frames, sentry_remote_registers_t *registers, bool symbolize) { if (registers) { memset(registers, 0, sizeof(*registers)); } - if (ptrace(PTRACE_ATTACH, tid, NULL, NULL) != 0) { - SENTRY_WARNF("remote_unwind: ptrace attach failed for %d: %s", tid, - strerror(errno)); - return 0; - } - - // Poll with WNOHANG to avoid hanging on threads in D state. PTRACE_ATTACH - // sends SIGSTOP but the thread won't stop until it leaves uninterruptible - // sleep, which may never happen. - int status = 0; - int retries = 20; - for (;;) { - pid_t waited = waitpid(tid, &status, __WALL | WNOHANG); - if (waited == tid) { - break; - } - if (waited < 0) { - SENTRY_WARNF("remote_unwind: waitpid failed for %d: %s", tid, - strerror(errno)); - ptrace(PTRACE_DETACH, tid, NULL, NULL); - return 0; - } - if (--retries <= 0) { - SENTRY_WARNF("remote_unwind: waitpid timed out for %d", tid); - ptrace(PTRACE_DETACH, tid, NULL, NULL); - return 0; - } - usleep(100000); - } - - if (!WIFSTOPPED(status)) { - SENTRY_WARNF( - "remote_unwind: thread %d did not stop after attach: status=%d", - tid, status); - ptrace(PTRACE_DETACH, tid, NULL, NULL); + // libunwind only unwinds attached threads + if (context || !sentry__ptrace_attach_thread(tid)) { return 0; } @@ -185,10 +149,11 @@ sentry__unwind_stack_from_thread_libunwind_remote(pid_t tid, size_t sentry__unwind_stack_from_thread_libunwind_remote(pid_t tid, - sentry_remote_frame_t *frames, size_t max_frames, + const ucontext_t *context, sentry_remote_frame_t *frames, size_t max_frames, sentry_remote_registers_t *registers, bool symbolize) { (void)tid; + (void)context; (void)frames; (void)max_frames; (void)registers; diff --git a/src/unwinder/sentry_unwinder_libunwindstack_remote.cpp b/src/unwinder/sentry_unwinder_libunwindstack_remote.cpp new file mode 100644 index 0000000000..97af578e9c --- /dev/null +++ b/src/unwinder/sentry_unwinder_libunwindstack_remote.cpp @@ -0,0 +1,130 @@ +extern "C" { +#include "sentry_boot.h" +#include "sentry_logger.h" +#include "sentry_unwinder.h" +} + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void +capture_registers(unwindstack::Regs *regs, sentry_remote_registers_t *registers) +{ + regs->IterateRegisters([registers](const char *name, uint64_t value) { + size_t len = strlen(name); + if (registers->count >= SENTRY_REMOTE_UNWIND_MAX_REGISTERS || len == 0 + || len >= sizeof(registers->values[0].name)) { + return; + } + sentry_remote_register_t *remote_register + = ®isters->values[registers->count++]; + memcpy(remote_register->name, name, len + 1); + remote_register->value = value; + }); +} + +static size_t +unwind_thread(pid_t tid, const ucontext_t *context, + sentry_remote_frame_t *frames, size_t max_frames, + sentry_remote_registers_t *registers, bool symbolize) +{ + // an uncaught exception, e.g. std::bad_alloc, would abort the daemon + try { + std::unique_ptr regs(context + ? unwindstack::Regs::CreateFromUcontext( + unwindstack::Regs::CurrentArch(), + const_cast(context)) + : unwindstack::Regs::RemoteGet(tid)); + if (!regs) { + SENTRY_WARNF("libunwindstack failed to read registers of %d", tid); + return 0; + } + if (registers) { + capture_registers(regs.get(), registers); + } + + unwindstack::RemoteMaps maps(tid); + if (!maps.Parse()) { + SENTRY_WARNF("libunwindstack failed to parse /proc/%d/maps", tid); + return 0; + } + + std::shared_ptr process_memory + = unwindstack::Memory::CreateProcessMemoryCached(tid); + if (!process_memory) { + SENTRY_WARNF( + "libunwindstack failed to read process memory for %d", tid); + return 0; + } + + unwindstack::Unwinder unwinder( + max_frames, &maps, regs.get(), process_memory); + unwinder.SetResolveNames(symbolize); + unwinder.Unwind(); + + if (unwinder.LastErrorCode() != unwindstack::ERROR_NONE) { + SENTRY_DEBUGF("libunwindstack finished with %s at 0x%llx", + unwinder.LastErrorCodeString(), + (unsigned long long)unwinder.LastErrorAddress()); + } + + size_t count = 0; + for (const unwindstack::FrameData &frame : unwinder.frames()) { + if (count >= max_frames) { + break; + } + frames[count].ip = frame.pc; + frames[count].symbol[0] = '\0'; + frames[count].symbol_offset = 0; + if (!frame.function_name.empty()) { + snprintf(frames[count].symbol, sizeof(frames[count].symbol), + "%s", frame.function_name.c_str()); + frames[count].symbol_offset = frame.function_offset; + } + count++; + } + + SENTRY_DEBUGF( + "libunwindstack remote unwind captured %zu frames", count); + return count; + } catch (...) { + SENTRY_WARN("libunwindstack failed with an exception"); + return 0; + } +} + +extern "C" size_t +sentry__unwind_stack_from_thread_libunwindstack_remote(pid_t tid, + const ucontext_t *context, sentry_remote_frame_t *frames, size_t max_frames, + sentry_remote_registers_t *registers, bool symbolize) +{ + if (registers) { + registers->count = 0; + } + + if (tid <= 0 || !frames || max_frames == 0) { + return 0; + } + + if (context) { + return unwind_thread( + tid, context, frames, max_frames, registers, symbolize); + } + + if (!sentry__ptrace_attach_thread(tid)) { + return 0; + } + + size_t count + = unwind_thread(tid, NULL, frames, max_frames, registers, symbolize); + + ptrace(PTRACE_DETACH, tid, NULL, NULL); + return count; +} diff --git a/tests/__init__.py b/tests/__init__.py index e7103c9887..7e50e691b3 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -45,7 +45,8 @@ def run_command(name): # https://docs.pytest.org/en/latest/assert.html#assert-details pytest.register_assert_rewrite("tests.assertions") -SENTRY_VERSION = "0.17.6" +SENTRY_VERSION = "1.0.0-beta.1" +SENTRY_VERSION_BASE = SENTRY_VERSION.split("-", 1)[0] # must match the fixed id set by the example's "replay-context" arg REPLAY_ID = "deadbeefdeadbeefdeadbeefdeadbeef" @@ -299,12 +300,10 @@ def run( ) from None -def run_crash(tmp_path, exe, args, env, **kwargs): +def crash_env(env): """ - Run a crash test. - - When running under ASAN, we configure it to not intercept crash signals - so that our native crash handler can run and capture the crash. + Configure ASAN to not intercept crash signals, so that our native crash + handler can run and capture the crash. """ # When running under ASAN, disable ASAN's signal handling so our crash # handler can run. ASAN would otherwise intercept SIGSEGV/SIGABRT/etc @@ -321,8 +320,17 @@ def run_crash(tmp_path, exe, args, env, **kwargs): env = dict(env, ASAN_OPTIONS=f"{asan_opts}:{asan_signal_opts}") else: env = dict(env, ASAN_OPTIONS=asan_signal_opts) + return env + - run(tmp_path, exe, args, expect_failure=True, env=env, **kwargs) +def run_crash(tmp_path, exe, args, env, **kwargs): + """ + Run a crash test. + + When running under ASAN, we configure it to not intercept crash signals + so that our native crash handler can run and capture the crash. + """ + run(tmp_path, exe, args, expect_failure=True, env=crash_env(env), **kwargs) def check_output(*args, **kwargs): diff --git a/tests/assertions.py b/tests/assertions.py index 2b855f487a..2052aef9dc 100644 --- a/tests/assertions.py +++ b/tests/assertions.py @@ -13,7 +13,7 @@ import msgpack from . import REPLAY_ID, SENTRY_VERSION -from .conditions import is_android, is_asan, is_tsan, is_wine +from .conditions import is_android, is_asan, is_tsan VERSION_RE = re.compile(r"(\d+\.\d+\.\d+)[-.]?(.*)") @@ -22,6 +22,31 @@ ) +OS_RELEASE_PATHS = [ + "/run/host/etc/os-release", + "/run/host/usr/lib/os-release", + "/run/host/os-release", + "/etc/os-release", + "/usr/lib/os-release", +] + + +def read_os_release(): + for path in OS_RELEASE_PATHS: + try: + with open(path) as f: + lines = f.read().splitlines() + except OSError: + continue + fields = {} + for line in lines: + key, sep, value = line.partition("=") + if sep: + fields[key] = value.strip('"') + return fields + return {} + + def matches(actual, expected): return {k: v for (k, v) in actual.items() if k in expected.keys()} == expected @@ -64,18 +89,6 @@ def assert_user_feedback(envelope): assert user_feedback["message"] == "some-message" -def assert_user_report(envelope): - user_report = None - for item in envelope: - if item.headers.get("type") == "user_report" and item.payload.json is not None: - user_report = item.payload.json - - assert user_report is not None - assert user_report["name"] == "some-name" - assert user_report["email"] == "some-email" - assert user_report["comments"] == "some-comment" - - def assert_meta( envelope, release="test-example-release", @@ -131,11 +144,11 @@ def assert_event_meta( if is_android: expected_sdk["name"] = "sentry.native.android" else: - if sys.platform == "win32" or is_wine: - expected_os_context = {"name": "Windows"} - if not is_wine: - expected_os_context["version"] = platform.version() - assert_matches(event["contexts"]["os"], expected_os_context) + if sys.platform == "win32": + assert_matches( + event["contexts"]["os"], + {"name": "Windows", "version": platform.version()}, + ) assert event["contexts"]["os"]["version"] is not None assert event["contexts"]["os"]["build"] is not None elif sys.platform == "linux": @@ -143,13 +156,26 @@ def assert_event_meta( match = VERSION_RE.match(version) version = match.group(1) build = match.group(2) - expected_os_context = {"name": "Linux", "version": version} - if build: - expected_os_context["build"] = build - - assert_matches(event["contexts"]["os"], expected_os_context) - assert "distribution_name" in event["contexts"]["os"] - assert "distribution_version" in event["contexts"]["os"] + os_release = read_os_release() + if os_release.get("ID") in ("steamos", "bazzite"): + expected_os_context = { + "name": os_release.get("NAME", os_release["ID"]), + "version": os_release.get("VERSION_ID", version), + "kernel_version": platform.release(), + } + if "BUILD_ID" in os_release: + expected_os_context["build"] = os_release["BUILD_ID"] + + assert_matches(event["contexts"]["os"], expected_os_context) + assert "distribution_name" not in event["contexts"]["os"] + else: + expected_os_context = {"name": "Linux", "version": version} + if build: + expected_os_context["build"] = build + + assert_matches(event["contexts"]["os"], expected_os_context) + assert "distribution_name" in event["contexts"]["os"] + assert "distribution_version" in event["contexts"]["os"] elif sys.platform == "darwin": version = platform.mac_ver()[0].split(".") if len(version) < 3: @@ -194,6 +220,8 @@ def assert_event_meta( "sentry_test_integration" in image["code_file"] for image in event["debug_meta"]["images"] ) + elif event.get("type") == "transaction": + assert "debug_meta" not in event def assert_debug_meta_images_do_not_overlap(event): @@ -455,6 +483,7 @@ def assert_exception(envelope): def assert_inproc_crash(envelope): event = envelope.get_event() assert_matches(event, {"level": "fatal"}) + assert event["debug_meta"]["images"] # depending on the unwinder, we currently don’t get any stack frames from # a `ucontext` assert_stacktrace(envelope, inside_exception=True, check_size=False) @@ -498,6 +527,23 @@ def assert_no_before_send(envelope): assert ("adapted_by", "before_send") not in event.items() +def assert_crash_hint_attachments(envelope, callback): + assert not any( + item.headers.get("filename") in ("CMakeCache.txt", "bytes.bin") + for item in envelope + ) + filename = callback.replace("-", "_") + ".json" + snapshot = json.loads( + next( + item.payload.bytes + for item in envelope + if item.headers.get("filename") == filename + ) + ) + assert snapshot["level"] == "fatal" + return snapshot + + def assert_before_breadcrumb(envelope): event = envelope.get_event() breadcrumbs = event.get("breadcrumbs", []) @@ -556,7 +602,7 @@ def _load_crashpad_attachments(msg): cmake_cache = len(part.get_payload(decode=True)) case "bytes.bin": bytes_bin = part.get_payload(decode=True) - case "callback.txt": + case "before_send.json" | "on_crash.json": callback = part.get_payload(decode=True) if ( @@ -610,6 +656,7 @@ def assert_crashpad_upload( expect_breadcrumbs=True, expect_default_scope=True, breadcrumb_count=0, + expect_byte_attachment=None, ): multipart = gzip.decompress(req.get_data()) msg = email.message_from_bytes(bytes(str(req.headers), encoding="utf8") + multipart) @@ -624,9 +671,13 @@ def assert_crashpad_upload( assert_event_meta(attachments.event, integrations=["crashpad"]) if expect_attachment: assert attachments.cmake_cache > 0 - assert attachments.bytes_bin == b"\xc0\xff\xee" else: assert attachments.cmake_cache == -1 + if expect_byte_attachment is None: + expect_byte_attachment = expect_attachment + if expect_byte_attachment: + assert attachments.bytes_bin == b"\xc0\xff\xee" + else: assert attachments.bytes_bin == None if expect_view_hierarchy: assert_attachment_content_view_hierarchy(attachments.view_hierarchy) @@ -874,3 +925,17 @@ def assert_replay_envelope(envelope, video, replay_id=REPLAY_ID): assert crumbs[2]["category"] == "something else" assert body["replay_video"] == video + + +def assert_crash_stack(event): + assert event["level"] == "fatal" + stack = event["exception"]["values"][0]["stacktrace"] + ips = [int(frame["instruction_addr"], 16) for frame in stack["frames"]] + assert ips and all(ip >= 0x1000 for ip in ips[:-1]) + assert ips[-1] == 0 or ips[-1] >= 0x1000 + registers = stack["registers"] + register = next(key for key in ("rip", "eip", "pc") if key in registers) + assert ips[-1] == int(registers[register], 16) + # ARM32 frame-pointer fallback can provide only the faulting instruction + if "pc" not in registers or "x0" in registers: + assert len(ips) > 1 diff --git a/tests/build_config.py b/tests/build_config.py index b0ecec3f3f..7049b8e091 100644 --- a/tests/build_config.py +++ b/tests/build_config.py @@ -44,6 +44,7 @@ def get_platform_cmake_args(): - 32-bit builds (TEST_X86) - Wine cross-builds (TEST_WINE) - ASAN/TSAN sanitizers (RUN_ANALYZER) + - ERROR_ON_WARNINGS -> SENTRY_ERROR_ON_WARNINGS - Additional CMAKE_DEFINES from environment """ args = [] @@ -62,10 +63,23 @@ def get_platform_cmake_args(): "-DCMAKE_ASM_COMPILER=arm-linux-gnueabihf-gcc", ] ) + elif sys.platform == "linux" and os.environ.get("TEST_RISCV"): + args.extend( + [ + "-DCMAKE_SYSTEM_NAME=Linux", + "-DCMAKE_SYSTEM_PROCESSOR=riscv64", + "-DCMAKE_C_COMPILER=riscv64-linux-gnu-gcc", + "-DCMAKE_CXX_COMPILER=riscv64-linux-gnu-g++", + "-DCMAKE_ASM_COMPILER=riscv64-linux-gnu-gcc", + ] + ) elif sys.platform == "linux" and os.environ.get("TEST_WINE"): cc = os.environ.get("CC") or "clang" cxx = os.environ.get("CXX") or "clang++" - linker_flags = "-fuse-ld=lld -static-libgcc -static-libstdc++" + linker_flags = ( + "-fuse-ld=lld -static-libgcc -static-libstdc++ " + "-Wno-unused-command-line-argument" + ) args.extend( [ "-DCMAKE_SYSTEM_NAME=Windows", @@ -87,6 +101,9 @@ def get_platform_cmake_args(): if "tsan" in os.environ.get("RUN_ANALYZER", ""): args.append("-DWITH_TSAN_OPTION=ON") + if os.environ.get("ERROR_ON_WARNINGS"): + args.append(f"-DSENTRY_ERROR_ON_WARNINGS={os.environ['ERROR_ON_WARNINGS']}") + if "CMAKE_DEFINES" in os.environ: args.extend(os.environ.get("CMAKE_DEFINES").split()) @@ -98,7 +115,6 @@ def get_cflags(extra_cflags=None): Returns compiler flags (CFLAGS/CXXFLAGS) for the build. This handles: - - ERROR_ON_WARNINGS -> -Werror - MSVC parallel builds, warnings as errors, and code analysis - GCC analyzer @@ -107,9 +123,6 @@ def get_cflags(extra_cflags=None): """ cflags = list(extra_cflags) if extra_cflags else [] - if os.environ.get("ERROR_ON_WARNINGS"): - cflags.append("-Werror") - if sys.platform == "win32" and not os.environ.get("TEST_MINGW"): cpus = os.cpu_count() cflags.append("/WX /MP{}".format(cpus)) diff --git a/tests/cmake.py b/tests/cmake.py index 0da3d40532..bb45b4779a 100644 --- a/tests/cmake.py +++ b/tests/cmake.py @@ -4,6 +4,8 @@ import subprocess import sys import platform +import re +from collections import Counter, deque from pathlib import Path import pytest @@ -17,13 +19,24 @@ get_tsan_env, ) +# give up the whole run when the same build error repeats this many times +build_error_limit = int(os.environ.get("SENTRY_TEST_BUILD_ERROR_LIMIT") or 0) +build_errors = Counter() + +# build errors as annotated on CI +with open(Path(__file__).parent.parent / ".github" / "problem-matchers.json") as f: + problem_matchers = [ + [re.compile(p["regexp"]) for p in m["pattern"]] + for m in json.load(f)["problemMatcher"] + ] + class CMake: def __init__(self, factory): self.runs = dict() self.factory = factory - def compile(self, targets, options=None, cflags=None): + def compile(self, targets, options=None, cflags=None, source_dir=None): # We build in tmp for all of our tests. Disable the warning MSVC generates to not clutter the build logs. if cflags is None: cflags = [] @@ -35,11 +48,12 @@ def compile(self, targets, options=None, cflags=None): key = ";".join(f"{k}={v}" for k, v in options.items()) if cflags: key += ";" + ";".join(cflags) + key = (source_dir, key) # cache the build configuration if key not in self.runs: cwd = self.factory.mktemp("cmake") - cmake_configure(cwd, options, cflags) + cmake_configure(cwd, options, cflags, source_dir) cmake_build(cwd, targets, options) self.runs[key] = (cwd, set(targets)) else: @@ -97,6 +111,7 @@ def destroy(self): exe_name("sentry-crash"), exe_name("sentry_early_init"), exe_name("sentry_test_platform"), + exe_name("sentry_test_pkgconfig"), ] cmd = [ os.environ.get("LLVM_COV", "llvm-cov"), @@ -129,7 +144,7 @@ def destroy(self): ) -def cmake_configure(cwd, options, cflags=None): +def cmake_configure(cwd, options, cflags=None, source_dir=None): if cflags is None: cflags = [] __tracebackhide__ = True @@ -166,7 +181,8 @@ def cmake_configure(cwd, options, cflags=None): options.update(get_android_config()) - source_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + if source_dir is None: + source_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) cmake = ["cmake"] if "scan-build" in os.environ.get("RUN_ANALYZER", ""): @@ -206,7 +222,7 @@ def cmake_configure(cwd, options, cflags=None): env = dict(os.environ) env["CFLAGS"] = env["CXXFLAGS"] = " ".join(cflags) - config_cmd.append(source_dir) + config_cmd.append(os.fspath(source_dir)) print("\n{} > {}".format(cwd, " ".join(config_cmd)), flush=True) try: @@ -265,9 +281,32 @@ def cmake_build(cwd, targets, options): ] print("{} > {}".format(cwd, " ".join(buildcmd)), flush=True) - try: - subprocess.run(buildcmd, cwd=cwd, env=env, check=True) - except subprocess.CalledProcessError: + errors = set() + if build_error_limit: + lines = deque(maxlen=max(map(len, problem_matchers))) + with subprocess.Popen( + buildcmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT + ) as process: + for line in process.stdout: + sys.stdout.buffer.write(line) + sys.stdout.buffer.flush() + lines.append(line.decode(errors="replace").rstrip("\r\n")) + for patterns in problem_matchers: + if len(lines) < len(patterns): + continue + window = list(lines)[-len(patterns) :] + matches = [p.search(l) for p, l in zip(patterns, window)] + if all(matches): + errors.add(tuple(g for m in matches for g in m.groups())) + returncode = process.returncode + else: + returncode = subprocess.run(buildcmd, cwd=cwd, env=env).returncode + if returncode != 0: + build_errors.update(errors) + if any(build_errors[e] >= build_error_limit for e in errors): + reason = f"cmake build failed {build_error_limit} times with the same error" + print(f"::error::{reason}", flush=True) + pytest.exit(reason, returncode=pytest.ExitCode.TESTS_FAILED) raise pytest.fail.Exception("cmake build failed") from None # check if the DLL and EXE artifacts contain version-information diff --git a/tests/conditions.py b/tests/conditions.py index 04e21514fc..e4dccc157a 100644 --- a/tests/conditions.py +++ b/tests/conditions.py @@ -3,10 +3,11 @@ import shutil is_aix = sys.platform == "aix" or sys.platform == "os400" -is_android = os.environ.get("ANDROID_API") +is_android = int(os.environ.get("ANDROID_API") or "0") is_wine = bool(os.environ.get("TEST_WINE")) is_x86 = os.environ.get("TEST_X86") is_arm32 = bool(os.environ.get("TEST_ARM32")) +is_riscv = bool(os.environ.get("TEST_RISCV")) is_qemu = bool(os.environ.get("TEST_QEMU")) # opt-in because the tests change the user's system proxy settings (with sudo on macOS) has_system_proxy = bool(os.environ.get("TEST_SYSTEM_PROXY")) @@ -54,6 +55,8 @@ # Native backend works on all platforms (lightweight, no external dependencies) # It's always available - tests explicitly set SENTRY_BACKEND: native in cmake # On macOS ASAN, the signal handling conflicts with ASAN's memory interception -has_native = has_http and not (is_asan and sys.platform == "darwin") +has_native = not (is_asan and sys.platform == "darwin") and ( + not is_android or is_android >= 23 +) has_sccache = os.environ.get("USE_SCCACHE") and shutil.which("sccache") diff --git a/tests/fixtures/android_e2e/CMakeLists.txt b/tests/fixtures/android_e2e/CMakeLists.txt new file mode 100644 index 0000000000..e0e7ee399b --- /dev/null +++ b/tests/fixtures/android_e2e/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 3.10) +project(sentry_android_e2e LANGUAGES C) + +add_library(e2e SHARED crash.c) diff --git a/tests/fixtures/android_e2e/README.md b/tests/fixtures/android_e2e/README.md new file mode 100644 index 0000000000..ae25b26c35 --- /dev/null +++ b/tests/fixtures/android_e2e/README.md @@ -0,0 +1,20 @@ +# Android native E2E fixture + +Prepare the APK separately from pytest, using a sentry-java checkout with the +native crash service. Set `ANDROID_HOME`, `ANDROID_NDK` (the NDK directory), and +`ANDROID_ARCH` for the build: + +```sh +python scripts/setup-android-e2e.py ../sentry-java +pytest -s -v tests/test_e2e_sentry.py +``` + +Run these commands from the sentry-native root. Testing needs a running emulator +or device, `ANDROID_API`, and the `SENTRY_E2E_*` credentials documented in the test +module. The crash service needs API 30+; tombstone merging needs API 31+. + +The setup script builds this checkout's native NDK package and the Java SDK +into an isolated Maven repository, overriding the Java SDK's pinned NDK dependency. +It then builds debuggable and non-debuggable fixture APKs under +`build/android-e2e`. Use `--build-dir` to choose another output directory and +set `SENTRY_E2E_ANDROID_BUILD_DIR` to it when running pytest. diff --git a/tests/fixtures/android_e2e/build.gradle b/tests/fixtures/android_e2e/build.gradle new file mode 100644 index 0000000000..17b59b228a --- /dev/null +++ b/tests/fixtures/android_e2e/build.gradle @@ -0,0 +1,45 @@ +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath "com.android.tools.build:gradle:${agpVersion}" + } +} + +apply plugin: "com.android.application" + +android { + namespace = "io.sentry.e2e" + compileSdk = project.property("compileSdk").toInteger() + compileSdkMinor = project.property("compileSdkMinor").toInteger() + ndkVersion = new File(System.getenv("ANDROID_NDK")).name + + defaultConfig { + applicationId = "io.sentry.e2e" + minSdk = 30 + targetSdk = project.property("targetSdk").toInteger() + ndk { abiFilters.add(System.getenv("ANDROID_ARCH")) } + } + + buildTypes { + // non-debuggable apps are not dumpable + nondebuggable { + initWith(debug) + debuggable = false + } + } + + externalNativeBuild { + cmake { path = file("CMakeLists.txt") } + } +} + +dependencies { + implementation "io.sentry:sentry-android-ndk-outproc:${sentryVersion}" +} + +configurations.configureEach { + resolutionStrategy.force("io.sentry:sentry-native-ndk-outproc:${sentryVersion}") +} diff --git a/tests/fixtures/android_e2e/crash.c b/tests/fixtures/android_e2e/crash.c new file mode 100644 index 0000000000..ae49ea41e8 --- /dev/null +++ b/tests/fixtures/android_e2e/crash.c @@ -0,0 +1,19 @@ +#include + +__attribute__((noinline, optnone)) void +e2e_segfault(void) +{ + *(volatile int *)0 = 42; +} + +__attribute__((noinline, optnone)) void +e2e_native_crash(void) +{ + e2e_segfault(); +} + +JNIEXPORT void JNICALL +Java_io_sentry_e2e_MainActivity_crash(JNIEnv *env, jclass cls) +{ + e2e_native_crash(); +} diff --git a/tests/fixtures/android_e2e/gradle.properties b/tests/fixtures/android_e2e/gradle.properties new file mode 100644 index 0000000000..5bac8ac504 --- /dev/null +++ b/tests/fixtures/android_e2e/gradle.properties @@ -0,0 +1 @@ +android.useAndroidX=true diff --git a/tests/fixtures/android_e2e/settings.gradle b/tests/fixtures/android_e2e/settings.gradle new file mode 100644 index 0000000000..43a5fd4de7 --- /dev/null +++ b/tests/fixtures/android_e2e/settings.gradle @@ -0,0 +1,12 @@ +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + exclusiveContent { + forRepository { maven { url = uri(localRepo) } } + filter { includeGroup("io.sentry") } + } + } +} + +rootProject.name = "app" diff --git a/tests/fixtures/android_e2e/src/main/AndroidManifest.xml b/tests/fixtures/android_e2e/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..cd00810a98 --- /dev/null +++ b/tests/fixtures/android_e2e/src/main/AndroidManifest.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/tests/fixtures/android_e2e/src/main/java/io/sentry/e2e/CrashReceiver.java b/tests/fixtures/android_e2e/src/main/java/io/sentry/e2e/CrashReceiver.java new file mode 100644 index 0000000000..1be9fb5722 --- /dev/null +++ b/tests/fixtures/android_e2e/src/main/java/io/sentry/e2e/CrashReceiver.java @@ -0,0 +1,24 @@ +package io.sentry.e2e; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.os.Handler; +import android.os.Looper; +import io.sentry.Sentry; + +public class CrashReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + if (intent.hasExtra("dsn")) { + MainActivity.init(context.getApplicationContext(), intent); + } + // a restarted process lost its crash service, so it must not crash + if (!Sentry.isEnabled()) { + return; + } + // keep the process active until the crash + goAsync(); + new Handler(Looper.getMainLooper()).postDelayed(MainActivity::triggerNativeCrash, 1000); + } +} diff --git a/tests/fixtures/android_e2e/src/main/java/io/sentry/e2e/MainActivity.java b/tests/fixtures/android_e2e/src/main/java/io/sentry/e2e/MainActivity.java new file mode 100644 index 0000000000..a9f0bd6ff6 --- /dev/null +++ b/tests/fixtures/android_e2e/src/main/java/io/sentry/e2e/MainActivity.java @@ -0,0 +1,53 @@ +package io.sentry.e2e; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import io.sentry.Sentry; +import io.sentry.android.core.SentryAndroid; +import io.sentry.protocol.User; + +public class MainActivity extends Activity { + private static native void crash(); + + @Override + public void onCreate(Bundle state) { + super.onCreate(state); + init(getApplicationContext(), getIntent()); + if (getIntent().getBooleanExtra("crash", true)) { + new Handler(getMainLooper()).postDelayed(MainActivity::triggerNativeCrash, 1000); + } + } + + static void init(Context context, Intent intent) { + System.loadLibrary("e2e"); + SentryAndroid.init( + context, + options -> { + options.setDsn(intent.getStringExtra("dsn")); + options.setDebug(true); + options.setRelease("sentry-native-e2e"); + options.setTombstoneEnabled(intent.getBooleanExtra("tombstone", false)); + options.setEnableAutoSessionTracking(false); + options.setShutdownTimeoutMillis(30000); + }); + String testId = intent.getStringExtra("test_id"); + Sentry.configureScope( + scope -> { + scope.setTag("test.id", testId); + User user = new User(); + user.setId(testId); + scope.setUser(user); + }); + } + + private static void callNativeCrash() { + crash(); + } + + static void triggerNativeCrash() { + callNativeCrash(); + } +} diff --git a/tests/fixtures/integration.c b/tests/fixtures/integration.c index e3b53828ed..dbfd672214 100644 --- a/tests/fixtures/integration.c +++ b/tests/fixtures/integration.c @@ -135,10 +135,11 @@ before_send_callback(sentry_value_t event, sentry_hint_t *hint, void *user_data) { (void)user_data; + char *json = sentry_value_to_json(event); sentry_hint_clear_attachments(hint); sentry_hint_add_attachment(hint, - sentry_attachment_from_bytes( - "before_send", strlen("before_send"), "callback.txt")); + sentry_attachment_from_bytes(json, strlen(json), "before_send.json")); + sentry_free(json); // make our mark on the event sentry_value_set_by_key( @@ -188,10 +189,11 @@ on_crash_callback(const sentry_ucontext_t *uctx, sentry_value_t event, } } + char *json = sentry_value_to_json(event); sentry_hint_clear_attachments(hint); sentry_hint_add_attachment(hint, - sentry_attachment_from_bytes( - "on_crash", strlen("on_crash"), "callback.txt")); + sentry_attachment_from_bytes(json, strlen(json), "on_crash.json")); + sentry_free(json); // tell the backend to retain the event return event; @@ -443,6 +445,14 @@ test_logger_callback( fflush(stdout); } +static void +report_trace_header(const char *key, const char *value, void *userdata) +{ + (void)userdata; + printf("%s: %s\n", key, value); + sentry_set_extra(key, sentry_value_new_string(value)); +} + static void print_envelope(sentry_envelope_t *envelope, void *unused_state) { @@ -667,6 +677,14 @@ trigger_oom_exhaust(void) #endif } +static void +trigger_null_call(void) +{ + // keep a caller frame independent of libc startup + void (*volatile func)(void) = NULL; + func(); +} + static sentry_value_t create_debug_crumb(const char *message) { @@ -819,6 +837,9 @@ main(int argc, char **argv) if (has_arg(argc, argv, "log")) { sentry_options_set_debug(options, 1); } + if (has_arg(argc, argv, "trace")) { + sentry_options_set_logger_level(options, SENTRY_LEVEL_TRACE); + } if (has_arg(argc, argv, "attachment")) { // assuming the example / test is run directly from the cmake build @@ -1061,6 +1082,10 @@ main(int argc, char **argv) sentry_options_set_crash_upload_mode( options, SENTRY_CRASH_UPLOAD_MODE_ASYNC); } + const char *minidump_mode = get_arg_value(argc, argv, "minidump-mode"); + if (minidump_mode) { + sentry_options_set_minidump_mode(options, atoi(minidump_mode)); + } // E2E test mode: generate unique test ID for event correlation char e2e_test_id[37] = { 0 }; @@ -1175,7 +1200,7 @@ main(int argc, char **argv) fclose(f); sentry_value_t attachment = sentry_attachment_from_file(large_file); sentry_attachment_set_type( - attachment, SENTRY_ATTACHMENT_TYPE_MINIDUMP); + attachment, SENTRY_ATTACHMENT_TYPE_GENERIC); sentry_add_attachment(attachment); } } @@ -1263,6 +1288,22 @@ main(int argc, char **argv) sentry_set_trace(direct_trace_id, direct_parent_span_id); } + if (has_arg(argc, argv, "continue-trace")) { + // the headers of an upstream app, if given + const char *sentry_trace = getenv("SENTRY_TEST_SENTRY_TRACE"); + const char *baggage = getenv("SENTRY_TEST_BAGGAGE"); + sentry_continue_trace(sentry_trace + ? sentry_trace + : "aaaabbbbccccddddeeeeffff00001111-f0f0f0f0f0f0f0f0-1", + baggage ? baggage + : "sentry-trace_id=aaaabbbbccccddddeeeeffff00001111," + "sentry-environment=upstream,sentry-sample_rand=0.25"); + } + + if (has_arg(argc, argv, "iter-trace-headers")) { + sentry_iter_trace_propagation_headers(report_trace_header, NULL); + } + if (has_arg(argc, argv, "replay-context")) { // mimics an embedder (e.g. sentry-unreal) that stages replay clips in // `/replays/` and announces the active replay on the scope @@ -1287,6 +1328,25 @@ main(int argc, char **argv) sentry_set_environment("updated-environment"); } + if (has_arg(argc, argv, "acquire-scope")) { + sentry_scope_t *scope = sentry_scope_acquire(); + sentry_scope_set_tag(scope, "acquired", "yes"); + sentry_scope_set_release(scope, "scope-release"); + sentry_scope_set_environment(scope, "scope-environment"); + sentry_scope_set_user( + scope, sentry_value_new_user("scope-user", NULL, NULL, NULL)); + sentry_scope_add_breadcrumb( + scope, sentry_value_new_breadcrumb(NULL, "acquired breadcrumb")); + sentry_scope_attach_bytes(scope, "scope", 5, "scope.txt"); + sentry_scope_release(scope); + } + + if (has_arg(argc, argv, "clear-scope")) { + sentry_scope_t *scope = sentry_scope_acquire(); + sentry_scope_clear(scope); + sentry_scope_release(scope); + } + if (has_arg(argc, argv, "start-session")) { sentry_start_session(); } @@ -1331,6 +1391,12 @@ main(int argc, char **argv) sentry_scope_add_attachment(scope, bytes); } + if (has_arg(argc, argv, "set-scope-trace")) { + const char *scope_trace_id = "11112222333344445555666677778888"; + const char *scope_parent_span_id = "0f0f0f0f0f0f0f0f"; + sentry_scope_set_trace(scope, scope_trace_id, scope_parent_span_id); + } + sentry_scope_capture_event(scope, event, NULL); } @@ -1409,9 +1475,23 @@ main(int argc, char **argv) sentry_span_start_child(ospan, "open.grand.span", NULL)); } + const char *allocation_mib = get_arg_value(argc, argv, "large-allocation"); + if (allocation_mib) { + const size_t size = strtoul(allocation_mib, NULL, 10) * 1024 * 1024; + char *allocation = malloc(size); + if (allocation) { + const size_t touched + = has_arg(argc, argv, "sparse-allocation") ? 32 : size; + memset(allocation + size - touched, 0xA5, touched); + } + } + if (has_arg(argc, argv, "crash")) { sentry_crash(); } + if (has_arg(argc, argv, "crash-null")) { + trigger_null_call(); + } #ifdef SENTRY_PLATFORM_LINUX if (has_arg(argc, argv, "crash-high-address")) { # ifdef MAP_FIXED_NOREPLACE @@ -1534,19 +1614,6 @@ main(int argc, char **argv) // Clean up the temporary file remove(attachment_path); } - if (has_arg(argc, argv, "capture-user-report")) { - sentry_value_t event = sentry_value_new_message_event( - SENTRY_LEVEL_INFO, "my-logger", "Hello user feedback!"); - sentry_uuid_t event_id = sentry_capture_event(event); - - SENTRY_SUPPRESS_DEPRECATED - sentry_value_t user_feedback = sentry_value_new_user_feedback( - &event_id, "some-name", "some-email", "some-comment"); - - sentry_capture_user_feedback(user_feedback); - SENTRY_RESTORE_DEPRECATED - } - if (has_arg(argc, argv, "capture-transaction")) { sentry_transaction_context_t *tx_ctx = sentry_transaction_context_new("little.teapot", diff --git a/tests/fixtures/pkgconfig/CMakeLists.txt b/tests/fixtures/pkgconfig/CMakeLists.txt new file mode 100644 index 0000000000..d7b2a340a3 --- /dev/null +++ b/tests/fixtures/pkgconfig/CMakeLists.txt @@ -0,0 +1,37 @@ +cmake_minimum_required(VERSION 3.10) +project(sentry_pkgconfig C) + +# Options that match the main sentry-native build +option(SENTRY_BUILD_FORCE32 "Force a 32bit compile on a 64bit host" OFF) +option(WITH_ASAN_OPTION "Build with address sanitizer" OFF) +option(WITH_TSAN_OPTION "Build with thread sanitizer" OFF) + +find_package(PkgConfig REQUIRED) +pkg_check_modules(SENTRY REQUIRED IMPORTED_TARGET sentry) + +pkg_get_variable(SENTRY_BINDIR sentry bindir) +find_program(SENTRY_HANDLER_PATH sentry-crash + PATHS "${SENTRY_BINDIR}" + NO_DEFAULT_PATH ONLY_CMAKE_FIND_ROOT_PATH) + +add_executable(sentry_test_pkgconfig main.c) +target_link_libraries(sentry_test_pkgconfig PRIVATE PkgConfig::SENTRY) +target_compile_definitions(sentry_test_pkgconfig PRIVATE + SENTRY_HANDLER_PATH=\"${SENTRY_HANDLER_PATH}\") + +if(NOT MSVC) + if(SENTRY_BUILD_FORCE32) + target_compile_options(sentry_test_pkgconfig PRIVATE -m32) + target_link_libraries(sentry_test_pkgconfig PRIVATE -m32) + endif() + + if(WITH_ASAN_OPTION) + target_compile_options(sentry_test_pkgconfig PRIVATE -fsanitize=address) + target_link_libraries(sentry_test_pkgconfig PRIVATE -fsanitize=address) + endif() + + if(WITH_TSAN_OPTION) + target_compile_options(sentry_test_pkgconfig PRIVATE -fsanitize=thread) + target_link_libraries(sentry_test_pkgconfig PRIVATE -fsanitize=thread) + endif() +endif() diff --git a/tests/fixtures/pkgconfig/main.c b/tests/fixtures/pkgconfig/main.c new file mode 100644 index 0000000000..933d085519 --- /dev/null +++ b/tests/fixtures/pkgconfig/main.c @@ -0,0 +1,20 @@ +#include +#include + +int +main(void) +{ + const char *database = getenv("SENTRY_DATABASE_PATH"); + if (!database) { + return 1; + } + + sentry_options_t *options = sentry_options_new(); + sentry_options_set_handler_path(options, SENTRY_HANDLER_PATH); + sentry_options_set_database_path(options, database); + if (sentry_init(options) != 0) { + return 1; + } + sentry_close(); + return 0; +} diff --git a/tests/proxy.py b/tests/proxy.py index 155e527759..a30f4ec168 100644 --- a/tests/proxy.py +++ b/tests/proxy.py @@ -213,7 +213,11 @@ def _wait_for_output_file(process, output_file, timeout=10): def start_proxy( - proxy_type, proxy_auth: str = None, listen_host: str = "127.0.0.1", retries: int = 3 + proxy_type, + proxy_auth: str = None, + listen_host: str = "127.0.0.1", + retries: int = 3, + throttle: int = 0, ): """Start the stdlib test proxy on a free port. Returns (process, port).""" proxy_server = Path(__file__).with_name("proxy_server.py") @@ -242,6 +246,8 @@ def start_proxy( if proxy_auth: proxy_command += ["--proxy-auth", proxy_auth] + if throttle: + proxy_command += ["--throttle", str(throttle)] proxy_process = subprocess.Popen( proxy_command, diff --git a/tests/proxy_server.py b/tests/proxy_server.py index 78628372a1..d3a429ace8 100644 --- a/tests/proxy_server.py +++ b/tests/proxy_server.py @@ -6,6 +6,7 @@ import socket import sys import threading +import time from urllib.parse import urlsplit BUFFER_SIZE = 64 * 1024 @@ -163,7 +164,17 @@ def _read_http_response(server): return header + b"\r\n\r\n" + body, status_line -def _forward_http(client, proxy_auth): +def _sendall(sock, data, throttle): + if not throttle: + sock.sendall(data) + return + for offset in range(0, len(data), BUFFER_SIZE): + chunk = data[offset : offset + BUFFER_SIZE] + time.sleep(len(chunk) / throttle) + sock.sendall(chunk) + + +def _forward_http(client, proxy_auth, throttle): data = _recv_until(client, b"\r\n\r\n") header, initial_body = data.split(b"\r\n\r\n", 1) lines = header.decode("iso-8859-1").split("\r\n") @@ -175,6 +186,15 @@ def _forward_http(client, proxy_auth): _send_proxy_auth_required(client, method) return + if method == "CONNECT": + host, port = _split_host_port(target, 443) + with socket.create_connection((host, port), timeout=10) as server: + client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n") + print("CONNECT 200 Connection Established", flush=True) + _sendall(server, body, throttle) + _relay_tunnel(client, server, throttle) + return + url = urlsplit(target) if not url.scheme or not url.hostname: host = _get_header(headers, "Host") @@ -205,7 +225,7 @@ def _forward_http(client, proxy_auth): ) with socket.create_connection((target_host, target_port), timeout=10) as server: - server.sendall(request) + _sendall(server, request, throttle) response, status_line = _read_http_response(server) client.sendall(response) @@ -282,7 +302,7 @@ def _forward_socks5(client): _relay_tunnel(client, server) -def _relay_tunnel(client, server): +def _relay_tunnel(client, server, throttle=0): readable_sockets = [client, server] request_method = None response_status = None @@ -304,7 +324,7 @@ def _relay_tunnel(client, server): except OSError: pass continue - target.sendall(data) + _sendall(target, data, throttle if source is client else 0) if logged: continue @@ -326,18 +346,18 @@ def _relay_tunnel(client, server): logged = True -def _handle_client(client, proxy_type, proxy_auth): +def _handle_client(client, proxy_type, proxy_auth, throttle): with client: try: if proxy_type == "socks5-proxy": _forward_socks5(client) else: - _forward_http(client, proxy_auth) + _forward_http(client, proxy_auth, throttle) except Exception as exc: print(f"proxy error: {exc}", file=sys.stderr, flush=True) -def serve(proxy_type, listen_host, port, proxy_auth, output): +def serve(proxy_type, listen_host, port, proxy_auth, output, throttle=0): family = socket.AF_INET6 if ":" in listen_host else socket.AF_INET with socket.socket(family, socket.SOCK_STREAM) as listener: listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) @@ -351,7 +371,7 @@ def serve(proxy_type, listen_host, port, proxy_auth, output): client, _ = listener.accept() thread = threading.Thread( target=_handle_client, - args=(client, proxy_type, proxy_auth), + args=(client, proxy_type, proxy_auth, throttle), daemon=True, ) thread.start() @@ -363,10 +383,22 @@ def main(): parser.add_argument("--listen-host", default="127.0.0.1") parser.add_argument("--port", type=int, default=0) parser.add_argument("--proxy-auth") + parser.add_argument( + "--throttle", type=int, default=0, help="Upload bytes per second" + ) parser.add_argument("--output", required=True) args = parser.parse_args() - - serve(args.type, args.listen_host, args.port, args.proxy_auth, args.output) + if args.throttle < 0: + parser.error("--throttle must be non-negative") + + serve( + args.type, + args.listen_host, + args.port, + args.proxy_auth, + args.output, + args.throttle, + ) if __name__ == "__main__": diff --git a/tests/requirements.txt b/tests/requirements.txt index 4559a2527b..7e0e5ddc44 100644 --- a/tests/requirements.txt +++ b/tests/requirements.txt @@ -4,7 +4,7 @@ pytest-httpserver==1.0.10 flaky==3.8.1 msgpack==1.2.3 pytest-xdist==3.8.0 -clang-format==20.1.5 +clang-format==20.1.5; platform_machine != "riscv64" pywin32==311; sys_platform == "win32" psutil==7.1.1 # For E2E tests that call Sentry API diff --git a/tests/test_build_static.py b/tests/test_build.py similarity index 56% rename from tests/test_build_static.py rename to tests/test_build.py index 4dc15d6fdf..4a111c6bad 100644 --- a/tests/test_build_static.py +++ b/tests/test_build.py @@ -1,17 +1,76 @@ import subprocess import sys import os +import struct +import shutil +import shlex +from pathlib import Path + import pytest + +from . import SENTRY_VERSION, SENTRY_VERSION_BASE, lib_name, run +from .build_config import get_test_executable_env from .conditions import ( has_breakpad, has_crashpad, has_native, + is_aix, is_android, is_qemu, is_wine, ) +def _assert_symlink(path, target): + assert path.is_symlink() + assert os.readlink(path) == target + + +def _assert_shared_version(directory): + major, minor, _ = SENTRY_VERSION_BASE.split(".") + + if sys.platform == "darwin": + real_name = f"libsentry.{SENTRY_VERSION_BASE}.dylib" + abi_name = f"libsentry.{major}.dylib" + _assert_symlink(directory / "libsentry.dylib", abi_name) + _assert_symlink(directory / abi_name, real_name) + output = subprocess.check_output( + ["otool", "-L", directory / real_name], text=True + ) + assert ( + f"{abi_name} (compatibility version {major}.0.0, " + f"current version {SENTRY_VERSION_BASE})" + ) in output + elif sys.platform == "win32": + dll = directory / lib_name("sentry") + with dll.open("rb") as binary: + binary.seek(0x3C) + pe_offset = struct.unpack("= 1), got {thread_count}" verify_no_thread_duplication(threads_data, "test_e2e_crashpad") + + +@pytest.mark.skipif(is_android, reason="Standalone E2E tests require http transport") +def test_e2e_trace_propagation(cmake): + """Verify that Sentry links the events of an upstream and a downstream app + when the downstream app continues the trace from the upstream headers.""" + tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "none"}) + env = dict(os.environ, SENTRY_DSN=os.environ["SENTRY_E2E_DSN"]) + + # upstream: capture an event and print the propagation headers of its trace + output = check_output( + tmp_path, + "sentry_test_integration", + ["log", "e2e-test", "iter-trace-headers", "capture-event"], + env=env, + ) + upstream_id = extract_test_id(output) + headers = dict( + re.findall(r"^(sentry-trace|baggage): (.+)$", output.decode(), re.MULTILINE) + ) + + # downstream: continue the trace from those headers and capture an event + env["SENTRY_TEST_SENTRY_TRACE"] = headers["sentry-trace"] + env["SENTRY_TEST_BAGGAGE"] = headers["baggage"] + output = check_output( + tmp_path, + "sentry_test_integration", + ["log", "e2e-test", "continue-trace", "capture-event"], + env=env, + ) + downstream_id = extract_test_id(output) + + upstream_trace = poll_sentry_for_event(upstream_id)["contexts"]["trace"] + downstream_trace = poll_sentry_for_event(downstream_id)["contexts"]["trace"] + + assert downstream_trace["trace_id"] == upstream_trace["trace_id"] + assert downstream_trace["parent_span_id"] == upstream_trace["span_id"] + + +@pytest.mark.skipif(not has_native, reason="native backend not available") +@pytest.mark.skipif(is_android, reason="Standalone E2E tests require http transport") +def test_e2e_tus(cmake): + """Verify a large crash attachment reaches Sentry after an interrupted upload.""" + tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "native"}) + env = dict(os.environ, SENTRY_DSN=os.environ["SENTRY_E2E_DSN"]) + + # The daemon uploads the crash through a throttled proxy, so its shutdown + # timeout interrupts the upload and persists the envelope for the restart. + proxy, port = start_proxy("http-proxy", throttle=1024 * 1024) + try: + output = run_crash_e2e( + tmp_path, + "sentry_test_integration", + [ + "log", + "e2e-test", + "http-proxy", + "large-attachment", + "shutdown-timeout", + "5000", + "crash", + ], + env=dict(env, SENTRY_TEST_PROXY_PORT=str(port)), + wait_for_daemon=True, + ) + test_id = extract_test_id(output) + finally: + proxy.terminate() + proxy.communicate(timeout=10) + + envelopes = list(tmp_path.glob(".sentry-native/*.run/*.envelope")) + assert envelopes, "Interrupted upload should persist its envelope" + refs = [ + item + for envelope in envelopes + for item in Envelope.deserialize(envelope.read_bytes()) + if item.headers.get("content_type") + == "application/vnd.sentry.attachment-ref+json" + ] + assert len(refs) == 1, "Interrupted upload should retain its attachment" + location = refs[0].payload.json.get("location") + assert location, "Upload location should be persisted" + + output = check_output( + tmp_path, + "sentry_test_integration", + ["log", "trace", "no-setup", "shutdown-timeout", "120000"], + env=env, + stderr=subprocess.STDOUT, + ) + output = output.decode("utf-8", errors="replace") + + # The persisted upload must be resumed, not re-created: only HEAD targets + # the persisted location, and nothing may hit the creation URL. The curl + # client traces request lines, the winhttp client logs request URLs. + target = urlsplit(location) + assert ( + urlunsplit(("", "", target.path, target.query, "")) in output + ), "Resumed upload should query the offset of its location" + assert not re.search( + r'/upload/["\s]', output + ), "Resumed upload should not create a new upload" + + event = poll_sentry_for_event(test_id) + attachments = poll_sentry_for_attachments( + event["eventID"], ".sentry-large-attachment" + ) + assert_large_attachment(attachments) + + +@pytest.mark.skipif(is_android, reason="Standalone E2E tests require http transport") +def test_e2e_tus_compressed(cmake): + """Verify a large attachment reaches Sentry in gzip-compressed chunks.""" + tmp_path = cmake( + ["sentry_test_integration"], + {"SENTRY_BACKEND": "none", "SENTRY_TRANSPORT_COMPRESSION": "On"}, + ) + env = dict(os.environ, SENTRY_DSN=os.environ["SENTRY_E2E_DSN"]) + + output = check_output( + tmp_path, + "sentry_test_integration", + [ + "log", + "trace", + "e2e-test", + "large-attachment", + "capture-event", + "shutdown-timeout", + "120000", + ], + env=env, + stderr=subprocess.STDOUT, + ) + test_id = extract_test_id(output) + output = output.decode("utf-8", errors="replace") + + # Envelopes are compressed too, but only upload chunks carry the decoded + # length. + assert ( + "x-decoded-content-length:" in output + ), "Upload chunks should be gzip-compressed" + + event = poll_sentry_for_event(test_id) + attachments = poll_sentry_for_attachments( + event["eventID"], ".sentry-large-attachment" + ) + assert_large_attachment(attachments) + + +@pytest.fixture(scope="module") +def android_e2e_app(request): + get_sentry_headers() + get_sentry_org_project() + build_dir = ( + Path( + os.environ.get( + "SENTRY_E2E_ANDROID_BUILD_DIR", Path(sourcedir) / "build/android-e2e" + ) + ) + .expanduser() + .resolve() + ) + build_type = getattr(request, "param", "debug") + apk = build_dir / f"app/build/outputs/apk/{build_type}/app-{build_type}.apk" + assert apk.is_file(), "Prepare the APK with scripts/setup-android-e2e.py first" + package = "io.sentry.e2e" + adb("install", "-r", str(apk), check=True) + yield package + adb("uninstall", package, check=False) + + +def assert_android_native_event(event, test_id, tombstone, debuggable=True): + assert event["platform"] == "native" + assert event["release"]["version"] == "sentry-native-e2e" + assert event["user"]["id"] == test_id + + exception = get_exception_from_event(event)["values"][0] + mechanism = exception["mechanism"] + assert mechanism["handled"] is False + if tombstone: + assert mechanism["type"] == "TombstoneMerged" + else: + assert mechanism["type"] == "signalhandler" + frames = exception["stacktrace"]["frames"] + # the frame-pointer walk stops before libart in non-debuggable apps + assert len(frames) >= (3 if debuggable else 2) + if tombstone: + functions = [frame.get("function") or "" for frame in frames] + assert {"e2e_segfault", "e2e_native_crash"}.issubset(functions) + assert any( + "io.sentry.e2e.MainActivity.triggerNativeCrash" in function + for function in functions + ) + assert any( + "io.sentry.e2e.MainActivity.callNativeCrash" in function + for function in functions + ) + + threads = get_threads_from_event(event) + # a single thread means the daemon could not read the app's /proc + assert len(threads["values"]) >= 2 + assert any(thread["crashed"] for thread in threads["values"]) + verify_no_thread_duplication(threads, "test_e2e_android_native") + + images = get_debug_meta_from_event(event)["images"] + # default packaging maps the libraries straight from the APK + assert any( + image["code_file"].endswith(("libe2e.so", "/base.apk")) for image in images + ) + + +@pytest.mark.skipif( + not is_android or not has_native, reason="Tests need Android + native" +) +@pytest.mark.skipif( + is_android < 30, reason="The native crash service needs Android API 30+" +) +@pytest.mark.parametrize( + "android_e2e_app, debuggable", + [("debug", True), ("nondebuggable", False)], + ids=["debuggable", "nondebuggable"], + indirect=["android_e2e_app"], + scope="module", +) +@pytest.mark.parametrize("tombstone", [False, True], ids=["native", "tombstone"]) +def test_e2e_android_native(android_e2e_app, debuggable, tombstone): + """The crash service sends native crashes, optionally merged with a tombstone.""" + if tombstone and is_android < 31: + pytest.skip("Tombstone merging needs Android API 31+") + test_id = str(uuid.uuid4()) + package = android_e2e_app + adb("shell", "pm", "clear", package, check=True, capture_output=True) + try: + adb( + "shell", + "am", + "start", + "-n", + f"{package}/.MainActivity", + "--es", + "dsn", + os.environ["SENTRY_E2E_DSN"], + "--es", + "test_id", + test_id, + "--ez", + "tombstone", + str(tombstone).lower(), + check=True, + capture_output=True, + ) + # no restart: delivery must happen from the surviving crash service + event = poll_sentry_for_event(test_id) + assert_android_native_event(event, test_id, tombstone, debuggable) + finally: + adb("shell", "am", "force-stop", package, check=False) + + +@pytest.mark.skipif( + not is_android or not has_native, reason="Tests need Android + native" +) +@pytest.mark.skipif( + is_android < 30, reason="The native crash service needs Android API 30+" +) +def test_e2e_android_native_broadcast(android_e2e_app): + """A process that a broadcast starts in the background gets the crash service.""" + test_id = str(uuid.uuid4()) + package = android_e2e_app + adb("shell", "pm", "clear", package, check=True, capture_output=True) + try: + adb( + "shell", + "am", + "broadcast", + "--include-stopped-packages", + "-n", + f"{package}/.CrashReceiver", + "--es", + "dsn", + os.environ["SENTRY_E2E_DSN"], + "--es", + "test_id", + test_id, + check=True, + capture_output=True, + ) + event = poll_sentry_for_event(test_id) + assert_android_native_event(event, test_id, False) + finally: + adb("shell", "am", "force-stop", package, check=False) + + +@pytest.mark.skipif( + not is_android or not has_native, reason="Tests need Android + native" +) +@pytest.mark.skipif( + is_android < 30, reason="The native crash service needs Android API 30+" +) +def test_e2e_android_native_background(android_e2e_app): + """The crash service outlives the idle timeout of background services.""" + test_id = str(uuid.uuid4()) + package = android_e2e_app + adb("shell", "pm", "clear", package, check=True, capture_output=True) + try: + adb( + "shell", + "am", + "start", + "-W", + "-n", + f"{package}/.MainActivity", + "--es", + "dsn", + os.environ["SENTRY_E2E_DSN"], + "--es", + "test_id", + test_id, + "--ez", + "crash", + "false", + check=True, + capture_output=True, + ) + adb("shell", "input", "keyevent", "KEYCODE_HOME", check=True) + # Android stops idle background services after about a minute + time.sleep(90) + adb( + "shell", + "am", + "broadcast", + "-n", + f"{package}/.CrashReceiver", + check=True, + capture_output=True, + ) + event = poll_sentry_for_event(test_id) + assert_android_native_event(event, test_id, False) + finally: + adb("shell", "am", "force-stop", package, check=False) diff --git a/tests/test_embedded_info.py b/tests/test_embedded_info.py index bb906e2bd3..b22f90c4b7 100644 --- a/tests/test_embedded_info.py +++ b/tests/test_embedded_info.py @@ -2,7 +2,7 @@ import shutil import subprocess import pytest -from . import run, SENTRY_VERSION +from . import run, SENTRY_VERSION, SENTRY_VERSION_BASE from .conditions import has_http has_strings = shutil.which("strings") is not None @@ -187,7 +187,7 @@ def test_sdk_version_override(cmake): # Verify that version and build ID are correctly separated assert ( - f"SENTRY_VERSION:{SENTRY_VERSION};" in output + f"SENTRY_VERSION:{SENTRY_VERSION_BASE};" in output ), "Version should be base version without build metadata" assert ( "BUILD:20251016-test-build;" in output @@ -236,7 +236,7 @@ def test_sdk_version_override_with_explicit_build_id(cmake): # Verify that explicit build ID takes precedence assert ( - f"SENTRY_VERSION:{SENTRY_VERSION};" in output + f"SENTRY_VERSION:{SENTRY_VERSION_BASE};" in output ), "Version should be base version" assert ( "BUILD:explicit-build-id;" in output diff --git a/tests/test_integration_android.py b/tests/test_integration_android.py new file mode 100644 index 0000000000..088fe3c7f7 --- /dev/null +++ b/tests/test_integration_android.py @@ -0,0 +1,66 @@ +import time + +import pytest + +from . import adb, run +from .conditions import has_native, is_android, is_asan, is_tsan + +pytestmark = pytest.mark.skipif( + not is_android, + reason="Tests need Android", +) + + +@pytest.mark.skipif( + not has_native, + reason="Tests need the native backend enabled", +) +@pytest.mark.skipif( + 0 < is_android < 23, + reason="Android native backend test needs API 23+ (process_vm_readv)", +) +def test_native_android(cmake): + database_path = "/data/local/tmp/.sentry-native" + + def find_minidumps(timeout=30 if is_asan or is_tsan else 10): + deadline = time.time() + timeout + last_result = None + while last_result is None or time.time() < deadline: + last_result = adb( + "shell", + f'for f in {database_path}/*.run/__sentry-crash.dmp; do [ -f "$f" ] && echo "$f"; done', + capture_output=True, + text=True, + check=False, + ) + if last_result.returncode == 0 and last_result.stdout.strip(): + return [ + line.strip() + for line in last_result.stdout.splitlines() + if line.strip() + ] + time.sleep(0.5) + if last_result is not None: + print(last_result.stdout) + print(last_result.stderr) + return [] + + tmp_path = cmake( + ["sentry_test_integration"], + {"SENTRY_BACKEND": "native", "SENTRY_TRANSPORT": "none"}, + ) + + adb("shell", f"rm -rf {database_path}", check=True) + assert find_minidumps(timeout=0) == [] + + try: + run(tmp_path, "sentry_test_integration", ["log", "crash"], expect_failure=True) + + minidumps = find_minidumps() + assert minidumps, "native backend should create a minidump on Android" + + local_minidump = tmp_path / "android.dmp" + adb("pull", minidumps[0], str(local_minidump), check=True, capture_output=True) + assert local_minidump.stat().st_size > 0 + finally: + adb("shell", f"rm -rf {database_path}", check=False) diff --git a/tests/test_integration_crashpad.py b/tests/test_integration_crashpad.py index cccf918a80..f1dd640206 100644 --- a/tests/test_integration_crashpad.py +++ b/tests/test_integration_crashpad.py @@ -1,3 +1,4 @@ +import json import os import struct import subprocess @@ -22,8 +23,16 @@ is_replay_envelope, lib_name, REPLAY_ID, + SENTRY_VERSION_BASE, +) +from .conditions import ( + has_crashpad, + has_files, + has_oom, + has_system_proxy, + is_qemu, + is_riscv, ) -from .conditions import has_crashpad, has_files, has_oom, has_system_proxy from .proxy import ( setup_proxy_env_vars, cleanup_proxy_env_vars, @@ -47,8 +56,9 @@ wait_for_file, ) +# ptrace is unavailable under RISC-V user-mode emulation pytestmark = pytest.mark.skipif( - not has_crashpad, + not has_crashpad or (is_riscv and is_qemu), reason="Tests need a crashpad backend and a valid environment for it", ) @@ -164,7 +174,13 @@ def test_crashpad_codeview(cmake, httpserver): name.replace("\\", "/").rsplit("/", 1)[-1]: codeview for name, codeview in _minidump_modules(attachments.minidump) } - codeview = codeviews[lib_name("sentry")] + library = lib_name("sentry") + major = SENTRY_VERSION_BASE.split(".", 1)[0] + if sys.platform == "linux": + library = f"{library}.{major}" + elif sys.platform == "darwin": + library = library.replace(".dylib", f".{SENTRY_VERSION_BASE}.dylib") + codeview = codeviews[library] signature = codeview[:4] if sys.platform == "linux": assert signature == b"LEpB" @@ -656,20 +672,22 @@ def test_crashpad_dumping_crash(cmake, httpserver, run_args, build_args): envelope = Envelope.deserialize(session) assert_session(envelope, {"status": "crashed", "errors": 1}) - expect_attachments = not any( - arg in run_args for arg in ("before-send", "on-crash", "clear-attachments") - ) + expect_attachments = not any(arg in run_args for arg in ("before-send", "on-crash")) + cleared = "clear-attachments" in run_args attachments = assert_crashpad_upload( multipart, expect_attachment=expect_attachments, - expect_view_hierarchy=expect_attachments, + expect_view_hierarchy=expect_attachments and not cleared, breadcrumb_count=101, + expect_byte_attachment=expect_attachments and not cleared, ) callback = next( (arg for arg in run_args if arg in ("before-send", "on-crash")), None ) - expected_callback = callback.replace("-", "_").encode() if callback else None - assert attachments.callback == expected_callback + if callback: + assert json.loads(attachments.callback)["level"] == "fatal" + else: + assert attachments.callback is None event_id = attachments.event["event_id"] if sys.platform == "win32": minidump = tmp_path / ".sentry-native" / "reports" / f"{event_id}.dmp" @@ -1549,6 +1567,49 @@ def test_crashpad_breadcrumbs(cmake, httpserver, count, reinstall, crash_arg): assert wait_for_no_werfault() +@pytest.mark.parametrize("clear", [False, True]) +def test_crashpad_acquired_scope(cmake, httpserver, clear): + tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "crashpad"}) + httpserver.expect_oneshot_request("/api/123456/minidump/").respond_with_data("OK") + args = [ + "log", + "no-setup", + "attachment", + "acquire-scope", + "crashpad-wait-for-upload", + "crash", + ] + if clear: + args.append("clear-scope") + with httpserver.wait(timeout=10) as waiting: + run( + tmp_path, + "sentry_test_integration", + args, + expect_failure=True, + env=dict(os.environ, SENTRY_DSN=make_dsn(httpserver)), + ) + assert waiting.result + + attachments = assert_crashpad_upload( + httpserver.log[0][0], + expect_attachment=True, + expect_breadcrumbs=False, + expect_default_scope=False, + expect_byte_attachment=not clear, + ) + event = attachments.event + assert event["release"] == ("test-example-release" if clear else "scope-release") + assert event["environment"] == ("development" if clear else "scope-environment") + assert ("acquired" in event.get("tags", {})) == (not clear) + assert any( + crumb.get("message") == "acquired breadcrumb" + for crumb in attachments.breadcrumb1 + attachments.breadcrumb2 + ) == (not clear) + if not clear: + assert event["user"]["id"] == "scope-user" + + def start_until_handler(tmp_path, args, env=None): # sentry_init flushes the scope to the handler before it processes old # runs. With no-setup, nothing else reaches the handler until the fixture's diff --git a/tests/test_integration_http.py b/tests/test_integration_http.py index 5b0a36b9cd..b01d04ca39 100644 --- a/tests/test_integration_http.py +++ b/tests/test_integration_http.py @@ -31,7 +31,6 @@ assert_replay_envelope, assert_session, assert_user_feedback, - assert_user_report, assert_minidump, assert_breakpad_crash, assert_crash_timestamp, @@ -303,34 +302,6 @@ def test_user_feedback_with_attachments_http(cmake, httpserver): assert attachment_count == 2 -def test_user_report_http(cmake, httpserver): - tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "none"}) - - httpserver.expect_request( - "/api/123456/envelope/", - headers={"x-sentry-auth": auth_header}, - ).respond_with_data("OK") - env = dict(os.environ, SENTRY_DSN=make_dsn(httpserver)) - - run( - tmp_path, - "sentry_test_integration", - ["log", "capture-user-report"], - env=env, - ) - - assert len(httpserver.log) == 2 - output = httpserver.log[0][0].get_data() - envelope = Envelope.deserialize(output) - - assert_event(envelope, "Hello user feedback!") - - output = httpserver.log[1][0].get_data() - envelope = Envelope.deserialize(output) - - assert_user_report(envelope) - - @pytest.mark.parametrize( "build_args", [ @@ -1749,3 +1720,37 @@ def test_early_init(cmake, backend): result = run(tmp_path, "sentry_early_init", []) assert result.returncode == 0 + + +@pytest.mark.parametrize("capture", ["capture-event", "capture-with-scope"]) +@pytest.mark.parametrize("clear", [False, True]) +def test_capture_acquired_scope(cmake, httpserver, capture, clear): + tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "none"}) + httpserver.expect_oneshot_request("/api/123456/envelope/").respond_with_data("OK") + args = ["log", "no-setup", "attachment", "acquire-scope", capture] + if clear: + args.append("clear-scope") + run( + tmp_path, + "sentry_test_integration", + args, + env=dict(os.environ, SENTRY_DSN=make_dsn(httpserver)), + ) + + assert len(httpserver.log) == 1 + envelope = Envelope.deserialize(httpserver.log[0][0].get_data()) + event = envelope.get_event() + assert event["release"] == ("test-example-release" if clear else "scope-release") + assert event["environment"] == ("development" if clear else "scope-environment") + assert event["sdk"]["version"] == SENTRY_VERSION + assert event["contexts"]["os"]["name"] + assert ("acquired" in event.get("tags", {})) == (not clear) + assert any( + crumb.get("message") == "acquired breadcrumb" + for crumb in (event.get("breadcrumbs") or []) + ) == (not clear) + filenames = {item.headers.get("filename") for item in envelope} + assert "CMakeCache.txt" in filenames + assert ("scope.txt" in filenames) == (not clear) + if not clear: + assert event["user"]["id"] == "scope-user" diff --git a/tests/test_integration_logger.py b/tests/test_integration_logger.py index e752c4a732..6105019c49 100644 --- a/tests/test_integration_logger.py +++ b/tests/test_integration_logger.py @@ -129,7 +129,8 @@ def parse_logger_output(output): "native", marks=[ pytest.mark.skipif( - not has_native or is_qemu, reason="native backend not available" + not has_native or is_qemu or is_android, + reason="native backend not available", ), ], ), @@ -177,7 +178,8 @@ def test_logger_enabled_when_crashed(backend, cmake): "native", marks=[ pytest.mark.skipif( - not has_native or is_qemu, reason="native backend not available" + not has_native or is_qemu or is_android, + reason="native backend not available", ), ], ), diff --git a/tests/test_integration_macos_sandbox.py b/tests/test_integration_macos_sandbox.py index 14f4a3598f..7d3013f615 100644 --- a/tests/test_integration_macos_sandbox.py +++ b/tests/test_integration_macos_sandbox.py @@ -18,10 +18,10 @@ from . import make_dsn, Envelope from .assertions import wait_for_file -from .conditions import has_native +from .conditions import has_native, is_android pytestmark = pytest.mark.skipif( - not (has_native and sys.platform == "darwin"), + not (has_native and sys.platform == "darwin" and not is_android), reason="macOS App Sandbox tests require native backend on macOS", ) @@ -36,7 +36,9 @@ def _create_sandbox_app_bundle(tmp_path, exe_name="sentry_test_integration"): app_dir = os.path.join(str(tmp_path), "SentryTest.app") contents_dir = os.path.join(app_dir, "Contents") macos_dir = os.path.join(contents_dir, "MacOS") - os.makedirs(macos_dir, exist_ok=True) + if os.path.exists(app_dir): + shutil.rmtree(app_dir) + os.makedirs(macos_dir) # Copy executable and sentry-crash into the bundle src_exe = os.path.join(str(tmp_path), exe_name) @@ -48,11 +50,13 @@ def _create_sandbox_app_bundle(tmp_path, exe_name="sentry_test_integration"): if os.path.exists(src_daemon): shutil.copy2(src_daemon, dst_daemon) - # Copy libsentry.dylib if it exists (shared library build) - src_lib = os.path.join(str(tmp_path), "libsentry.dylib") - if os.path.exists(src_lib): - dst_lib = os.path.join(macos_dir, "libsentry.dylib") - shutil.copy2(src_lib, dst_lib) + # Copy the shared library and its versioned symlink chain into the bundle + for src_lib in tmp_path.glob("libsentry*.dylib"): + shutil.copy2( + src_lib, + os.path.join(macos_dir, src_lib.name), + follow_symlinks=False, + ) # Write minimal Info.plist info_plist = { @@ -97,6 +101,8 @@ def _codesign_bundle(app_dir, entitlements_path, exe_name="sentry_test_integrati if name == exe_name: continue # Main exe gets signed with the bundle path = os.path.join(macos_dir, name) + if os.path.islink(path): + continue if os.access(path, os.X_OK) or name.endswith(".dylib"): subprocess.run( ["codesign", "--force", "--sign", "-", path], @@ -128,7 +134,7 @@ def _run_sandboxed(app_dir, exe_name, args, env, expect_failure=False): """ exe_path = os.path.join(app_dir, "Contents", "MacOS", exe_name) - # Set DYLD_LIBRARY_PATH so the executable can find libsentry.dylib + # Set DYLD_LIBRARY_PATH so the executable can find the bundled dylib # inside the bundle (dyld respects this even in sandbox for ad-hoc signed) run_env = dict(env) run_env["DYLD_LIBRARY_PATH"] = os.path.join(app_dir, "Contents", "MacOS") diff --git a/tests/test_integration_native.py b/tests/test_integration_native.py index 392bde0a74..2c4be4abaf 100644 --- a/tests/test_integration_native.py +++ b/tests/test_integration_native.py @@ -5,18 +5,20 @@ multi-thread capture, and FPU/SIMD register capture on all platforms. """ -import json import os +import queue import signal import subprocess import sys +import threading import time import struct -import msgpack +import psutil import pytest from . import ( + crash_env, is_feedback_envelope, is_replay_envelope, lib_name, @@ -31,8 +33,10 @@ ) from .assertions import ( assert_attachment, + assert_attachment_view_hierarchy, assert_breadcrumb, assert_crash_timestamp, + assert_crash_hint_attachments, assert_no_crash_timestamp, assert_debug_meta_images_do_not_overlap, assert_meta, @@ -44,20 +48,28 @@ wait_for, wait_for_file, assert_user_feedback, + assert_crash_stack, ) -from .conditions import has_files, has_system_proxy, is_kcov +from .conditions import has_files, has_http, has_system_proxy, is_arm64e, is_kcov from .conditions import has_native, has_oom, is_asan, is_tsan, is_qemu, is_wine, is_x86 from .proxy import proxy_test_finally, start_proxy, system_proxy pytestmark = pytest.mark.skipif( - not has_native or is_qemu, - reason="Tests need the native backend enabled", + not has_native or not has_http or is_qemu, + reason="Tests need the native backend and HTTP support", ) # Sanitizer builds are slower, so selected native crash tests use the same 10s # timeout the native daemon used before it respected the SDK shutdown timeout. SANITIZER_ARGS = ["shutdown-timeout", "10000"] if is_asan or is_tsan else [] +# A stall costs one 1s send timeout, and later updates only try a nonblocking write. +STALL_UPDATES_TIMEOUT = 30 if is_asan or is_tsan or is_kcov else 5 +# A sanitizer crash handler alone may wait 30s for the daemon. +STALL_STEP_TIMEOUT = 60 if is_asan or is_tsan or is_kcov else 30 +STALL_KILLED_TIMEOUT = 5 if is_asan or is_tsan or is_kcov else 1 +STALL_CLOSED_TIMEOUT = 5 if is_asan or is_tsan or is_kcov else 4 + STATUS_STACK_OVERFLOW = 0xC00000FD STATUS_STACK_BUFFER_OVERRUN = 0xC0000409 STATUS_HEAP_CORRUPTION = 0xC0000374 @@ -74,7 +86,7 @@ def test_native_capture_crash(cmake, httpserver): run_crash( tmp_path, "sentry_test_integration", - ["log", "stdout", "test-logger", "crash"], + ["log", "stdout", "test-logger", "attach-view-hierarchy", "crash"], env=dict(os.environ, SENTRY_DSN=make_dsn(httpserver)), ) assert waiting.result @@ -82,10 +94,25 @@ def test_native_capture_crash(cmake, httpserver): assert len(httpserver.log) >= 1 envelope = Envelope.deserialize(httpserver.log[0][0].get_data()) assert_native_crash(envelope) + assert_attachment_view_hierarchy(envelope) -@pytest.mark.parametrize("callback", ["before-send", "on-crash"]) -def test_native_crash_hint_attachments(cmake, httpserver, callback): +@pytest.mark.parametrize( + "callback, crash", + [ + ("before-send", "crash"), + ("on-crash", "crash"), + pytest.param( + "on-crash", + "crash-null", + marks=pytest.mark.skipif( + sys.platform not in ["linux", "darwin"] or is_wine or is_arm64e, + reason="Null function-pointer calls must fault at IP zero", + ), + ), + ], +) +def test_native_crash_hint_attachments(cmake, httpserver, callback, crash): tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "native"}) httpserver.expect_oneshot_request("/api/123456/envelope/").respond_with_data("OK") @@ -94,21 +121,30 @@ def test_native_crash_hint_attachments(cmake, httpserver, callback): run_crash( tmp_path, "sentry_test_integration", - ["log", "attachment", callback, "crash"], + ["log", "attachment", callback, crash], env=dict(os.environ, SENTRY_DSN=make_dsn(httpserver)), ) assert waiting.result assert len(httpserver.log) >= 1 envelope = Envelope.deserialize(httpserver.log[0][0].get_data()) - assert not any( - item.headers.get("filename") == "CMakeCache.txt" for item in envelope - ) + snapshot = assert_crash_hint_attachments(envelope, callback) assert any( - item.headers.get("filename") == "callback.txt" - and item.payload.bytes == callback.replace("-", "_").encode() - for item in envelope + "sentry_test_integration" in image["code_file"] + for image in snapshot["debug_meta"]["images"] ) + assert_crash_stack(snapshot) + if crash == "crash-null": + frames = snapshot["exception"]["values"][0]["stacktrace"]["frames"] + assert int(frames[-1]["instruction_addr"], 16) == 0 + exceptions = envelope.get_event()["exception"]["values"] + assert len(exceptions) == len(snapshot["exception"]["values"]) + exc = exceptions[0] + local_exc = snapshot["exception"]["values"][0] + assert exc["mechanism"] == local_exc["mechanism"] + assert [frame["instruction_addr"] for frame in exc["stacktrace"]["frames"]] == [ + frame["instruction_addr"] for frame in local_exc["stacktrace"]["frames"] + ] def test_native_on_crashed_last_run(cmake, httpserver): @@ -230,7 +266,7 @@ def test_native_wer_crash(cmake, httpserver, crash_arg, exception_code): run_crash( tmp_path, "sentry_test_integration", - ["log", "stdout", crash_arg], + ["log", "stdout", "initial-scope", "no-setup", crash_arg], env=dict(os.environ, SENTRY_DSN=make_dsn(httpserver)), ) assert waiting.result @@ -238,6 +274,9 @@ def test_native_wer_crash(cmake, httpserver, crash_arg, exception_code): assert len(httpserver.log) >= 1 envelope = Envelope.deserialize(httpserver.log[0][0].get_data()) assert_native_crash(envelope, exception_code=exception_code) + event = envelope.get_event() + assert event["tags"]["test.initial-tag"] == "initial-value" + assert event["contexts"]["initial"]["foo"] == "bar" @pytest.mark.skipif(not has_oom, reason="OOM test unreliable in this environment") @@ -359,21 +398,17 @@ def test_native_capture_minidump_generated(cmake, httpserver): assert not list(db_dir.glob("*.run*.lock")) -# Both daemon envelope writers merge the breadcrumb ring files: the native -# stacktrace writer builds the event from scratch, while the minidump-only -# writer re-parses the parent's event JSON, merges, and re-serializes. Exercise -# both so the minidump path's extra parse/serialize roundtrip is covered too. +# Both daemon envelope writers use the scope received over IPC. +# Exercise breadcrumbs in both native-stacktrace and minidump-only events. BREADCRUMB_CRASH_MODES = ["native", "minidump"] @pytest.mark.parametrize("crash_mode", BREADCRUMB_CRASH_MODES) def test_native_breadcrumbs(cmake, httpserver, crash_mode): - """Test that breadcrumbs survive the daemon's ring-file merge. + """Test that breadcrumbs survive the daemon's IPC scope updates. - The crashing process appends breadcrumbs as msgpack to the ring files; the - daemon reads, merges, and attaches them to the event. Asserting on the - default `debug crumb` verifies that whole roundtrip, not just that an event - arrived. + Asserting on the default `debug crumb` verifies the whole roundtrip, not + just that an event arrived. """ tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "native"}) @@ -398,7 +433,7 @@ def test_native_breadcrumbs(cmake, httpserver, crash_mode): @pytest.mark.parametrize("crash_mode", BREADCRUMB_CRASH_MODES) def test_native_overflow_breadcrumbs(cmake, httpserver, crash_mode): - """Test that the daemon caps merged breadcrumbs at max_breadcrumbs. + """Test that the daemon caps staged breadcrumbs at max_breadcrumbs. The example adds 3 default crumbs plus 101 numbered crumbs ("0".."100"). With the default max_breadcrumbs (100), the daemon keeps the newest 100, @@ -432,62 +467,197 @@ def test_native_overflow_breadcrumbs(cmake, httpserver, crash_mode): assert any(b.get("message") == "100" for b in breadcrumbs) -def test_native_attachment_manifest_is_current(cmake, httpserver): - """The attachment manifest must reflect the live attachment state (#1933). +@pytest.mark.parametrize("mode", [0, 1, 2]) +@pytest.mark.parametrize("scoped_trace", [False, True]) +def test_native_scope_updates_without_snapshot(cmake, httpserver, mode, scoped_trace): + tmp_path = cmake(["sentry_test_unit", "sentry-crash"], {"SENTRY_BACKEND": "native"}) + httpserver.expect_oneshot_request("/api/123456/envelope/").respond_with_data("OK") + env = dict( + os.environ, + SENTRY_DSN=make_dsn(httpserver), + SENTRY_TEST_NATIVE_SCOPE_CRASH=str(mode), + ) + if scoped_trace: + env["SENTRY_TEST_NATIVE_SCOPE_SPAN"] = "1" + with httpserver.wait(timeout=15) as waiting: + run_crash( + tmp_path, + "sentry_test_unit", + ["--no-exec", "native_scope_updates"], + env=env, + ) + assert waiting.result + envelope = Envelope.deserialize(httpserver.log[0][0].get_data()) + event = envelope.get_event() + assert event["release"] == "ipc-release" + assert event["environment"] == "ipc-environment" + assert event["transaction"] == "ipc-transaction" + assert event["level"] == "fatal" + assert event["fingerprint"] == ["ipc", "latest"] + assert event["user"]["username"] == "ipc-user" + assert event["user"]["id"] + assert event["tags"] == {"tag": "latest", "binary-tag": "v\0x"} + assert event["extra"]["large"] == "x" * (1024 * 1024) + assert set(event["extra"]) == {"large", "expected-trace"} + contexts = {"trace", "ipc", "os"} + if sys.platform == "win32" or is_wine: + contexts.add("device") + if is_wine: + contexts.add("wine") + assert set(event["contexts"]) == contexts + assert event["contexts"]["ipc"] == {"status": "latest"} + assert event["contexts"]["trace"] == event["extra"]["expected-trace"] + assert [crumb["index"] for crumb in event["breadcrumbs"]] == [2, 3, 4] + attachments = { + item.headers.get("filename"): item.payload.bytes + for item in envelope + if item.headers.get("type") == "attachment" + and item.headers.get("attachment_type") != "event.minidump" + } + assert attachments == {"latest.txt": b"new"} + for name in ( + "__sentry-event", + "__sentry-breadcrumb1", + "__sentry-breadcrumb2", + "__sentry-attachments", + ): + assert not list((tmp_path / ".sentry-native").glob(f"*.run/{name}")) - The daemon builds hard-crash envelopes from `/__sentry-attachments`, - which the backend only rewrites on a scope flush. `sentry_add_attachment` - adds the fully configured attachment before that flush, so the manifest - must contain all its metadata immediately. - Asserting on the manifest rather than on a crash envelope keeps this - deterministic: the in-process crash handler happens to flush the scope (via - `sentry__trace_finish`), which repairs the manifest before the daemon reads - it, but out-of-process paths such as WER never run that handler. - """ - tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "native"}) +class StallChild: + """Runs the `native_stall` unit test, which waits for `proceed` at each step.""" - cmd = run_command(str(tmp_path / "sentry_test_integration")) - child = subprocess.Popen( - [*cmd, "log", "attach-custom-filename", "sleep"], - cwd=tmp_path, - env=dict(os.environ, SENTRY_DSN=make_dsn(httpserver)), - ) - db_dir = tmp_path / ".sentry-native" + def __init__(self, tmp_path, mode, dsn): + self.child = subprocess.Popen( + [ + *run_command(str(tmp_path / "sentry_test_unit")), + "--no-exec", + "native_stall", + ], + cwd=tmp_path, + env=crash_env( + dict(os.environ, SENTRY_DSN=dsn, SENTRY_TEST_NATIVE_STALL=mode) + ), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + ) + self.lines = queue.Queue() + threading.Thread(target=self._read_lines, daemon=True).start() + + def _read_lines(self): + for line in self.child.stdout: + self.lines.put(line) + + def __enter__(self): + return self + + def __exit__(self, *args): + self.child.kill() + self.child.wait() + + def wait_for_step(self, step, timeout=STALL_STEP_TIMEOUT): + deadline = time.monotonic() + timeout + while f"stall:{step}".encode() not in self.lines.get( + timeout=max(0, deadline - time.monotonic()) + ): + pass + + def proceed(self): + self.child.stdin.write(b"\n") + self.child.stdin.flush() + + def daemon(self): + # Wine reparents the processes it spawns + procs = ( + psutil.process_iter() + if is_wine + else psutil.Process(self.child.pid).children() + ) + for proc in procs: + if "sentry-crash" in proc.name(): + return proc + pytest.fail("native crash daemon not found") + + +def is_gone(proc): + try: + return proc.status() == psutil.STATUS_ZOMBIE + except psutil.NoSuchProcess: + return True - last_manifest = None - def manifest_is_current(): - # Validate the complete expected state against a single snapshot - # instead of waiting on one field and re-reading the file. - nonlocal last_manifest - paths = list(db_dir.glob("*.run/__sentry-attachments")) - if not paths: - return False +def test_native_stall_bounds_updates(cmake, unreachable_dsn): + tmp_path = cmake(["sentry_test_unit", "sentry-crash"], {"SENTRY_BACKEND": "native"}) + with StallChild(tmp_path, "updates", unreachable_dsn) as stall: + stall.wait_for_step("ready") + daemon = stall.daemon() + daemon.suspend() try: - unpacker = msgpack.Unpacker(raw=False) - unpacker.feed(paths[0].read_bytes()) - manifest = list(unpacker) - except (OSError, msgpack.UnpackException): - # rewritten in place, so a read can catch a partial file - return False - last_manifest = manifest - return ( - len(manifest) == 1 - and manifest[0].get("filename") == "custom-name.log" - and manifest[0].get("content_type") == "application/zstd" - and manifest[0].get("path", "").endswith("CMakeCache.txt") - ) + started_at = time.monotonic() + stall.proceed() + stall.wait_for_step("done") + assert time.monotonic() - started_at < STALL_UPDATES_TIMEOUT + finally: + daemon.resume() + started_at = time.monotonic() + stall.proceed() + assert stall.child.wait(timeout=STALL_STEP_TIMEOUT) == 0 + # the resumed daemon exits on its shutdown frame, before the 5s kill + assert time.monotonic() - started_at < STALL_CLOSED_TIMEOUT + + +def test_native_stall_crash(cmake, httpserver): + tmp_path = cmake(["sentry_test_unit", "sentry-crash"], {"SENTRY_BACKEND": "native"}) + httpserver.expect_oneshot_request("/api/123456/envelope/").respond_with_data("OK") + with httpserver.wait(timeout=STALL_STEP_TIMEOUT) as waiting: + with StallChild(tmp_path, "crash", make_dsn(httpserver)) as stall: + stall.wait_for_step("ready") + daemon = stall.daemon() + daemon.suspend() + try: + stall.proceed() + # the crash handler reaches on_crash behind the stalled sender + stall.wait_for_step("crash") + finally: + daemon.resume() + assert stall.child.wait(timeout=STALL_STEP_TIMEOUT) != 0 + assert waiting.result - try: - up_to_date = wait_for(manifest_is_current) - finally: - child.terminate() - child.wait() - assert ( - up_to_date - ), f"attachment manifest does not reflect the live attachment state: {last_manifest}" +def test_native_stall_recovery(cmake, httpserver): + tmp_path = cmake(["sentry_test_unit", "sentry-crash"], {"SENTRY_BACKEND": "native"}) + httpserver.expect_oneshot_request("/api/123456/envelope/").respond_with_data("OK") + with httpserver.wait(timeout=STALL_STEP_TIMEOUT) as waiting: + with StallChild(tmp_path, "recover", make_dsn(httpserver)) as stall: + stall.wait_for_step("ready") + daemon = stall.daemon() + daemon.suspend() + try: + stall.proceed() + stall.wait_for_step("done") + finally: + daemon.resume() + stall.proceed() + assert stall.child.wait(timeout=STALL_STEP_TIMEOUT) != 0 + assert waiting.result + event = Envelope.deserialize(httpserver.log[0][0].get_data()).get_event() + assert [crumb["index"] for crumb in event["breadcrumbs"]] == list(range(74)) + assert event["extra"]["large"] == "x" * (2 * 1024 * 1024) + + +def test_native_stall_killed_daemon(cmake, unreachable_dsn): + tmp_path = cmake(["sentry_test_unit", "sentry-crash"], {"SENTRY_BACKEND": "native"}) + with StallChild(tmp_path, "killed", unreachable_dsn) as stall: + stall.wait_for_step("ready") + daemon = stall.daemon() + daemon.kill() + assert wait_for(lambda: is_gone(daemon)) + started_at = time.monotonic() + stall.proceed() + stall.wait_for_step("done") + assert time.monotonic() - started_at < STALL_KILLED_TIMEOUT + stall.proceed() + assert stall.child.wait(timeout=STALL_STEP_TIMEOUT) == 0 def test_native_byte_attachment_is_confined(cmake, unreachable_dsn): @@ -753,6 +923,7 @@ def _parse_minidump(path): is_arm64 = cpu_arch in (0x8003, 0xC) is_amd64 = cpu_arch == 9 is_x86 = cpu_arch == 0 + is_riscv = cpu_arch == 0x8006 threads = [] if 3 in streams: # ThreadList @@ -779,6 +950,9 @@ def _parse_minidump(path): elif is_x86: # CONTEXT_X86: esp at offset 0xC4. sp = struct.unpack_from(" 0 - if sys.platform == "darwin": + if sys.platform in ["linux", "darwin"] and not is_wine: assert_debug_meta_images_do_not_overlap(event) @@ -1506,7 +1685,7 @@ def test_crash_mode_native_with_minidump(cmake, httpserver): # Should have debug_meta assert "debug_meta" in event - if sys.platform == "darwin": + if sys.platform in ["linux", "darwin"] and not is_wine: assert_debug_meta_images_do_not_overlap(event) @@ -1754,8 +1933,7 @@ def daemon_log(): assert "Parent process exited without crash" not in daemon_log() assert "Crash notification received, processing" not in daemon_log() assert not list(db_dir.glob("*.run/*.dmp")) - snapshot = json.loads(next(db_dir.glob("*.run/__sentry-event")).read_text()) - assert "exception" not in snapshot + assert not list(db_dir.glob("*.run/__sentry-event")) finally: if child.poll() is None: child.kill() @@ -1763,6 +1941,59 @@ def daemon_log(): assert wait_for(lambda: not list(db_dir.glob("*.run.daemon.lock"))) +@pytest.mark.parametrize("clear", [False, True]) +def test_native_acquired_scope(cmake, httpserver, clear): + tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "native"}) + httpserver.expect_oneshot_request("/api/123456/envelope/").respond_with_data("OK") + args = ["log", "no-setup", "attachment", "acquire-scope", "crash"] + if clear: + args.append("clear-scope") + with httpserver.wait(timeout=10) as waiting: + run_crash( + tmp_path, + "sentry_test_integration", + args, + env=dict(os.environ, SENTRY_DSN=make_dsn(httpserver)), + ) + assert waiting.result + + envelope = Envelope.deserialize(httpserver.log[0][0].get_data()) + assert_native_crash(envelope) + event = envelope.get_event() + assert event["release"] == ("test-example-release" if clear else "scope-release") + assert event["environment"] == ("development" if clear else "scope-environment") + assert event["sdk"]["name"] == "sentry.native" + assert event["contexts"]["os"]["name"] + assert ("acquired" in event.get("tags", {})) == (not clear) + assert any( + crumb.get("message") == "acquired breadcrumb" + for crumb in (event.get("breadcrumbs") or []) + ) == (not clear) + filenames = {item.headers.get("filename") for item in envelope} + assert "CMakeCache.txt" in filenames + assert ("scope.txt" in filenames) == (not clear) + + +def test_native_scope_snapshot(cmake, httpserver): + tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "native"}) + httpserver.expect_oneshot_request("/api/123456/envelope/").respond_with_data("OK") + + with httpserver.wait(timeout=10) as waiting: + run_crash( + tmp_path, + "sentry_test_integration", + ["initial-scope", "no-setup", "crash"], + env=dict(os.environ, SENTRY_DSN=make_dsn(httpserver)), + ) + assert waiting.result + + envelope = Envelope.deserialize(httpserver.log[0][0].get_data()) + event = envelope.get_event() + assert event["tags"]["test.initial-tag"] == "initial-value" + assert event["event_id"] + assert event["level"] == "fatal" + + @pytest.mark.parametrize( "cache_args", [ @@ -1876,6 +2107,58 @@ def test_native_symbolication(cmake, httpserver, crash_mode, symbolize): ), "missing symbolicated function names" +@pytest.mark.parametrize("clear_hint", [False, True]) +def test_native_scope_updates_in_crash_callback(cmake, httpserver, clear_hint): + tmp_path = cmake(["sentry_test_unit", "sentry-crash"], {"SENTRY_BACKEND": "native"}) + httpserver.expect_oneshot_request("/api/123456/envelope/").respond_with_data("OK") + env = dict( + os.environ, + SENTRY_DSN=make_dsn(httpserver), + SENTRY_TEST_NATIVE_SCOPE_CRASH="1", + SENTRY_TEST_NATIVE_SCOPE_CALLBACK="1", + ) + if clear_hint: + env["SENTRY_TEST_NATIVE_SCOPE_HINT_CLEAR"] = "1" + with httpserver.wait(timeout=15) as waiting: + run_crash( + tmp_path, + "sentry_test_unit", + ["--no-exec", "native_scope_updates"], + env=env, + ) + assert waiting.result + envelope = Envelope.deserialize(httpserver.log[0][0].get_data()) + event = envelope.get_event() + assert event["callback"] is True + assert event["tags"]["tag"] == "callback" + attachments = [ + item for item in envelope if item.headers.get("type") == "attachment" + ] + if clear_hint: + assert attachments == [] + else: + assert len(attachments) == 1 + assert attachments[0].headers["filename"] == "callback.txt" + assert attachments[0].payload.bytes == b"callback" + + +@pytest.mark.skipif( + sys.platform != "linux" or is_wine, + reason="Test uses Linux daemon startup", +) +def test_native_shutdown_during_crash(cmake): + tmp_path = cmake( + ["sentry_test_unit", "sentry-crash"], + {"SENTRY_BACKEND": "native", "SENTRY_TRANSPORT": "none"}, + ) + run( + tmp_path, + "sentry_test_unit", + ["--no-exec", "crash_daemon_shutdown_during_crash"], + env=dict(os.environ, SENTRY_TEST_NATIVE_DAEMON=str(tmp_path / "sentry-crash")), + ) + + def test_native_proxy_set_empty(cmake, httpserver): proxy_process = None # store the proxy process to terminate it later try: @@ -1938,3 +2221,67 @@ def test_native_proxy_system(cmake, httpserver, proxy_empty): proxy_process, expected_proxy_logsize=0 if proxy_empty else None, ) + + +@pytest.mark.skipif( + sys.platform == "win32" or is_wine or is_asan or is_tsan or is_kcov, + reason="Covers the Linux and macOS writers, without sanitizer shadow memory " + "or kcov's ptrace tracer", +) +@pytest.mark.parametrize( + "args, embedded, uploaded", + [ + (["large-allocation", "8"], True, False), + (["sparse-allocation", "large-allocation", "600"], True, False), + (["large-allocation", "600"], False, False), + (["large-attachment", "large-allocation", "128"], False, True), + ], +) +def test_native_full_mode(cmake, httpserver, args, embedded, uploaded): + # Static build so the hardened-runtime process can load itself without + # tripping the dyld "different team IDs" check on ad-hoc-signed dylibs. + tmp_path = cmake( + ["sentry_test_integration"], + {"SENTRY_BACKEND": "native", "BUILD_SHARED_LIBS": "OFF"}, + ) + + if sys.platform == "darwin": + _codesign_for_task_for_pid( + str(tmp_path / "sentry_test_integration"), + str(tmp_path / "sentry-crash"), + ) + + httpserver.expect_request("/api/123456/upload/").respond_with_data( + "Not Found", status=404 + ) + httpserver.expect_oneshot_request("/api/123456/envelope/").respond_with_data("OK") + + with httpserver.wait(timeout=300) as waiting: + run_crash( + tmp_path, + "sentry_test_integration", + ["log", "stdout", "minidump-mode", "2", *args, "crash"], + env=dict(os.environ, SENTRY_DSN=make_dsn(httpserver)), + ) + assert waiting.result + + requests = [entry[0] for entry in httpserver.log] + envelope = Envelope.deserialize( + next(req for req in requests if "/envelope/" in req.path).get_data() + ) + assert envelope.get_event() is not None + + minidumps = [ + item.payload.bytes + for item in envelope + if item.headers.get("attachment_type") == "event.minidump" + ] + assert len(minidumps) == int(embedded) + # The fixture ends its allocation with this pattern + assert all(b"\xa5" * 32 in minidump for minidump in minidumps) + + # sentry + metadata = "sentry eyJhdHRhY2htZW50X3R5cGUiOiJldmVudC5taW5pZHVtcCJ9" + assert uploaded == any( + req.headers.get("upload-metadata") == metadata for req in requests + ) diff --git a/tests/test_integration_stdout.py b/tests/test_integration_stdout.py index cc7651dbbb..b28e84ba19 100644 --- a/tests/test_integration_stdout.py +++ b/tests/test_integration_stdout.py @@ -13,6 +13,7 @@ assert_breadcrumb, assert_stacktrace, assert_event, + assert_event_meta, assert_inproc_crash, assert_minidump, assert_before_send, @@ -20,7 +21,9 @@ assert_no_crash_timestamp, assert_breakpad_crash, assert_exception, + assert_crash_hint_attachments, wait_for, + assert_crash_stack, ) from .conditions import has_breakpad, has_files, is_qemu, is_wine @@ -37,14 +40,14 @@ def test_capture_stdout(cmake): ["sentry_test_integration"], { "SENTRY_BACKEND": "none", - "SENTRY_TRANSPORT": "none", + "SENTRY_TRANSPORT": "stdout", }, ) output = check_output( tmp_path, "sentry_test_integration", - ["stdout", "attachment", "capture-event", "add-stacktrace"], + ["attachment", "capture-event", "add-stacktrace"], ) envelope = Envelope.deserialize(output) @@ -260,18 +263,6 @@ def run_crash_stdout_for(backend, cmake, example_args): return run_stdout_for(backend, cmake, ["attachment", "crash"] + example_args) -def assert_crash_hint_attachments(envelope, callback): - assert not any( - item.headers.get("filename") in ("CMakeCache.txt", "bytes.bin") - for item in envelope - ) - assert any( - item.headers.get("filename") == "callback.txt" - and item.payload.bytes == callback.replace("-", "_").encode() - for item in envelope - ) - - def test_inproc_crash_stdout(cmake): tmp_path, output = run_crash_stdout_for("inproc", cmake, []) @@ -349,9 +340,12 @@ def test_inproc_crash_stdout_before_send(cmake): assert_no_crash_timestamp(has_files, tmp_path) assert_meta(envelope, integration="inproc") assert_breadcrumb(envelope) - assert_crash_hint_attachments(envelope, "before-send") + snapshot = assert_crash_hint_attachments(envelope, "before-send") + assert_event_meta(snapshot, integrations=["inproc"]) + assert snapshot["debug_meta"] == envelope.get_event()["debug_meta"] assert_inproc_crash(envelope) assert_before_send(envelope) + assert_crash_stack(snapshot) @pytest.mark.skipif(is_qemu, reason="unreliable under qemu-user") @@ -378,8 +372,10 @@ def test_inproc_crash_stdout_before_send_and_on_crash(cmake): assert_no_crash_timestamp(has_files, tmp_path) assert_meta(envelope, integration="inproc") assert_breadcrumb(envelope) - assert_crash_hint_attachments(envelope, "on-crash") + snapshot = assert_crash_hint_attachments(envelope, "on-crash") + assert snapshot["debug_meta"] == envelope.get_event()["debug_meta"] assert_inproc_crash(envelope) + assert_crash_stack(snapshot) @pytest.mark.parametrize( diff --git a/tests/test_integration_transactions.py b/tests/test_integration_transactions.py index 410715e7b4..3fdb193639 100644 --- a/tests/test_integration_transactions.py +++ b/tests/test_integration_transactions.py @@ -1,6 +1,7 @@ import os -import time +import urllib.parse import uuid +from datetime import datetime import pytest @@ -20,7 +21,6 @@ pytestmark = pytest.mark.skipif(not has_http, reason="tests need http") -RFC3339_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" UPSTREAM_TRACE_ID = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" UPSTREAM_PARENT_SPAN_ID = "bbbbbbbbbbbbbbbb" @@ -85,9 +85,9 @@ def test_transaction_only(cmake, httpserver, build_args): assert trace_context["span_id"] assert trace_context["status"] == "ok" - start_timestamp = time.strptime(payload["start_timestamp"], RFC3339_FORMAT) + start_timestamp = datetime.fromisoformat(payload["start_timestamp"]) assert start_timestamp - timestamp = time.strptime(payload["timestamp"], RFC3339_FORMAT) + timestamp = datetime.fromisoformat(payload["timestamp"]) assert timestamp >= start_timestamp assert trace_context["data"] == {"url": "https://example.com"} @@ -141,9 +141,9 @@ def test_before_transaction_callback(cmake, httpserver): assert trace_context["span_id"] assert trace_context["status"] == "ok" - start_timestamp = time.strptime(payload["start_timestamp"], RFC3339_FORMAT) + start_timestamp = datetime.fromisoformat(payload["start_timestamp"]) assert start_timestamp - timestamp = time.strptime(payload["timestamp"], RFC3339_FORMAT) + timestamp = datetime.fromisoformat(payload["timestamp"]) assert timestamp >= start_timestamp assert trace_context["data"] == {"url": "https://example.com"} @@ -344,6 +344,136 @@ def test_set_trace_event(cmake, httpserver): assert trace_context["parent_span_id"] == "f0f0f0f0f0f0f0f0" +def test_set_scope_trace_event(cmake, httpserver): + tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "none"}) + + httpserver.expect_oneshot_request("/api/123456/envelope/").respond_with_data("OK") + env = dict(os.environ, SENTRY_DSN=make_dsn(httpserver), SENTRY_RELEASE="🤮🚀") + + run( + tmp_path, + "sentry_test_integration", + ["log", "set-trace", "set-scope-trace", "capture-with-scope"], + env=env, + ) + + assert len(httpserver.log) == 1 + event_req = httpserver.log[0][0] + event_body = event_req.get_data() + + event_envelope = Envelope.deserialize(event_body) + + # Extract the one-and-only-item + (event,) = event_envelope.items + + payload = event.payload.json + + # the local scope's trace takes precedence over the isolation scope's + trace_context = payload["contexts"]["trace"] + assert trace_context["trace_id"] == "11112222333344445555666677778888" + assert trace_context["parent_span_id"] == "0f0f0f0f0f0f0f0f" + + trace_header = event_envelope.headers["trace"] + assert trace_header["sample_rand"] == trace_context["sample_rand"] + del trace_header["sample_rand"] + assert trace_header == { + "environment": "development", + "public_key": "uiaeosnrtdy", + "release": "test-example-release", + "sample_rate": 0, + "sampled": "false", + "trace_id": "11112222333344445555666677778888", + } + + assert "dsc" not in payload + + +def test_continue_trace_event(cmake, httpserver): + tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "none"}) + + httpserver.expect_oneshot_request("/api/123456/envelope/").respond_with_data("OK") + env = dict(os.environ, SENTRY_DSN=make_dsn(httpserver), SENTRY_RELEASE="🤮🚀") + + run( + tmp_path, + "sentry_test_integration", + ["log", "continue-trace", "capture-event"], + env=env, + ) + + assert len(httpserver.log) == 1 + event_req = httpserver.log[0][0] + event_body = event_req.get_data() + + event_envelope = Envelope.deserialize(event_body) + + # Extract the one-and-only-item + (event,) = event_envelope.items + + payload = event.payload.json + + trace_context = payload["contexts"]["trace"] + assert trace_context["trace_id"] == "aaaabbbbccccddddeeeeffff00001111" + assert trace_context["parent_span_id"] == "f0f0f0f0f0f0f0f0" + assert trace_context["sampled"] is True + + # the frozen upstream DSC with the inherited sampling decision + assert event_envelope.headers["trace"] == { + "environment": "upstream", + "sample_rand": "0.25", + "sampled": "true", + "trace_id": "aaaabbbbccccddddeeeeffff00001111", + } + + +@pytest.mark.parametrize("continue_trace", [False, True]) +def test_iter_trace_propagation_headers(cmake, httpserver, continue_trace): + tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "none"}) + + httpserver.expect_oneshot_request("/api/123456/envelope/").respond_with_data("OK") + env = dict(os.environ, SENTRY_DSN=make_dsn(httpserver), SENTRY_RELEASE="🤮🚀") + + args = ["log", "iter-trace-headers", "capture-event"] + if continue_trace: + args.insert(1, "continue-trace") + run(tmp_path, "sentry_test_integration", args, env=env) + + assert len(httpserver.log) == 1 + event_req = httpserver.log[0][0] + event_body = event_req.get_data() + + event_envelope = Envelope.deserialize(event_body) + + # Extract the one-and-only-item + (event,) = event_envelope.items + + payload = event.payload.json + + # the propagated headers continue the event's trace + trace_context = payload["contexts"]["trace"] + sentry_trace = f"{trace_context['trace_id']}-{trace_context['span_id']}" + if continue_trace: + sentry_trace += "-1" + assert payload["extra"]["sentry-trace"] == sentry_trace + + # the baggage carries the event's DSC, without a deferred sampling decision + baggage = dict(m.split("=", 1) for m in payload["extra"]["baggage"].split(",")) + assert baggage.pop("sentry-trace_id") == trace_context["trace_id"] + trace_header = event_envelope.headers["trace"] + assert {f"sentry-{key}" for key in trace_header} - { + "sentry-trace_id", + "sentry-sampled", + } == set(baggage) + for key, value in baggage.items(): + expected = trace_header[key.removeprefix("sentry-")] + value = urllib.parse.unquote(value) + if isinstance(expected, str): + assert value == expected + else: + # baggage stringifies doubles with %g + assert float(value) == pytest.approx(expected, rel=1e-5) + + def test_set_trace_transaction_scoped_event(cmake, httpserver): tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "none"}) diff --git a/tests/test_integration_tus.py b/tests/test_integration_tus.py index 97df4854be..29c3ec61a8 100644 --- a/tests/test_integration_tus.py +++ b/tests/test_integration_tus.py @@ -8,10 +8,15 @@ from . import ( make_dsn, run, + run_crash, Envelope, SENTRY_VERSION, ) -from .assertions import assert_attachment +from .assertions import ( + assert_attachment, + assert_gzip_content_encoding, + assert_gzip_file_header, +) from .conditions import has_breakpad, has_files, has_http, has_native, is_qemu pytestmark = [ @@ -23,20 +28,84 @@ auth_header = ( f"Sentry sentry_key=uiaeosnrtdy, sentry_version=7, sentry_client=sentry.native/{SENTRY_VERSION}" ) -# sentry -upload_metadata = "sentry eyJhdHRhY2htZW50X3R5cGUiOiJldmVudC5taW5pZHVtcCJ9" +# sentry +upload_metadata = "sentry eyJhdHRhY2htZW50X3R5cGUiOiJldmVudC5hdHRhY2htZW50In0=" # fmt: on -def test_tus_upload(cmake, httpserver): +upload_size = 100 * 1024 * 1024 +chunk_size = 25 * 1024 * 1024 +chunk_headers = { + "Upload-Chunk-Granularity": "1048576", + "Upload-Min-Chunk-Size": "1048576", + "Upload-Max-Chunk-Size": str(chunk_size), +} + + +def expect_upload_chunks( + httpserver, + upload_uri, + upload_qs, + final_location, + offset=0, + size=chunk_size, + compressed=False, +): + while offset < upload_size: + length = min(size, upload_size - offset) + headers = {"Upload-Offset": str(offset + length)} + if offset + length == upload_size: + headers["Location"] = final_location + length_header = ( + {"x-decoded-content-length": str(length)} + if compressed + else {"content-length": str(length)} + ) + httpserver.expect_oneshot_request( + upload_uri, + method="PATCH", + headers={ + "tus-resumable": "1.0.0", + "upload-offset": str(offset), + **length_header, + }, + query_string=upload_qs, + ).respond_with_data("", status=204, headers=headers) + offset += length + + +@pytest.mark.parametrize( + "granularity, build_args", + [ + (1, {}), + (6, {}), + (None, {}), + (1, {"SENTRY_TRANSPORT_COMPRESSION": "On"}), + ], + ids=["chunked", "rounded", "single", "compressed"], +) +def test_tus_upload(cmake, httpserver, granularity, build_args): tmp_path = cmake( ["sentry_test_integration"], - {"SENTRY_BACKEND": "none"}, + {"SENTRY_BACKEND": "none", **build_args}, ) + compressed = build_args.get("SENTRY_TRANSPORT_COMPRESSION") == "On" upload_uri = "/api/123456/upload/abc123def456789/" upload_qs = "length=104857600&signature=xyz" location = httpserver.url_for(upload_uri) + "?" + upload_qs + final_qs = "upload_length=104857600&upload_signature=xyz" + final_location = httpserver.url_for(upload_uri) + "?" + final_qs + + size = upload_size + headers = {"Location": location} + if granularity: + unit = granularity * 1024 * 1024 + size = chunk_size - chunk_size % unit + headers.update(chunk_headers) + headers["Upload-Chunk-Granularity"] = str(unit) + headers["Upload-Min-Chunk-Size"] = str(unit) + count = (upload_size + size - 1) // size # TUS creation request (POST, no body) -> 201 + Location httpserver.expect_oneshot_request( @@ -46,16 +115,17 @@ def test_tus_upload(cmake, httpserver): ).respond_with_data( "OK", status=201, - headers={"Location": location}, + headers=headers, ) - # TUS upload request (PATCH with body) -> 204 - httpserver.expect_oneshot_request( + expect_upload_chunks( + httpserver, upload_uri, - method="PATCH", - headers={"tus-resumable": "1.0.0"}, - query_string=upload_qs, - ).respond_with_data("", status=204) + upload_qs, + final_location, + size=size, + compressed=compressed, + ) httpserver.expect_request( "/api/123456/envelope/", @@ -67,11 +137,20 @@ def test_tus_upload(cmake, httpserver): run( tmp_path, "sentry_test_integration", - ["log", "no-setup", "attachment", "large-attachment", "capture-event"], + [ + "log", + "no-setup", + "attachment", + "large-attachment", + "capture-event", + # extra time for compressing 100 MiB + "shutdown-timeout", + "30000", + ], env=env, ) - assert len(httpserver.log) == 3 + assert len(httpserver.log) == count + 2 # Find the create, upload, and envelope requests create_req = None @@ -100,7 +179,10 @@ def test_tus_upload(cmake, httpserver): # Verify TUS upload request headers assert upload_req.headers.get("tus-resumable") == "1.0.0" assert upload_req.headers.get("content-type") == "application/offset+octet-stream" - assert upload_req.headers.get("upload-offset") == "0" + assert upload_req.headers.get("upload-offset") == str((count - 1) * size) + if compressed: + assert_gzip_content_encoding(upload_req) + assert_gzip_file_header(upload_req.get_data()) # The envelope contains normal small attachments and the large # attachment-ref. @@ -118,11 +200,12 @@ def test_tus_upload(cmake, httpserver): attachment_ref = item break + # The placeholder uses the Location of the final PATCH response, not the + # one from the creation request. assert attachment_ref is not None - assert attachment_ref.payload.json["location"] == location - assert not os.path.isabs(attachment_ref.payload.json["path"]) + assert attachment_ref.payload.json["location"] == final_location assert attachment_ref.headers.get("attachment_length") == 100 * 1024 * 1024 - assert attachment_ref.headers.get("attachment_type") == "event.minidump" + assert attachment_ref.headers.get("attachment_type") == "event.attachment" # large attachment files should be cleaned up after send cache_dir = os.path.join(tmp_path, ".sentry-native", "cache") @@ -197,15 +280,10 @@ def test_tus_rate_limit(cmake, httpserver): ).respond_with_data( "OK", status=201, - headers={"Location": location}, + headers={"Location": location, **chunk_headers}, ) - httpserver.expect_oneshot_request( - upload_uri, - method="PATCH", - headers={"tus-resumable": "1.0.0"}, - query_string=upload_qs, - ).respond_with_data("", status=204) + expect_upload_chunks(httpserver, upload_uri, upload_qs, location) httpserver.expect_oneshot_request( "/api/123456/envelope/", @@ -248,9 +326,9 @@ def test_tus_rate_limit(cmake, httpserver): req for req, _resp in httpserver.log if req.path == "/api/123456/envelope/" ] - assert len(httpserver.log) == 3 + assert len(httpserver.log) == 6 assert len(uploads) == 1 - assert len(patches) == 1 + assert len(patches) == 4 assert len(envelopes) == 1 cache_dir = os.path.join(tmp_path, ".sentry-native", "cache") @@ -259,7 +337,8 @@ def test_tus_rate_limit(cmake, httpserver): assert leftovers == [] -def test_tus_shutdown(cmake, httpserver): +@pytest.mark.parametrize("chunked", [True, False], ids=["chunked", "legacy"]) +def test_tus_resume_after_shutdown(cmake, httpserver, chunked): tmp_path = cmake( ["sentry_test_integration"], {"SENTRY_BACKEND": "none"}, @@ -270,17 +349,31 @@ def test_tus_shutdown(cmake, httpserver): upload_uri = "/api/123456/upload/abc123def456789/" upload_qs = "length=104857600&signature=xyz" location = httpserver.url_for(upload_uri) + "?" + upload_qs - - release_create = threading.Event() - - def delayed_create(_req): - release_create.wait() - return Response("OK", status=201, headers={"Location": location}) + final_qs = "upload_length=104857600&upload_signature=xyz" + final_location = httpserver.url_for(upload_uri) + "?" + final_qs + upload_offset = chunk_size if chunked else upload_size // 2 httpserver.expect_oneshot_request( "/api/123456/upload/", headers={"tus-resumable": "1.0.0"}, - ).respond_with_handler(delayed_create) + ).respond_with_data( + "OK", + status=201, + headers={"Location": location, **(chunk_headers if chunked else {})}, + ) + + release_upload = threading.Event() + + def delayed_upload(_req): + release_upload.wait() + return Response("", status=204, headers={"Upload-Offset": str(upload_offset)}) + + httpserver.expect_oneshot_request( + upload_uri, + method="PATCH", + headers={"tus-resumable": "1.0.0", "upload-offset": "0"}, + query_string=upload_qs, + ).respond_with_handler(delayed_upload) with httpserver.wait(timeout=10): try: @@ -292,13 +385,15 @@ def delayed_create(_req): "no-setup", "large-attachment", "capture-event", + # extra time for sending the first PATCH + "shutdown-timeout", + "10000", "sleep-after-shutdown", ], env=env, - timeout=30, ) finally: - release_create.set() + release_upload.set() db_dir = os.path.join(tmp_path, ".sentry-native") cache_dir = os.path.join(db_dir, "cache") @@ -312,26 +407,185 @@ def delayed_create(_req): envelope_files = [f for f in os.listdir(run_dir) if f.endswith(".envelope")] assert len(envelope_files) == 1 base = envelope_files[0][: -len(".envelope")] + with open(os.path.join(run_dir, envelope_files[0]), "rb") as f: + persisted = Envelope.deserialize(f.read()) + ref = next(item for item in persisted if item.headers.get("type") == "attachment") + assert ref.payload.json.get("chunk_size", 0) == (chunk_size if chunked else 0) siblings = [f for f in os.listdir(cache_dir) if f.startswith(base)] assert len(siblings) > 0 + resume_marker = b"resumed-body" + with open(os.path.join(cache_dir, siblings[0]), "r+b") as attachment: + attachment.seek(upload_offset) + attachment.write(resume_marker) httpserver.clear_all_handlers() + httpserver.expect_oneshot_request( + upload_uri, + method="HEAD", + headers={"tus-resumable": "1.0.0"}, + query_string=upload_qs, + ).respond_with_data("", status=204, headers={"Upload-Offset": str(upload_offset)}) + + expect_upload_chunks( + httpserver, + upload_uri, + upload_qs, + final_location, + offset=upload_offset, + size=chunk_size if chunked else upload_size, + ) + + httpserver.expect_oneshot_request( + "/api/123456/envelope/", + headers={"x-sentry-auth": auth_header}, + ).respond_with_data("OK") + + with httpserver.wait(timeout=10): + run( + tmp_path, + "sentry_test_integration", + [ + "log", + "no-setup", + # extra time for resuming 100 MiB upload + "shutdown-timeout", + "10000", + ], + env=env, + ) + + envelope_reqs = [ + entry[0] for entry in httpserver.log if "/envelope/" in entry[0].path + ] + assert len(envelope_reqs) == 1 + + envelope = Envelope.deserialize(envelope_reqs[0].get_data()) + attachment_ref = None + for item in envelope: + if ( + item.headers.get("content_type") + == "application/vnd.sentry.attachment-ref+json" + ): + if hasattr(item.payload, "json") and "location" in item.payload.json: + attachment_ref = item + break + + assert attachment_ref is not None + assert attachment_ref.payload.json["location"] == final_location + + upload_reqs = [ + req + for req, _resp in httpserver.log + if req.path == upload_uri and req.method == "PATCH" + ] + assert len(upload_reqs) == (4 if chunked else 2) + assert int(upload_reqs[1].headers["content-length"]) == ( + chunk_size if chunked else upload_size - upload_offset + ) + assert upload_reqs[1].get_data().startswith(resume_marker) + + leftover_siblings = [f for f in os.listdir(cache_dir) if f.startswith(base)] + assert leftover_siblings == [] + + +@pytest.mark.parametrize( + "status", [409, 503, 204], ids=["conflict", "unavailable", "partial"] +) +def test_tus_resume_after_retry(cmake, httpserver, status): + tmp_path = cmake( + ["sentry_test_integration"], + {"SENTRY_BACKEND": "none"}, + ) + + env = dict(os.environ, SENTRY_DSN=make_dsn(httpserver)) + + upload_uri = "/api/123456/upload/abc123def456789/" + upload_qs = "length=104857600&signature=xyz" + location = httpserver.url_for(upload_uri) + "?" + upload_qs + final_qs = "upload_length=104857600&upload_signature=xyz" + final_location = httpserver.url_for(upload_uri) + "?" + final_qs + upload_offset = 5 * 1024 * 1024 + httpserver.expect_oneshot_request( "/api/123456/upload/", headers={"tus-resumable": "1.0.0"}, ).respond_with_data( - "OK", - status=201, - headers={"Location": location}, + "OK", status=201, headers={"Location": location, **chunk_headers} ) + # The server only received part of the body, reported as an offset + # conflict, as unavailable, or as a partial Upload-Offset on the 204. httpserver.expect_oneshot_request( upload_uri, method="PATCH", + headers={"tus-resumable": "1.0.0", "upload-offset": "0"}, + query_string=upload_qs, + ).respond_with_data( + "", status=status, headers={"Upload-Offset": str(upload_offset)} + ) + + if status == 204: + expect_upload_chunks( + httpserver, upload_uri, upload_qs, final_location, offset=upload_offset + ) + httpserver.expect_oneshot_request( + "/api/123456/envelope/", headers={"x-sentry-auth": auth_header} + ).respond_with_data("OK") + + run( + tmp_path, + "sentry_test_integration", + [ + "log", + "no-setup", + "http-retry", + "large-attachment", + "capture-event", + # extra time for resuming 100 MiB upload + "shutdown-timeout", + "10000", + ], + env=env, + ) + + if status == 204: + assert len(httpserver.log) == 7 + envelope_req = httpserver.log[-1][0] + envelope = Envelope.deserialize(envelope_req.get_data()) + ref = next( + item for item in envelope if item.headers.get("type") == "attachment" + ) + assert ref.payload.json["location"] == final_location + return + + # The envelope is kept for retry instead of being sent without the + # attachment-ref. + assert len(httpserver.log) == 2 + cache_dir = os.path.join(tmp_path, ".sentry-native", "cache") + envelope_files = [f for f in os.listdir(cache_dir) if f.endswith(".envelope")] + assert len(envelope_files) == 1 + assert "-00-" in envelope_files[0] + uuid = envelope_files[0][-len(".envelope") - 36 : -len(".envelope")] + siblings = [f for f in os.listdir(cache_dir) if f.startswith(uuid)] + assert len(siblings) > 0 + resume_marker = b"resumed-body" + with open(os.path.join(cache_dir, siblings[0]), "r+b") as attachment: + attachment.seek(upload_offset) + attachment.write(resume_marker) + + httpserver.clear_all_handlers() + + httpserver.expect_oneshot_request( + upload_uri, + method="HEAD", headers={"tus-resumable": "1.0.0"}, query_string=upload_qs, - ).respond_with_data("", status=204) + ).respond_with_data("", status=204, headers={"Upload-Offset": str(upload_offset)}) + + expect_upload_chunks( + httpserver, upload_uri, upload_qs, final_location, offset=upload_offset + ) httpserver.expect_oneshot_request( "/api/123456/envelope/", @@ -345,6 +599,7 @@ def delayed_create(_req): [ "log", "no-setup", + "http-retry", # extra time for resuming 100 MiB upload "shutdown-timeout", "10000", @@ -358,6 +613,7 @@ def delayed_create(_req): assert len(envelope_reqs) == 1 envelope = Envelope.deserialize(envelope_reqs[0].get_data()) + assert envelope.headers["event_id"] == uuid attachment_ref = None for item in envelope: if ( @@ -369,10 +625,20 @@ def delayed_create(_req): break assert attachment_ref is not None - assert attachment_ref.payload.json["location"] == location + assert attachment_ref.payload.json["location"] == final_location - leftover_siblings = [f for f in os.listdir(cache_dir) if f.startswith(base)] - assert leftover_siblings == [] + upload_reqs = [ + req + for req, _resp in httpserver.log + if req.path == upload_uri and req.method == "PATCH" + ] + assert len(upload_reqs) == 5 + assert int(upload_reqs[1].headers["content-length"]) == chunk_size + assert upload_reqs[1].get_data().startswith(resume_marker) + + leftovers = [f for f in os.listdir(cache_dir) if f.startswith(uuid)] + assert leftovers == [] + assert [f for f in os.listdir(cache_dir) if f.endswith(".envelope")] == [] @pytest.mark.parametrize( @@ -397,11 +663,10 @@ def test_tus_crash_restart(cmake, httpserver, backend): env = dict(os.environ, SENTRY_DSN=make_dsn(httpserver)) # First run: crash with large attachment (no server expectations needed) - run( + run_crash( tmp_path, "sentry_test_integration", ["log", "large-attachment", "crash"], - expect_failure=True, env=env, ) @@ -429,6 +694,8 @@ def test_tus_crash_restart(cmake, httpserver, backend): upload_uri = "/api/123456/upload/abc123def456789/" upload_qs = "length=104857600&signature=xyz" location = httpserver.url_for(upload_uri) + "?" + upload_qs + final_qs = "upload_length=104857600&upload_signature=xyz" + final_location = httpserver.url_for(upload_uri) + "?" + final_qs # Second run: restart picks up crash and uploads via TUS httpserver.expect_oneshot_request( @@ -437,15 +704,10 @@ def test_tus_crash_restart(cmake, httpserver, backend): ).respond_with_data( "OK", status=201, - headers={"Location": location}, + headers={"Location": location, **chunk_headers}, ) - httpserver.expect_oneshot_request( - upload_uri, - method="PATCH", - headers={"tus-resumable": "1.0.0"}, - query_string=upload_qs, - ).respond_with_data("", status=204) + expect_upload_chunks(httpserver, upload_uri, upload_qs, final_location) httpserver.expect_request( "/api/123456/envelope/", @@ -455,11 +717,17 @@ def test_tus_crash_restart(cmake, httpserver, backend): run( tmp_path, "sentry_test_integration", - ["log", "no-setup"], + [ + "log", + "no-setup", + # extra time for uploading 100 MiB + "shutdown-timeout", + "10000", + ], env=env, ) - assert len(httpserver.log) == 3 + assert len(httpserver.log) == 6 create_req = None upload_req = None @@ -485,7 +753,7 @@ def test_tus_crash_restart(cmake, httpserver, backend): # Verify TUS upload request headers assert upload_req.headers.get("tus-resumable") == "1.0.0" assert upload_req.headers.get("content-type") == "application/offset+octet-stream" - assert upload_req.headers.get("upload-offset") == "0" + assert upload_req.headers.get("upload-offset") == str(3 * chunk_size) # The envelope contains the event and the attachment-ref body = envelope_req.get_data() @@ -501,8 +769,7 @@ def test_tus_crash_restart(cmake, httpserver, backend): break assert attachment_ref is not None - assert attachment_ref.payload.json["location"] == location - assert not os.path.isabs(attachment_ref.payload.json["path"]) + assert attachment_ref.payload.json["location"] == final_location assert attachment_ref.headers.get("attachment_length") == 100 * 1024 * 1024 # Staged sibling files should be cleaned up after successful send. @@ -521,18 +788,17 @@ def test_tus_crash_native(cmake, httpserver): upload_uri = "/api/123456/upload/abc123def456789/" upload_qs = "length=104857600&signature=xyz" location = httpserver.url_for(upload_uri) + "?" + upload_qs + final_qs = "upload_length=104857600&upload_signature=xyz" + final_location = httpserver.url_for(upload_uri) + "?" + final_qs httpserver.expect_oneshot_request( "/api/123456/upload/", headers={"tus-resumable": "1.0.0"}, - ).respond_with_data("OK", status=201, headers={"Location": location}) + ).respond_with_data( + "OK", status=201, headers={"Location": location, **chunk_headers} + ) - httpserver.expect_oneshot_request( - upload_uri, - method="PATCH", - headers={"tus-resumable": "1.0.0"}, - query_string=upload_qs, - ).respond_with_data("", status=204) + expect_upload_chunks(httpserver, upload_uri, upload_qs, final_location) httpserver.expect_oneshot_request( "/api/123456/envelope/", @@ -542,7 +808,7 @@ def test_tus_crash_native(cmake, httpserver): env = dict(os.environ, SENTRY_DSN=make_dsn(httpserver)) with httpserver.wait(timeout=15) as waiting: - run( + run_crash( tmp_path, "sentry_test_integration", [ @@ -551,7 +817,6 @@ def test_tus_crash_native(cmake, httpserver): "async-crash-upload", "crash", ], - expect_failure=True, env=env, wait_for_daemon=True, ) @@ -584,7 +849,7 @@ def test_tus_crash_native(cmake, httpserver): attachment_ref = item break assert attachment_ref is not None - assert attachment_ref.payload.json["location"] == location + assert attachment_ref.payload.json["location"] == final_location db_dir = os.path.join(tmp_path, ".sentry-native") run_dirs = [ @@ -595,3 +860,250 @@ def test_tus_crash_native(cmake, httpserver): assert len(run_dirs) == 1 run_dir = os.path.join(db_dir, run_dirs[0]) assert not [f for f in os.listdir(run_dir) if f.endswith(".envelope")] + + +@pytest.mark.skipif(not has_native or is_qemu, reason="native backend not available") +def test_tus_crash_native_retry(cmake, httpserver): + tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "native"}) + httpserver.expect_oneshot_request("/api/123456/upload/").respond_with_data( + "", status=503 + ) + + run_crash( + tmp_path, + "sentry_test_integration", + [ + "log", + "http-retry", + "large-attachment", + "crash", + # extra time for slow sanitizer runners + "shutdown-timeout", + "10000", + ], + env=dict(os.environ, SENTRY_DSN=make_dsn(httpserver)), + wait_for_daemon=True, + ) + + # the daemon keeps the envelope for retry instead of sending it without the + # attachment-ref + assert len(httpserver.log) == 1 + cache_dir = tmp_path / ".sentry-native" / "cache" + envelopes = list(cache_dir.glob("*-00-*.envelope")) + assert len(envelopes) == 1 + event_id = envelopes[0].stem[-36:] + assert list(cache_dir.glob(f"{event_id}-*")) + + +@pytest.mark.parametrize("status", [404, 410]) +@pytest.mark.parametrize("chunked", [True, False], ids=["chunked", "single"]) +def test_tus_recreate_after_head_404(cmake, httpserver, status, chunked): + tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "none"}) + cache_dir = tmp_path / ".sentry-native" / "cache" + cache_dir.mkdir(parents=True) + event_id = "b951e5e8-2b70-473f-91f3-667daf78d3de" + run_dir = tmp_path / ".sentry-native" / f"{event_id}.run" + run_dir.mkdir() + filename = f"{event_id}-attachment.bin" + with (cache_dir / filename).open("wb") as attachment: + attachment.truncate(upload_size) + + upload_uri = "/api/123456/upload/recreated/" + upload_qs = "length=104857600&signature=new" + location = httpserver.url_for(upload_uri) + "?" + upload_qs + final_location = httpserver.url_for(upload_uri) + "?upload_signature=final" + payload = { + "path": filename, + "location": "/api/123456/upload/expired/", + "content_type": "application/octet-stream", + "chunk_size": 32 * 1024 * 1024, + } + data = json.dumps(payload) + headers = { + "type": "attachment", + "content_type": "application/vnd.sentry.attachment-ref+json", + "filename": "attachment.bin", + "attachment_length": upload_size, + "length": len(data), + } + (run_dir / f"{event_id}.envelope").write_text( + json.dumps({"event_id": event_id.replace("-", "")}) + + "\n" + + json.dumps(headers) + + "\n" + + data + ) + + httpserver.expect_oneshot_request( + "/api/123456/upload/expired/", method="HEAD" + ).respond_with_data("", status=status) + httpserver.expect_oneshot_request( + "/api/123456/upload/", method="POST" + ).respond_with_data( + "", + status=201, + headers={"Location": location, **(chunk_headers if chunked else {})}, + ) + expect_upload_chunks( + httpserver, + upload_uri, + upload_qs, + final_location, + size=chunk_size if chunked else upload_size, + ) + httpserver.expect_oneshot_request( + "/api/123456/envelope/", headers={"x-sentry-auth": auth_header} + ).respond_with_data("OK") + + run( + tmp_path, + "sentry_test_integration", + ["log", "no-setup", "shutdown-timeout", "10000"], + env=dict(os.environ, SENTRY_DSN=make_dsn(httpserver)), + ) + + assert len(httpserver.log) == (7 if chunked else 4) + envelope = Envelope.deserialize(httpserver.log[-1][0].get_data()) + ref = next(iter(envelope)) + assert ref.payload.json["location"] == final_location + assert not list(cache_dir.iterdir()) + + +@pytest.mark.parametrize( + "offset", + [None, "0", "-1", "invalid", "26214400", "104857601", "18446744073709551616"], +) +def test_tus_invalid_offset(cmake, httpserver, offset): + tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "none"}) + upload_uri = "/api/123456/upload/invalid-offset/" + httpserver.expect_oneshot_request( + "/api/123456/upload/", method="POST" + ).respond_with_data( + "", status=201, headers={"Location": upload_uri, **chunk_headers} + ) + httpserver.expect_oneshot_request( + upload_uri, method="PATCH", headers={"upload-offset": "0"} + ).respond_with_data( + "", + status=204, + headers={"Upload-Offset": str(chunk_size), "Location": "/non-final/"}, + ) + httpserver.expect_oneshot_request( + upload_uri, method="PATCH", headers={"upload-offset": str(chunk_size)} + ).respond_with_data( + "", status=204, headers={"Upload-Offset": offset} if offset is not None else {} + ) + + run( + tmp_path, + "sentry_test_integration", + [ + "log", + "no-setup", + "http-retry", + "large-attachment", + "capture-event", + # extra time for uploading 50 MiB + "shutdown-timeout", + "10000", + ], + env=dict(os.environ, SENTRY_DSN=make_dsn(httpserver)), + ) + + assert len(httpserver.log) == 3 + cache_dir = tmp_path / ".sentry-native" / "cache" + envelopes = list(cache_dir.glob("*.envelope")) + assert len(envelopes) == 1 + envelope = Envelope.deserialize(envelopes[0].read_bytes()) + ref = next(item for item in envelope if item.headers.get("type") == "attachment") + assert ref.payload.json["location"] == upload_uri + assert ref.payload.json["chunk_size"] == chunk_size + + +@pytest.mark.parametrize( + "has_location", [True, False], ids=["location", "missing-location"] +) +def test_tus_resume_completed_upload(cmake, httpserver, has_location): + tmp_path = cmake(["sentry_test_integration"], {"SENTRY_BACKEND": "none"}) + cache_dir = tmp_path / ".sentry-native" / "cache" + cache_dir.mkdir(parents=True) + event_id = "b951e5e8-2b70-473f-91f3-667daf78d3de" + run_dir = tmp_path / ".sentry-native" / f"{event_id}.run" + run_dir.mkdir() + filename = f"{event_id}-attachment.bin" + with (cache_dir / filename).open("wb") as attachment: + attachment.truncate(upload_size) + + upload_uri = "/api/123456/upload/completed/" + upload_qs = "length=104857600&signature=xyz" + location = upload_uri + "?" + upload_qs + final_qs = "upload_length=104857600&upload_signature=xyz" + final_location = httpserver.url_for(upload_uri) + "?" + final_qs + payload = { + "path": filename, + "location": location, + "content_type": "application/octet-stream", + "chunk_size": chunk_size, + } + data = json.dumps(payload) + headers = { + "type": "attachment", + "content_type": "application/vnd.sentry.attachment-ref+json", + "filename": "attachment.bin", + "attachment_length": upload_size, + "length": len(data), + } + (run_dir / f"{event_id}.envelope").write_text( + json.dumps({"event_id": event_id.replace("-", "")}) + + "\n" + + json.dumps(headers) + + "\n" + + data + ) + + httpserver.expect_oneshot_request( + upload_uri, method="HEAD", query_string=upload_qs + ).respond_with_data("", status=204, headers={"Upload-Offset": str(upload_size)}) + httpserver.expect_oneshot_request( + upload_uri, + method="PATCH", + headers={ + "tus-resumable": "1.0.0", + "content-type": "application/offset+octet-stream", + "upload-offset": str(upload_size), + }, + query_string=upload_qs, + data=b"", + ).respond_with_data( + "", + status=204, + headers={ + "Upload-Offset": str(upload_size), + **({"Location": final_location} if has_location else {}), + }, + ) + httpserver.expect_oneshot_request( + "/api/123456/envelope/", headers={"x-sentry-auth": auth_header} + ).respond_with_data("OK") + + run( + tmp_path, + "sentry_test_integration", + ["log", "no-setup", "http-retry"], + env=dict(os.environ, SENTRY_DSN=make_dsn(httpserver)), + ) + + assert len(httpserver.log) == (3 if has_location else 2) + if has_location: + envelope = Envelope.deserialize(httpserver.log[-1][0].get_data()) + ref = next(iter(envelope)) + assert ref.payload.json["location"] == final_location + assert not list(cache_dir.iterdir()) + else: + envelopes = list(cache_dir.glob("*.envelope")) + assert len(envelopes) == 1 + envelope = Envelope.deserialize(envelopes[0].read_bytes()) + ref = next(iter(envelope)) + assert ref.payload.json["location"] == location + assert ref.payload.json["chunk_size"] == chunk_size + assert (cache_dir / filename).is_file() diff --git a/tests/test_proxy_server.py b/tests/test_proxy_server.py index ab3cb0b164..1088b339a2 100644 --- a/tests/test_proxy_server.py +++ b/tests/test_proxy_server.py @@ -57,7 +57,7 @@ def start_proxy(tmp_path): processes = [] proxy_server = Path(__file__).with_name("proxy_server.py") - def start(proxy_type, proxy_auth=None): + def start(proxy_type, proxy_auth=None, throttle=0): output = tmp_path / "proxy-{}.port".format(len(processes)) command = [ sys.executable, @@ -74,6 +74,8 @@ def start(proxy_type, proxy_auth=None): ] if proxy_auth: command += ["--proxy-auth", proxy_auth] + if throttle: + command += ["--throttle", str(throttle)] process = subprocess.Popen( command, @@ -218,3 +220,46 @@ def test_socks5_tunneling(start_proxy, target_server): assert response.endswith(b"OK") method, path, _, body = target_server.requests.get(timeout=5) assert (method, path, body) == ("GET", "/through-socks", b"") + + +@pytest.mark.parametrize("tunnel", [False, True], ids=["http", "connect"]) +def test_upload_throttle(start_proxy, target_server, tunnel): + throttle = 128 * 1024 + port = start_proxy("http-proxy", throttle=throttle) + target_port = target_server.server_address[1] + body = b"x" * (64 * 1024) + + with socket.create_connection(("127.0.0.1", port), timeout=5) as client: + if tunnel: + client.sendall( + ( + f"CONNECT 127.0.0.1:{target_port} HTTP/1.1\r\n" + f"Host: 127.0.0.1:{target_port}\r\n\r\n" + ).encode("ascii") + ) + response = b"HTTP/1.1 200 Connection Established\r\n\r\n" + assert _recv_exact(client, len(response)) == response + + target = "/upload" if tunnel else f"http://127.0.0.1:{target_port}/upload" + request = ( + f"POST {target} HTTP/1.1\r\n" + f"Host: 127.0.0.1:{target_port}\r\n" + f"Content-Length: {len(body)}\r\n" + "Connection: close\r\n\r\n" + ).encode("ascii") + body + started = time.monotonic() + client.sendall(request) + client.shutdown(socket.SHUT_WR) + response = b"" + while True: + chunk = client.recv(64 * 1024) + if not chunk: + break + response += chunk + elapsed = time.monotonic() - started + + assert response.startswith(b"HTTP/1.1 200") + assert response.endswith(b"OK") + method, path, _, received = target_server.requests.get(timeout=5) + assert (method, path, received) == ("POST", "/upload", body) + assert elapsed >= len(body) / throttle diff --git a/tests/test_unit.py b/tests/test_unit.py index 4f418fb9fd..e4f2401eeb 100644 --- a/tests/test_unit.py +++ b/tests/test_unit.py @@ -1,7 +1,7 @@ import os import pytest from . import run -from .conditions import has_http, is_wine +from .conditions import has_http, has_native, is_wine def _skip_if_unsupported(unittest): @@ -56,3 +56,16 @@ def test_unit_with_test_path(cmake, unittest): ) env = dict(os.environ) run(cwd, "sentry_test_unit", ["--no-summary", unittest], env=env) + + +@pytest.mark.skipif(not has_native, reason="tests need the native backend enabled") +def test_unit_native(cmake, unittest): + if unittest in ["basic_transport_thread_name", "cache_keep"]: + pytest.skip("excluded from unit test-suite") + _skip_if_unsupported(unittest) + cwd = cmake( + ["sentry_test_unit", "sentry-crash"], + {"SENTRY_BACKEND": "native", "SENTRY_TRANSPORT": "none"}, + ) + env = dict(os.environ) + run(cwd, "sentry_test_unit", ["--no-summary", unittest], env=env) diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 2869a2f013..e6a8eea4d8 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -82,6 +82,9 @@ target_link_libraries(sentry_test_unit PRIVATE if(MINGW) if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + set_source_files_properties( + "${PROJECT_SOURCE_DIR}/src/unwinder/sentry_unwinder_dbghelp.c" + PROPERTIES COMPILE_OPTIONS -fms-extensions) target_link_options(sentry_test_unit PRIVATE -Wl,-pdb=) # IMPORTANT ! LLD must generate pdb files target_compile_options(sentry_test_unit PRIVATE -gcodeview) # IMPORTANT ! Clang must generate pdb to CodeView format else() @@ -98,6 +101,9 @@ endif() if(MSVC) target_compile_options(sentry_test_unit PRIVATE $) +elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + # GCC 12 ignores the `-Wmultichar` pragma in the crashpad backend + target_compile_options(sentry_test_unit PRIVATE $) endif() # set static runtime if enabled @@ -109,6 +115,14 @@ target_compile_definitions(sentry PRIVATE SIZEOF_LONG=${CMAKE_SIZEOF_LONG}) target_compile_definitions(sentry_test_unit PRIVATE SENTRY_UNITTEST) +foreach(handler crashpad::handler sentry-crash) + if(TARGET ${handler}) + add_custom_command(TARGET sentry_test_unit POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different "$" "$" + VERBATIM) + endif() +endforeach() + option(SENTRY_CTEST_INDIVIDUAL "Register sentry unit tests as individual tests instead of a single binary" ON) if(SENTRY_CTEST_INDIVIDUAL) @@ -121,10 +135,12 @@ if(SENTRY_CTEST_INDIVIDUAL) message(WARNING "Failed to extract test name from line: ${line}") else() add_test(NAME sentry/${CMAKE_MATCH_1} COMMAND sentry_test_unit --no-summary ${CMAKE_MATCH_1}) + set_tests_properties(sentry/${CMAKE_MATCH_1} PROPERTIES RUN_SERIAL TRUE) endif() endforeach() else() add_test(NAME sentry/unit-tests COMMAND sentry_test_unit) + set_tests_properties(sentry/unit-tests PROPERTIES RUN_SERIAL TRUE) endif() add_executable(sentry_fuzz_json @@ -144,6 +160,9 @@ target_link_libraries(sentry_fuzz_json PRIVATE if(MSVC) target_compile_options(sentry_fuzz_json PRIVATE $) +elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + # GCC 12 ignores the `-Wmultichar` pragma in the crashpad backend + target_compile_options(sentry_fuzz_json PRIVATE $) endif() # set static runtime if enabled diff --git a/tests/unit/sentry_testsupport.h b/tests/unit/sentry_testsupport.h index 6300f7e29b..1a4992aabc 100644 --- a/tests/unit/sentry_testsupport.h +++ b/tests/unit/sentry_testsupport.h @@ -108,13 +108,6 @@ sentry_dsn_t *Varname = sentry__dsn_new(DSN_URL); \ TEST_ASSERT(!!Varname) -#define SENTRY_TEST_DEPRECATED(call) \ - do { \ - SENTRY_SUPPRESS_DEPRECATED \ - call; \ - SENTRY_RESTORE_DEPRECATED \ - } while (0) - #ifdef SENTRY_PLATFORM_WINDOWS # include # define sleep_s(SECONDS) Sleep((SECONDS) * 1000) diff --git a/tests/unit/test_attachments.c b/tests/unit/test_attachments.c index 1f2bfe70aa..57c2cc8239 100644 --- a/tests/unit/test_attachments.c +++ b/tests/unit/test_attachments.c @@ -168,6 +168,7 @@ SENTRY_TEST(attachments_add_dedupe) sentry_attach_file(SENTRY_TEST_PATH_PREFIX ".a.txt"); sentry_attach_file(SENTRY_TEST_PATH_PREFIX ".b.txt"); sentry_attach_file(SENTRY_TEST_PATH_PREFIX ".c.txt"); + sentry_attach_file(SENTRY_TEST_PATH_PREFIX ".c.txt"); #ifdef SENTRY_PLATFORM_WINDOWS sentry_attach_filew(SENTRY_TEST_PATH_PREFIX L".a.txt"); sentry_attach_filew(SENTRY_TEST_PATH_PREFIX L".b.txt"); @@ -193,10 +194,10 @@ SENTRY_TEST(attachments_add_dedupe) TEST_CHECK_STRING_EQUAL(serialized, "{}\n" + "{\"type\":\"attachment\",\"length\":3,\"filename\":\".c.txt\"}\nccc\n" "{\"type\":\"attachment\",\"length\":3,\"filename\":\".a.txt\"}\naaa\n" - "{\"type\":\"attachment\",\"length\":3,\"filename\":\".b.txt\"}\nbbb\n" - "{\"type\":\"attachment\",\"length\":3,\"filename\":\".c.txt\"}" - "\nccc"); + "{\"type\":\"attachment\",\"length\":3,\"filename\":\".b.txt\"}" + "\nbbb"); sentry_free(serialized); @@ -273,18 +274,19 @@ SENTRY_TEST(attachments_add_remove) TEST_CHECK_STRING_EQUAL(serialized, "{}\n" "{\"type\":\"attachment\",\"length\":3,\"filename\":\".a.txt\"}\naaa\n" + "{\"type\":\"attachment\",\"length\":3,\"filename\":\".c.txt\"}\nccc\n" "{\"type\":\"attachment\",\"length\":3,\"filename\":\".b.txt\"}" "\nbbb"); - sentry_free(serialized); - + sentry_attach_bytes("ddd", 3, ".d.txt"); sentry_clear_attachments(); envelope = sentry__envelope_new(NULL); add_scope_attachments(envelope); - serialized = sentry_envelope_serialize(envelope, NULL); + char *cleared = sentry_envelope_serialize(envelope, NULL); sentry_envelope_free(envelope); - TEST_CHECK_STRING_EQUAL(serialized, "{}"); + TEST_CHECK_STRING_EQUAL(cleared, serialized); + sentry_free(cleared); sentry_free(serialized); sentry_close(); diff --git a/tests/unit/test_basic.c b/tests/unit/test_basic.c index 1a1daa31e5..6abfee2150 100644 --- a/tests/unit/test_basic.c +++ b/tests/unit/test_basic.c @@ -34,6 +34,11 @@ send_envelope_test_basic(sentry_envelope_t *envelope, void *data) const char *trans = sentry_value_as_string( sentry_value_get_by_key(event, "transaction")); TEST_CHECK_STRING_EQUAL(trans, "demo-trans"); + } else { + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key( + sentry_value_get_by_key(event, "debug_meta"), "custom")), + "kept"); } sentry_envelope_free(envelope); } @@ -63,6 +68,10 @@ SENTRY_TEST(basic_function_transport) sentry_value_t obj = sentry_value_new_object(); // something that is not a UUID, as this will be forcibly changed sentry_value_set_by_key(obj, "event_id", sentry_value_new_int32(1234)); + sentry_value_t debug_meta = sentry_value_new_object(); + sentry_value_set_by_key( + debug_meta, "custom", sentry_value_new_string("kept")); + sentry_value_set_by_key(obj, "debug_meta", debug_meta); sentry_capture_event(obj); sentry_user_consent_revoke(); @@ -237,10 +246,6 @@ SENTRY_TEST(crash_marker) SENTRY_TEST(crashed_last_run) { - // fails before init() is called - SENTRY_TEST_DEPRECATED( - TEST_CHECK_INT_EQUAL(sentry_clear_crashed_last_run(), 1)); - // clear any leftover from previous test runs { SENTRY_TEST_OPTIONS_NEW(options); @@ -293,9 +298,7 @@ SENTRY_TEST(crashed_last_run) TEST_CHECK_INT_EQUAL(sentry_get_crashed_last_run(), 1); TEST_CHECK(sentry__has_crash_marker(options)); - // explicit clearing remains supported on all platforms - SENTRY_TEST_DEPRECATED( - TEST_CHECK_INT_EQUAL(sentry_clear_crashed_last_run(), 0)); + TEST_CHECK(sentry__clear_crash_marker(options)); sentry_close(); } @@ -893,3 +896,19 @@ SENTRY_TEST(attach_stacktrace_leaves_events_with_a_stacktrace_alone) sentry_value_decref(state.threads); } + +SENTRY_TEST(options_global_lifetime) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry__options_set(options); + TEST_CHECK_INT_EQUAL(options->refcount, 2); + + SENTRY_WITH_OPTIONS (current) { + TEST_CHECK_PTR_EQUAL(current, options); + sentry__options_set(NULL); + TEST_CHECK(!sentry_is_enabled()); + TEST_CHECK_INT_EQUAL(options->refcount, 2); + } + TEST_CHECK_INT_EQUAL(options->refcount, 1); + sentry_options_free(options); +} diff --git a/tests/unit/test_cache.c b/tests/unit/test_cache.c index 371eb7ff5e..e54d593ca9 100644 --- a/tests/unit/test_cache.c +++ b/tests/unit/test_cache.c @@ -11,6 +11,7 @@ #include "sentry_testsupport.h" #include "sentry_uuid.h" #include "sentry_value.h" +#include "transports/sentry_http_transport.h" #ifdef SENTRY_PLATFORM_WINDOWS # include @@ -139,16 +140,29 @@ state_has_event_id( return false; } +static int +test_http_send_fails(void *client, sentry_prepared_http_request_t *req, + sentry_http_response_t *resp) +{ + (void)client; + (void)req; + (void)resp; + return false; +} + SENTRY_TEST(cache_keep) { #if defined(SENTRY_PLATFORM_NX) || defined(SENTRY_PLATFORM_PS) SKIP_TEST(); #endif SENTRY_TEST_OPTIONS_NEW(options); - TEST_ASSERT(!!options->transport); sentry_options_set_dsn(options, "https://foo@sentry.invalid/42"); sentry_options_set_cache_keep(options, true); sentry_options_set_http_retry(options, false); + sentry_transport_t *transport + = sentry__http_transport_new(NULL, test_http_send_fails); + TEST_ASSERT(!!transport); + sentry_options_set_transport(options, transport); sentry_init(options); sentry_path_t *cache_path diff --git a/tests/unit/test_concurrency.c b/tests/unit/test_concurrency.c index 7530356a5a..b00965c901 100644 --- a/tests/unit/test_concurrency.c +++ b/tests/unit/test_concurrency.c @@ -281,7 +281,7 @@ SENTRY_TEST(concurrent_reinstall) // Holding the scope observer lock simulates an observer callback in // progress. Backend reinstall must wait until that callback finishes. - sentry_scope_t *scope = sentry__scope_getref(); + sentry_scope_t *scope = sentry_scope_acquire(); TEST_ASSERT(!!scope); sentry__mutex_lock(&scope->observers_lock); sentry_threadid_t thread; @@ -300,7 +300,7 @@ SENTRY_TEST(concurrent_reinstall) TEST_CHECK_INT_EQUAL(sentry__atomic_fetch(&state.shutdowns), 0); sentry__mutex_unlock(&scope->observers_lock); - sentry__scope_finish(scope); + sentry_scope_release(scope); sentry__thread_join(thread); sentry__thread_free(&thread); TEST_CHECK_INT_EQUAL(sentry__atomic_fetch(&state.shutdowns), 1); @@ -322,7 +322,7 @@ SENTRY_THREAD_FN scope_access_thread(void *data) { scope_cleanup_state_t *state = data; - sentry_scope_t *scope = sentry__scope_getref(); + sentry_scope_t *scope = sentry_scope_acquire(); sentry__mutex_lock(&state->lock); state->accesses++; @@ -338,7 +338,7 @@ scope_access_thread(void *data) SENTRY_WITH_SCOPE (nested) { (void)sentry__scope_get_level(nested); } - sentry__scope_finish(scope); + sentry_scope_release(scope); return 0; } @@ -392,15 +392,19 @@ SENTRY_TEST(scope_cleanup) while (!state.cleanup_started) { sentry__cond_wait(&state.cleanup_signal, &state.lock); } - sentry__cond_wait_timeout(&state.cleanup_signal, &state.lock, 250); - TEST_CHECK(!state.cleanup_finished); + for (int i = 0; i < 100 && !state.cleanup_finished; i++) { + sentry__cond_wait_timeout(&state.cleanup_signal, &state.lock, 100); + } + TEST_CHECK(state.cleanup_finished); sentry_threadid_t late_thread; sentry__thread_init(&late_thread); TEST_ASSERT_INT_EQUAL( sentry__thread_spawn(&late_thread, scope_access_thread, &state), 0); - sentry__cond_wait_timeout(&state.access_signal, &state.lock, 250); - TEST_CHECK_INT_EQUAL(state.accesses, 1); + for (int i = 0; i < 100 && state.accesses < 2; i++) { + sentry__cond_wait_timeout(&state.access_signal, &state.lock, 100); + } + TEST_CHECK_INT_EQUAL(state.accesses, 2); state.release_access = true; sentry__cond_wake_all(&state.access_signal); sentry__mutex_unlock(&state.lock); diff --git a/tests/unit/test_envelopes.c b/tests/unit/test_envelopes.c index 93546ee926..7a0d78099c 100644 --- a/tests/unit/test_envelopes.c +++ b/tests/unit/test_envelopes.c @@ -21,10 +21,7 @@ static char *const SERIALIZED_ENVELOPE_STR = "{\"dsn\":\"https://foo@sentry.invalid/42\"," - "\"event_id\":\"c993afb6-b4ac-48a6-b61b-2558e601d65d\",\"trace\":{" - "\"public_key\":\"foo\",\"sample_rate\":0,\"sample_" - "rand\":0.01006918276309107,\"release\":\"test-release\",\"environment\":" - "\"production\",\"sampled\":\"false\"}}\n" + "\"event_id\":\"c993afb6-b4ac-48a6-b61b-2558e601d65d\"}\n" "{\"type\":\"event\",\"length\":71}\n" "{\"event_id\":\"c993afb6-b4ac-48a6-b61b-2558e601d65d\",\"some-" "context\":1234}\n" @@ -96,39 +93,6 @@ SENTRY_TEST(basic_http_request_preparation_for_transaction) sentry__dsn_decref(dsn); } -SENTRY_TEST(basic_http_request_preparation_for_user_report) -{ - SENTRY_TEST_DSN_NEW_DEFAULT(dsn); - - sentry_uuid_t event_id - = sentry_uuid_from_string("c993afb6-b4ac-48a6-b61b-2558e601d65d"); - sentry_envelope_t *envelope = sentry__envelope_new(NULL); - sentry_value_t user_report; - SENTRY_TEST_DEPRECATED( - user_report = sentry_value_new_user_feedback( - &event_id, "some-name", "some-email", "some-comment")); - sentry__envelope_add_user_report(envelope, user_report); - - sentry_prepared_http_request_t *req - = sentry__prepare_http_request(envelope, dsn, NULL, NULL); - TEST_CHECK_STRING_EQUAL(req->method, "POST"); - TEST_CHECK_STRING_EQUAL( - req->url, "https://sentry.invalid:443/api/42/envelope/"); -#ifndef SENTRY_TRANSPORT_COMPRESSION - TEST_CHECK_STRING_EQUAL(req->body, - "{\"event_id\":\"c993afb6-b4ac-48a6-b61b-2558e601d65d\"}\n" - "{\"type\":\"user_report\",\"length\":117}\n" - "{\"event_id\":\"c993afb6-b4ac-48a6-b61b-2558e601d65d\",\"name\":" - "\"some-name\",\"email\":\"some-email\",\"comments\":" - "\"some-comment\"}"); -#endif - sentry__prepared_http_request_free(req); - sentry_value_decref(user_report); - sentry_envelope_free(envelope); - - sentry__dsn_decref(dsn); -} - SENTRY_TEST(basic_http_request_preparation_for_user_feedback) { SENTRY_TEST_DSN_NEW_DEFAULT(dsn); @@ -1536,3 +1500,36 @@ SENTRY_TEST(minidump_rate_limit) sentry__rate_limiter_free(rl); sentry_envelope_free(envelope); } + +SENTRY_TEST(attachment_ref_chunk_size_roundtrip) +{ + size_t sizes[] = { 32 * 1024 * 1024, SIZE_MAX }; + for (size_t i = 0; i < sizeof(sizes) / sizeof(sizes[0]); i++) { + sentry_envelope_t *envelope = sentry__envelope_new(NULL); + sentry_attachment_ref_t ref = { 0 }; + ref.path = "abc-crashlog.bin"; + sentry_envelope_item_t *item = sentry__envelope_add_attachment_ref( + envelope, &ref, "crashlog.bin", NULL, 12345); + TEST_ASSERT(!!item); + TEST_CHECK(sentry__envelope_item_get_attachment_ref(item, &ref)); + TEST_CHECK_INT_EQUAL(ref.chunk_size, 0); + sentry__attachment_ref_cleanup(&ref); + TEST_CHECK(sentry__envelope_item_resolve_attachment_ref( + item, "abc-crashlog.bin", "/upload/abc", sizes[i])); + + size_t len = 0; + char *buf = sentry_envelope_serialize(envelope, &len); + TEST_ASSERT(!!buf); + sentry_envelope_free(envelope); + envelope = sentry_envelope_deserialize(buf, len); + sentry_free(buf); + TEST_ASSERT(!!envelope); + item = sentry__envelope_get_item(envelope, 0); + TEST_CHECK(sentry__envelope_item_get_attachment_ref(item, &ref)); + TEST_CHECK_STRING_EQUAL(ref.path, "abc-crashlog.bin"); + TEST_CHECK_STRING_EQUAL(ref.location, "/upload/abc"); + TEST_CHECK(ref.chunk_size == sizes[i]); + sentry__attachment_ref_cleanup(&ref); + sentry_envelope_free(envelope); + } +} diff --git a/tests/unit/test_http_transport.c b/tests/unit/test_http_transport.c index b3a3552b32..b3a63f8690 100644 --- a/tests/unit/test_http_transport.c +++ b/tests/unit/test_http_transport.c @@ -18,14 +18,27 @@ SENTRY_TEST(http_response_set_header_sets_known_headers) sentry_http_response_set_header( &resp, "x-sentry-rate-limits", "60:error:key"); sentry_http_response_set_header(&resp, "location", "/uploads/1"); + sentry_http_response_set_header(&resp, "upload-offset", "42"); + sentry_http_response_set_header(&resp, "upload-chunk-granularity", "256"); + sentry_http_response_set_header(&resp, "upload-min-chunk-size", "1048576"); + sentry_http_response_set_header( + &resp, "upload-max-chunk-size", "1073741824"); TEST_CHECK_STRING_EQUAL(resp.retry_after, "60"); TEST_CHECK_STRING_EQUAL(resp.x_sentry_rate_limits, "60:error:key"); TEST_CHECK_STRING_EQUAL(resp.location, "/uploads/1"); + TEST_CHECK_STRING_EQUAL(resp.upload_offset, "42"); + TEST_CHECK_STRING_EQUAL(resp.upload_chunk_granularity, "256"); + TEST_CHECK_STRING_EQUAL(resp.upload_min_chunk_size, "1048576"); + TEST_CHECK_STRING_EQUAL(resp.upload_max_chunk_size, "1073741824"); sentry_free(resp.retry_after); sentry_free(resp.x_sentry_rate_limits); sentry_free(resp.location); + sentry_free(resp.upload_offset); + sentry_free(resp.upload_chunk_granularity); + sentry_free(resp.upload_min_chunk_size); + sentry_free(resp.upload_max_chunk_size); } SENTRY_TEST(http_response_set_header_is_case_insensitive) @@ -37,14 +50,27 @@ SENTRY_TEST(http_response_set_header_is_case_insensitive) sentry_http_response_set_header( &resp, "X-SENTRY-RATE-LIMITS", "30:error:key"); sentry_http_response_set_header(&resp, "Location", "/uploads/2"); + sentry_http_response_set_header(&resp, "Upload-Offset", "84"); + sentry_http_response_set_header(&resp, "Upload-Chunk-Granularity", "256"); + sentry_http_response_set_header(&resp, "Upload-Min-Chunk-Size", "1048576"); + sentry_http_response_set_header( + &resp, "Upload-Max-Chunk-Size", "1073741824"); TEST_CHECK_STRING_EQUAL(resp.retry_after, "30"); TEST_CHECK_STRING_EQUAL(resp.x_sentry_rate_limits, "30:error:key"); TEST_CHECK_STRING_EQUAL(resp.location, "/uploads/2"); + TEST_CHECK_STRING_EQUAL(resp.upload_offset, "84"); + TEST_CHECK_STRING_EQUAL(resp.upload_chunk_granularity, "256"); + TEST_CHECK_STRING_EQUAL(resp.upload_min_chunk_size, "1048576"); + TEST_CHECK_STRING_EQUAL(resp.upload_max_chunk_size, "1073741824"); sentry_free(resp.retry_after); sentry_free(resp.x_sentry_rate_limits); sentry_free(resp.location); + sentry_free(resp.upload_offset); + sentry_free(resp.upload_chunk_granularity); + sentry_free(resp.upload_min_chunk_size); + sentry_free(resp.upload_max_chunk_size); } SENTRY_TEST(http_response_set_header_ignores_unknown_headers) @@ -58,6 +84,10 @@ SENTRY_TEST(http_response_set_header_ignores_unknown_headers) TEST_CHECK(resp.retry_after == NULL); TEST_CHECK(resp.x_sentry_rate_limits == NULL); TEST_CHECK(resp.location == NULL); + TEST_CHECK(resp.upload_offset == NULL); + TEST_CHECK(resp.upload_chunk_granularity == NULL); + TEST_CHECK(resp.upload_min_chunk_size == NULL); + TEST_CHECK(resp.upload_max_chunk_size == NULL); } SENTRY_TEST(http_response_set_header_overwrites_previous_value) @@ -165,6 +195,7 @@ SENTRY_TEST(http_request_accessors_file_backed_body) req->headers_len = 0; req->body_path = sentry__path_from_str("/tmp/does-not-need-to-exist"); req->body_len = 100 * 1024 * 1024; + req->body_offset = 42; size_t len = 0; TEST_CHECK(sentry_http_request_get_body(req, &len) == NULL); @@ -174,6 +205,8 @@ SENTRY_TEST(http_request_accessors_file_backed_body) const char *path = sentry_http_request_get_body_file_path(req, &len); TEST_CHECK_STRING_EQUAL(path, "/tmp/does-not-need-to-exist"); TEST_CHECK_INT_EQUAL((int)len, 100 * 1024 * 1024); + TEST_CHECK_INT_EQUAL( + (int)sentry_http_request_get_body_file_offset(req), 42); #ifdef SENTRY_PLATFORM_WINDOWS // The wide variant must stay in sync with the narrow one, since that is @@ -210,6 +243,7 @@ SENTRY_TEST(http_request_accessors_bodyless_request) len = 123; TEST_CHECK(sentry_http_request_get_body_file_path(req, &len) == NULL); TEST_CHECK_INT_EQUAL((int)len, 0); + TEST_CHECK_INT_EQUAL((int)sentry_http_request_get_body_file_offset(req), 0); sentry__prepared_http_request_free(req); } @@ -223,6 +257,8 @@ SENTRY_TEST(http_request_accessors_null_safety) size_t len = 0; TEST_CHECK(sentry_http_request_get_body(NULL, &len) == NULL); TEST_CHECK(sentry_http_request_get_body_file_path(NULL, &len) == NULL); + TEST_CHECK_INT_EQUAL( + (int)sentry_http_request_get_body_file_offset(NULL), 0); } static void * diff --git a/tests/unit/test_logs.c b/tests/unit/test_logs.c index 2e75f7839f..332bd440b4 100644 --- a/tests/unit/test_logs.c +++ b/tests/unit/test_logs.c @@ -607,6 +607,10 @@ SENTRY_TEST(scope_capture_log_attributes) sentry_set_attribute("from_global", string_attribute("global")); sentry_set_attribute("scope_over_global", string_attribute("global")); sentry_set_attribute("log_over_all", string_attribute("global")); + sentry_value_t os = sentry_value_new_object(); + sentry_value_set_by_key(os, "name", sentry_value_new_string("ParentOS")); + sentry_value_set_by_key(os, "version", sentry_value_new_string("1.0")); + sentry_set_context("os", os); sentry_scope_t *scope = sentry_scope_new(); sentry_scope_set_attribute(scope, "from_scope", string_attribute("scope")); @@ -614,6 +618,9 @@ SENTRY_TEST(scope_capture_log_attributes) scope, "scope_over_global", string_attribute("scope")); sentry_scope_set_attribute( scope, "log_over_all", string_attribute("scope")); + os = sentry_value_new_object(); + sentry_value_set_by_key(os, "name", sentry_value_new_string("ChildOS")); + sentry_scope_set_context(scope, "os", os); sentry_value_t attrs = sentry_value_new_object(); sentry_value_set_by_key(attrs, "from_log", string_attribute("log")); @@ -636,6 +643,8 @@ SENTRY_TEST(scope_capture_log_attributes) TEST_CHECK_STRING_EQUAL( attribute_value(log_attrs, "scope_over_global"), "scope"); TEST_CHECK_STRING_EQUAL(attribute_value(log_attrs, "log_over_all"), "log"); + TEST_CHECK_STRING_EQUAL(attribute_value(log_attrs, "os.name"), "ChildOS"); + TEST_CHECK_STRING_EQUAL(attribute_value(log_attrs, "os.version"), "1.0"); sentry_scope_free(scope); sentry_value_decref(captured_log); diff --git a/tests/unit/test_native_backend.c b/tests/unit/test_native_backend.c index b18744af95..98fee62182 100644 --- a/tests/unit/test_native_backend.c +++ b/tests/unit/test_native_backend.c @@ -5,18 +5,30 @@ * and low-level crash handling functionality. */ +#include "sentry_backend.h" +#include "sentry_core.h" #include "sentry_database.h" #include "sentry_envelope.h" #include "sentry_options.h" #include "sentry_path.h" +#include "sentry_scope.h" +#include "sentry_string.h" +#include "sentry_sync.h" #include "sentry_testsupport.h" +#include "sentry_tracing.h" +#include "sentry_utils.h" #include +#include #include #ifdef SENTRY_BACKEND_NATIVE // Include native backend headers # include "../../src/backends/native/minidump/sentry_minidump_format.h" # include "../../src/backends/native/sentry_crash_context.h" +# include "../../src/backends/native/sentry_crash_ipc.h" +# if defined(SENTRY_PLATFORM_ANDROID) +# include +# endif static void noop_crashed_last_run(const sentry_envelope_t *envelope, void *user_data) @@ -40,8 +52,11 @@ count_sent_envelopes(sentry_envelope_t *envelope, void *state) #if defined(SENTRY_PLATFORM_LINUX) # include +# include # include +# include # include +# include # include #endif @@ -235,6 +250,27 @@ SENTRY_TEST(elf_rejects_non_regular_files) #endif } +SENTRY_TEST(elf_offset) +{ +#if !defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) + SKIP_TEST(); +#else + // an APK-like zip with an uncompressed library at a page-aligned offset + char path[] = "/tmp/sentry-minidump-apk-XXXXXX"; + int fd = mkstemp(path); + TEST_ASSERT(fd >= 0); + TEST_ASSERT(write(fd, "PK\3\4", 4) == 4); + TEST_ASSERT(pwrite(fd, ELFMAG, SELFMAG, 4096) == (ssize_t)SELFMAG); + close(fd); + + TEST_CHECK(!sentry__elf_is_file(path)); + TEST_CHECK(sentry__elf_is_file_at(path, 4096)); + TEST_CHECK(!sentry__elf_is_file_at(path, 8192)); + + TEST_CHECK(unlink(path) == 0); +#endif +} + /** * Test minidump directory entry structure */ @@ -294,6 +330,12 @@ SENTRY_TEST(minidump_context_sizes) ctx.fpsr = 0x12345678; TEST_CHECK(ctx.fpsr == 0x12345678); +# elif defined(__riscv) && __riscv_xlen == 64 + TEST_CHECK(sizeof(minidump_context_riscv64_t) == 528); + TEST_CHECK(offsetof(minidump_context_riscv64_t, regs) == 8); + TEST_CHECK(offsetof(minidump_context_riscv64_t, fpregs) == 264); + TEST_CHECK(offsetof(minidump_context_riscv64_t, fcsr) == 520); + # endif #else SKIP_TEST(); @@ -439,6 +481,7 @@ SENTRY_TEST(minidump_cpu_architectures) TEST_CHECK(MINIDUMP_CPU_ARM == 5); // PROCESSOR_ARCHITECTURE_ARM TEST_CHECK(MINIDUMP_CPU_ARM64 == 12); // PROCESSOR_ARCHITECTURE_ARM64 TEST_CHECK(MINIDUMP_CPU_X86_64 == 9); // PROCESSOR_ARCHITECTURE_AMD64 + TEST_CHECK(MINIDUMP_CPU_RISCV64 == 0x8006); // MD_CPU_ARCHITECTURE_RISCV64 #else SKIP_TEST(); #endif @@ -793,7 +836,8 @@ SENTRY_TEST(elf_header_entry_sizes) size_t shdr_size; size_t phdr_size; -# if defined(__x86_64__) || defined(__aarch64__) +# if defined(__x86_64__) || defined(__aarch64__) \ + || (defined(__riscv) && __riscv_xlen == 64) e_ident[EI_CLASS] = ELFCLASS64; other_class = ELFCLASS32; shdr_size = sizeof(Elf64_Shdr); @@ -820,3 +864,1098 @@ SENTRY_TEST(elf_header_entry_sizes) TEST_CHECK(!sentry__elf_has_phdr_size(e_ident, phdr_size)); #endif } + +SENTRY_TEST(crash_ipc_message_roundtrip) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + const char payload[] = "\x81\xa3key\xa5value"; + char *buf = NULL; + size_t buf_len = 0; + + sentry_crash_ipc_message_result_t result + = sentry__crash_ipc_message_encode(SENTRY_CRASH_IPC_MESSAGE_SET_TAG, 7, + 42, payload, sizeof(payload) - 1, &buf, &buf_len); + TEST_CHECK_INT_EQUAL(result, SENTRY_CRASH_IPC_MESSAGE_OK); + TEST_CHECK(buf != NULL); + TEST_CHECK_INT_EQUAL( + buf_len, SENTRY_CRASH_IPC_MESSAGE_HEADER_SIZE + sizeof(payload) - 1); + + sentry_crash_ipc_message_t message; + result = sentry__crash_ipc_message_decode(buf, buf_len, &message); + TEST_CHECK_INT_EQUAL(result, SENTRY_CRASH_IPC_MESSAGE_OK); + TEST_CHECK_INT_EQUAL(message.type, SENTRY_CRASH_IPC_MESSAGE_SET_TAG); + TEST_CHECK_INT_EQUAL(message.flags, 7); + TEST_CHECK_INT_EQUAL(message.sequence, 42); + TEST_CHECK_INT_EQUAL(message.payload_len, sizeof(payload) - 1); + TEST_CHECK(memcmp(message.payload, payload, sizeof(payload) - 1) == 0); + + sentry_free(buf); +#endif +} + +SENTRY_TEST(crash_ipc_message_partial) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + char *buf = NULL; + size_t buf_len = 0; + + sentry_crash_ipc_message_result_t result = sentry__crash_ipc_message_encode( + SENTRY_CRASH_IPC_MESSAGE_CRASH, 0, 9, NULL, 0, &buf, &buf_len); + TEST_CHECK_INT_EQUAL(result, SENTRY_CRASH_IPC_MESSAGE_OK); + + sentry_crash_ipc_message_t message; + result = sentry__crash_ipc_message_decode(buf, 3, &message); + TEST_CHECK_INT_EQUAL(result, SENTRY_CRASH_IPC_MESSAGE_PARTIAL); + + result = sentry__crash_ipc_message_decode(buf, buf_len - 1, &message); + TEST_CHECK_INT_EQUAL(result, SENTRY_CRASH_IPC_MESSAGE_PARTIAL); + + sentry_free(buf); +#endif +} + +SENTRY_TEST(crash_ipc_message_invalid_lengths) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + char too_small_len[4] = { 11, 0, 0, 0 }; + sentry_crash_ipc_message_t message; + + sentry_crash_ipc_message_result_t result = sentry__crash_ipc_message_decode( + too_small_len, sizeof(too_small_len), &message); + TEST_CHECK_INT_EQUAL(result, SENTRY_CRASH_IPC_MESSAGE_INVALID); + + char *buf = NULL; + size_t buf_len = 0; + result = sentry__crash_ipc_message_encode( + SENTRY_CRASH_IPC_MESSAGE_SHUTDOWN, 0, 1, NULL, 0, &buf, &buf_len); + TEST_CHECK_INT_EQUAL(result, SENTRY_CRASH_IPC_MESSAGE_OK); + + char extra[32]; + memcpy(extra, buf, buf_len); + extra[buf_len] = 0; + result = sentry__crash_ipc_message_decode(extra, buf_len + 1, &message); + TEST_CHECK_INT_EQUAL(result, SENTRY_CRASH_IPC_MESSAGE_INVALID); + + sentry_free(buf); +#endif +} + +SENTRY_TEST(crash_ipc_message_unknown_type) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + char *buf = NULL; + size_t buf_len = 0; + + sentry_crash_ipc_message_result_t result = sentry__crash_ipc_message_encode( + SENTRY_CRASH_IPC_MESSAGE_CRASH, 0, 1, NULL, 0, &buf, &buf_len); + TEST_CHECK_INT_EQUAL(result, SENTRY_CRASH_IPC_MESSAGE_OK); + buf[4] = 0xff; + buf[5] = 0x7f; + + sentry_crash_ipc_message_t message; + result = sentry__crash_ipc_message_decode(buf, buf_len, &message); + TEST_CHECK_INT_EQUAL(result, SENTRY_CRASH_IPC_MESSAGE_UNKNOWN_TYPE); + + sentry_free(buf); +#endif +} + +SENTRY_TEST(crash_ipc_message_oversized) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + char oversized_len[4] = { 0 }; + uint32_t len = SENTRY_CRASH_IPC_MESSAGE_MAX_LEN + 1; + oversized_len[0] = (char)(len & 0xffu); + oversized_len[1] = (char)((len >> 8) & 0xffu); + oversized_len[2] = (char)((len >> 16) & 0xffu); + oversized_len[3] = (char)((len >> 24) & 0xffu); + + sentry_crash_ipc_message_t message; + sentry_crash_ipc_message_result_t result = sentry__crash_ipc_message_decode( + oversized_len, sizeof(oversized_len), &message); + TEST_CHECK_INT_EQUAL(result, SENTRY_CRASH_IPC_MESSAGE_OVERSIZED); + + char payload = 0; + char *buf = NULL; + size_t buf_len = 0; + result = sentry__crash_ipc_message_encode( + SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT, 0, 0, &payload, + SENTRY_CRASH_IPC_MESSAGE_MAX_LEN, &buf, &buf_len); + TEST_CHECK_INT_EQUAL(result, SENTRY_CRASH_IPC_MESSAGE_OVERSIZED); + result = sentry__crash_ipc_message_encode( + SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT, 0, 0, &payload, + SIZE_MAX - SENTRY_CRASH_IPC_MESSAGE_HEADER_SIZE + 1, &buf, &buf_len); + TEST_CHECK_INT_EQUAL(result, SENTRY_CRASH_IPC_MESSAGE_OVERSIZED); +#endif +} + +SENTRY_TEST(crash_ipc_message_large_roundtrip) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + size_t payload_len = 200u * 1024u * 1024u; + char *payload = sentry_malloc(payload_len); + TEST_ASSERT(payload != NULL); + memset(payload, 0xa5, payload_len); + char *buf = NULL; + size_t buf_len = 0; + + sentry_crash_ipc_message_result_t result = sentry__crash_ipc_message_encode( + SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT, 0, 42, payload, payload_len, + &buf, &buf_len); + TEST_ASSERT(result == SENTRY_CRASH_IPC_MESSAGE_OK); + TEST_CHECK(buf_len == SENTRY_CRASH_IPC_MESSAGE_HEADER_SIZE + payload_len); + + sentry_crash_ipc_message_t message; + result = sentry__crash_ipc_message_decode(buf, buf_len - 1, &message); + TEST_CHECK_INT_EQUAL(result, SENTRY_CRASH_IPC_MESSAGE_PARTIAL); + result = sentry__crash_ipc_message_decode(buf, buf_len, &message); + TEST_ASSERT(result == SENTRY_CRASH_IPC_MESSAGE_OK); + TEST_CHECK(message.payload_len == payload_len); + TEST_CHECK(memcmp(message.payload, payload, payload_len) == 0); + + sentry_free(buf); + sentry_free(payload); +#endif +} + +#ifdef SENTRY_BACKEND_NATIVE +static bool +apply_scope_message( + sentry_crash_scope_t *scope, uint16_t type, sentry_value_t value) +{ + size_t len = 0; + char *payload = sentry_value_to_msgpack(value, &len); + sentry_crash_ipc_message_t message + = { type, 0, scope->sequence + 1, payload, len }; + bool applied = sentry__crash_scope_apply(scope, &message); + sentry_free(payload); + sentry_value_decref(value); + return applied; +} + +static sentry_value_t +scope_snapshot(void) +{ + sentry_value_t snapshot = sentry_value_new_object(); + sentry_value_set_by_key(snapshot, "event", sentry_value_new_object()); + sentry_value_set_by_key(snapshot, "attachments", sentry_value_new_list()); + return snapshot; +} + +static sentry_value_t +scope_pair(const char *key, sentry_value_t value) +{ + sentry_value_t pair = sentry_value_new_list(); + sentry_value_append(pair, sentry_value_new_string(key)); + sentry_value_append(pair, value); + return pair; +} +#endif + +SENTRY_TEST(crash_scope_updates) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + sentry_crash_scope_t scope; + TEST_ASSERT(sentry__crash_scope_init(&scope, 2)); + TEST_CHECK(!apply_scope_message( + &scope, SENTRY_CRASH_IPC_MESSAGE_SET_USER, sentry_value_new_object())); + TEST_ASSERT(apply_scope_message( + &scope, SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT, scope_snapshot())); + struct { + uint16_t set; + uint16_t remove; + const char *field; + } keyed[] = { + { SENTRY_CRASH_IPC_MESSAGE_SET_TAG, SENTRY_CRASH_IPC_MESSAGE_REMOVE_TAG, + "tags" }, + { SENTRY_CRASH_IPC_MESSAGE_SET_EXTRA, + SENTRY_CRASH_IPC_MESSAGE_REMOVE_EXTRA, "extra" }, + { SENTRY_CRASH_IPC_MESSAGE_SET_CONTEXT, + SENTRY_CRASH_IPC_MESSAGE_REMOVE_CONTEXT, "contexts" }, + }; + for (size_t i = 0; i < sizeof(keyed) / sizeof(keyed[0]); i++) { + TEST_CHECK(apply_scope_message(&scope, keyed[i].set, + scope_pair("key", sentry_value_new_string("first")))); + TEST_CHECK(apply_scope_message( + &scope, keyed[i].remove, sentry_value_new_string("key"))); + TEST_CHECK(sentry_value_is_null(sentry_value_get_by_key( + sentry_value_get_by_key(scope.event, keyed[i].field), "key"))); + TEST_CHECK(apply_scope_message(&scope, keyed[i].set, + scope_pair("key", sentry_value_new_string("last")))); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key( + sentry_value_get_by_key(scope.event, keyed[i].field), "key")), + "last"); + } + struct { + uint16_t type; + const char *field; + } fields[] = { + { SENTRY_CRASH_IPC_MESSAGE_SET_RELEASE, "release" }, + { SENTRY_CRASH_IPC_MESSAGE_SET_ENVIRONMENT, "environment" }, + { SENTRY_CRASH_IPC_MESSAGE_SET_TRANSACTION, "transaction" }, + { SENTRY_CRASH_IPC_MESSAGE_SET_LEVEL, "level" }, + }; + for (size_t i = 0; i < sizeof(fields) / sizeof(fields[0]); i++) { + TEST_CHECK(apply_scope_message( + &scope, fields[i].type, sentry_value_new_string_n("a\0b", 3))); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(sentry_value_get_by_key( + scope.event, fields[i].field)), + 3); + TEST_CHECK(apply_scope_message( + &scope, fields[i].type, sentry_value_new_null())); + TEST_CHECK(sentry_value_is_null( + sentry_value_get_by_key(scope.event, fields[i].field))); + } + TEST_CHECK(apply_scope_message( + &scope, SENTRY_CRASH_IPC_MESSAGE_SET_USER, sentry_value_new_object())); + TEST_CHECK(apply_scope_message( + &scope, SENTRY_CRASH_IPC_MESSAGE_SET_USER, sentry_value_new_null())); + TEST_CHECK(apply_scope_message(&scope, + SENTRY_CRASH_IPC_MESSAGE_SET_FINGERPRINT, sentry_value_new_list())); + TEST_CHECK(apply_scope_message(&scope, + SENTRY_CRASH_IPC_MESSAGE_SET_FINGERPRINT, sentry_value_new_null())); + for (int i = 0; i < 3; i++) { + sentry_value_t crumb = sentry_value_new_object(); + sentry_value_set_by_key(crumb, "index", sentry_value_new_int32(i)); + TEST_CHECK(apply_scope_message( + &scope, SENTRY_CRASH_IPC_MESSAGE_ADD_BREADCRUMB, crumb)); + } + sentry_value_t event = sentry__crash_scope_event(&scope); + sentry_value_t crumbs = sentry_value_get_by_key(event, "breadcrumbs"); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(crumbs), 2); + TEST_CHECK_INT_EQUAL(sentry_value_as_int32(sentry_value_get_by_key( + sentry_value_get_by_index(crumbs, 0), "index")), + 1); + sentry_value_decref(event); + sentry_value_t attachments = sentry_value_new_list(); + sentry_value_append(attachments, sentry_value_new_object()); + TEST_CHECK(apply_scope_message( + &scope, SENTRY_CRASH_IPC_MESSAGE_SET_ATTACHMENT_LIST, attachments)); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(scope.attachments), 1); + TEST_CHECK(apply_scope_message(&scope, + SENTRY_CRASH_IPC_MESSAGE_SET_ATTACHMENT_LIST, sentry_value_new_list())); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(scope.attachments), 0); + TEST_CHECK(apply_scope_message( + &scope, SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT, scope_snapshot())); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(scope.event), 0); + sentry_crash_ipc_message_t crash + = { SENTRY_CRASH_IPC_MESSAGE_CRASH, 0, scope.sequence + 1, NULL, 0 }; + TEST_CHECK(sentry__crash_scope_apply(&scope, &crash)); + TEST_CHECK(!apply_scope_message( + &scope, SENTRY_CRASH_IPC_MESSAGE_SET_USER, sentry_value_new_object())); + sentry__crash_scope_free(&scope); +#endif +} + +SENTRY_TEST(crash_scope_invalid_updates) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + sentry_crash_scope_t scope; + TEST_ASSERT(sentry__crash_scope_init(&scope, 0)); + TEST_ASSERT(apply_scope_message( + &scope, SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT, scope_snapshot())); + TEST_CHECK(!apply_scope_message(&scope, SENTRY_CRASH_IPC_MESSAGE_SET_TAG, + sentry_value_new_string("invalid"))); + TEST_CHECK(!apply_scope_message( + &scope, SENTRY_CRASH_IPC_MESSAGE_SET_USER, sentry_value_new_int32(1))); + TEST_CHECK(!apply_scope_message(&scope, + SENTRY_CRASH_IPC_MESSAGE_SET_ATTACHMENT_LIST, + sentry_value_new_object())); + sentry_crash_ipc_message_t message + = { SENTRY_CRASH_IPC_MESSAGE_SET_USER, 0, 2, "\x81", 1 }; + TEST_CHECK(!sentry__crash_scope_apply(&scope, &message)); + message.payload = "\xc0\xc0"; + message.payload_len = 2; + TEST_CHECK(!sentry__crash_scope_apply(&scope, &message)); + message.payload = "\xc0"; + message.payload_len = 1; + message.sequence = 3; + TEST_CHECK(!sentry__crash_scope_apply(&scope, &message)); + message.sequence = 2; + message.flags = 1; + TEST_CHECK(!sentry__crash_scope_apply(&scope, &message)); + TEST_CHECK_INT_EQUAL(scope.sequence, 1); + TEST_CHECK(apply_scope_message(&scope, + SENTRY_CRASH_IPC_MESSAGE_ADD_BREADCRUMB, sentry_value_new_object())); + sentry_value_t event = sentry__crash_scope_event(&scope); + TEST_CHECK_INT_EQUAL( + sentry_value_get_length(sentry_value_get_by_key(event, "breadcrumbs")), + 0); + sentry_value_decref(event); + sentry__crash_scope_free(&scope); +#endif +} + +#ifdef SENTRY_BACKEND_NATIVE +static sentry_value_t +native_scope_on_crash(const sentry_ucontext_t *UNUSED(uctx), + sentry_value_t event, sentry_hint_t *hint, void *UNUSED(data)) +{ + sentry_set_tag("tag", "callback"); + if (getenv("SENTRY_TEST_NATIVE_SCOPE_HINT_CLEAR")) { + sentry_hint_clear_attachments(hint); + } else { + sentry_clear_attachments(); + sentry_attach_bytes("callback", 8, "callback.txt"); + } + sentry_value_set_by_key(event, "callback", sentry_value_new_bool(true)); + return event; +} +#endif + +SENTRY_TEST(native_scope_updates) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + const char *crash_mode = getenv("SENTRY_TEST_NATIVE_SCOPE_CRASH"); + bool callback = getenv("SENTRY_TEST_NATIVE_SCOPE_CALLBACK") != NULL; + SENTRY_TEST_OPTIONS_NEW(options); + if (callback) { + sentry_options_set_on_crash(options, native_scope_on_crash, NULL); + } + sentry_options_set_auto_session_tracking(options, false); + sentry_options_set_max_breadcrumbs(options, 3); + sentry_options_set_traces_sample_rate(options, 1); + sentry_options_set_debug(options, true); + if (crash_mode) { + sentry_options_set_dsn(options, getenv("SENTRY_DSN")); + sentry_options_set_crash_reporting_mode(options, atoi(crash_mode)); + } + TEST_ASSERT(sentry_init(options) == 0); + sentry_set_tag("cleared", "old"); + sentry_attach_bytes("old", 3, "cleared.txt"); + SENTRY_WITH_SCOPE_MUT (scope) { + sentry_scope_clear(scope); + } + for (int i = 0; i < 1000; i++) { + sentry_set_tag("tag", "old"); + sentry_remove_tag("tag"); + } + sentry_set_tag("tag", "latest"); + sentry_set_tag_n("binary-tag-tail", 10, "v\0x", 3); + sentry_set_tag_n("gone-tag-tail", 8, "old", 3); + sentry_remove_tag_n("gone-tag-tail", 8); + sentry_set_extra_n("gone-extra-tail", 10, sentry_value_new_int32(1)); + sentry_remove_extra_n("gone-extra-tail", 10); + sentry_set_context_n("gone-context-tail", 12, sentry_value_new_object()); + sentry_remove_context_n("gone-context-tail", 12); + sentry_set_release("ipc-release"); + sentry_set_environment("ipc-environment"); + sentry_set_transaction("ipc-transaction"); + sentry_set_level(SENTRY_LEVEL_WARNING); + sentry_set_fingerprint("ipc", "latest", NULL); + sentry_value_t user = sentry_value_new_object(); + sentry_value_set_by_key( + user, "username", sentry_value_new_string("ipc-user")); + sentry_set_user(user); + sentry_set_extra("removed", sentry_value_new_int32(1)); + sentry_remove_extra("removed"); + size_t size = 1024 * 1024; + char *large = sentry_malloc(size); + TEST_ASSERT(large != NULL); + memset(large, 'x', size); + sentry_set_extra("large", sentry_value_new_string_n(large, size)); + sentry_free(large); + sentry_set_context("removed", sentry_value_new_object()); + sentry_remove_context("removed"); + sentry_value_t context = sentry_value_new_object(); + sentry_value_set_by_key( + context, "status", sentry_value_new_string("latest")); + sentry_set_context("ipc", context); + sentry_transaction_t *tx = sentry_transaction_start( + sentry_transaction_context_new("bound", "work"), + sentry_value_new_null()); + sentry_set_transaction_object(tx); + sentry_span_t *span = sentry_transaction_start_child(tx, "child", "work"); + sentry_set_span(span); + bool scoped_trace = getenv("SENTRY_TEST_NATIVE_SCOPE_SPAN") != NULL; + if (!scoped_trace) { + sentry_set_span(NULL); + } + sentry_set_context("trace", sentry_value_new_object()); + sentry_value_t trace = sentry_value_new_null(); + SENTRY_WITH_SCOPE_MUT (scope) { + sentry__scope_regenerate_propagation_context(scope); + if (scoped_trace) { + sentry_value_t active + = sentry__scope_load_span_or_transaction(scope); + trace = sentry__value_get_trace_context(active); + sentry_value_decref(active); + } else { + trace = sentry__scope_load_trace_context(scope); + } + } + sentry_set_extra("expected-trace", trace); + for (int i = 0; i < 5; i++) { + sentry_value_t crumb = sentry_value_new_breadcrumb(NULL, NULL); + sentry_value_set_by_key(crumb, "index", sentry_value_new_int32(i)); + sentry_add_breadcrumb(crumb); + } + sentry_attach_bytes("old", 3, "cleared-again.txt"); + sentry_clear_attachments(); + sentry_uuid_t removed = sentry_attach_bytes("old", 3, "removed.txt"); + sentry_attach_bytes("new", 3, "latest.txt"); + sentry_remove_attachment(removed); + SENTRY_WITH_OPTIONS (current) { + const char *names[] = { "__sentry-event", "__sentry-breadcrumb1", + "__sentry-breadcrumb2", "__sentry-attachments" }; + for (size_t i = 0; i < sizeof(names) / sizeof(names[0]); i++) { + sentry_path_t *path + = sentry__path_join_str(current->run->run_path, names[i]); + TEST_CHECK(!sentry__path_is_file(path)); + sentry__path_free(path); + } + if (crash_mode && !callback) { + // exercise staged IPC state without a crash-time snapshot + current->backend->except_func = NULL; + } + } + if (crash_mode) { +# if defined(SENTRY_PLATFORM_WINDOWS) + RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL); +# else + raise(SIGSEGV); +# endif + } + sentry_span_finish(span); + sentry_transaction_finish(tx); + sentry_close(); +#endif +} + +#ifdef SENTRY_BACKEND_NATIVE +static void +stall_step(const char *step) +{ + printf("stall:%s\n", step); + fflush(stdout); + getchar(); +} + +static sentry_value_t +stall_on_crash(const sentry_ucontext_t *UNUSED(uctx), sentry_value_t event, + sentry_hint_t *UNUSED(hint), void *UNUSED(data)) +{ + printf("stall:crash\n"); + fflush(stdout); + return event; +} + +static void +stall_add_breadcrumb(int index) +{ + char message[16 * 1024]; + memset(message, 'x', sizeof(message) - 1); + message[sizeof(message) - 1] = '\0'; + sentry_value_t crumb = sentry_value_new_breadcrumb(NULL, message); + sentry_value_set_by_key(crumb, "index", sentry_value_new_int32(index)); + sentry_add_breadcrumb(crumb); +} + +static void +stall_set_large_extra(void) +{ + size_t size = 2 * 1024 * 1024; + char *large = sentry_malloc(size); + TEST_ASSERT(large != NULL); + memset(large, 'x', size); + sentry_set_extra("large", sentry_value_new_string_n(large, size)); + sentry_free(large); +} + +SENTRY_THREAD_FN +stall_sender_thread(void *UNUSED(data)) +{ + stall_set_large_extra(); + return 0; +} + +static void +stall_crash(void) +{ +# if defined(SENTRY_PLATFORM_WINDOWS) + RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL); +# else + raise(SIGSEGV); +# endif +} +#endif + +// driven by test_native_stall_* in test_integration_native.py +SENTRY_TEST(native_stall) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + const char *mode = getenv("SENTRY_TEST_NATIVE_STALL"); + if (!mode) { + SKIP_TEST(); + } + bool crash = sentry__string_eq(mode, "crash"); + bool recover = sentry__string_eq(mode, "recover"); + int crumbs = 64; + int recovery_crumbs = 10; + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_dsn(options, getenv("SENTRY_DSN")); + sentry_options_set_max_breadcrumbs(options, crumbs + recovery_crumbs); + if (crash) { + sentry_options_set_on_crash(options, stall_on_crash, NULL); + } + TEST_ASSERT(sentry_init(options) == 0); + stall_step("ready"); + + if (crash) { + sentry_threadid_t thread; + sentry__thread_init(&thread); + TEST_ASSERT(!sentry__thread_spawn(&thread, stall_sender_thread, NULL)); + // let the sender fill the stream + sleep_ms(100); + stall_crash(); + } + + for (int i = 0; i < crumbs; i++) { + stall_add_breadcrumb(i); + } + stall_set_large_extra(); + stall_step("done"); + + if (recover) { + for (int i = 0; i < recovery_crumbs; i++) { + sleep_ms(100); + stall_add_breadcrumb(crumbs + i); + } + SENTRY_WITH_OPTIONS (current) { + // exercise staged IPC state without a crash-time snapshot + current->backend->except_func = NULL; + } + stall_crash(); + } + sentry_close(); +#endif +} + +#ifdef SENTRY_BACKEND_NATIVE +static sentry_crash_ipc_t * +new_test_ipc(void) +{ +# if defined(SENTRY_PLATFORM_ANDROID) + sentry_crash_ipc_t *ipc = sentry__crash_ipc_init_app(".", NULL); +# else + sentry_crash_ipc_t *ipc = sentry__crash_ipc_init_app(NULL); +# endif + TEST_ASSERT(ipc != NULL); + TEST_ASSERT(sentry__crash_scope_init(&ipc->scope, 2)); + sentry_value_t snapshot = scope_snapshot(); + TEST_ASSERT(sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT, snapshot)); + sentry_value_decref(snapshot); + return ipc; +} + +static void +write_test_frame(sentry_crash_ipc_t *ipc, const char *buf, size_t len) +{ +# if defined(SENTRY_PLATFORM_WINDOWS) + OVERLAPPED overlapped = { 0 }; + overlapped.hEvent = ipc->message_write.hEvent; + DWORD written = 0; + TEST_ASSERT(WriteFile( + ipc->message_write_handle, buf, (DWORD)len, NULL, &overlapped)); + TEST_ASSERT(GetOverlappedResult( + ipc->message_write_handle, &overlapped, &written, FALSE)); + TEST_CHECK_INT_EQUAL(written, len); +# else + TEST_CHECK_INT_EQUAL(write(ipc->message_fd[0], buf, len), len); +# endif +} +#endif + +SENTRY_TEST(crash_ipc_stream_ordering) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + sentry_crash_ipc_t *ipc = new_test_ipc(); + sentry_value_t value = sentry_value_new_string("latest"); + TEST_CHECK(sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SET_RELEASE, value)); + sentry_value_decref(value); + sentry__crash_ipc_notify(ipc); + TEST_CHECK(sentry__crash_ipc_receive(ipc, 100)); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(sentry_value_get_by_key( + ipc->scope.event, "release")), + "latest"); + TEST_CHECK(!sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SET_USER, sentry_value_new_null())); + sentry__crash_ipc_free(ipc); +#endif +} + +SENTRY_TEST(crash_ipc_interrupted_frame) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + sentry_crash_ipc_t *ipc = new_test_ipc(); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + char *buf = NULL; + size_t len = 0; + const char payload[] = "\xa6latest"; + TEST_ASSERT( + sentry__crash_ipc_message_encode(SENTRY_CRASH_IPC_MESSAGE_SET_RELEASE, + 0, 2, payload, sizeof(payload) - 1, &buf, &len) + == SENTRY_CRASH_IPC_MESSAGE_OK); + write_test_frame(ipc, buf, 7); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + write_test_frame(ipc, buf + 7, len - 8); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + ipc->writing = 1; + sentry__crash_ipc_notify(ipc); + TEST_CHECK(sentry__crash_ipc_receive(ipc, 100)); + TEST_CHECK_INT_EQUAL(ipc->scope.sequence, 1); + TEST_CHECK(sentry_value_is_null( + sentry_value_get_by_key(ipc->scope.event, "release"))); + sentry_free(buf); + sentry__crash_ipc_free(ipc); +#endif +} + +SENTRY_TEST(crash_ipc_torn_frame) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + sentry_crash_ipc_t *ipc = new_test_ipc(); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + const char payload[] = "\xa6latest"; + const size_t offsets[] = { 0, 1, SENTRY_CRASH_IPC_MESSAGE_PREFIX_SIZE, + SENTRY_CRASH_IPC_MESSAGE_HEADER_SIZE, + SENTRY_CRASH_IPC_MESSAGE_HEADER_SIZE + sizeof(payload) - 2 }; + for (size_t i = 0; i < sizeof(offsets) / sizeof(offsets[0]); i++) { + uint64_t sequence = ipc->sequence + 1; + char *buf = NULL; + size_t len = 0; + TEST_ASSERT(sentry__crash_ipc_message_encode( + SENTRY_CRASH_IPC_MESSAGE_SET_RELEASE, 0, sequence, + payload, sizeof(payload) - 1, &buf, &len) + == SENTRY_CRASH_IPC_MESSAGE_OK); + write_test_frame(ipc, buf, offsets[i]); + ipc->torn_frame = buf; + ipc->torn_len = len; + ipc->torn_sent = offsets[i]; + ipc->stalled = 1; + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + TEST_CHECK_INT_EQUAL(ipc->scope.sequence, sequence - 1); + + TEST_CHECK(sentry__crash_ipc_flush(ipc)); + TEST_CHECK(ipc->torn_frame == NULL); + TEST_CHECK_INT_EQUAL(ipc->sequence, sequence); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + TEST_CHECK_INT_EQUAL(ipc->scope.sequence, sequence); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(sentry_value_get_by_key( + ipc->scope.event, "release")), + "latest"); + + sentry_value_t snapshot = scope_snapshot(); + TEST_CHECK(sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT, snapshot)); + sentry_value_decref(snapshot); + TEST_CHECK(!ipc->stalled); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + TEST_CHECK_INT_EQUAL(ipc->scope.sequence, sequence + 1); + } + sentry__crash_ipc_free(ipc); +#endif +} + +SENTRY_TEST(crash_ipc_stalled_stream) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + sentry_crash_ipc_t *ipc = new_test_ipc(); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + size_t size = 8 * 1024 * 1024; + char *large = sentry_malloc(size); + TEST_ASSERT(large != NULL); + memset(large, 'x', size); + sentry_value_t value = sentry_value_new_string_n(large, size); + sentry_free(large); + TEST_CHECK(!sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SET_RELEASE, value)); + sentry_value_decref(value); + TEST_CHECK(ipc->stalled); + TEST_CHECK(ipc->torn_frame != NULL); + TEST_CHECK_INT_EQUAL(ipc->sequence, 1); + + value = sentry_value_new_string("skipped"); + TEST_CHECK(!sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SET_ENVIRONMENT, value)); + sentry_value_decref(value); + TEST_CHECK_INT_EQUAL(ipc->sequence, 1); + + while (!sentry__crash_ipc_flush(ipc)) { + sentry__crash_ipc_receive(ipc, 0); + } + TEST_CHECK(ipc->stalled); + TEST_CHECK_INT_EQUAL(ipc->sequence, 2); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + TEST_CHECK_INT_EQUAL(ipc->scope.sequence, 2); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(sentry_value_get_by_key( + ipc->scope.event, "release")), + size); + TEST_CHECK(sentry_value_is_null( + sentry_value_get_by_key(ipc->scope.event, "environment"))); + + sentry_value_t snapshot = scope_snapshot(); + TEST_CHECK(sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT, snapshot)); + sentry_value_decref(snapshot); + TEST_CHECK(!ipc->stalled); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + TEST_CHECK_INT_EQUAL(ipc->scope.sequence, 3); + sentry__crash_ipc_free(ipc); +#endif +} + +SENTRY_TEST(crash_ipc_awaiting_ready) +{ +#if !defined(SENTRY_BACKEND_NATIVE) \ + || !(defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID)) + SKIP_TEST(); +#else + sentry_crash_ipc_t *ipc = new_test_ipc(); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + ipc->awaiting_ready = 1; + size_t size = 2 * 1024 * 1024; + char *large = sentry_malloc(size); + TEST_ASSERT(large != NULL); + memset(large, 'x', size); + sentry_value_t value = sentry_value_new_string_n(large, size); + sentry_free(large); + // the send serializes too, so leave that time out of the bound + uint64_t start = sentry__monotonic_time(); + size_t len = 0; + sentry_free(sentry_value_to_msgpack(value, &len)); + uint64_t serialize = sentry__monotonic_time() - start; + // nothing reads yet, so the frame stalls at once and counts as sent + start = sentry__monotonic_time(); + TEST_CHECK(sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SET_RELEASE, value)); + // a blocking write would wait out the whole send timeout + TEST_CHECK(sentry__monotonic_time() - start + < serialize + SENTRY_CRASH_IPC_SEND_TIMEOUT_MS / 2); + sentry_value_decref(value); + TEST_CHECK(ipc->stalled); + TEST_CHECK(ipc->awaiting_ready); + + uint64_t ready = 1; + TEST_CHECK_INT_EQUAL( + write(ipc->ready_fd, &ready, sizeof(ready)), sizeof(ready)); + while (!sentry__crash_ipc_flush(ipc)) { + sentry__crash_ipc_receive(ipc, 0); + } + sentry_value_t snapshot = scope_snapshot(); + TEST_CHECK(sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT, snapshot)); + sentry_value_decref(snapshot); + TEST_CHECK(!ipc->awaiting_ready); + TEST_CHECK(!ipc->stalled); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + TEST_CHECK_INT_EQUAL(ipc->scope.sequence, 3); + sentry__crash_ipc_free(ipc); +#endif +} + +SENTRY_TEST(crash_ipc_stalled_notify) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + sentry_crash_ipc_t *ipc = new_test_ipc(); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + const char payload[] = "\xa6latest"; + char *buf = NULL; + size_t len = 0; + TEST_ASSERT( + sentry__crash_ipc_message_encode(SENTRY_CRASH_IPC_MESSAGE_SET_RELEASE, + 0, 2, payload, sizeof(payload) - 1, &buf, &len) + == SENTRY_CRASH_IPC_MESSAGE_OK); + write_test_frame(ipc, buf, 7); + ipc->torn_frame = buf; + ipc->torn_len = len; + ipc->torn_sent = 7; + ipc->stalled = 1; + sentry__crash_ipc_notify(ipc); + TEST_CHECK(sentry__crash_ipc_receive(ipc, 100)); + TEST_CHECK(!ipc->message_closed); + TEST_CHECK_INT_EQUAL(ipc->scope.sequence, 1); + sentry__crash_ipc_free(ipc); +#endif +} + +SENTRY_TEST(crash_ipc_reattach_stalled) +{ +#if !defined(SENTRY_BACKEND_NATIVE) || !defined(SENTRY_PLATFORM_ANDROID) + SKIP_TEST(); +#else + sentry_crash_ipc_t *ipc = new_test_ipc(); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + size_t size = 8 * 1024 * 1024; + char *large = sentry_malloc(size); + TEST_ASSERT(large != NULL); + memset(large, 'x', size); + sentry_value_t value = sentry_value_new_string_n(large, size); + sentry_free(large); + TEST_CHECK(!sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SET_RELEASE, value)); + TEST_CHECK(ipc->stalled); + TEST_CHECK(ipc->torn_frame != NULL); + + int fds[2]; + TEST_ASSERT(socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == 0); + int notify_fd = eventfd(0, EFD_CLOEXEC); + int ready_fd = eventfd(0, EFD_CLOEXEC); + TEST_CHECK(sentry__crash_ipc_reattach(ipc, notify_fd, ready_fd, fds[0])); + TEST_CHECK(ipc->awaiting_ready); + TEST_CHECK(!ipc->stalled); + TEST_CHECK(ipc->torn_frame == NULL); + TEST_CHECK_INT_EQUAL(ipc->sequence, 0); + + // the new daemon starts at a snapshot with sequence 1 + sentry_value_t snapshot = scope_snapshot(); + TEST_CHECK(sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SCOPE_SNAPSHOT, snapshot)); + sentry_value_decref(snapshot); + char header[SENTRY_CRASH_IPC_MESSAGE_HEADER_SIZE]; + TEST_CHECK_INT_EQUAL(read(fds[1], header, sizeof(header)), sizeof(header)); + TEST_CHECK_INT_EQUAL((uint8_t)header[8], 1); + + // the send timeout applies to the new stream once its daemon is ready + uint64_t ready = 1; + TEST_CHECK_INT_EQUAL( + write(ipc->ready_fd, &ready, sizeof(ready)), sizeof(ready)); + struct timeval timeout = { 0, 0 }; + socklen_t len = sizeof(timeout); + getsockopt(ipc->message_fd[0], SOL_SOCKET, SO_SNDTIMEO, &timeout, &len); + TEST_CHECK(timeout.tv_sec || timeout.tv_usec); + TEST_CHECK(!sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SET_RELEASE, value)); + TEST_CHECK(ipc->stalled); + sentry_value_decref(value); + close(fds[1]); + sentry__crash_ipc_free(ipc); +#endif +} + +SENTRY_TEST(crash_ipc_partial_reads) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + sentry_crash_ipc_t *ipc = new_test_ipc(); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + char *buf = NULL; + size_t len = 0; + const char payload[] = "\xa6latest"; + TEST_ASSERT( + sentry__crash_ipc_message_encode(SENTRY_CRASH_IPC_MESSAGE_SET_RELEASE, + 0, 2, payload, sizeof(payload) - 1, &buf, &len) + == SENTRY_CRASH_IPC_MESSAGE_OK); + for (size_t i = 0; i < len; i++) { + write_test_frame(ipc, buf + i, 1); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + TEST_CHECK_INT_EQUAL(ipc->scope.sequence, i + 1 == len ? 2 : 1); + } + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(sentry_value_get_by_key( + ipc->scope.event, "release")), + "latest"); + sentry_free(buf); + sentry__crash_ipc_free(ipc); +#endif +} + +SENTRY_TEST(crash_ipc_shutdown) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + sentry_crash_ipc_t *ipc = new_test_ipc(); + TEST_CHECK(sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SHUTDOWN, sentry_value_new_null())); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 100)); + TEST_CHECK(ipc->scope.stopped); + sentry__crash_ipc_free(ipc); +#endif +} + +SENTRY_TEST(crash_ipc_broken_stream) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + sentry_crash_ipc_t *ipc = new_test_ipc(); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + char invalid[SENTRY_CRASH_IPC_MESSAGE_HEADER_SIZE] + = { 12, 0, 0, 0, (char)0xff, (char)0xff, 0, 0, 2 }; + write_test_frame(ipc, invalid, sizeof(invalid)); + TEST_CHECK(!sentry__crash_ipc_receive(ipc, 0)); + TEST_CHECK(ipc->message_closed); + TEST_CHECK_INT_EQUAL(ipc->scope.sequence, 1); + TEST_CHECK(!sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SET_USER, sentry_value_new_null())); + sentry__crash_ipc_notify(ipc); + TEST_CHECK(sentry__crash_ipc_receive(ipc, 100)); + sentry__crash_ipc_free(ipc); +#endif +} + +SENTRY_TEST(crash_ipc_crashing) +{ +#ifndef SENTRY_BACKEND_NATIVE + SKIP_TEST(); +#else + sentry_crash_ipc_t *ipc = new_test_ipc(); + sentry__atomic_store(&ipc->shmem->state, SENTRY_CRASH_STATE_CRASHING); + sentry__crash_ipc_notify(ipc); + TEST_CHECK(sentry__crash_ipc_receive(ipc, 100)); + TEST_CHECK(!ipc->scope.stopped); + TEST_CHECK(!ipc->notify_pending); + + sentry_value_t value = sentry_value_new_string("latest"); + TEST_CHECK(sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SET_RELEASE, value)); + sentry_value_decref(value); + sentry__atomic_store(&ipc->shmem->state, SENTRY_CRASH_STATE_CRASHED); + sentry__crash_ipc_notify(ipc); + TEST_CHECK(sentry__crash_ipc_receive(ipc, 100)); + TEST_CHECK(ipc->scope.stopped); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(sentry_value_get_by_key( + ipc->scope.event, "release")), + "latest"); + sentry__crash_ipc_free(ipc); +#endif +} + +SENTRY_TEST(crash_daemon_shutdown_during_crash) +{ +#if !defined(SENTRY_BACKEND_NATIVE) || !defined(SENTRY_PLATFORM_LINUX) + SKIP_TEST(); +#else + const char *daemon = getenv("SENTRY_TEST_NATIVE_DAEMON"); + if (!daemon) { + SKIP_TEST(); + } + SENTRY_TEST_OPTIONS_NEW(options); + TEST_ASSERT(sentry__path_create_dir_all(options->database_path) == 0); + sentry_run_t *run = sentry__run_new(options->database_path); + TEST_ASSERT(run != NULL); + sentry_crash_ipc_t *ipc = new_test_ipc(); + snprintf(ipc->shmem->database_path, sizeof(ipc->shmem->database_path), "%s", + options->database_path->path); + snprintf(ipc->shmem->run_path, sizeof(ipc->shmem->run_path), "%s", + run->run_path->path); + ipc->shmem->event_discarded = true; + sentry__atomic_store(&ipc->shmem->state, SENTRY_CRASH_STATE_CRASHING); + TEST_ASSERT(sentry__crash_ipc_send( + ipc, SENTRY_CRASH_IPC_MESSAGE_SHUTDOWN, sentry_value_new_null())); + + char pid[32], tid[32], notify[32], ready[32], shm[32], message[32]; + snprintf(pid, sizeof(pid), "%d", (int)getpid()); + snprintf(tid, sizeof(tid), "%llx", (unsigned long long)pthread_self()); + snprintf(notify, sizeof(notify), "%d", ipc->notify_fd); + snprintf(ready, sizeof(ready), "%d", ipc->ready_fd); + snprintf(shm, sizeof(shm), "%d", ipc->shm_fd); + snprintf(message, sizeof(message), "%d", ipc->message_fd[1]); + pid_t child = fork(); + TEST_ASSERT(child >= 0); + if (child == 0) { + int fds[] = { ipc->notify_fd, ipc->ready_fd, ipc->shm_fd, + ipc->message_fd[1] }; + for (size_t i = 0; i < sizeof(fds) / sizeof(fds[0]); i++) { + fcntl(fds[i], F_SETFD, 0); + } + execl(daemon, daemon, pid, tid, notify, ready, shm, message, NULL); + _exit(1); + } + TEST_CHECK(sentry__crash_ipc_wait_for_ready( + ipc, SENTRY_CRASH_DAEMON_READY_TIMEOUT_MS)); + // wait until the daemon has read SHUTDOWN + int queued = -1; + for (int i = 0; i < SENTRY_CRASH_HANDLER_WAIT_TIMEOUT_MS / 10; i++) { + if (ioctl(ipc->message_fd[0], SIOCOUTQ, &queued) != 0 || queued == 0) { + break; + } + sleep_ms(10); + } + TEST_CHECK_INT_EQUAL(queued, 0); + sleep_ms(100); + TEST_CHECK_INT_EQUAL(waitpid(child, NULL, WNOHANG), 0); + + sentry__atomic_store(&ipc->shmem->state, SENTRY_CRASH_STATE_CRASHED); + sentry__crash_ipc_notify(ipc); + int status = 0; + pid_t result = 0; + for (int i = 0; i < SENTRY_CRASH_HANDLER_WAIT_TIMEOUT_MS / 10; i++) { + result = waitpid(child, &status, WNOHANG); + if (result != 0) { + break; + } + sleep_ms(10); + } + if (result == 0) { + kill(child, SIGKILL); + waitpid(child, &status, 0); + } + TEST_CHECK_INT_EQUAL(result, child); + TEST_CHECK(WIFEXITED(status) && WEXITSTATUS(status) == 0); + TEST_CHECK_INT_EQUAL( + sentry__atomic_fetch(&ipc->shmem->state), SENTRY_CRASH_STATE_DONE); + sentry__crash_ipc_free(ipc); + sentry__run_free(run); + sentry_options_free(options); +#endif +} + +SENTRY_TEST(crash_ipc_notify_without_daemon) +{ +#if !defined(SENTRY_BACKEND_NATIVE) \ + || !(defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID)) + SKIP_TEST(); +#else + sentry_crash_ipc_t *ipc = new_test_ipc(); + // the daemon's ends are gone, as in a killed crash service + close(ipc->message_fd[1]); + ipc->message_fd[1] = -1; + int notify_pipe[2]; + TEST_ASSERT(pipe(notify_pipe) == 0); + close(notify_pipe[0]); + TEST_ASSERT(dup2(notify_pipe[1], ipc->notify_fd) == ipc->notify_fd); + close(notify_pipe[1]); + + void (*previous)(int) = signal(SIGPIPE, SIG_DFL); + TEST_CHECK(!sentry__crash_ipc_notify(ipc)); + sentry__atomic_store(&ipc->shmem->state, SENTRY_CRASH_STATE_CRASHING); + TEST_CHECK(!sentry__crash_ipc_notify(ipc)); + signal(SIGPIPE, previous); + sentry__crash_ipc_free(ipc); +#endif +} diff --git a/tests/unit/test_options.c b/tests/unit/test_options.c index 955d425777..cde8cd6cda 100644 --- a/tests/unit/test_options.c +++ b/tests/unit/test_options.c @@ -431,3 +431,23 @@ SENTRY_TEST(options_attach_stacktrace) TEST_CHECK_INT_EQUAL(sentry_options_get_attach_stacktrace(options), 0); sentry_options_free(options); } + +SENTRY_TEST(options_shutdown_timeout) +{ + SENTRY_TEST_OPTIONS_NEW(options); + + // not set + TEST_CHECK(!sentry__options_has_shutdown_timeout(options)); + TEST_CHECK_UINT64_EQUAL(sentry_options_get_shutdown_timeout(options), 2000); + + // explicit values are respected + sentry_options_set_shutdown_timeout(options, 0); + TEST_CHECK(sentry__options_has_shutdown_timeout(options)); + TEST_CHECK_UINT64_EQUAL(sentry_options_get_shutdown_timeout(options), 0); + + sentry_options_set_shutdown_timeout(options, 60000); + TEST_CHECK_UINT64_EQUAL( + sentry_options_get_shutdown_timeout(options), 60000); + + sentry_options_free(options); +} diff --git a/tests/unit/test_os.c b/tests/unit/test_os.c index 7eacf43c1e..be8e64cc4c 100644 --- a/tests/unit/test_os.c +++ b/tests/unit/test_os.c @@ -129,6 +129,24 @@ assert_equals_snap(sentry_value_t os_dist) } extern sentry_value_t get_linux_os_release(const char *os_rel_path); +extern void set_os_distribution( + sentry_value_t os, sentry_value_t os_dist, const char *release); + +static sentry_value_t +make_linux_os(void) +{ + sentry_value_t os = sentry_value_new_object(); + sentry_value_set_by_key(os, "name", sentry_value_new_string("Linux")); + sentry_value_set_by_key(os, "version", sentry_value_new_string("6.1.0")); + sentry_value_set_by_key(os, "build", sentry_value_new_string("test")); + return os; +} + +static const char * +os_string(sentry_value_t os, const char *key) +{ + return sentry_value_as_string(sentry_value_get_by_key(os, key)); +} #endif // defined(SENTRY_PLATFORM_LINUX) && !defined(SENTRY_PLATFORM_ANDROID) SENTRY_TEST(os_releases_snapshot) @@ -195,6 +213,63 @@ SENTRY_TEST(os_release_non_existent_files) #endif // !defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) } +SENTRY_TEST(os_release_named_distributions) +{ +#if !defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) + SKIP_TEST(); +#else + sentry_value_t os = make_linux_os(); + sentry_value_t os_dist = sentry_value_new_object(); + sentry_value_set_by_key( + os_dist, "name", sentry_value_new_string("steamos")); + sentry_value_set_by_key( + os_dist, "display_name", sentry_value_new_string("SteamOS")); + sentry_value_set_by_key(os_dist, "version", sentry_value_new_string("3.7")); + sentry_value_set_by_key( + os_dist, "build", sentry_value_new_string("20250101.1")); + set_os_distribution(os, os_dist, "6.1.0-test"); + TEST_CHECK_STRING_EQUAL(os_string(os, "name"), "SteamOS"); + TEST_CHECK_STRING_EQUAL(os_string(os, "version"), "3.7"); + TEST_CHECK_STRING_EQUAL(os_string(os, "build"), "20250101.1"); + TEST_CHECK_STRING_EQUAL(os_string(os, "kernel_version"), "6.1.0-test"); + TEST_CHECK( + sentry_value_is_null(sentry_value_get_by_key(os, "distribution_name"))); + sentry_value_decref(os_dist); + sentry_value_decref(os); + + // falls back to ID and the kernel version, and drops the kernel build + os = make_linux_os(); + os_dist = sentry_value_new_object(); + sentry_value_set_by_key( + os_dist, "name", sentry_value_new_string("bazzite")); + set_os_distribution(os, os_dist, "6.1.0-test"); + TEST_CHECK_STRING_EQUAL(os_string(os, "name"), "bazzite"); + TEST_CHECK_STRING_EQUAL(os_string(os, "version"), "6.1.0"); + TEST_CHECK(sentry_value_is_null(sentry_value_get_by_key(os, "build"))); + TEST_CHECK_STRING_EQUAL(os_string(os, "kernel_version"), "6.1.0-test"); + sentry_value_decref(os_dist); + sentry_value_decref(os); + + os = make_linux_os(); + os_dist = sentry_value_new_object(); + sentry_value_set_by_key(os_dist, "name", sentry_value_new_string("ubuntu")); + sentry_value_set_by_key( + os_dist, "display_name", sentry_value_new_string("Ubuntu")); + sentry_value_set_by_key( + os_dist, "version", sentry_value_new_string("24.04")); + set_os_distribution(os, os_dist, "6.1.0-test"); + TEST_CHECK_STRING_EQUAL(os_string(os, "name"), "Linux"); + TEST_CHECK_STRING_EQUAL(os_string(os, "version"), "6.1.0"); + TEST_CHECK_STRING_EQUAL(os_string(os, "build"), "test"); + TEST_CHECK_STRING_EQUAL(os_string(os, "distribution_name"), "ubuntu"); + TEST_CHECK_STRING_EQUAL(os_string(os, "distribution_version"), "24.04"); + TEST_CHECK( + sentry_value_is_null(sentry_value_get_by_key(os, "kernel_version"))); + sentry_value_decref(os_dist); + sentry_value_decref(os); +#endif // !defined(SENTRY_PLATFORM_LINUX) || defined(SENTRY_PLATFORM_ANDROID) +} + #ifdef SENTRY_PLATFORM_WINDOWS extern BOOL(WINAPI *g_kernel32_SetThreadStackGuarantee)(PULONG); extern void(WINAPI *g_kernel32_GetCurrentThreadStackLimits)( @@ -372,3 +447,46 @@ SENTRY_TEST(stack_guarantee_auto_init) g_kernel32_GetCurrentThreadStackLimits = NULL; #endif } + +SENTRY_TEST(sigaltstack) +{ +#if !defined(SENTRY_PLATFORM_UNIX) || defined(SENTRY_PLATFORM_PS) + SKIP_TEST(); +#else + const size_t size = 64 * 1024; + stack_t old_stack; + TEST_ASSERT_INT_EQUAL(sigaltstack(NULL, &old_stack), 0); + stack_t disabled = { 0 }; + disabled.ss_size = size; + disabled.ss_flags = SS_DISABLE; + TEST_ASSERT_INT_EQUAL(sigaltstack(&disabled, NULL), 0); + + stack_t stack; + TEST_ASSERT_INT_EQUAL(sentry__setup_sigaltstack(&stack, size, "test"), 0); + TEST_CHECK(!!stack.ss_sp); + + stack_t current; + TEST_ASSERT_INT_EQUAL(sigaltstack(NULL, ¤t), 0); + TEST_CHECK(current.ss_sp == stack.ss_sp); + TEST_CHECK_INT_EQUAL(current.ss_size, size); + TEST_CHECK_INT_EQUAL(current.ss_flags, 0); + + stack_t other; + TEST_ASSERT_INT_EQUAL( + sentry__setup_sigaltstack(&other, size * 2, "test"), 0); + TEST_CHECK(!other.ss_sp); + sentry__teardown_sigaltstack(&other); + TEST_ASSERT_INT_EQUAL(sigaltstack(NULL, ¤t), 0); + TEST_CHECK(current.ss_sp == stack.ss_sp); + TEST_CHECK_INT_EQUAL(current.ss_size, size); + TEST_CHECK_INT_EQUAL(current.ss_flags, 0); + + sentry__teardown_sigaltstack(&stack); + TEST_CHECK(!stack.ss_sp); + TEST_ASSERT_INT_EQUAL(sigaltstack(NULL, ¤t), 0); + TEST_CHECK_INT_EQUAL(current.ss_flags, SS_DISABLE); + if (!(old_stack.ss_flags & SS_DISABLE)) { + TEST_ASSERT_INT_EQUAL(sigaltstack(&old_stack, NULL), 0); + } +#endif +} diff --git a/tests/unit/test_retry.c b/tests/unit/test_retry.c index f5a6e8155f..3804e777a9 100644 --- a/tests/unit/test_retry.c +++ b/tests/unit/test_retry.c @@ -672,3 +672,29 @@ SENTRY_TEST(retry_consent) sentry__retry_free(retry); sentry_close(); } + +SENTRY_TEST(transport_dump_failed) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_dsn(options, "https://foo@sentry.invalid/42"); + sentry_transport_t *transport + = sentry__http_transport_new(NULL, test_http_send_fails); + TEST_ASSERT(!!transport); + sentry_options_set_transport(options, transport); + sentry_init(options); + sentry__http_transport_set_dump_failed(transport, true); + + sentry_path_t *run_path = sentry__path_clone(options->run->run_path); + TEST_ASSERT(!!run_path); + TEST_CHECK_INT_EQUAL(count_envelope_files(run_path), 0); + + sentry_capture_event( + sentry_value_new_message_event(SENTRY_LEVEL_INFO, NULL, "test")); + sentry_flush(5000); + + TEST_CHECK_INT_EQUAL(count_envelope_files(run_path), 1); + + sentry_close(); + sentry__path_remove_all(run_path); + sentry__path_free(run_path); +} diff --git a/tests/unit/test_scope.c b/tests/unit/test_scope.c index fbc46edb81..b8f4dff15f 100644 --- a/tests/unit/test_scope.c +++ b/tests/unit/test_scope.c @@ -14,6 +14,8 @@ TEST_CHECK(memcmp(&(Actual), &(Expected), sizeof(sentry_uuid_t)) == 0) typedef sentry_value_t (*scope_value_getter_t)(const sentry_scope_t *scope); +typedef void (*scope_value_setter_t)( + sentry_scope_t *scope, const char *key, const char *value); static sentry_value_t scope_value_get_by_key( @@ -35,6 +37,123 @@ scope_value_get_length(scope_value_getter_t get, const sentry_scope_t *scope) return length; } +SENTRY_TEST(scope_write_nested) +{ + sentry_scope_t *scope = sentry_scope_new(); + TEST_ASSERT(!!scope); + + TEST_ASSERT(sentry_scope_begin_write(scope) == 0); + sentry_scope_set_tag(scope, "first", "value"); + + TEST_ASSERT(sentry_scope_begin_write(scope) == 0); + sentry_scope_set_tag(scope, "second", "value"); + TEST_ASSERT(sentry_scope_begin_read(scope) == 0); + TEST_CHECK(scope_value_get_length(sentry__scope_load_tags, scope) == 2); + sentry_scope_end_read(scope); + sentry_scope_end_write(scope); + + sentry_scope_set_environment(scope, "production"); + sentry_value_t environment = sentry__scope_ref_environment(scope); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(environment), "production"); + sentry_value_decref(environment); + sentry_scope_end_write(scope); + + TEST_CHECK(scope_value_get_length(sentry__scope_load_tags, scope) == 2); + sentry_scope_free(scope); +} + +typedef struct { + sentry_scope_t *scope; + sentry_waitable_flag_t started; + sentry_waitable_flag_t finished; + sentry_value_t environment; + sentry_value_t tag; + int result; + sentry_options_t *options; +} scope_access_thread_t; + +SENTRY_THREAD_FN +read_scope_batch(void *data) +{ + scope_access_thread_t *state = data; + sentry__waitable_flag_set(&state->started); + if (state->options) { + sentry_value_t event = sentry_value_new_event(); + sentry__scope_apply_to_event( + state->scope, state->options, event, SENTRY_SCOPE_NONE); + state->environment + = sentry_value_get_by_key_owned(event, "environment"); + state->tag = sentry_value_get_by_key_owned( + sentry_value_get_by_key(event, "tags"), "version"); + sentry_value_decref(event); + } else { + state->result = sentry_scope_begin_read(state->scope); + if (state->result == 0) { + state->environment = sentry__scope_ref_environment(state->scope); + state->tag = scope_value_get_by_key( + sentry__scope_load_tags, state->scope, "version"); + sentry_scope_end_read(state->scope); + } + } + sentry__waitable_flag_set(&state->finished); + return 0; +} + +SENTRY_TEST(scope_write_exclusive) +{ + sentry_scope_t *scope = sentry_scope_new(); + TEST_ASSERT(!!scope); + + scope_access_thread_t state = { .scope = scope }; + sentry__waitable_flag_init(&state.started); + sentry__waitable_flag_init(&state.finished); + + TEST_ASSERT(sentry_scope_begin_write(scope) == 0); + sentry_scope_set_environment(scope, "new"); + sentry_threadid_t thread; + sentry__thread_init(&thread); + TEST_ASSERT(!sentry__thread_spawn(&thread, read_scope_batch, &state)); + TEST_ASSERT(sentry__waitable_flag_wait(&state.started, 1000)); + TEST_CHECK(!sentry__waitable_flag_wait(&state.finished, 10)); + + sentry_scope_set_tag(scope, "version", "new"); + sentry_scope_end_write(scope); + TEST_CHECK(sentry__waitable_flag_wait(&state.finished, 1000)); + sentry__thread_join(thread); + sentry__thread_free(&thread); + TEST_CHECK_INT_EQUAL(state.result, 0); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(state.environment), "new"); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(state.tag), "new"); + sentry_value_decref(state.environment); + sentry_value_decref(state.tag); + + sentry_scope_clear(scope); + sentry_scope_set_tag(scope, "version", "old"); + sentry_scope_t *parent = sentry_scope_acquire(); + TEST_ASSERT(sentry_scope_begin_write(parent) == 0); + sentry_scope_set_environment(parent, "old"); + scope_access_thread_t apply + = { .scope = scope, .options = sentry_options_new() }; + sentry__waitable_flag_init(&apply.started); + sentry__waitable_flag_init(&apply.finished); + TEST_ASSERT(!sentry__thread_spawn(&thread, read_scope_batch, &apply)); + TEST_ASSERT(sentry__waitable_flag_wait(&apply.started, 1000)); + TEST_CHECK(!sentry__waitable_flag_wait(&apply.finished, 10)); + sentry_scope_set_tag(scope, "version", "new"); + sentry_scope_set_environment(parent, "new"); + sentry_scope_end_write(parent); + TEST_CHECK(sentry__waitable_flag_wait(&apply.finished, 1000)); + sentry__thread_join(thread); + sentry__thread_free(&thread); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(apply.environment), "new"); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(apply.tag), "new"); + sentry_value_decref(apply.environment); + sentry_value_decref(apply.tag); + sentry_options_free(apply.options); + sentry_scope_release(parent); + sentry_scope_free(scope); +} + SENTRY_TEST(scope_contexts) { SENTRY_TEST_OPTIONS_NEW(options); @@ -104,6 +223,13 @@ SENTRY_TEST(scope_contexts) TEST_CHECK(sentry_value_is_null(removed)); sentry_value_decref(removed); + sentry_value_t contexts = sentry__scope_load_contexts(local_scope); + TEST_CHECK_JSON_VALUE( + sentry_value_get_by_key(contexts, "global"), "\"global\""); + TEST_CHECK_JSON_VALUE( + sentry_value_get_by_key(contexts, "scope"), "\"local\""); + sentry_value_decref(contexts); + // event: // {"all":"event","event":"event"} sentry_value_t event = sentry_value_new_object(); @@ -280,6 +406,26 @@ SENTRY_TEST(scope_propagation_context) // local scope applied first must not prevent the global scope // from adding the trace context afterwards sentry_scope_t *local_scope = sentry_local_scope_new(); + sentry_value_t trace = sentry__scope_load_trace_context(local_scope); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(trace, "trace_id")), + "aaaabbbbccccddddeeeeffff00001111"); + TEST_CHECK(!sentry__scope_is_trace_managed(local_scope)); + sentry__scope_update_dsc(local_scope, options); + sentry_value_t dsc = sentry__scope_load_dsc(local_scope); + TEST_CHECK( + sentry_value_as_double(sentry_value_get_by_key(dsc, "sample_rand")) + == sentry_value_as_double( + sentry_value_get_by_key(trace, "sample_rand"))); + sentry_value_decref(dsc); + sentry_value_decref(trace); + sentry_value_t propagation + = sentry__scope_load_propagation_context(local_scope); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key( + sentry_value_get_by_key(propagation, "trace"), "trace_id")), + "aaaabbbbccccddddeeeeffff00001111"); + sentry_value_decref(propagation); sentry_value_t event = sentry_value_new_object(); sentry__scope_apply_to_event( local_scope, options, event, SENTRY_SCOPE_NONE); @@ -287,6 +433,13 @@ SENTRY_TEST(scope_propagation_context) global_scope, options, event, SENTRY_SCOPE_NONE); TEST_CHECK_EVENT_TRACE_ID_EQUAL( event, "aaaabbbbccccddddeeeeffff00001111"); + + sentry__scope_regenerate_propagation_context(local_scope); + TEST_CHECK(sentry__scope_is_trace_managed(local_scope)); + propagation = sentry__scope_load_propagation_context(local_scope); + TEST_CHECK(sentry_value_is_null(sentry_value_get_by_key( + sentry_value_get_by_key(propagation, "trace"), "parent_span_id"))); + sentry_value_decref(propagation); sentry_scope_free(local_scope); sentry_value_decref(event); } @@ -314,6 +467,195 @@ SENTRY_TEST(scope_propagation_context) sentry_close(); } +SENTRY_TEST(scope_set_trace) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_init(options); + + sentry_value_t global_trace = sentry_value_new_null(); + SENTRY_WITH_SCOPE (global_scope) { + global_trace = sentry__scope_load_trace_context(global_scope); + } + + sentry_scope_t *local_scope = sentry_local_scope_new(); + TEST_CHECK(sentry__scope_is_trace_managed(local_scope)); + + sentry_scope_set_trace( + local_scope, "aaaabbbbccccddddeeeeffff00001111", "9c2a92b49b7c4d1e"); + TEST_CHECK(!sentry__scope_is_trace_managed(local_scope)); + + sentry_value_t trace = sentry__scope_load_trace_context(local_scope); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(trace, "trace_id")), + "aaaabbbbccccddddeeeeffff00001111"); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(sentry_value_get_by_key( + trace, "parent_span_id")), + "9c2a92b49b7c4d1e"); + sentry_value_t dsc = sentry__scope_load_dsc(local_scope); + TEST_CHECK( + sentry_value_as_double(sentry_value_get_by_key(dsc, "sample_rand")) + == sentry_value_as_double( + sentry_value_get_by_key(trace, "sample_rand"))); + sentry_value_decref(dsc); + sentry_value_decref(trace); + + // the global scope keeps its trace + SENTRY_WITH_SCOPE (global_scope) { + trace = sentry__scope_load_trace_context(global_scope); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(trace, "trace_id")), + sentry_value_as_string( + sentry_value_get_by_key(global_trace, "trace_id"))); + sentry_value_decref(trace); + } + sentry_value_decref(global_trace); + + sentry_scope_set_trace_n( + local_scope, "11112222333344445555666677778888xxxx", 32, NULL, 0); + trace = sentry__scope_load_trace_context(local_scope); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(trace, "trace_id")), + "11112222333344445555666677778888"); + TEST_CHECK( + sentry_value_is_null(sentry_value_get_by_key(trace, "parent_span_id"))); + sentry_value_decref(trace); + + sentry_scope_free(local_scope); + sentry_close(); +} + +static void +store_trace_header(sentry_envelope_t *envelope, void *data) +{ + sentry_value_t *trace = data; + sentry_value_decref(*trace); + *trace = sentry_value_incref(sentry_envelope_get_header(envelope, "trace")); + TEST_CHECK(sentry_value_is_null( + sentry_value_get_by_key(sentry_envelope_get_event(envelope), "dsc"))); + sentry_envelope_free(envelope); +} + +SENTRY_TEST(scope_capture_dsc) +{ + sentry_value_t trace = sentry_value_new_null(); + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_dsn(options, "https://foo@sentry.invalid/42"); + sentry_options_set_traces_sample_rate(options, 0.5); + sentry_transport_t *transport = sentry_transport_new(store_trace_header); + sentry_transport_set_state(transport, &trace); + sentry_options_set_transport(options, transport); + sentry_init(options); + + SENTRY_WITH_SCOPE_MUT (global_scope) { + sentry__scope_set_trace_context( + global_scope, "sample_rand", sentry_value_new_double(0.25)); + } + + sentry_scope_t *scope = sentry_scope_new(); + sentry_scope_set_trace( + scope, "aaaabbbbccccddddeeeeffff00001111", "9c2a92b49b7c4d1e"); + sentry__scope_set_trace_context( + scope, "sample_rand", sentry_value_new_double(0.75)); + + sentry_scope_capture_event(scope, sentry_value_new_event(), NULL); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(trace, "trace_id")), + "aaaabbbbccccddddeeeeffff00001111"); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(trace, "sampled")), + "false"); + + sentry_value_decref(trace); + trace = sentry_value_new_null(); + sentry_scope_capture_feedback( + scope, sentry_value_new_feedback("feedback", NULL, NULL, NULL), NULL); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(trace, "trace_id")), + "aaaabbbbccccddddeeeeffff00001111"); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(trace, "sampled")), + "false"); + + sentry_scope_free(scope); + sentry_close(); + sentry_value_decref(trace); +} + +SENTRY_TEST(scope_continue_trace) +{ + sentry_value_t trace = sentry_value_new_null(); + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_dsn(options, "https://foo@sentry.invalid/42"); + sentry_transport_t *transport = sentry_transport_new(store_trace_header); + sentry_transport_set_state(transport, &trace); + sentry_options_set_transport(options, transport); + sentry_init(options); + + sentry_scope_t *scope = sentry_scope_new(); + sentry_scope_continue_trace(scope, + "aaaabbbbccccddddeeeeffff00001111-9c2a92b49b7c4d1e-1", + "sentry-environment=upstream"); + + // the global scope keeps its trace + SENTRY_WITH_SCOPE (global_scope) { + sentry_value_t global_trace + = sentry__scope_load_trace_context(global_scope); + TEST_CHECK(strcmp(sentry_value_as_string(sentry_value_get_by_key( + global_trace, "trace_id")), + "aaaabbbbccccddddeeeeffff00001111") + != 0); + sentry_value_decref(global_trace); + } + + sentry_scope_capture_event(scope, sentry_value_new_event(), NULL); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(trace, "trace_id")), + "aaaabbbbccccddddeeeeffff00001111"); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(trace, "environment")), + "upstream"); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(trace, "sampled")), + "true"); + + sentry_scope_free(scope); + sentry_close(); + sentry_value_decref(trace); +} + +static void +collect_sentry_trace(const char *key, const char *value, void *userdata) +{ + if (strcmp(key, "sentry-trace") == 0) { + snprintf((char *)userdata, 64, "%s", value); + } +} + +SENTRY_TEST(scope_iter_trace_propagation_headers) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_init(options); + + // a local scope without a trace falls back to the global one + sentry_scope_t *scope = sentry_scope_new(); + char global_trace[64] = { 0 }; + char local_trace[64] = { 0 }; + sentry_iter_trace_propagation_headers(collect_sentry_trace, global_trace); + sentry_scope_iter_trace_propagation_headers( + scope, collect_sentry_trace, local_trace); + TEST_CHECK_STRING_EQUAL(local_trace, global_trace); + + sentry_scope_set_trace( + scope, "aaaabbbbccccddddeeeeffff00001111", "9c2a92b49b7c4d1e"); + sentry_scope_iter_trace_propagation_headers( + scope, collect_sentry_trace, local_trace); + TEST_CHECK( + strncmp(local_trace, "aaaabbbbccccddddeeeeffff00001111-", 33) == 0); + + sentry_scope_free(scope); + sentry_close(); +} + SENTRY_TEST(scope_extra) { SENTRY_TEST_OPTIONS_NEW(options); @@ -383,6 +725,13 @@ SENTRY_TEST(scope_extra) TEST_CHECK(sentry_value_is_null(removed)); sentry_value_decref(removed); + sentry_value_t extra = sentry__scope_load_extra(local_scope); + TEST_CHECK_JSON_VALUE( + sentry_value_get_by_key(extra, "global"), "\"global\""); + TEST_CHECK_JSON_VALUE( + sentry_value_get_by_key(extra, "scope"), "\"local\""); + sentry_value_decref(extra); + // event: // {"all":"event","event":"event"} sentry_value_t event = sentry_value_new_object(); @@ -472,6 +821,10 @@ SENTRY_TEST(scope_fingerprint) // local: // ["local1", "local2"] sentry_scope_t *local_scope = sentry_local_scope_new(); + sentry_value_t local_fingerprint + = sentry__scope_ref_fingerprint(local_scope); + TEST_CHECK_JSON_VALUE(local_fingerprint, "[\"global1\",\"global2\"]"); + sentry_value_decref(local_fingerprint); sentry_scope_set_fingerprint(local_scope, "local1", "local2", NULL); // event: @@ -498,8 +851,7 @@ SENTRY_TEST(scope_fingerprint) TEST_CHECK_JSON_VALUE(sentry_value_get_by_key(event, "fingerprint"), "[\"event1\",\"event2\"]"); - sentry_value_t local_fingerprint - = sentry__scope_ref_fingerprint(local_scope); + local_fingerprint = sentry__scope_ref_fingerprint(local_scope); sentry_scope_remove_fingerprint(local_scope); TEST_CHECK_INT_EQUAL(sentry_value_get_length(local_fingerprint), 2); TEST_CHECK_STRING_EQUAL( @@ -508,6 +860,10 @@ SENTRY_TEST(scope_fingerprint) "local1"); sentry_value_decref(local_fingerprint); + local_fingerprint = sentry__scope_ref_fingerprint(local_scope); + TEST_CHECK_JSON_VALUE(local_fingerprint, "[\"global1\",\"global2\"]"); + sentry_value_decref(local_fingerprint); + sentry_scope_free(local_scope); sentry_value_decref(event); } @@ -631,9 +987,17 @@ SENTRY_TEST(scope_tags) // local: // {"all":"scope","scope":"scope","local":"local"} sentry_scope_t *local_scope = sentry_local_scope_new(); + sentry_value_t local_tags = sentry__scope_load_tags(local_scope); + sentry_value_set_by_key( + local_tags, "scope", sentry_value_new_string("detached")); + sentry_value_decref(local_tags); + local_tags = sentry__scope_load_tags(local_scope); + TEST_CHECK_JSON_VALUE( + sentry_value_get_by_key(local_tags, "scope"), "\"global\""); + sentry_value_decref(local_tags); sentry_scope_set_tag(local_scope, "all", "local"); sentry_scope_set_tag(local_scope, "scope", "overwritten"); - sentry_value_t local_tags = sentry_value_new_object(); + local_tags = sentry_value_new_object(); sentry_value_set_by_key( local_tags, "local", sentry_value_new_string("local")); sentry_value_set_by_key( @@ -652,6 +1016,13 @@ SENTRY_TEST(scope_tags) TEST_CHECK(sentry_value_is_null(removed)); sentry_value_decref(removed); + local_tags = sentry__scope_load_tags(local_scope); + TEST_CHECK_JSON_VALUE( + sentry_value_get_by_key(local_tags, "global"), "\"global\""); + TEST_CHECK_JSON_VALUE( + sentry_value_get_by_key(local_tags, "scope"), "\"local\""); + sentry_value_decref(local_tags); + // event: // {"all":"event","event":"event"} sentry_value_t event = sentry_value_new_object(); @@ -718,6 +1089,10 @@ SENTRY_TEST(scope_user) SENTRY_WITH_SCOPE (global_scope) { // local: {"id":"2","username":"local","email":"@local"} sentry_scope_t *local_scope = sentry_local_scope_new(); + sentry_value_t local_user = sentry__scope_ref_user(local_scope); + TEST_CHECK_JSON_VALUE(local_user, + "{\"id\":\"1\",\"username\":\"global\",\"email\":\"@global\"}"); + sentry_value_decref(local_user); sentry_scope_set_user( local_scope, sentry_value_new_user("2", "local", "@local", NULL)); @@ -738,13 +1113,18 @@ SENTRY_TEST(scope_user) TEST_CHECK_JSON_VALUE(sentry_value_get_by_key(event, "user"), "{\"id\":\"3\",\"username\":\"event\"}"); - sentry_value_t local_user = sentry__scope_ref_user(local_scope); + local_user = sentry__scope_ref_user(local_scope); sentry_scope_set_user(local_scope, sentry_value_new_null()); TEST_CHECK_STRING_EQUAL( sentry_value_as_string(sentry_value_get_by_key(local_user, "id")), "2"); sentry_value_decref(local_user); + local_user = sentry__scope_ref_user(local_scope); + TEST_CHECK_JSON_VALUE(local_user, + "{\"id\":\"1\",\"username\":\"global\",\"email\":\"@global\"}"); + sentry_value_decref(local_user); + sentry_scope_free(local_scope); sentry_value_decref(event); } @@ -879,7 +1259,11 @@ SENTRY_TEST(scope_level) SENTRY_WITH_SCOPE (global_scope) { // local: fatal sentry_scope_t *local_scope = sentry_local_scope_new(); + TEST_CHECK_INT_EQUAL( + sentry__scope_get_level(local_scope), SENTRY_LEVEL_WARNING); sentry_scope_set_level(local_scope, SENTRY_LEVEL_FATAL); + TEST_CHECK_INT_EQUAL( + sentry__scope_get_level(local_scope), SENTRY_LEVEL_FATAL); // event: debug sentry_value_t event = sentry_value_new_object(); @@ -896,6 +1280,25 @@ SENTRY_TEST(scope_level) local_scope, options, event, SENTRY_SCOPE_NONE); TEST_CHECK_LEVEL_EQUAL(event, "debug"); + sentry_scope_set_level(local_scope, SENTRY_LEVEL_ERROR); + TEST_CHECK_INT_EQUAL( + sentry__scope_get_level(local_scope), SENTRY_LEVEL_ERROR); + sentry_value_remove_by_key(event, "level"); + sentry__scope_apply_to_event( + local_scope, options, event, SENTRY_SCOPE_NONE); + TEST_CHECK_LEVEL_EQUAL(event, "error"); + + sentry_scope_clear(local_scope); + TEST_CHECK_INT_EQUAL( + sentry__scope_get_level(local_scope), SENTRY_LEVEL_WARNING); + sentry_value_remove_by_key(event, "level"); + sentry__scope_apply_to_event( + local_scope, options, event, SENTRY_SCOPE_NONE); + TEST_CHECK_LEVEL_EQUAL(event, "warning"); + sentry_set_level(SENTRY_LEVEL_DEBUG); + TEST_CHECK_INT_EQUAL( + sentry__scope_get_level(local_scope), SENTRY_LEVEL_DEBUG); + sentry_scope_free(local_scope); sentry_value_decref(event); } @@ -920,7 +1323,7 @@ SENTRY_TEST(scope_breadcrumbs) sentry_options_set_max_breadcrumbs(options, 5); sentry_init(options); - // global: ["global1", "global4"] + // isolation: ["global1", "global4"] sentry_add_breadcrumb(breadcrumb_ts("global1", 1)); sentry_add_breadcrumb(breadcrumb_ts("global4", 4)); @@ -930,13 +1333,13 @@ SENTRY_TEST(scope_breadcrumbs) sentry_value_get_by_index(breadcrumbs, index), "message")), \ message) - SENTRY_WITH_SCOPE (global_scope) { + SENTRY_WITH_SCOPE (isolation_scope) { // event: null sentry_value_t event = sentry_value_new_object(); - // event <- global: ["global1", "global4"] + // event <- isolation: ["global1", "global4"] sentry__scope_apply_to_event( - global_scope, options, event, SENTRY_SCOPE_BREADCRUMBS); + isolation_scope, options, event, SENTRY_SCOPE_BREADCRUMBS); sentry_value_t result = sentry_value_get_by_key(event, "breadcrumbs"); TEST_CHECK(sentry_value_get_type(result) == SENTRY_VALUE_TYPE_LIST); @@ -947,7 +1350,7 @@ SENTRY_TEST(scope_breadcrumbs) sentry_value_decref(event); } - SENTRY_WITH_SCOPE (global_scope) { + SENTRY_WITH_SCOPE (isolation_scope) { // event: ["event3", "event5"] sentry_value_t event = sentry_value_new_object(); { @@ -957,9 +1360,9 @@ SENTRY_TEST(scope_breadcrumbs) sentry_value_set_by_key(event, "breadcrumbs", breadcrumbs); } - // event <- global: ["global1", "event3", "global4", "event5"] + // event <- isolation: ["global1", "event3", "global4", "event5"] sentry__scope_apply_to_event( - global_scope, options, event, SENTRY_SCOPE_BREADCRUMBS); + isolation_scope, options, event, SENTRY_SCOPE_BREADCRUMBS); sentry_value_t result = sentry_value_get_by_key(event, "breadcrumbs"); TEST_CHECK(sentry_value_get_type(result) == SENTRY_VALUE_TYPE_LIST); @@ -972,12 +1375,22 @@ SENTRY_TEST(scope_breadcrumbs) sentry_value_decref(event); } - SENTRY_WITH_SCOPE (global_scope) { + SENTRY_WITH_SCOPE (isolation_scope) { // local: ["local2", "local6"] sentry_scope_t *local_scope = sentry_local_scope_new(); + TEST_CHECK_PTR_EQUAL(local_scope->parent, isolation_scope); sentry_scope_add_breadcrumb(local_scope, breadcrumb_ts("local2", 2)); sentry_scope_add_breadcrumb(local_scope, breadcrumb_ts("local6", 6)); + sentry_value_t breadcrumbs + = sentry__scope_breadcrumbs_to_list(local_scope); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(breadcrumbs), 4); + TEST_CHECK_MESSAGE_EQUAL(breadcrumbs, 0, "global1"); + TEST_CHECK_MESSAGE_EQUAL(breadcrumbs, 1, "local2"); + TEST_CHECK_MESSAGE_EQUAL(breadcrumbs, 2, "global4"); + TEST_CHECK_MESSAGE_EQUAL(breadcrumbs, 3, "local6"); + sentry_value_decref(breadcrumbs); + // event: ["event3", "event5"] sentry_value_t event = sentry_value_new_object(); { @@ -987,21 +1400,25 @@ SENTRY_TEST(scope_breadcrumbs) sentry_value_set_by_key(event, "breadcrumbs", breadcrumbs); } - // event <- local: ["local2", "event3", "event5", "local6"] - sentry__scope_apply_to_event( - local_scope, options, event, SENTRY_SCOPE_BREADCRUMBS); + // event <- isolation: ["global1", "event3", "global4", "event5"] + sentry_value_t isolation_event = sentry__value_clone(event); + sentry__scope_apply_to_event(isolation_scope, options, isolation_event, + SENTRY_SCOPE_BREADCRUMBS); - sentry_value_t result = sentry_value_get_by_key(event, "breadcrumbs"); + sentry_value_t result + = sentry_value_get_by_key(isolation_event, "breadcrumbs"); TEST_CHECK(sentry_value_get_type(result) == SENTRY_VALUE_TYPE_LIST); TEST_CHECK_INT_EQUAL(sentry_value_get_length(result), 4); - TEST_CHECK_MESSAGE_EQUAL(result, 0, "local2"); + TEST_CHECK_MESSAGE_EQUAL(result, 0, "global1"); TEST_CHECK_MESSAGE_EQUAL(result, 1, "event3"); - TEST_CHECK_MESSAGE_EQUAL(result, 2, "event5"); - TEST_CHECK_MESSAGE_EQUAL(result, 3, "local6"); + TEST_CHECK_MESSAGE_EQUAL(result, 2, "global4"); + TEST_CHECK_MESSAGE_EQUAL(result, 3, "event5"); + sentry_value_decref(isolation_event); - // event <- global: ["local2", "event3", "global4", "event5", "local6"] + // event <- local and isolation: + // ["local2", "event3", "global4", "event5", "local6"] sentry__scope_apply_to_event( - global_scope, options, event, SENTRY_SCOPE_BREADCRUMBS); + local_scope, options, event, SENTRY_SCOPE_BREADCRUMBS); result = sentry_value_get_by_key(event, "breadcrumbs"); TEST_CHECK(sentry_value_get_type(result) == SENTRY_VALUE_TYPE_LIST); @@ -1050,6 +1467,14 @@ SENTRY_TEST(before_breadcrumb_discard) sentry_value_decref(event); } + sentry_scope_t *local_scope = sentry_local_scope_new(); + sentry_scope_add_breadcrumb( + local_scope, sentry_value_new_breadcrumb(NULL, "discarded")); + sentry_value_t breadcrumbs = sentry__scope_breadcrumbs_to_list(local_scope); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(breadcrumbs), 0); + sentry_value_decref(breadcrumbs); + sentry_scope_free(local_scope); + sentry_close(); } @@ -1362,6 +1787,10 @@ SENTRY_TEST(scope_local_attributes) sentry_value_t local_attributes = sentry__scope_load_attributes(local_scope); + TEST_CHECK_JSON_VALUE( + sentry_value_get_by_key(local_attributes, "global"), + "{\"type\":\"string\",\"value\":\"global\"}"); + // Verify local attributes are set TEST_CHECK_STRING_EQUAL( sentry_value_as_string(sentry_value_get_by_key( @@ -1515,6 +1944,20 @@ SENTRY_TEST(scope_transaction) TEST_CHECK_STRING_EQUAL( sentry_value_as_string(transaction), "my-transaction"); sentry_value_decref(transaction); + + sentry_scope_t *local_scope = sentry_scope_new(); + for (size_t i = 0; i < 3; i++) { + if (i == 1) { + sentry_scope_set_transaction(local_scope, "local-transaction"); + } else if (i == 2) { + sentry_scope_clear(local_scope); + } + transaction = sentry__scope_ref_transaction(local_scope); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(transaction), + i == 1 ? "local-transaction" : "my-transaction"); + sentry_value_decref(transaction); + } + sentry_scope_free(local_scope); } sentry_close(); @@ -1698,20 +2141,20 @@ observe_add_breadcrumb(void *data, sentry_value_t breadcrumb) } static void -observe_set_tag(void *data, const char *key, const char *value) +observe_set_tag(void *data, const char *key, sentry_value_t value) { test_observer_data_t *d = (test_observer_data_t *)data; if (sentry_value_is_null(d->tags)) { d->tags = sentry_value_new_object(); } - sentry_value_set_by_key(d->tags, key, sentry_value_new_string(value)); + sentry_value_set_by_key(d->tags, key, sentry_value_incref(value)); d->was_called = true; d->set_tag_count++; } static void observe_set_tag_remove_self_and_add( - void *data, const char *key, const char *value) + void *data, const char *key, sentry_value_t value) { reentrant_observer_data_t *d = (reentrant_observer_data_t *)data; observe_set_tag(d->self_data, key, value); @@ -1725,7 +2168,7 @@ observe_set_tag_remove_self_and_add( } static void -observe_set_tag_remove_self(void *data, const char *key, const char *value) +observe_set_tag_remove_self(void *data, const char *key, sentry_value_t value) { reentrant_observer_data_t *d = (reentrant_observer_data_t *)data; observe_set_tag(d->self_data, key, value); @@ -1735,7 +2178,7 @@ observe_set_tag_remove_self(void *data, const char *key, const char *value) } static void -observe_set_tag_clear_scope(void *data, const char *key, const char *value) +observe_set_tag_clear_scope(void *data, const char *key, sentry_value_t value) { clear_observer_data_t *d = (clear_observer_data_t *)data; observe_set_tag(d->data, key, value); @@ -1744,7 +2187,7 @@ observe_set_tag_clear_scope(void *data, const char *key, const char *value) static void observe_set_tag_mutate_nested_scope( - void *data, const char *UNUSED(key), const char *UNUSED(value)) + void *data, const char *UNUSED(key), sentry_value_t UNUSED(value)) { deferred_flush_observer_data_t *d = (deferred_flush_observer_data_t *)data; d->was_called = true; @@ -2063,6 +2506,23 @@ SENTRY_TEST(scope_observer_deferred_flush) TEST_CHECK_INT_EQUAL(observer_data.nested_flush_count, 0); TEST_CHECK_INT_EQUAL(observer_data.total_flush_count, 1); + observer_data.total_flush_count = 0; + observer_data.nested_flush_count = 0; + sentry_scope_t *scope = sentry_scope_acquire(); + TEST_ASSERT(sentry_scope_begin_write(scope) == 0); + sentry_scope_set_tag(scope, "batched", "value"); + TEST_CHECK_INT_EQUAL(observer_data.nested_flush_count, 0); + TEST_CHECK_INT_EQUAL(observer_data.total_flush_count, 0); + TEST_ASSERT(sentry_scope_begin_read(scope) == 0); + sentry_scope_end_read(scope); + TEST_CHECK_INT_EQUAL(observer_data.total_flush_count, 0); + sentry_scope_end_write(scope); + TEST_CHECK_INT_EQUAL(observer_data.total_flush_count, 1); + TEST_ASSERT(sentry_scope_begin_read(scope) == 0); + sentry_scope_end_read(scope); + TEST_CHECK_INT_EQUAL(observer_data.total_flush_count, 1); + sentry_scope_release(scope); + sentry_close(); } @@ -2249,6 +2709,7 @@ SENTRY_TEST(scope_observer_user) TEST_CHECK(d.was_called); TEST_CHECK_JSON_VALUE(d.user, "{}"); + sentry_value_decref(d.user); sentry_close(); } @@ -2406,10 +2867,10 @@ SENTRY_TEST(scope_tags_flush) } TEST_CHECK_INT_EQUAL(flush_data.total_flush_count, 3); - sentry_scope_t *scope = sentry__scope_getref(); + sentry_scope_t *scope = sentry_scope_acquire(); sentry_scope_set_tag(scope, "direct", "value"); TEST_CHECK_INT_EQUAL(flush_data.total_flush_count, 3); - sentry__scope_finish_mut(scope); + sentry_scope_release(scope); TEST_CHECK_INT_EQUAL(flush_data.total_flush_count, 4); sentry_value_decref(observer_data.tags); @@ -2810,6 +3271,10 @@ SENTRY_TEST(scope_clone_preserves_data) SENTRY_TEST(scope_attachments) { + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_add_attachment(options, "configured.txt"); + TEST_ASSERT_INT_EQUAL(sentry_init(options), 0); + sentry_scope_t *scope = sentry_scope_new(); sentry_uuid_t first_id = sentry_scope_add_attachment( scope, sentry_attachment_from_bytes("first", 5, "first.txt")); @@ -2819,30 +3284,33 @@ SENTRY_TEST(scope_attachments) TEST_CHECK(!sentry_uuid_is_nil(&second_id)); sentry_value_t snapshot = sentry__scope_load_attachments(scope); - TEST_CHECK_INT_EQUAL(sentry_value_get_length(snapshot), 2); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(snapshot), 3); TEST_CHECK_STRING_EQUAL( sentry__attachment_get_filename(sentry_value_get_by_index(snapshot, 0)), "first.txt"); TEST_CHECK_STRING_EQUAL( sentry__attachment_get_filename(sentry_value_get_by_index(snapshot, 1)), "second.txt"); + TEST_CHECK_STRING_EQUAL( + sentry__attachment_get_filename(sentry_value_get_by_index(snapshot, 2)), + "configured.txt"); sentry_uuid_t third_id = sentry_scope_add_attachment( scope, sentry_attachment_from_bytes("third", 5, "third.txt")); TEST_CHECK(!sentry_uuid_is_nil(&third_id)); sentry_value_t current = sentry__scope_load_attachments(scope); - TEST_CHECK_INT_EQUAL(sentry_value_get_length(current), 3); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(current), 4); TEST_CHECK_STRING_EQUAL( sentry__attachment_get_filename(sentry_value_get_by_index(current, 2)), "third.txt"); sentry_value_decref(current); - TEST_CHECK_INT_EQUAL(sentry_value_get_length(snapshot), 2); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(snapshot), 3); sentry_scope_remove_attachment(scope, first_id); current = sentry__scope_load_attachments(scope); - TEST_CHECK_INT_EQUAL(sentry_value_get_length(current), 2); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(current), 3); TEST_CHECK_STRING_EQUAL( sentry__attachment_get_filename(sentry_value_get_by_index(current, 0)), "second.txt"); @@ -2850,22 +3318,26 @@ SENTRY_TEST(scope_attachments) sentry__attachment_get_filename(sentry_value_get_by_index(current, 1)), "third.txt"); sentry_value_decref(current); - TEST_CHECK_INT_EQUAL(sentry_value_get_length(snapshot), 2); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(snapshot), 3); TEST_CHECK_STRING_EQUAL( sentry__attachment_get_filename(sentry_value_get_by_index(snapshot, 0)), "first.txt"); sentry_scope_clear(scope); current = sentry__scope_load_attachments(scope); - TEST_CHECK_INT_EQUAL(sentry_value_get_length(current), 0); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(current), 1); + TEST_CHECK_STRING_EQUAL( + sentry__attachment_get_filename(sentry_value_get_by_index(current, 0)), + "configured.txt"); sentry_value_decref(current); - TEST_CHECK_INT_EQUAL(sentry_value_get_length(snapshot), 2); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(snapshot), 3); TEST_CHECK_STRING_EQUAL( sentry__attachment_get_filename(sentry_value_get_by_index(snapshot, 1)), "second.txt"); sentry_value_decref(snapshot); sentry_scope_free(scope); + sentry_close(); } SENTRY_TEST(scope_clone_shares_span) @@ -2997,7 +3469,10 @@ SENTRY_TEST(scope_clear) // Everything is reset to the state of a fresh scope. TEST_CHECK(scope_value_get_length(sentry__scope_load_tags, scope) == 0); TEST_CHECK(scope_value_get_length(sentry__scope_load_extra, scope) == 0); - TEST_CHECK(scope_value_get_length(sentry__scope_load_contexts, scope) == 0); + sentry_value_t contexts = sentry__scope_load_contexts(scope); + TEST_CHECK(sentry_value_is_null(sentry_value_get_by_key(contexts, "ctx"))); + TEST_CHECK(!sentry_value_is_null(sentry_value_get_by_key(contexts, "os"))); + sentry_value_decref(contexts); TEST_CHECK( scope_value_get_length(sentry__scope_load_attributes, scope) == 0); scope_user = sentry__scope_ref_user(scope); @@ -3376,10 +3851,25 @@ SENTRY_TEST(scope_bind_span_or_transaction_not_both) TEST_ASSERT(!!span); // Only one binding can be active at a time. + sentry_scope_t *parent = sentry_scope_acquire(); + sentry_scope_set_transaction_object(parent, tx); sentry_scope_t *scope = sentry_scope_new(); + sentry_transaction_t *inherited + = sentry__scope_ref_transaction_object(scope); + TEST_CHECK_PTR_EQUAL(inherited, tx); + sentry__transaction_decref(inherited); + sentry_value_t value = sentry__scope_load_span_or_transaction(scope); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(value, "span_id")), + sentry_value_as_string(sentry_value_get_by_key(tx->inner, "span_id"))); + sentry_value_decref(value); + sentry_scope_set_span(parent, span); + sentry_span_t *bound_span = sentry__scope_ref_span(scope); + TEST_CHECK_PTR_EQUAL(bound_span, span); + sentry__span_decref(bound_span); sentry_scope_set_span(scope, span); sentry_scope_set_transaction_object(scope, tx); - sentry_span_t *bound_span = sentry__scope_ref_span(scope); + bound_span = sentry__scope_ref_span(scope); sentry_transaction_t *bound_tx = sentry__scope_ref_transaction_object(scope); TEST_CHECK(bound_span == NULL); @@ -3387,11 +3877,18 @@ SENTRY_TEST(scope_bind_span_or_transaction_not_both) sentry__span_decref(bound_span); sentry__transaction_decref(bound_tx); + sentry_scope_set_transaction_object(parent, tx); sentry_scope_set_span(scope, span); bound_tx = sentry__scope_ref_transaction_object(scope); bound_span = sentry__scope_ref_span(scope); TEST_CHECK(bound_tx == NULL); TEST_CHECK_PTR_EQUAL(bound_span, span); + value = sentry__scope_load_span_or_transaction(scope); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(value, "span_id")), + sentry_value_as_string( + sentry_value_get_by_key(span->inner, "span_id"))); + sentry_value_decref(value); sentry__transaction_decref(bound_tx); sentry__span_decref(bound_span); @@ -3400,11 +3897,13 @@ SENTRY_TEST(scope_bind_span_or_transaction_not_both) bound_span = sentry__scope_ref_span(scope); bound_tx = sentry__scope_ref_transaction_object(scope); TEST_CHECK(bound_span == NULL); - TEST_CHECK(bound_tx == NULL); + TEST_CHECK_PTR_EQUAL(bound_tx, tx); + TEST_CHECK(!sentry__scope_remove_transaction_object(scope, tx)); sentry__span_decref(bound_span); sentry__transaction_decref(bound_tx); sentry_scope_free(scope); + sentry_scope_release(parent); sentry_span_finish(span); sentry_transaction_finish(tx); @@ -3490,3 +3989,903 @@ SENTRY_TEST(scope_clone_keeps_bound_span) sentry_close(); } + +SENTRY_TEST(scope_read_shared) +{ + sentry_scope_t *scope = sentry_scope_new(); + TEST_ASSERT(!!scope); + sentry_scope_set_environment(scope, "old"); + sentry_scope_set_tag(scope, "version", "old"); + + scope_access_thread_t state = { .scope = scope }; + sentry__waitable_flag_init(&state.started); + sentry__waitable_flag_init(&state.finished); + + TEST_ASSERT(sentry_scope_begin_read(scope) == 0); + sentry_threadid_t thread; + sentry__thread_init(&thread); + TEST_ASSERT(!sentry__thread_spawn(&thread, read_scope_batch, &state)); + TEST_CHECK(sentry__waitable_flag_wait(&state.finished, 1000)); + sentry_scope_end_read(scope); + sentry__thread_join(thread); + + TEST_CHECK_INT_EQUAL(state.result, 0); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(state.environment), "old"); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(state.tag), "old"); + sentry_value_decref(state.environment); + sentry_value_decref(state.tag); + sentry_scope_free(scope); +} + +SENTRY_THREAD_FN +write_scope_during_read(void *data) +{ + scope_access_thread_t *state = data; + sentry__waitable_flag_set(&state->started); + state->result = sentry_scope_begin_write(state->scope); + if (state->result == 0) { + sentry_scope_set_environment(state->scope, "new"); + sentry_scope_set_tag(state->scope, "version", "new"); + sentry_scope_end_write(state->scope); + } + sentry__waitable_flag_set(&state->finished); + return 0; +} + +SENTRY_TEST(scope_read_blocks_write) +{ + sentry_scope_t *scope = sentry_scope_new(); + TEST_ASSERT(!!scope); + sentry_scope_t *parent = sentry_scope_acquire(); + TEST_ASSERT(!!parent); + sentry_scope_t *targets[] = { scope, parent }; + for (size_t i = 0; i < 2; i++) { + sentry_scope_t *target = targets[i]; + sentry_scope_clear(scope); + sentry_scope_set_environment(target, "old"); + sentry_scope_set_tag(target, "version", "old"); + + scope_access_thread_t state = { .scope = target }; + sentry__waitable_flag_init(&state.started); + sentry__waitable_flag_init(&state.finished); + + TEST_ASSERT(sentry_scope_begin_read(scope) == 0); + sentry_value_t environment = sentry__scope_ref_environment(scope); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(environment), "old"); + sentry_value_decref(environment); + + sentry_threadid_t thread; + sentry__thread_init(&thread); + TEST_ASSERT( + !sentry__thread_spawn(&thread, write_scope_during_read, &state)); + TEST_ASSERT(sentry__waitable_flag_wait(&state.started, 1000)); + TEST_CHECK(!sentry__waitable_flag_wait(&state.finished, 10)); + + TEST_ASSERT(sentry_scope_begin_read(scope) == 0); + sentry_value_t tag + = scope_value_get_by_key(sentry__scope_load_tags, scope, "version"); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(tag), "old"); + sentry_value_decref(tag); + TEST_CHECK(sentry_scope_begin_write(target) == 1); + sentry_scope_end_read(scope); + TEST_CHECK(!sentry__waitable_flag_wait(&state.finished, 10)); + + sentry_scope_end_read(scope); + TEST_CHECK(sentry__waitable_flag_wait(&state.finished, 1000)); + sentry__thread_join(thread); + + TEST_CHECK_INT_EQUAL(state.result, 0); + environment = sentry__scope_ref_environment(scope); + tag = scope_value_get_by_key(sentry__scope_load_tags, scope, "version"); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(environment), "new"); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(tag), "new"); + sentry_value_decref(environment); + sentry_value_decref(tag); + } + sentry_scope_release(parent); + sentry_scope_free(scope); +} + +SENTRY_TEST(scope_access_multiple) +{ + sentry_scope_t *first = sentry_scope_new(); + sentry_scope_t *second = sentry_scope_new(); + TEST_ASSERT(!!first && !!second); + + TEST_ASSERT(sentry_scope_begin_write(first) == 0); + TEST_ASSERT(sentry_scope_begin_read(second) == 0); + TEST_ASSERT(sentry_scope_begin_read(first) == 0); + TEST_ASSERT(sentry_scope_begin_write(first) == 0); + sentry_scope_set_tag(first, "key", "value"); + sentry_scope_end_write(first); + sentry_scope_end_read(first); + sentry_scope_end_write(first); + + TEST_CHECK(scope_value_get_length(sentry__scope_load_tags, second) == 0); + TEST_CHECK(sentry_scope_begin_write(second) == 1); + sentry_scope_end_read(second); + TEST_CHECK(scope_value_get_length(sentry__scope_load_tags, first) == 1); + + TEST_ASSERT(sentry_scope_begin_write(second) == 0); + sentry_scope_set_tag(second, "key", "value"); + sentry_scope_end_write(second); + TEST_CHECK(scope_value_get_length(sentry__scope_load_tags, second) == 1); + + sentry_scope_free(first); + sentry_scope_free(second); +} + +SENTRY_TEST(scope_access_pool) +{ + sentry_scope_t *scope = sentry_scope_acquire(); + TEST_ASSERT(!!scope); + + TEST_ASSERT(sentry_scope_begin_read(scope) == 0); + sentry_scope_end_read(scope); + sentry_scope_release(scope); + + sentry_scope_t *first = sentry_scope_new(); + sentry_scope_t *second = sentry_scope_new(); + sentry_scope_t *third = sentry_scope_new(); + TEST_ASSERT(!!first && !!second && !!third); + + TEST_ASSERT(sentry_scope_begin_read(first) == 0); + TEST_ASSERT(sentry_scope_begin_read(second) == 0); + TEST_ASSERT(sentry_scope_begin_read(third) == 0); + + sentry_scope_end_read(second); + sentry_scope_end_read(first); + sentry_scope_end_read(third); + + TEST_ASSERT(sentry_scope_begin_read(third) == 0); + sentry_scope_end_read(third); + + sentry_scope_free(first); + sentry_scope_free(second); + sentry_scope_free(third); +} + +typedef struct { + scope_access_thread_t access; + sentry_threadid_t thread; + int started; + bool finished; +} breadcrumb_read_t; + +static sentry_value_t +before_breadcrumb_read_scope(sentry_value_t breadcrumb, void *data) +{ + breadcrumb_read_t *state = data; + state->started = sentry__thread_spawn( + &state->thread, read_scope_batch, &state->access); + state->finished = state->started == 0 + && sentry__waitable_flag_wait(&state->access.finished, 1000); + return breadcrumb; +} + +SENTRY_TEST(before_breadcrumb_read_scope) +{ + breadcrumb_read_t state = { 0 }; + sentry__waitable_flag_init(&state.access.started); + sentry__waitable_flag_init(&state.access.finished); + sentry__thread_init(&state.thread); + + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_before_breadcrumb( + options, before_breadcrumb_read_scope, &state); + TEST_ASSERT_INT_EQUAL(sentry_init(options), 0); + state.access.scope = sentry_scope_acquire(); + TEST_ASSERT(!!state.access.scope); + + sentry_add_breadcrumb(sentry_value_new_breadcrumb(NULL, "read scope")); + TEST_CHECK_INT_EQUAL(state.started, 0); + TEST_CHECK(state.finished); + TEST_CHECK_INT_EQUAL(state.access.result, 0); + if (state.started == 0) { + sentry__thread_join(state.thread); + } + sentry__thread_free(&state.thread); + sentry_value_decref(state.access.environment); + sentry_value_decref(state.access.tag); + sentry_scope_release(state.access.scope); + sentry_close(); +} + +SENTRY_TEST(scope_isolation_reset) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_release(options, "configured-release"); + sentry_options_set_environment(options, "configured-environment"); + sentry_options_set_sdk_name(options, "sentry.native.test"); + sentry_options_set_max_breadcrumbs(options, 2); + TEST_ASSERT_INT_EQUAL(sentry_init(options), 0); + + sentry_scope_t *scope = sentry_scope_acquire(); + TEST_ASSERT(!!scope); + sentry_scope_set_release(scope, "changed-release"); + sentry_scope_set_environment(scope, "changed-environment"); + sentry_scope_set_tag(scope, "tag", "value"); + sentry_scope_set_user(scope, sentry_value_new_user("42", NULL, NULL, NULL)); + + sentry_scope_clear(scope); + + sentry_value_t release = sentry__scope_ref_release(scope); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(release), "configured-release"); + sentry_value_decref(release); + sentry_value_t environment = sentry__scope_ref_environment(scope); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(environment), "configured-environment"); + sentry_value_decref(environment); + sentry_value_t sdk = sentry__scope_ref_client_sdk(scope); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(sdk, "name")), + "sentry.native.test"); + sentry_value_decref(sdk); + sentry_value_t user = sentry__scope_ref_user(scope); + TEST_CHECK(sentry_value_is_null(user)); + sentry_value_decref(user); + TEST_CHECK_INT_EQUAL( + scope_value_get_length(sentry__scope_load_tags, scope), 0); + + for (size_t i = 0; i < 3; i++) { + sentry_scope_add_breadcrumb( + scope, sentry_value_new_breadcrumb(NULL, "breadcrumb")); + } + TEST_CHECK_INT_EQUAL(scope_breadcrumb_count(scope), 2); + + sentry_scope_release(scope); + sentry_close(); +} + +typedef struct { + sentry_scope_t *scope; + sentry_value_t event; +} shared_scope_thread_t; + +SENTRY_THREAD_FN +capture_shared_scope(void *data) +{ + shared_scope_thread_t *state = data; + state->scope = sentry_scope_acquire(); + sentry_set_tag("thread", "worker"); + state->event = sentry_value_new_event(); + SENTRY_WITH_OPTIONS (options) { + sentry__scope_apply_to_event( + state->scope, options, state->event, SENTRY_SCOPE_NONE); + } + return 0; +} + +SENTRY_TEST(scope_isolation_shared) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_auto_session_tracking(options, false); + TEST_ASSERT_INT_EQUAL(sentry_init(options), 0); + sentry_scope_t *scope = sentry_scope_acquire(); + TEST_ASSERT(!!scope); + shared_scope_thread_t state = { 0 }; + sentry_threadid_t thread; + sentry__thread_init(&thread); + TEST_ASSERT(!sentry__thread_spawn(&thread, capture_shared_scope, &state)); + sentry__thread_join(thread); + sentry__thread_free(&thread); + TEST_CHECK_PTR_EQUAL(state.scope, scope); + sentry_value_t tag + = scope_value_get_by_key(sentry__scope_load_tags, scope, "thread"); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(tag), "worker"); + sentry_value_decref(tag); + TEST_CHECK(!sentry_value_is_null(sentry_value_get_by_key( + sentry_value_get_by_key(state.event, "contexts"), "os"))); + TEST_CHECK( + !sentry_value_is_null(sentry_value_get_by_key(state.event, "sdk"))); + sentry_value_decref(state.event); + sentry_scope_release(state.scope); + sentry_scope_release(scope); + sentry_close(); +} + +SENTRY_TEST(scope_global_immutable) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_auto_session_tracking(options, false); + TEST_ASSERT_INT_EQUAL(sentry_init(options), 0); + sentry_scope_t *scope = sentry_scope_acquire(); + const sentry_scope_t *global = scope->parent; + TEST_ASSERT(!!global); + TEST_CHECK(global->parent == NULL); + TEST_CHECK(global->state == NULL); + TEST_CHECK(global->flush_func == NULL); + TEST_CHECK_INT_EQUAL(global->num_observers, 0); + TEST_CHECK(scope->num_observers > 0); + TEST_CHECK(scope->flush_func != NULL); + sentry_scope_t *clone = sentry_scope_clone(scope); + TEST_ASSERT(!!clone); + sentry_value_t sdk = sentry__scope_ref_client_sdk(global); + sentry_value_t os + = scope_value_get_by_key(sentry__scope_load_contexts, global, "os"); + TEST_CHECK(sentry_value_is_frozen(sdk)); + char *sdk_json = sentry_value_to_json(sdk); + char *os_json = sentry_value_to_json(os); + TEST_CHECK_INT_EQUAL(sentry_value_set_by_key( + sdk, "name", sentry_value_new_string("changed")), + 1); + sentry_value_set_by_key(os, "name", sentry_value_new_string("changed")); + sentry_value_decref(sdk); + sentry_value_decref(os); + + sentry_set_context("os", sentry_value_new_object()); + sentry_scope_clear(scope); + sentry_value_t event = sentry_value_new_event(); + sentry__scope_apply_to_event(scope, options, event, SENTRY_SCOPE_NONE); + TEST_CHECK_JSON_VALUE(sentry_value_get_by_key( + sentry_value_get_by_key(event, "contexts"), "os"), + os_json); + sentry_value_decref(event); + sentry_close(); + + SENTRY_TEST_OPTIONS_NEW(next_options); + sentry_options_set_auto_session_tracking(next_options, false); + TEST_ASSERT_INT_EQUAL(sentry_init(next_options), 0); + sentry_scope_t *next = sentry_scope_acquire(); + TEST_CHECK(next != scope); + TEST_CHECK_PTR_EQUAL(next->parent, global); + sdk = sentry__scope_ref_client_sdk(global); + os = scope_value_get_by_key(sentry__scope_load_contexts, global, "os"); + TEST_CHECK_JSON_VALUE(sdk, sdk_json); + TEST_CHECK_JSON_VALUE(os, os_json); + sentry_value_decref(sdk); + sentry_value_decref(os); + sentry_scope_release(scope); + event = sentry_value_new_event(); + sentry__scope_apply_to_event(clone, next_options, event, SENTRY_SCOPE_NONE); + TEST_CHECK_JSON_VALUE(sentry_value_get_by_key(event, "sdk"), sdk_json); + TEST_CHECK_JSON_VALUE(sentry_value_get_by_key( + sentry_value_get_by_key(event, "contexts"), "os"), + os_json); + sentry_value_decref(event); + sentry_scope_free(clone); + sentry_free(sdk_json); + sentry_free(os_json); + sentry_scope_release(next); + sentry_close(); +} + +SENTRY_TEST(scope_sdk_inheritance) +{ + sentry_scope_t *before_init = sentry_scope_acquire(); + TEST_ASSERT(!!before_init); + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_auto_session_tracking(options, false); + sentry_options_set_sdk_name(options, "sentry.native.test"); + sentry_integration_t *integration = SENTRY_MAKE(sentry_integration_t); + TEST_ASSERT(!!integration); + integration->name = "test-integration"; + TEST_ASSERT(sentry__options_add_integration(options, integration)); + TEST_ASSERT_INT_EQUAL(sentry_init(options), 0); + sentry_scope_release(before_init); + + sentry_scope_t *scope = sentry_scope_acquire(); + sentry_value_t sdk = sentry__scope_ref_client_sdk(scope); + sentry_value_t global_sdk = sentry__scope_ref_client_sdk(scope->parent); + TEST_CHECK_JSON_VALUE( + sentry_value_get_by_key(global_sdk, "name"), "\"sentry.native.test\""); + TEST_CHECK(sentry_value_is_frozen(global_sdk)); + char *json = sentry_value_to_json(global_sdk); + TEST_CHECK_JSON_VALUE(sdk, json); + sentry_value_t integrations = sentry_value_get_by_key(sdk, "integrations"); + bool found = false; + for (size_t i = 0; i < sentry_value_get_length(integrations); i++) { + found |= !strcmp( + sentry_value_as_string(sentry_value_get_by_index(integrations, i)), + "test-integration"); + } + TEST_CHECK(found); + sentry_value_decref(sdk); + sentry_value_decref(global_sdk); + + sentry_scope_clear(scope); + sdk = sentry__scope_ref_client_sdk(scope); + TEST_CHECK_JSON_VALUE(sdk, json); + sentry_value_decref(sdk); + sentry_scope_t *local = sentry_scope_new(); + sdk = sentry__scope_ref_client_sdk(local); + TEST_CHECK_JSON_VALUE(sdk, json); + sentry_value_decref(sdk); + sentry_scope_free(local); + + sentry_value_t event = sentry_value_new_event(); + sentry__scope_apply_to_event(scope, options, event, SENTRY_SCOPE_NONE); + TEST_CHECK_JSON_VALUE(sentry_value_get_by_key(event, "sdk"), json); + sentry_value_decref(event); + sentry_free(json); + sentry_scope_release(scope); + sentry_close(); +} + +SENTRY_TEST(scope_parent_lifetime) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_auto_session_tracking(options, false); + TEST_ASSERT_INT_EQUAL(sentry_init(options), 0); + sentry_set_tag("parent", "original"); + sentry_scope_t *scope = sentry_scope_new(); + TEST_ASSERT(!!scope); + sentry_scope_t *clone = sentry_scope_clone(scope); + TEST_ASSERT(!!clone); + sentry_scope_free(scope); + sentry_close(); + + SENTRY_TEST_OPTIONS_NEW(next_options); + sentry_options_set_auto_session_tracking(next_options, false); + TEST_ASSERT_INT_EQUAL(sentry_init(next_options), 0); + sentry_set_tag("parent", "new"); + sentry_value_t event = sentry_value_new_event(); + sentry__scope_apply_to_event(clone, next_options, event, SENTRY_SCOPE_NONE); + TEST_CHECK_JSON_VALUE(sentry_value_get_by_key( + sentry_value_get_by_key(event, "tags"), "parent"), + "\"original\""); + sentry_value_decref(event); + sentry_scope_free(clone); + sentry_close(); +} + +SENTRY_TEST(scope_global_before_init) +{ + sentry_scope_t *scope = sentry_scope_acquire(); + TEST_ASSERT(!!scope); + const sentry_scope_t *global = scope->parent; + TEST_ASSERT(!!global); + sentry_value_t sdk = sentry__scope_ref_client_sdk(global); + TEST_ASSERT(sentry_value_get_type(sdk) == SENTRY_VALUE_TYPE_OBJECT); + TEST_CHECK(sentry_value_is_frozen(sdk)); + TEST_CHECK( + sentry_value_get_length(sentry_value_get_by_key(sdk, "name")) > 0); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(sdk, "version")), + SENTRY_SDK_VERSION); + sentry_value_decref(sdk); + sentry_value_t contexts = sentry__scope_load_contexts(global); + TEST_CHECK(sentry_value_get_type(contexts) == SENTRY_VALUE_TYPE_OBJECT); + sentry_value_decref(contexts); + sentry_scope_release(scope); + sentry_close(); +} + +SENTRY_TEST(scope_global_reset) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_release(options, "configured-release"); + sentry_options_set_environment(options, "configured-environment"); + sentry_options_set_sdk_name(options, "sentry.native.test"); + sentry_options_add_attachment(options, SENTRY_TEST_PATH_PREFIX ".a.txt"); + TEST_ASSERT_INT_EQUAL(sentry_init(options), 0); + sentry_close(); + + sentry_scope_t *scope = sentry_scope_acquire(); + TEST_ASSERT(!!scope); + sentry_value_t release = sentry__scope_ref_release(scope); + TEST_CHECK(sentry_value_is_null(release)); + sentry_value_decref(release); + sentry_value_t environment = sentry__scope_ref_environment(scope); + TEST_CHECK(sentry_value_is_null(environment)); + sentry_value_decref(environment); + sentry_value_t sdk = sentry__scope_ref_client_sdk(scope); + TEST_CHECK( + strcmp(sentry_value_as_string(sentry_value_get_by_key(sdk, "name")), + "sentry.native.test") + != 0); + sentry_value_decref(sdk); + TEST_CHECK_INT_EQUAL( + scope_value_get_length(sentry__scope_load_attachments, scope), 0); + sentry_scope_release(scope); + sentry_close(); +} + +SENTRY_TEST(scope_defaults) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_release(options, "configured-release"); + sentry_options_set_environment(options, "configured-environment"); + sentry_options_set_traces_sample_rate(options, 0.25); + TEST_ASSERT_INT_EQUAL(sentry_init(options), 0); + sentry_scope_t *scope = sentry_scope_acquire(); + TEST_ASSERT(!!scope); + sentry_scope_t *local = sentry_scope_new(); + TEST_ASSERT(!!local); + + for (int i = 0; i < 4; i++) { + if (i == 1 || i == 3) { + sentry_set_release("override-release"); + sentry_set_environment("override-environment"); + } + if (i == 2) { + sentry_set_release(NULL); + sentry_set_environment(NULL); + } else if (i == 3) { + sentry_scope_clear(scope); + } + const char *release + = i == 1 ? "override-release" : "configured-release"; + const char *environment + = i == 1 ? "override-environment" : "configured-environment"; + sentry_value_t event = sentry_value_new_event(); + sentry__scope_apply_to_event(scope, options, event, SENTRY_SCOPE_NONE); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(event, "release")), + release); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(sentry_value_get_by_key( + event, "environment")), + environment); + sentry_value_decref(event); + sentry_value_t dsc = sentry__scope_load_dsc(scope); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(dsc, "release")), + release); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(dsc, "environment")), + environment); + sentry_value_decref(dsc); + dsc = sentry__scope_load_dsc(local); + TEST_CHECK( + sentry_value_as_double(sentry_value_get_by_key(dsc, "sample_rate")) + == 0.25); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(dsc, "release")), + release); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(sentry_value_get_by_key(dsc, "environment")), + environment); + sentry_value_decref(dsc); + sentry_value_t global_release + = sentry__scope_ref_release(scope->parent); + TEST_CHECK_STRING_EQUAL( + sentry_value_as_string(global_release), "configured-release"); + sentry_value_decref(global_release); + sentry_value_t global_environment + = sentry__scope_ref_environment(scope->parent); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(global_environment), + "configured-environment"); + sentry_value_decref(global_environment); + } + sentry_scope_set_release(local, "local-release"); + sentry_value_t dsc = sentry__scope_load_dsc(local); + TEST_CHECK_JSON_VALUE( + sentry_value_get_by_key(dsc, "release"), "\"local-release\""); + sentry_value_decref(dsc); + dsc = sentry_value_new_object(); + sentry_value_set_by_key( + dsc, "release", sentry_value_new_string("upstream")); + sentry__scope_freeze_dsc(scope, dsc); + sentry_value_decref(dsc); + dsc = sentry__scope_load_dsc(local); + TEST_CHECK_JSON_VALUE(dsc, "{\"release\":\"upstream\"}"); + sentry_value_decref(dsc); + sentry_scope_free(local); + sentry_scope_release(scope); + sentry_close(); +} + +SENTRY_TEST(scope_parent_lock) +{ + sentry_scope_t *scope = sentry_scope_new(); + TEST_ASSERT(!!scope); + sentry_scope_t *parent = sentry_scope_acquire(); + TEST_ASSERT(!!parent); + sentry_scope_set_environment(parent, "old"); + sentry_scope_set_tag(parent, "version", "old"); + + scope_access_thread_t state = { .scope = parent }; + sentry__waitable_flag_init(&state.started); + sentry__waitable_flag_init(&state.finished); + + TEST_ASSERT(sentry_scope_begin_write(scope) == 0); + sentry_threadid_t thread; + sentry__thread_init(&thread); + TEST_ASSERT( + !sentry__thread_spawn(&thread, write_scope_during_read, &state)); + TEST_ASSERT(sentry__waitable_flag_wait(&state.started, 1000)); + TEST_CHECK(!sentry__waitable_flag_wait(&state.finished, 10)); + + sentry_value_t environment = sentry__scope_ref_environment(scope); + sentry_value_t tag + = scope_value_get_by_key(sentry__scope_load_tags, scope, "version"); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(environment), "old"); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(tag), "old"); + sentry_value_decref(environment); + sentry_value_decref(tag); + + sentry_scope_end_write(scope); + TEST_CHECK(sentry__waitable_flag_wait(&state.finished, 1000)); + sentry__thread_join(thread); + sentry__thread_free(&thread); + TEST_CHECK_INT_EQUAL(state.result, 0); + environment = sentry__scope_ref_environment(scope); + TEST_CHECK_STRING_EQUAL(sentry_value_as_string(environment), "new"); + sentry_value_decref(environment); + sentry_scope_release(parent); + sentry_scope_free(scope); +} + +typedef struct { + sentry_scope_t *scope; + sentry_waitable_flag_t started; + sentry_waitable_flag_t finished; + sentry_waitable_flag_t read_finished; + sentry_threadid_t writer; + sentry_threadid_t reader; + volatile long calls; +} trace_notify_state_t; + +static void +observe_trace(void *data, sentry_value_t UNUSED(trace)) +{ + trace_notify_state_t *state = data; + sentry__atomic_fetch_and_add(&state->calls, 1); +} + +SENTRY_THREAD_FN +notify_scope_trace(void *data) +{ + trace_notify_state_t *state = data; + sentry__waitable_flag_set(&state->started); + sentry_scope_set_span(state->scope, NULL); + sentry__waitable_flag_set(&state->finished); + return 0; +} + +SENTRY_THREAD_FN +read_scope_during_notify(void *data) +{ + trace_notify_state_t *state = data; + sentry_value_decref(sentry__scope_load_tags(state->scope)); + sentry__waitable_flag_set(&state->read_finished); + return 0; +} + +static void +observe_tag_with_trace( + void *data, const char *UNUSED(key), sentry_value_t UNUSED(value)) +{ + trace_notify_state_t *state = data; + TEST_ASSERT( + !sentry__thread_spawn(&state->writer, notify_scope_trace, state)); + TEST_ASSERT(sentry__waitable_flag_wait(&state->started, 1000)); + TEST_CHECK(!sentry__waitable_flag_wait(&state->finished, 100)); + TEST_CHECK_INT_EQUAL(sentry__atomic_fetch(&state->calls), 0); + + TEST_ASSERT( + !sentry__thread_spawn(&state->reader, read_scope_during_notify, state)); + TEST_CHECK(sentry__waitable_flag_wait(&state->read_finished, 1000)); +} + +SENTRY_TEST(scope_observer_trace_serialized) +{ + sentry_scope_t *scope = sentry_scope_new(); + TEST_ASSERT(!!scope); + trace_notify_state_t state = { .scope = scope }; + sentry__waitable_flag_init(&state.started); + sentry__waitable_flag_init(&state.finished); + sentry__waitable_flag_init(&state.read_finished); + sentry__thread_init(&state.writer); + sentry__thread_init(&state.reader); + sentry_scope_observer_t *observer = sentry__scope_observer_new(); + TEST_ASSERT(!!observer); + observer->data = &state; + observer->set_tag = observe_tag_with_trace; + observer->set_trace = observe_trace; + + TEST_ASSERT(sentry__scope_add_observer(scope, observer)); + sentry_scope_set_tag(scope, "tag", "value"); + + TEST_CHECK(sentry__waitable_flag_wait(&state.finished, 1000)); + sentry__thread_join(state.writer); + sentry__thread_join(state.reader); + sentry__thread_free(&state.writer); + sentry__thread_free(&state.reader); + TEST_CHECK_INT_EQUAL(sentry__atomic_fetch(&state.calls), 1); + sentry_scope_free(scope); +} + +static bool +init_trace_observer(void *data, const sentry_scope_t *scope) +{ + trace_notify_state_t *state = data; + TEST_CHECK(scope == state->scope); + TEST_ASSERT(scope->num_observers == 1); + TEST_CHECK(scope->observers[0]->data == data); + TEST_ASSERT( + !sentry__thread_spawn(&state->writer, notify_scope_trace, state)); + TEST_ASSERT(sentry__waitable_flag_wait(&state->started, 1000)); + TEST_CHECK(!sentry__waitable_flag_wait(&state->finished, 100)); + TEST_CHECK_INT_EQUAL(sentry__atomic_fetch(&state->calls), 0); + + TEST_ASSERT( + !sentry__thread_spawn(&state->reader, read_scope_during_notify, state)); + TEST_CHECK(sentry__waitable_flag_wait(&state->read_finished, 1000)); + return true; +} + +SENTRY_TEST(scope_observer_init) +{ + sentry_scope_t *scope = sentry_scope_new(); + TEST_ASSERT(!!scope); + trace_notify_state_t state = { .scope = scope }; + sentry__waitable_flag_init(&state.started); + sentry__waitable_flag_init(&state.finished); + sentry__waitable_flag_init(&state.read_finished); + sentry__thread_init(&state.writer); + sentry__thread_init(&state.reader); + sentry_scope_observer_t *observer = sentry__scope_observer_new(); + TEST_ASSERT(!!observer); + observer->data = &state; + observer->set_trace = observe_trace; + + TEST_ASSERT(sentry__scope_add_observer_with_init( + scope, observer, init_trace_observer)); + + TEST_CHECK(sentry__waitable_flag_wait(&state.finished, 1000)); + sentry__thread_join(state.writer); + sentry__thread_join(state.reader); + sentry__thread_free(&state.writer); + sentry__thread_free(&state.reader); + TEST_CHECK_INT_EQUAL(sentry__atomic_fetch(&state.calls), 1); + sentry_scope_free(scope); +} + +static bool +reject_scope_observer(void *data, const sentry_scope_t *scope) +{ + TEST_CHECK_INT_EQUAL(scope->num_observers, 2); + *(bool *)data = true; + return false; +} + +SENTRY_TEST(scope_observer_init_failure) +{ + sentry_scope_t *scope = sentry_scope_new(); + TEST_ASSERT(!!scope); + sentry_scope_observer_t *existing = sentry__scope_observer_new(); + TEST_ASSERT(!!existing); + TEST_ASSERT(sentry__scope_add_observer(scope, existing)); + + bool initialized = false; + sentry_scope_observer_t *observer = sentry__scope_observer_new(); + TEST_ASSERT(!!observer); + observer->data = &initialized; + TEST_CHECK(!sentry__scope_add_observer_with_init( + scope, observer, reject_scope_observer)); + TEST_CHECK(initialized); + TEST_CHECK_INT_EQUAL(scope->num_observers, 1); + TEST_CHECK(scope->observers[0] == existing); + sentry_scope_free(scope); +} + +static void +set_tag(sentry_scope_t *scope, const char *key, const char *value) +{ + sentry_scope_set_tag(scope, key, value); +} + +static void +set_extra(sentry_scope_t *scope, const char *key, const char *value) +{ + sentry_scope_set_extra(scope, key, sentry_value_new_string(value)); +} + +static void +set_context(sentry_scope_t *scope, const char *key, const char *value) +{ + sentry_value_t context = sentry_value_new_object(); + sentry_value_set_by_key(context, "value", sentry_value_new_string(value)); + sentry_scope_set_context(scope, key, context); +} + +static void +set_attribute(sentry_scope_t *scope, const char *key, const char *value) +{ + sentry_scope_set_attribute(scope, key, + sentry_value_new_attribute(sentry_value_new_string(value), NULL)); +} + +static void +set_propagation_context( + sentry_scope_t *scope, const char *key, const char *value) +{ + sentry__scope_set_propagation_context( + scope, key, sentry_value_new_string(value)); +} + +static sentry_scope_t * +scope_new_child(sentry_scope_t *parent) +{ + sentry_scope_t *scope = sentry_scope_new(); + TEST_ASSERT(!!scope); + sentry__scope_decref((sentry_scope_t *)scope->parent); + scope->parent = parent; + return scope; +} + +static const char * +get_string(sentry_value_t values, const char *key) +{ + sentry_value_t value = sentry_value_get_by_key(values, key); + if (sentry_value_get_type(value) == SENTRY_VALUE_TYPE_OBJECT) { + value = sentry_value_get_by_key(value, "value"); + } + return sentry_value_as_string(value); +} + +static void +check_scope_inheritance(scope_value_getter_t load, scope_value_setter_t set) +{ + sentry_scope_t *root = scope_new_child(NULL); + sentry_scope_t *middle = scope_new_child(root); + sentry_scope_t *leaf = scope_new_child(middle); + + sentry_value_t values = load(leaf); + TEST_CHECK(sentry_value_get_type(values) == SENTRY_VALUE_TYPE_OBJECT); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(values), 0); + sentry_value_decref(values); + + // the empty middle and leaf inherit the root values + set(root, "root", "root"); + set(root, "shared", "root"); + values = load(leaf); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(values), 2); + TEST_CHECK_STRING_EQUAL(get_string(values, "root"), "root"); + TEST_CHECK_STRING_EQUAL(get_string(values, "shared"), "root"); + + // the loaded values are detached from the root + sentry_value_set_by_key(values, "root", sentry_value_new_string("changed")); + sentry_value_set_by_key(sentry_value_get_by_key(values, "shared"), "value", + sentry_value_new_string("changed")); + sentry_value_decref(values); + values = load(root); + TEST_CHECK_STRING_EQUAL(get_string(values, "root"), "root"); + TEST_CHECK_STRING_EQUAL(get_string(values, "shared"), "root"); + sentry_value_decref(values); + + // the leaf overrides the root across the empty middle + set(leaf, "leaf", "leaf"); + set(leaf, "shared", "leaf"); + values = load(leaf); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(values), 3); + TEST_CHECK_STRING_EQUAL(get_string(values, "root"), "root"); + TEST_CHECK_STRING_EQUAL(get_string(values, "leaf"), "leaf"); + TEST_CHECK_STRING_EQUAL(get_string(values, "shared"), "leaf"); + sentry_value_decref(values); + + values = load(middle); + TEST_CHECK_INT_EQUAL(sentry_value_get_length(values), 2); + TEST_CHECK_STRING_EQUAL(get_string(values, "shared"), "root"); + sentry_value_decref(values); + + sentry_scope_free(leaf); +} + +SENTRY_TEST(scope_inheritance_tags) +{ + check_scope_inheritance(sentry__scope_load_tags, set_tag); +} + +SENTRY_TEST(scope_inheritance_extra) +{ + check_scope_inheritance(sentry__scope_load_extra, set_extra); +} + +SENTRY_TEST(scope_inheritance_contexts) +{ + check_scope_inheritance(sentry__scope_load_contexts, set_context); +} + +SENTRY_TEST(scope_inheritance_attributes) +{ + check_scope_inheritance(sentry__scope_load_attributes, set_attribute); +} + +SENTRY_TEST(scope_inheritance_propagation_context) +{ + check_scope_inheritance( + sentry__scope_load_propagation_context, set_propagation_context); +} diff --git a/tests/unit/test_tracing.c b/tests/unit/test_tracing.c index ef405c2972..df82bc8549 100644 --- a/tests/unit/test_tracing.c +++ b/tests/unit/test_tracing.c @@ -2582,6 +2582,272 @@ SENTRY_TEST(set_trace_rebuilds_dsc_sample_rand) sentry_close(); } +SENTRY_TEST(continue_trace) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_dsn(options, "https://k@o123456.ingest.sentry.io/1"); + sentry_options_set_transport( + options, sentry_transport_new(discard_envelope)); + // the upstream sampling decision wins over the local rate + sentry_options_set_traces_sample_rate(options, 0.0); + sentry_init(options); + + sentry_continue_trace(UPSTREAM_SENTRY_TRACE, + "sentry-org_id=123456,sentry-environment=upstream," + "sentry-sample_rand=0.25"); + + SENTRY_WITH_SCOPE (scope) { + sentry_value_t trace = sentry__scope_load_trace_context(scope); + CHECK_STRING_PROPERTY(trace, "trace_id", UPSTREAM_TRACE_ID); + CHECK_STRING_PROPERTY(trace, "parent_span_id", UPSTREAM_PARENT_SPAN_ID); + TEST_CHECK( + sentry_value_is_true(sentry_value_get_by_key(trace, "sampled"))); + TEST_CHECK(sentry_value_as_double( + sentry_value_get_by_key(trace, "sample_rand")) + == 0.25); + sentry_value_decref(trace); + + sentry_value_t dsc = sentry__scope_load_dsc(scope); + CHECK_STRING_PROPERTY(dsc, "org_id", "123456"); + CHECK_STRING_PROPERTY(dsc, "environment", "upstream"); + CHECK_STRING_PROPERTY(dsc, "sample_rand", "0.25"); + sentry_value_decref(dsc); + } + + sentry_transaction_t *tx = sentry_transaction_start( + sentry_transaction_context_new("name", "op"), sentry_value_new_null()); + CHECK_STRING_PROPERTY(tx->inner, "trace_id", UPSTREAM_TRACE_ID); + CHECK_STRING_PROPERTY(tx->inner, "parent_span_id", UPSTREAM_PARENT_SPAN_ID); + TEST_CHECK( + sentry_value_is_true(sentry_value_get_by_key(tx->inner, "sampled"))); + + sentry_transaction_finish(tx); + sentry_close(); +} + +SENTRY_TEST(continue_trace_org_mismatch_starts_new_trace) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_dsn(options, "https://k@o123456.ingest.sentry.io/1"); + sentry_init(options); + + sentry_continue_trace(UPSTREAM_SENTRY_TRACE, "sentry-org_id=99999"); + + SENTRY_WITH_SCOPE (scope) { + sentry_value_t trace = sentry__scope_load_trace_context(scope); + TEST_CHECK(strcmp(sentry_value_as_string( + sentry_value_get_by_key(trace, "trace_id")), + UPSTREAM_TRACE_ID) + != 0); + TEST_CHECK(IS_NULL(trace, "parent_span_id")); + TEST_CHECK(IS_NULL(trace, "sampled")); + sentry_value_decref(trace); + + sentry_value_t dsc = sentry__scope_load_dsc(scope); + CHECK_STRING_PROPERTY(dsc, "org_id", "123456"); + sentry_value_decref(dsc); + } + + sentry_close(); +} + +SENTRY_TEST(continue_trace_without_trace_starts_new_trace) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_init(options); + + const char *headers[] = { NULL, "invalid" }; + for (size_t i = 0; i < 2; i++) { + char *trace_id = NULL; + SENTRY_WITH_SCOPE (scope) { + sentry_value_t trace = sentry__scope_load_trace_context(scope); + trace_id = sentry__string_clone(sentry_value_as_string( + sentry_value_get_by_key(trace, "trace_id"))); + sentry_value_decref(trace); + } + + sentry_continue_trace(headers[i], NULL); + + SENTRY_WITH_SCOPE (scope) { + sentry_value_t trace = sentry__scope_load_trace_context(scope); + TEST_CHECK(strcmp(sentry_value_as_string( + sentry_value_get_by_key(trace, "trace_id")), + trace_id) + != 0); + TEST_CHECK(IS_NULL(trace, "parent_span_id")); + sentry_value_decref(trace); + } + sentry_free(trace_id); + } + + sentry_close(); +} + +static double +load_sample_rand(void) +{ + double sample_rand = 1.0; + SENTRY_WITH_SCOPE (scope) { + sentry_value_t trace = sentry__scope_load_trace_context(scope); + sample_rand = sentry_value_as_double( + sentry_value_get_by_key(trace, "sample_rand")); + sentry_value_decref(trace); + + // the derived value propagates downstream + sentry_value_t dsc = sentry__scope_load_dsc(scope); + TEST_CHECK( + sentry_value_as_double(sentry_value_get_by_key(dsc, "sample_rand")) + == sample_rand); + sentry_value_decref(dsc); + } + return sample_rand; +} + +SENTRY_TEST(continue_trace_derives_sample_rand) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_init(options); + + sentry_continue_trace(UPSTREAM_TRACE_ID "-" UPSTREAM_PARENT_SPAN_ID "-1", + "sentry-sample_rate=0.25"); + double sample_rand = load_sample_rand(); + TEST_CHECK(sample_rand >= 0.0 && sample_rand < 0.25); + + sentry_continue_trace(UPSTREAM_TRACE_ID "-" UPSTREAM_PARENT_SPAN_ID "-0", + "sentry-sample_rate=0.25"); + sample_rand = load_sample_rand(); + TEST_CHECK(sample_rand >= 0.25 && sample_rand < 1.0); + + sentry_close(); +} + +static void +continue_upstream_trace(sentry_scope_t *scope, void *UNUSED(data)) +{ + sentry_scope_continue_trace( + scope, UPSTREAM_SENTRY_TRACE, "sentry-environment=upstream"); +} + +SENTRY_TEST(continue_trace_on_init) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_initial_scope(options, continue_upstream_trace, NULL); + sentry_init(options); + + SENTRY_WITH_SCOPE (scope) { + sentry_value_t trace = sentry__scope_load_trace_context(scope); + CHECK_STRING_PROPERTY(trace, "trace_id", UPSTREAM_TRACE_ID); + sentry_value_decref(trace); + + sentry_value_t dsc = sentry__scope_load_dsc(scope); + CHECK_STRING_PROPERTY(dsc, "environment", "upstream"); + sentry_value_decref(dsc); + } + + sentry_close(); +} + +static void +set_upstream_trace(sentry_scope_t *scope, void *UNUSED(data)) +{ + sentry_scope_set_trace(scope, UPSTREAM_TRACE_ID, UPSTREAM_PARENT_SPAN_ID); +} + +SENTRY_TEST(set_trace_on_init) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_initial_scope(options, set_upstream_trace, NULL); + sentry_init(options); + + SENTRY_WITH_SCOPE (scope) { + sentry_value_t trace = sentry__scope_load_trace_context(scope); + CHECK_STRING_PROPERTY(trace, "trace_id", UPSTREAM_TRACE_ID); + + sentry_value_t dsc = sentry__scope_load_dsc(scope); + TEST_CHECK( + sentry_value_as_double(sentry_value_get_by_key(dsc, "sample_rand")) + == sentry_value_as_double( + sentry_value_get_by_key(trace, "sample_rand"))); + sentry_value_decref(dsc); + sentry_value_decref(trace); + } + + sentry_close(); +} + +SENTRY_TEST(continue_trace_on_clone) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_init(options); + + sentry_scope_t *clone = NULL; + SENTRY_WITH_SCOPE (scope) { + clone = sentry_scope_clone(scope); + } + sentry_scope_continue_trace(clone, UPSTREAM_SENTRY_TRACE, NULL); + + sentry_value_t trace = sentry__scope_load_trace_context(clone); + CHECK_STRING_PROPERTY(trace, "trace_id", UPSTREAM_TRACE_ID); + sentry_value_decref(trace); + + sentry_scope_free(clone); + sentry_close(); +} + +SENTRY_TEST(iter_trace_propagation_headers) +{ + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_dsn(options, "https://k@o123456.ingest.sentry.io/1"); + sentry_options_set_transport( + options, sentry_transport_new(discard_envelope)); + sentry_options_set_traces_sample_rate(options, 1.0); + sentry_init(options); + + // no span: the propagation context with a deferred sampling decision + char sentry_trace[64]; + char baggage_prefix[64]; + SENTRY_WITH_SCOPE (scope) { + sentry_value_t trace = sentry__scope_load_trace_context(scope); + const char *trace_id = sentry_value_as_string( + sentry_value_get_by_key(trace, "trace_id")); + snprintf(sentry_trace, sizeof(sentry_trace), "%s-%s", trace_id, + sentry_value_as_string(sentry_value_get_by_key(trace, "span_id"))); + snprintf(baggage_prefix, sizeof(baggage_prefix), "sentry-trace_id=%s,", + trace_id); + sentry_value_decref(trace); + } + continuation_collector_t c = { 0 }; + sentry_iter_trace_propagation_headers(collect_continuation_headers, &c); + TEST_CHECK_STRING_EQUAL(c.sentry_trace, sentry_trace); + TEST_CHECK(strncmp(c.baggage, baggage_prefix, strlen(baggage_prefix)) == 0); + TEST_CHECK(strstr(c.baggage, "sentry-org_id=123456") != NULL); + TEST_CHECK(strstr(c.baggage, "sentry-sampled") == NULL); + + // inherited sampling decision + sentry_continue_trace(UPSTREAM_SENTRY_TRACE, "sentry-environment=upstream"); + memset(&c, 0, sizeof(c)); + sentry_iter_trace_propagation_headers(collect_continuation_headers, &c); + TEST_CHECK(strncmp(c.sentry_trace, UPSTREAM_TRACE_ID "-", 33) == 0); + TEST_CHECK(strcmp(c.sentry_trace + strlen(c.sentry_trace) - 2, "-1") == 0); + TEST_CHECK(strstr(c.baggage, "sentry-trace_id=" UPSTREAM_TRACE_ID) != NULL); + TEST_CHECK(strstr(c.baggage, "sentry-environment=upstream") != NULL); + + // bound transaction + sentry_transaction_t *tx = sentry_transaction_start( + sentry_transaction_context_new("name", "op"), sentry_value_new_null()); + sentry_set_transaction_object(tx); + continuation_collector_t tx_headers = { 0 }; + sentry_transaction_iter_headers( + tx, collect_continuation_headers, &tx_headers); + memset(&c, 0, sizeof(c)); + sentry_iter_trace_propagation_headers(collect_continuation_headers, &c); + TEST_CHECK_STRING_EQUAL(c.sentry_trace, tx_headers.sentry_trace); + TEST_CHECK_STRING_EQUAL(c.baggage, tx_headers.baggage); + + sentry_transaction_finish(tx); + sentry_close(); +} + #undef UPSTREAM_SENTRY_TRACE #undef UPSTREAM_PARENT_SPAN_ID #undef UPSTREAM_TRACE_ID diff --git a/tests/unit/test_tus.c b/tests/unit/test_tus.c index 7009bb92b0..8a793cf5b1 100644 --- a/tests/unit/test_tus.c +++ b/tests/unit/test_tus.c @@ -65,12 +65,14 @@ SENTRY_TEST(tus_request_preparation) } if (strcmp(req->headers[i].key, "upload-metadata") == 0) { has_upload_metadata = true; + TEST_CHECK_STRING_EQUAL(req->headers[i].value, + "sentry eyJhdHRhY2htZW50X3R5cGUiOiJldmVudC5hdHRhY2htZW50In0="); } } TEST_CHECK(has_tus_resumable); TEST_CHECK(has_upload_length); TEST_CHECK(!has_content_type); - TEST_CHECK(!has_upload_metadata); + TEST_CHECK(has_upload_metadata); sentry__prepared_http_request_free(req); @@ -96,13 +98,15 @@ SENTRY_TEST(tus_request_preparation) const char *location = "https://sentry.invalid/api/42/upload/abc123/"; req = sentry__prepare_tus_upload_request( - location, test_file_path, 9, dsn, NULL); + location, test_file_path, 9, 0, 9, dsn, NULL); TEST_CHECK(!!req); TEST_CHECK_STRING_EQUAL(req->method, "PATCH"); TEST_CHECK_STRING_EQUAL(req->url, location); +#ifndef SENTRY_TRANSPORT_COMPRESSION TEST_CHECK(!!req->body_path); TEST_CHECK_INT_EQUAL(req->body_len, 9); TEST_CHECK(!req->body); +#endif has_tus_resumable = false; has_content_type = false; @@ -127,6 +131,31 @@ SENTRY_TEST(tus_request_preparation) TEST_CHECK(has_upload_offset); sentry__prepared_http_request_free(req); + + // Test a resumed upload starts at the requested file offset. + req = sentry__prepare_tus_upload_request( + location, test_file_path, 9, 4, 3, dsn, NULL); + TEST_CHECK(!!req); +#ifndef SENTRY_TRANSPORT_COMPRESSION + TEST_CHECK_INT_EQUAL(req->body_offset, 4); + TEST_CHECK_INT_EQUAL(req->body_len, 3); +#endif + has_upload_offset = false; + for (size_t i = 0; i < req->headers_len; i++) { + if (strcmp(req->headers[i].key, "upload-offset") == 0) { + TEST_CHECK_STRING_EQUAL(req->headers[i].value, "4"); + has_upload_offset = true; + } + } + TEST_CHECK(has_upload_offset); + sentry__prepared_http_request_free(req); + + TEST_CHECK(!sentry__prepare_tus_upload_request( + location, test_file_path, 9, 10, 0, dsn, NULL)); + + TEST_CHECK(!sentry__prepare_tus_upload_request( + location, test_file_path, 9, 4, 6, dsn, NULL)); + sentry__path_remove(test_file_path); sentry__path_free(test_file_path); sentry__dsn_decref(dsn); @@ -251,17 +280,21 @@ SENTRY_TEST(tus_upload_error) } // Mock that drives a full TUS round-trip: returns a relative `Location` from -// the create POST (per spec), 204 from the upload PATCH, and captures the -// final envelope POST body so the test can inspect the placeholder payload. +// the create POST (per spec), 204 with the final `Location` from the upload +// PATCH, and captures the final envelope POST body so the test can inspect +// the placeholder payload. typedef struct { char *captured_body; size_t captured_body_len; + char *upload_length; int create_count; int patch_count; } tus_capture_state_t; static const char *TUS_RELATIVE_LOCATION = "/api/42/upload/019db3e0/?length=104857600&signature=test"; +static const char *TUS_FINAL_LOCATION + = "/api/42/upload/019db3e0/?upload_length=104857600&upload_signature=test"; static int tus_capture_send(void *client, sentry_prepared_http_request_t *req, @@ -272,14 +305,24 @@ tus_capture_send(void *client, sentry_prepared_http_request_t *req, // TUS create: POST with no body if (strcmp(req->method, "POST") == 0 && !req->body && !req->body_path) { cap->create_count++; + for (size_t i = 0; i < req->headers_len; i++) { + if (strcmp(req->headers[i].key, "upload-length") == 0) { + sentry_free(cap->upload_length); + cap->upload_length + = sentry__string_clone(req->headers[i].value); + } + } resp->status_code = 201; resp->location = sentry__string_clone(TUS_RELATIVE_LOCATION); return true; } - // TUS upload: PATCH with body_path - if (strcmp(req->method, "PATCH") == 0 && req->body_path) { + // TUS upload: PATCH + if (strcmp(req->method, "PATCH") == 0) { cap->patch_count++; resp->status_code = 204; + resp->location = sentry__string_clone(TUS_FINAL_LOCATION); + // the single PATCH completes the upload + resp->upload_offset = sentry__string_clone(cap->upload_length); return true; } // Envelope POST: capture body @@ -341,7 +384,9 @@ SENTRY_TEST(tus_placeholder_uses_raw_location) if (!sentry__envelope_item_get_attachment_ref(item, &ref)) { continue; } - TEST_CHECK_STRING_EQUAL(ref.location, TUS_RELATIVE_LOCATION); + // The placeholder must carry the final PATCH `Location`, not the + // one from the create POST. + TEST_CHECK_STRING_EQUAL(ref.location, TUS_FINAL_LOCATION); sentry__attachment_ref_cleanup(&ref); found_ref = true; } @@ -349,6 +394,7 @@ SENTRY_TEST(tus_placeholder_uses_raw_location) sentry_envelope_free(parsed); sentry_free(cap.captured_body); + sentry_free(cap.upload_length); sentry__path_remove(test_file_path); sentry__path_free(test_file_path); #endif @@ -378,6 +424,25 @@ capture_serialized_ref(const char *path) TEST_CHECK_INT_EQUAL(sentry_flush(5000), 0); } +static bool +captured_final_location(const tus_capture_state_t *cap) +{ + sentry_envelope_t *envelope = sentry_envelope_deserialize( + cap->captured_body, cap->captured_body_len); + bool found = false; + size_t count = envelope ? sentry__envelope_get_item_count(envelope) : 0; + for (size_t i = 0; i < count; i++) { + sentry_attachment_ref_t ref; + if (sentry__envelope_item_get_attachment_ref( + sentry__envelope_get_item(envelope, i), &ref)) { + found = sentry__string_eq(ref.location, TUS_FINAL_LOCATION); + sentry__attachment_ref_cleanup(&ref); + } + } + sentry_envelope_free(envelope); + return found; +} + SENTRY_TEST(tus_attachment_ref_confinement) { #if defined(SENTRY_PLATFORM_ANDROID) || defined(SENTRY_PLATFORM_NX) \ @@ -429,6 +494,7 @@ SENTRY_TEST(tus_attachment_ref_confinement) capture_serialized_ref("safe.bin"); TEST_CHECK_INT_EQUAL(cap.create_count, 1); TEST_CHECK_INT_EQUAL(cap.patch_count, 1); + TEST_CHECK(captured_final_location(&cap)); TEST_CHECK(!sentry__path_is_file(inside)); TEST_CHECK(sentry__path_is_file(outside)); @@ -446,6 +512,7 @@ SENTRY_TEST(tus_attachment_ref_confinement) sentry_close(); sentry_free(cap.captured_body); + sentry_free(cap.upload_length); sentry__path_free(outside_abs); sentry__path_free(inside); TEST_CHECK_INT_EQUAL(sentry__path_remove(outside), 0); @@ -455,3 +522,105 @@ SENTRY_TEST(tus_attachment_ref_confinement) sentry__path_free(db); #endif } + +SENTRY_TEST(tus_chunk_size) +{ + struct { + const char *granularity; + const char *min; + const char *max; + bool valid; + size_t size; + } cases[] = { + { "256", "1048576", "1073741824", true, 32 * 1024 * 1024 }, + { "1048576", "1048576", "26214400", true, 25 * 1024 * 1024 }, + { "1048576", "41943040", "1073741824", true, 40 * 1024 * 1024 }, + { "5242880", "5242880", "1073741824", true, 30 * 1024 * 1024 }, + { "10485760", "32505856", "104857600", true, 40 * 1024 * 1024 }, + { "67108864", "1048576", "134217728", true, 64 * 1024 * 1024 }, + { NULL, "1048576", "1073741824", true, 0 }, + { "256", NULL, "1073741824", true, 0 }, + { "256", "1048576", NULL, true, 0 }, + { "0", "1048576", "1073741824", false, 0 }, + { "256", "0", "1073741824", false, 0 }, + { "256", "1048576", "0", false, 0 }, + { "256", "1048576", "1024", false, 0 }, + { "1024", "513", "1023", false, 0 }, + { "", "1048576", "1073741824", false, 0 }, + { "-1", "1048576", "1073741824", false, 0 }, + { "256", "+1048576", "1073741824", false, 0 }, + { "256", "1048576", "1073741824x", false, 0 }, + { "256", "1048576", "18446744073709551616", false, 0 }, + }; + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + sentry_http_response_t resp = { 0 }; + resp.upload_chunk_granularity = (char *)cases[i].granularity; + resp.upload_min_chunk_size = (char *)cases[i].min; + resp.upload_max_chunk_size = (char *)cases[i].max; + size_t size = 0; + TEST_CHECK( + sentry__tus_choose_chunk_size(&resp, &size) == cases[i].valid); + TEST_CHECK_INT_EQUAL(size, cases[i].size); + } +} + +static int +tus_rate_limit_send(void *client, sentry_prepared_http_request_t *req, + sentry_http_response_t *resp) +{ + int *create_count = client; + if (strcmp(req->method, "POST") == 0 && !req->body && !req->body_path) { + (*create_count)++; + resp->status_code = 429; + resp->retry_after = sentry__string_clone("60"); + return true; + } + resp->status_code = 200; + return true; +} + +SENTRY_TEST(tus_rate_limit) +{ +#if defined(SENTRY_PLATFORM_ANDROID) || defined(SENTRY_PLATFORM_NX) \ + || defined(SENTRY_PLATFORM_PS) || defined(SENTRY_PLATFORM_XBOX) + SKIP_TEST(); +#else + const char *test_file_str + = SENTRY_TEST_PATH_PREFIX "sentry_test_tus_rate_limit"; + sentry_path_t *test_file_path = sentry__path_from_str(test_file_str); + create_large_test_file(test_file_str); + + int create_count = 0; + sentry_transport_t *transport + = sentry__http_transport_new(&create_count, tus_rate_limit_send); + TEST_ASSERT(!!transport); + sentry__client_report_reset(); + + SENTRY_TEST_OPTIONS_NEW(options); + sentry_options_set_dsn(options, "https://foo@sentry.invalid/42"); + sentry_options_set_transport(options, transport); + sentry_options_set_enable_large_attachments(options, 1); + sentry_options_add_attachment(options, test_file_str); + sentry_init(options); + + sentry_capture_event( + sentry_value_new_message_event(SENTRY_LEVEL_INFO, NULL, "test")); + + sentry_close(); + + // The upload's 429 rate-limits the event without a send error report. + TEST_CHECK_INT_EQUAL(create_count, 1); + sentry_client_report_t report = { { 0 } }; + TEST_CHECK(sentry__client_report_save(&report)); + TEST_CHECK_INT_EQUAL(report.counts[SENTRY_DISCARD_REASON_SEND_ERROR] + [SENTRY_DATA_CATEGORY_ATTACHMENT], + 0); + TEST_CHECK_INT_EQUAL(report.counts[SENTRY_DISCARD_REASON_RATELIMIT_BACKOFF] + [SENTRY_DATA_CATEGORY_ERROR], + 1); + sentry__client_report_reset(); + + sentry__path_remove(test_file_path); + sentry__path_free(test_file_path); +#endif +} diff --git a/tests/unit/test_unwinder.c b/tests/unit/test_unwinder.c index 70f4d7de68..5b4ff8e90b 100644 --- a/tests/unit/test_unwinder.c +++ b/tests/unit/test_unwinder.c @@ -223,12 +223,29 @@ SENTRY_TEST(find_mem_range) mem_range_t crafted_range = { 0, 0 }; found = find_mem_range_from_fd(fd, (uintptr_t)0xdead1000, &crafted_range); - close(fd); - unlink(tmp_path); TEST_CHECK(found); TEST_CHECK_PTR_EQUAL( (void *)crafted_range.lo, (void *)(uintptr_t)0xdead0000); TEST_CHECK_PTR_EQUAL( (void *)crafted_range.hi, (void *)(uintptr_t)0xdeadf000); + + // Test that the address prefix can span two 512-byte reads. + TEST_ASSERT(ftruncate(fd, 0) == 0); + lseek(fd, 0, SEEK_SET); + TEST_ASSERT(write(fd, skip_prefix, strlen(skip_prefix)) + == (ssize_t)strlen(skip_prefix)); + size_t padding = 507 - strlen(skip_prefix); + TEST_ASSERT(write(fd, filler, padding) == (ssize_t)padding); + TEST_ASSERT(write(fd, "\n", 1) == 1); + TEST_ASSERT(write(fd, target, strlen(target)) == (ssize_t)strlen(target)); + lseek(fd, 0, SEEK_SET); + + mem_range_t split_range = { 0, 0 }; + found = find_mem_range_from_fd(fd, (uintptr_t)0xdead1000, &split_range); + close(fd); + unlink(tmp_path); + TEST_CHECK(found); + TEST_CHECK_PTR_EQUAL((void *)split_range.lo, (void *)(uintptr_t)0xdead0000); + TEST_CHECK_PTR_EQUAL((void *)split_range.hi, (void *)(uintptr_t)0xdeadf000); #endif } diff --git a/tests/unit/test_value.c b/tests/unit/test_value.c index f366275b11..ea6261c18c 100644 --- a/tests/unit/test_value.c +++ b/tests/unit/test_value.c @@ -1685,94 +1685,6 @@ SENTRY_TEST(thread_without_name_still_valid) sentry_value_decref(thread); } -SENTRY_TEST(user_report_is_valid) -{ - sentry_uuid_t event_id - = sentry_uuid_from_string("c993afb6-b4ac-48a6-b61b-2558e601d65d"); - sentry_value_t user_feedback; - SENTRY_TEST_DEPRECATED( - user_feedback = sentry_value_new_user_feedback( - &event_id, "some-name", "some-email", "some-comment")); - - TEST_CHECK(!sentry_value_is_null(user_feedback)); - TEST_CHECK_STRING_EQUAL( - sentry_value_as_string(sentry_value_get_by_key(user_feedback, "name")), - "some-name"); - TEST_CHECK_STRING_EQUAL( - sentry_value_as_string(sentry_value_get_by_key(user_feedback, "email")), - "some-email"); - TEST_CHECK_STRING_EQUAL(sentry_value_as_string(sentry_value_get_by_key( - user_feedback, "comments")), - "some-comment"); - - sentry_value_decref(user_feedback); -} - -SENTRY_TEST(user_feedback_with_null_args) -{ - sentry_uuid_t event_id - = sentry_uuid_from_string("c993afb6-b4ac-48a6-b61b-2558e601d65d"); - sentry_value_t user_feedback; - SENTRY_TEST_DEPRECATED(user_feedback - = sentry_value_new_user_feedback(&event_id, NULL, NULL, NULL)); - - TEST_CHECK(!sentry_value_is_null(user_feedback)); - TEST_CHECK( - sentry_value_is_null(sentry_value_get_by_key(user_feedback, "name"))); - TEST_CHECK( - sentry_value_is_null(sentry_value_get_by_key(user_feedback, "email"))); - TEST_CHECK(sentry_value_is_null( - sentry_value_get_by_key(user_feedback, "comments"))); - - sentry_value_decref(user_feedback); - - SENTRY_TEST_DEPRECATED(user_feedback = sentry_value_new_user_feedback( - &event_id, NULL, "some-email", "some-comment")); - - TEST_CHECK(!sentry_value_is_null(user_feedback)); - TEST_CHECK( - sentry_value_is_null(sentry_value_get_by_key(user_feedback, "name"))); - TEST_CHECK_STRING_EQUAL( - sentry_value_as_string(sentry_value_get_by_key(user_feedback, "email")), - "some-email"); - TEST_CHECK_STRING_EQUAL(sentry_value_as_string(sentry_value_get_by_key( - user_feedback, "comments")), - "some-comment"); - - sentry_value_decref(user_feedback); - - SENTRY_TEST_DEPRECATED(user_feedback = sentry_value_new_user_feedback( - &event_id, "some-name", NULL, "some-comment")); - - TEST_CHECK(!sentry_value_is_null(user_feedback)); - TEST_CHECK_STRING_EQUAL( - sentry_value_as_string(sentry_value_get_by_key(user_feedback, "name")), - "some-name"); - TEST_CHECK( - sentry_value_is_null(sentry_value_get_by_key(user_feedback, "email"))); - TEST_CHECK_STRING_EQUAL(sentry_value_as_string(sentry_value_get_by_key( - user_feedback, "comments")), - "some-comment"); - - sentry_value_decref(user_feedback); - - SENTRY_TEST_DEPRECATED(user_feedback = sentry_value_new_user_feedback( - &event_id, "some-name", "some-email", NULL)); - - TEST_CHECK(!sentry_value_is_null(user_feedback)); - - TEST_CHECK_STRING_EQUAL( - sentry_value_as_string(sentry_value_get_by_key(user_feedback, "name")), - "some-name"); - TEST_CHECK_STRING_EQUAL( - sentry_value_as_string(sentry_value_get_by_key(user_feedback, "email")), - "some-email"); - TEST_CHECK(sentry_value_is_null( - sentry_value_get_by_key(user_feedback, "comments"))); - - sentry_value_decref(user_feedback); -} - SENTRY_TEST(user_feedback_is_valid) { sentry_uuid_t event_id diff --git a/tests/unit/tests.inc b/tests/unit/tests.inc index 417366f513..d0dad688d3 100644 --- a/tests/unit/tests.inc +++ b/tests/unit/tests.inc @@ -19,6 +19,7 @@ XX(attachment_properties) XX(attachment_rate_limit) XX(attachment_ref_cache_cleanup) XX(attachment_ref_cache_discard) +XX(attachment_ref_chunk_size_roundtrip) XX(attachment_ref_copy) XX(attachment_ref_creation) XX(attachment_ref_from_path) @@ -49,7 +50,6 @@ XX(basic_http_request_preparation_for_event_with_attachment) XX(basic_http_request_preparation_for_minidump) XX(basic_http_request_preparation_for_transaction) XX(basic_http_request_preparation_for_user_feedback) -XX(basic_http_request_preparation_for_user_report) XX(basic_logging_functionality) XX(basic_spans) XX(basic_tracing_context) @@ -76,6 +76,7 @@ XX(batcher_sync_flush_sends) XX(before_breadcrumb_discard) XX(before_breadcrumb_modify) XX(before_breadcrumb_passthrough) +XX(before_breadcrumb_read_scope) XX(bgworker_delayed_cleanup) XX(bgworker_delayed_current) XX(bgworker_delayed_drop_current) @@ -134,6 +135,12 @@ XX(concurrent_uninit) XX(cond_wait_timeout_overflow) XX(cond_wake_all) XX(continuation_no_baggage_uses_sdk_dsc) +XX(continue_trace) +XX(continue_trace_derives_sample_rand) +XX(continue_trace_on_clone) +XX(continue_trace_on_init) +XX(continue_trace_org_mismatch_starts_new_trace) +XX(continue_trace_without_trace_starts_new_trace) XX(corrupt_crash_envelope_does_not_block_old_run) XX(count_sampled_events) XX(crash_context_handler_path_propagation) @@ -141,11 +148,32 @@ XX(crash_context_init) XX(crash_context_null_options) XX(crash_context_options_propagation) XX(crash_context_transport_fields) +XX(crash_daemon_shutdown_during_crash) +XX(crash_ipc_awaiting_ready) +XX(crash_ipc_broken_stream) +XX(crash_ipc_crashing) +XX(crash_ipc_interrupted_frame) +XX(crash_ipc_message_invalid_lengths) +XX(crash_ipc_message_large_roundtrip) +XX(crash_ipc_message_oversized) +XX(crash_ipc_message_partial) +XX(crash_ipc_message_roundtrip) +XX(crash_ipc_message_unknown_type) +XX(crash_ipc_notify_without_daemon) +XX(crash_ipc_partial_reads) +XX(crash_ipc_reattach_stalled) +XX(crash_ipc_shutdown) +XX(crash_ipc_stalled_notify) +XX(crash_ipc_stalled_stream) +XX(crash_ipc_stream_ordering) +XX(crash_ipc_torn_frame) XX(crash_marker) XX(crash_reserve_alloc_release) XX(crash_reserve_disabled) XX(crash_reserve_init_close) XX(crash_reserve_realloc) +XX(crash_scope_invalid_updates) +XX(crash_scope_updates) XX(crashed_last_run) XX(custom_logger) XX(daemon_adopts_existing_run) @@ -189,6 +217,7 @@ XX(effective_org_id_resolution) XX(elf_find_note) XX(elf_header_entry_sizes) XX(elf_metadata_section) +XX(elf_offset) XX(elf_rejects_non_regular_files) XX(embedded_info_basic) XX(embedded_info_build_id) @@ -246,6 +275,7 @@ XX(invalid_dsn) XX(invalid_proxy) XX(is_enabled) XX(iso_time) +XX(iter_trace_propagation_headers) XX(lazy_attachments) XX(logger_enable_disable_functionality) XX(logger_level) @@ -304,6 +334,8 @@ XX(mpack_newlines) XX(mpack_removed_tags) XX(multiple_inits) XX(multiple_transactions) +XX(native_scope_updates) +XX(native_stall) XX(old_run_retry) XX(on_crashed_last_run) XX(on_crashed_last_run_cache) @@ -311,6 +343,7 @@ XX(options_attach_stacktrace) XX(options_crash_reporting_mode_clamp) XX(options_crash_reporting_mode_default) XX(options_crash_reporting_mode_set_get) +XX(options_global_lifetime) XX(options_initial_scope_before_backend_startup) XX(options_initial_scope_replace) XX(options_initial_scope_rollback_after_startup_failure) @@ -320,10 +353,12 @@ XX(options_sample_rate) XX(options_sdk_name_custom) XX(options_sdk_name_defaults) XX(options_sdk_name_invalid) +XX(options_shutdown_timeout) XX(options_thread_stackwalk_mode_clamp) XX(options_thread_stackwalk_mode_default) XX(options_thread_stackwalk_mode_set_get) XX(os) +XX(os_release_named_distributions) XX(os_release_non_existent_files) XX(os_releases_snapshot) XX(overflow_spans) @@ -395,11 +430,14 @@ XX(sampling_before_send) XX(sampling_crash_handler) XX(sampling_decision) XX(sampling_transaction) +XX(scope_access_multiple) +XX(scope_access_pool) XX(scope_attachments) XX(scope_bind_span) XX(scope_bind_span_or_transaction_not_both) XX(scope_bind_transaction_object) XX(scope_breadcrumbs) +XX(scope_capture_dsc) XX(scope_capture_log_attributes) XX(scope_capture_log_one_shot) XX(scope_capture_log_trace_id) @@ -417,11 +455,24 @@ XX(scope_clone_keeps_bound_span) XX(scope_clone_preserves_data) XX(scope_clone_shares_span) XX(scope_contexts) +XX(scope_continue_trace) +XX(scope_defaults) XX(scope_environment) XX(scope_extra) XX(scope_fingerprint) XX(scope_fingerprint_n) XX(scope_global_attributes) +XX(scope_global_before_init) +XX(scope_global_immutable) +XX(scope_global_reset) +XX(scope_inheritance_attributes) +XX(scope_inheritance_contexts) +XX(scope_inheritance_extra) +XX(scope_inheritance_propagation_context) +XX(scope_inheritance_tags) +XX(scope_isolation_reset) +XX(scope_isolation_shared) +XX(scope_iter_trace_propagation_headers) XX(scope_last_event_id) XX(scope_level) XX(scope_local_attributes) @@ -433,28 +484,39 @@ XX(scope_observer_deferred_flush) XX(scope_observer_environment) XX(scope_observer_extras) XX(scope_observer_fingerprint) +XX(scope_observer_init) +XX(scope_observer_init_failure) XX(scope_observer_level) XX(scope_observer_multiple) XX(scope_observer_mutate) XX(scope_observer_null) XX(scope_observer_release) XX(scope_observer_tags) +XX(scope_observer_trace_serialized) XX(scope_observer_transaction) XX(scope_observer_user) XX(scope_ownership) +XX(scope_parent_lifetime) +XX(scope_parent_lock) XX(scope_propagation_context) +XX(scope_read_blocks_write) +XX(scope_read_shared) XX(scope_rebind_same_object) XX(scope_release) XX(scope_remove_fingerprint_capture) XX(scope_restore_trace) +XX(scope_sdk_inheritance) XX(scope_set_attribute_invalid_decref_value) XX(scope_set_attribute_null_key_decref_value) +XX(scope_set_trace) XX(scope_tags) XX(scope_tags_flush) XX(scope_transaction) XX(scope_update_context) XX(scope_user) XX(scope_user_id) +XX(scope_write_exclusive) +XX(scope_write_nested) XX(scoped_txn) XX(sentry__value_span_new_requires_unfinished_parent) XX(serialize_envelope) @@ -469,9 +531,11 @@ XX(set_trace) XX(set_trace_id_before_scoped_txn) XX(set_trace_id_twice) XX(set_trace_id_with_txn) +XX(set_trace_on_init) XX(set_trace_rebuilds_dsc_sample_rand) XX(set_trace_update_from_header) XX(set_trace_without_parent) +XX(sigaltstack) XX(slice) XX(slice_consume_uint64) XX(span_data) @@ -510,13 +574,16 @@ XX(traceparent_header_disabled_by_default) XX(traceparent_header_generation) XX(transaction_name_backfill_on_finish) XX(transactions_skip_before_send) +XX(transport_dump_failed) XX(transport_retry) XX(transport_sampling_transactions) XX(transport_sampling_transactions_set_trace) XX(transport_suspend) XX(tus_attachment_ref_confinement) +XX(tus_chunk_size) XX(tus_file_attachment_preserves_original) XX(tus_placeholder_uses_raw_location) +XX(tus_rate_limit) XX(tus_request_preparation) XX(tus_upload_error) XX(tus_upload_url) @@ -542,8 +609,6 @@ XX(url_parsing_no_path) XX(url_parsing_partial) XX(url_parsing_with_path) XX(user_feedback_is_valid) -XX(user_feedback_with_null_args) -XX(user_report_is_valid) XX(uuid_api) XX(uuid_is_valid) XX(uuid_v4) diff --git a/tests/win_utils.py b/tests/win_utils.py index 4deb85617c..571f4d553f 100644 --- a/tests/win_utils.py +++ b/tests/win_utils.py @@ -1,7 +1,7 @@ import pathlib import win32api -from tests import SENTRY_VERSION +from tests import SENTRY_VERSION_BASE def check_binary_version(binary_path: pathlib.Path): @@ -13,7 +13,7 @@ def check_binary_version(binary_path: pathlib.Path): ls = info["FileVersionLS"] file_version = (ms >> 16, ms & 0xFFFF, ls >> 16, ls & 0xFFFF) file_version = f"{file_version[0]}.{file_version[1]}.{file_version[2]}" - if SENTRY_VERSION != file_version: + if SENTRY_VERSION_BASE != file_version: raise RuntimeError( - f"Binary {binary_path.parts[-1]} has a different version ({file_version}) than expected ({SENTRY_VERSION})." + f"Binary {binary_path.parts[-1]} has a different version ({file_version}) than expected ({SENTRY_VERSION_BASE})." ) diff --git a/vendor/libunwind/CMakeLists.txt b/vendor/libunwind/CMakeLists.txt index 6b46e7c9e1..dfc8b32591 100644 --- a/vendor/libunwind/CMakeLists.txt +++ b/vendor/libunwind/CMakeLists.txt @@ -1,4 +1,4 @@ -# CMakeLists.txt for vendored libunwind (Linux only; x86_64, aarch64, x86, arm) +# CMakeLists.txt for vendored libunwind (Linux only; x86_64, aarch64, x86, arm, riscv64) # Builds the local unwinding library (libunwind.a equivalent). # When LIBUNWIND_BUILD_REMOTE is set, also builds unwind_remote with # generic (G-prefix) sources and ptrace accessors for remote unwinding. @@ -23,6 +23,8 @@ if(_UNWIND_PROCESSOR MATCHES "^(x86_64|amd64|x64|i[3-6]86|x86)$") elseif(_UNWIND_PROCESSOR MATCHES "^(aarch64|arm64|arm)") set(_UNWIND_ARCH_32 "arm") set(_UNWIND_ARCH_64 "aarch64") +elseif(_UNWIND_PROCESSOR STREQUAL "riscv64") + set(_UNWIND_ARCH_64 "riscv") else() message(FATAL_ERROR "Unsupported architecture for vendored libunwind: ${CMAKE_SYSTEM_PROCESSOR}") endif() @@ -193,6 +195,26 @@ elseif(UNWIND_ARCH STREQUAL "arm") ${LIBUNWIND_SRC}/arm/Lstep.c ${LIBUNWIND_SRC}/arm/Ltrace.c ) +elseif(UNWIND_ARCH STREQUAL "riscv") + set(UNWIND_ARCH_SOURCES + ${LIBUNWIND_SRC}/riscv/is_fpreg.c + ${LIBUNWIND_SRC}/riscv/regname.c + ${LIBUNWIND_SRC}/riscv/getcontext.S + ${LIBUNWIND_SRC}/riscv/Lapply_reg_state.c + ${LIBUNWIND_SRC}/riscv/Lcreate_addr_space.c + ${LIBUNWIND_SRC}/riscv/Lget_proc_info.c + ${LIBUNWIND_SRC}/riscv/Lget_save_loc.c + ${LIBUNWIND_SRC}/riscv/Lglobal.c + ${LIBUNWIND_SRC}/riscv/Linit.c + ${LIBUNWIND_SRC}/riscv/Linit_local.c + ${LIBUNWIND_SRC}/riscv/Linit_remote.c + ${LIBUNWIND_SRC}/riscv/Lis_signal_frame.c + ${LIBUNWIND_SRC}/riscv/Lregs.c + ${LIBUNWIND_SRC}/riscv/Lreg_states_iterate.c + ${LIBUNWIND_SRC}/riscv/Lresume.c + ${LIBUNWIND_SRC}/riscv/Lstep.c + ${LIBUNWIND_SRC}/riscv/setcontext.S + ) endif() add_library(unwind STATIC @@ -291,6 +313,9 @@ elseif(UNWIND_ARCH STREQUAL "x86") elseif(UNWIND_ARCH STREQUAL "arm") target_include_directories(unwind PRIVATE ${LIBUNWIND_INC}/tdep-arm) target_compile_definitions(unwind PRIVATE UNW_TARGET_ARM=1) +elseif(UNWIND_ARCH STREQUAL "riscv") + target_include_directories(unwind PRIVATE ${LIBUNWIND_INC}/tdep-riscv) + target_compile_definitions(unwind PRIVATE UNW_TARGET_RISCV=1) endif() target_compile_definitions(unwind PRIVATE @@ -419,6 +444,22 @@ elseif(UNWIND_ARCH STREQUAL "arm") ${LIBUNWIND_SRC}/arm/Gstep.c ${LIBUNWIND_SRC}/arm/Gtrace.c ) +elseif(UNWIND_ARCH STREQUAL "riscv") + set(UNWIND_GENERIC_ARCH_SOURCES + ${LIBUNWIND_SRC}/riscv/Gapply_reg_state.c + ${LIBUNWIND_SRC}/riscv/Gcreate_addr_space.c + ${LIBUNWIND_SRC}/riscv/Gget_proc_info.c + ${LIBUNWIND_SRC}/riscv/Gget_save_loc.c + ${LIBUNWIND_SRC}/riscv/Gglobal.c + ${LIBUNWIND_SRC}/riscv/Ginit.c + ${LIBUNWIND_SRC}/riscv/Ginit_local.c + ${LIBUNWIND_SRC}/riscv/Ginit_remote.c + ${LIBUNWIND_SRC}/riscv/Gis_signal_frame.c + ${LIBUNWIND_SRC}/riscv/Gregs.c + ${LIBUNWIND_SRC}/riscv/Greg_states_iterate.c + ${LIBUNWIND_SRC}/riscv/Gresume.c + ${LIBUNWIND_SRC}/riscv/Gstep.c + ) endif() # Ptrace accessor library (_UPT_* functions for remote unwinding via ptrace) @@ -475,6 +516,9 @@ elseif(UNWIND_ARCH STREQUAL "x86") elseif(UNWIND_ARCH STREQUAL "arm") target_include_directories(unwind_remote PRIVATE ${LIBUNWIND_INC}/tdep-arm) target_compile_definitions(unwind_remote PRIVATE UNW_TARGET_ARM=1) +elseif(UNWIND_ARCH STREQUAL "riscv") + target_include_directories(unwind_remote PRIVATE ${LIBUNWIND_INC}/tdep-riscv) + target_compile_definitions(unwind_remote PRIVATE UNW_TARGET_RISCV=1) endif() target_compile_definitions(unwind_remote PRIVATE diff --git a/vendor/libunwind/VENDORING.md b/vendor/libunwind/VENDORING.md index 4b1960eb9e..970d9e3371 100644 --- a/vendor/libunwind/VENDORING.md +++ b/vendor/libunwind/VENDORING.md @@ -30,6 +30,7 @@ Two CMake targets are provided: | x86 (i686, 32-bit) | `src/x86/` | `include/tdep-x86/` | | aarch64 | `src/aarch64/` | `include/tdep-aarch64/` | | arm (32-bit) | `src/arm/` | `include/tdep-arm/` | +| riscv | `src/riscv/` | `include/tdep-riscv/` | Core shared code: `src/mi/`, `src/dwarf/`, `src/os-linux.c`, `src/dl-iterate-phdr.c`. @@ -91,7 +92,6 @@ custom `CMakeLists.txt`: | Path | Notes | |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------| -| `src/riscv/`, `include/tdep-riscv/` | RISC-V — kept for potential future use | | `src/unwind/`, `src/mi/_ReadULEB.c`, `src/mi/_ReadSLEB.c` | C++ exception ABI conflicts with `libgcc_eh.a`; see [above](#excluded-c-exception-abi-sources) | | `include/libunwind-*.h` for removed arches | Referenced via `#ifdef` in `include/libunwind.h` — harmless dead code | | Autotools artifacts (`configure`, `configure.ac`, `Makefile.am`, `Makefile.in`, `aclocal.m4`, `INSTALL`) | Carried over from the release tarball. Not used by CMake, but `configure.ac` and `Makefile.am` are useful as reference for the build logic | @@ -115,7 +115,7 @@ never calls into the C++ exception ABI. | File | Purpose | |-------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------| -| `CMakeLists.txt` | Custom CMake build that replaces the upstream autotools + upstream CMake build. Builds a static `unwind` target for x86, x86_64, and aarch64 only | +| `CMakeLists.txt` | Custom CMake build that replaces the upstream autotools + upstream CMake build. Builds static `unwind` and `unwind_remote` targets | | `cmake/config.h.cmake.in` | CMake template for `config.h` (replaces autotools `configure`-generated header) | | `cmake/libunwind-common.h.cmake.in` | CMake template for `libunwind-common.h` | | `VENDORING.md` | This file | @@ -171,7 +171,8 @@ both GCC and Clang. `__attribute__((aligned(...)))`. - Scan for other C11/C23 constructs incompatible with C99. -7. Build and test on all four architectures: x86_64, x86 (32-bit), aarch64, arm (32-bit). +7. Build and test on all supported architectures: x86_64, x86 (32-bit), aarch64, + arm (32-bit), and riscv. 8. To add a **new architecture**, also: - Keep its `src//` and `include/tdep-/` directories from the diff --git a/vendor/stb_sprintf.c b/vendor/stb_sprintf.c index d60a91bae9..6cbd0f5ec1 100644 --- a/vendor/stb_sprintf.c +++ b/vendor/stb_sprintf.c @@ -1,2 +1,5 @@ +#include + +#define stbsp__uintptr uintptr_t #define STB_SPRINTF_IMPLEMENTATION #include "stb_sprintf.h" diff --git a/warden.toml b/warden.toml index 4277c98667..76f1350882 100644 --- a/warden.toml +++ b/warden.toml @@ -24,7 +24,6 @@ name = "native-code-review" paths = ["src/**", "include/**", "ndk/lib/src/main/jni/**"] ignorePaths = ["**/*.md", "src/CMakeLists.txt", "src/exports.map"] incremental = true -maxTurns = 30 [[skills.triggers]] type = "pull_request" @@ -52,7 +51,6 @@ paths = [ ] ignorePaths = ["**/*.md", "external/**", "vendor/**", ".github/ISSUE_TEMPLATE/**"] incremental = true -maxTurns = 30 [[skills.triggers]] type = "pull_request" @@ -72,7 +70,6 @@ ignorePaths = [ "tests/fixtures/*.so", ] incremental = true -maxTurns = 30 [[skills.triggers]] type = "pull_request"