Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/file-filters.yml
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,9 @@ run_thread_inspection_harness_for_prs:
- ".github/workflows/run-full-ci-workflow.yml"
- "Sources/Sentry/SentryThreadSnapshot.c"
- "Sources/Sentry/SentryThreadSnapshotKSCrash.c"
- "Sources/SentryNativeUtils/SentryThreadSuspension.c"
- "Sources/Sentry/include/SentryThreadSnapshot.h"
- "Sources/SentryNativeUtils/include/SentryThreadSuspension.h"
- "Tests/ThreadInspectionHarness/**"

# GH Actions
Expand Down
9 changes: 6 additions & 3 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -167,10 +167,13 @@ let sentryPrivateDependencies: [Target.Dependency] = [
]

targets += [
// Shared Objective-C++ utilities only. No Swift sources or Swift target dependencies.
// Shared native utilities. No Swift sources or Swift target dependencies.
.target(
name: "SentryNativeUtils",
publicHeadersPath: "include"
publicHeadersPath: "include",
cSettings: cSettings,
cxxSettings: cxxSettings,
linkerSettings: [.linkedLibrary("c++")]
),
.target(
name: "SentryProfiling",
Expand All @@ -180,7 +183,7 @@ targets += [
// At least one source file is required, therefore we use a dummy class to satisfy the SPM build system
.target(
name: "SentryHeaders",
dependencies: envSelectsV10 ? ["_SentryV10Configuration"] : [],
dependencies: envSelectsV10 ? ["_SentryV10Configuration", "SentryNativeUtils"] : ["SentryNativeUtils"],
path: "Sources/Sentry",
sources: ["SentryDummyPublicEmptyClass.m"],
publicHeadersPath: "Public",
Expand Down
9 changes: 6 additions & 3 deletions Package@swift-6.1.swift
Original file line number Diff line number Diff line change
Expand Up @@ -174,10 +174,13 @@ let sentryObjCInternalCSettings: [CSetting] = [
let sentryPrivateDependencies: [Target.Dependency] = ["SentryHeaders"] + kscrashDependencies

targets += [
// Shared Objective-C++ utilities only. No Swift sources or Swift target dependencies.
// Shared native utilities. No Swift sources or Swift target dependencies.
.target(
name: "SentryNativeUtils",
publicHeadersPath: "include"
publicHeadersPath: "include",
cSettings: cSettings,
cxxSettings: cxxSettings,
linkerSettings: [.linkedLibrary("c++")]
),
.target(
name: "SentryProfiling",
Expand All @@ -187,7 +190,7 @@ targets += [
// At least one source file is required, therefore we use a dummy class to satisfy the SPM build system
.target(
name: "SentryHeaders",
dependencies: envSelectsV10 ? [.target(name: "_SentryV10Configuration")] : [],
dependencies: envSelectsV10 ? ["_SentryV10Configuration", "SentryNativeUtils"] : ["SentryNativeUtils"],
path: "Sources/Sentry",
sources: ["SentryDummyPublicEmptyClass.m"],
publicHeadersPath: "Public",
Expand Down
9 changes: 6 additions & 3 deletions Package@swift-6.2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -170,10 +170,13 @@ let sentryObjCInternalCSettings: [CSetting] = [
let sentryPrivateDependencies: [Target.Dependency] = ["SentryHeaders"] + kscrashDependencies

targets += [
// Shared Objective-C++ utilities only. No Swift sources or Swift target dependencies.
// Shared native utilities. No Swift sources or Swift target dependencies.
.target(
name: "SentryNativeUtils",
publicHeadersPath: "include"
publicHeadersPath: "include",
cSettings: cSettings,
cxxSettings: cxxSettings,
linkerSettings: [.linkedLibrary("c++")]
),
.target(
name: "SentryProfiling",
Expand All @@ -183,7 +186,7 @@ targets += [
// At least one source file is required, therefore we use a dummy class to satisfy the SPM build system
.target(
name: "SentryHeaders",
dependencies: envSelectsV10 ? [.target(name: "_SentryV10Configuration")] : [],
dependencies: envSelectsV10 ? ["_SentryV10Configuration", "SentryNativeUtils"] : ["SentryNativeUtils"],
path: "Sources/Sentry",
sources: ["SentryDummyPublicEmptyClass.m"],
publicHeadersPath: "Public",
Expand Down
47 changes: 32 additions & 15 deletions Sentry.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions Sources/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@
- Use compile-time gates for code that cannot compile or link on a target, not for ordinary runtime behavior
- In Swift, use `os(...)`, `targetEnvironment(...)`, and `canImport(...)` for platform and module capabilities
- Gate UI code by both supported platforms and `!SENTRY_NO_UI_FRAMEWORK`
- In Objective-C and C/C++, prefer capability macros from [`SentryDefines.h`](Sentry/Public/SentryDefines.h) and [`SentryProfilingConditionals.h`](Sentry/Public/SentryProfilingConditionals.h), including `SENTRY_HAS_UIKIT`, `SENTRY_TARGET_REPLAY_SUPPORTED`, and `SENTRY_TARGET_PROFILING_SUPPORTED`
- In Objective-C and C/C++, prefer capability macros from [`SentryDefines.h`](Sentry/Public/SentryDefines.h) and [`SentryProfilingConditionals.h`](SentryNativeUtils/include/SentryProfilingConditionals.h), including `SENTRY_HAS_UIKIT`, `SENTRY_TARGET_REPLAY_SUPPORTED`, and `SENTRY_TARGET_PROFILING_SUPPORTED`
- Keep Swift, Objective-C, and `SentryObjC` declaration and implementation gates aligned
- Preserve older Xcode compatibility with `#if swift(>=...)`, compiler feature probes from [`SentryCompiler.h`](Sentry/include/SentryCompiler.h), and `canImport` or `__has_include` checks
- Preserve older Xcode compatibility with `#if swift(>=...)`, compiler feature probes from [`SentryCompiler.h`](SentryNativeUtils/include/SentryCompiler.h), and `canImport` or `__has_include` checks
- Use `#available` or `@available` for runtime OS availability only after the code can compile with the oldest supported Xcode
- When newer SDK symbols are absent from older Xcode headers, combine runtime availability with a compile-time gate or dynamic lookup instead of referencing the symbol directly

Expand Down
9 changes: 5 additions & 4 deletions Sources/Configuration/Sentry.xcconfig
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@
SENTRY_SDK_MACH_O_TYPE = mh_dylib
MACH_O_TYPE = $(SENTRY_SDK_MACH_O_TYPE)

// Retain the existing C exports on platforms without internal callers, such as watchOS.
SENTRY_NATIVE_UTILS_EXPORTS_mh_dylib = -u _timeIntervalToNanoseconds
OTHER_LDFLAGS = $(inherited) $(SENTRY_NATIVE_UTILS_EXPORTS_$(MACH_O_TYPE))

INFOPLIST_FILE = Sources/Resources/Info.plist

SENTRY_MODULE_NAME = Sentry
Expand Down Expand Up @@ -38,6 +34,11 @@ LD_DYLIB_INSTALL_NAME = $(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_
LD_RUNPATH_SEARCH_PATHS = $(inherited) @executable_path/Frameworks @loader_path/Frameworks
USE_HEADERMAP = YES

// Keep shared C entry points exported even on platforms where the SDK has no internal caller.
// Do not force-load the archive: Xcode also places static package dependencies in it.
SENTRY_NATIVE_UTILS_EXPORTS_mh_dylib = -u _sentry_asyncLogC -u _sentryThreadSuspensionTryAcquire -u _timeIntervalToNanoseconds
OTHER_LDFLAGS = $(inherited) $(SENTRY_NATIVE_UTILS_EXPORTS_$(MACH_O_TYPE))

CODE_SIGN_STYLE = Manual
DEVELOPMENT_TEAM =
CODE_SIGN_IDENTITY =
Expand Down
3 changes: 2 additions & 1 deletion Sources/Configuration/SentryNativeUtils.xcconfig
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Native utilities are implemented in Objective-C++ (.mm), never Swift.
// Shared native utilities contain no Swift sources.
// Keep this target independent of Swift targets and the SDK implementation.
#include "DeploymentTargets.xcconfig"

Expand All @@ -12,6 +12,7 @@ SUPPORTS_MACCATALYST = YES
ARCHS = $(ARCHS_STANDARD) arm64e
ARCHS[sdk=*simulator] = $(ARCHS_STANDARD)
SKIP_INSTALL = YES
GCC_C_LANGUAGE_STANDARD = gnu11
HEADER_SEARCH_PATHS = $(SRCROOT)/Sources/SentryNativeUtils/include $(SRCROOT)/Sources/SentryNativeUtils/include
MODULEMAP_FILE = $(SRCROOT)/Sources/SentryNativeUtils/include/module.modulemap
OTHER_LDFLAGS =
Expand Down
5 changes: 5 additions & 0 deletions Sources/Sentry/Profiling/SentryProfilerSDKAdapter.mm
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ - (SentryProfilingDebugImageSerialization _Nullable)debugImageSerialization
return [self.target debugImageSerialization];
}

- (SentryProfilingMemoryReader)memoryReader
{
return [self.target memoryReader];
}

- (SentryProfilingSystemMetrics *_Nullable)systemMetrics
{
return [self.target systemMetrics];
Expand Down
14 changes: 0 additions & 14 deletions Sources/Sentry/Profiling/SentryProfilerTestHelpers.m
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,6 @@
# import "SentryInternalDefines.h"
# import "SentrySerialization.h"

BOOL
sentry_threadSanitizerIsPresent(void)
{
# if defined(__has_feature)
# if __has_feature(thread_sanitizer)
return YES;
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunreachable-code"
# endif // __has_feature(thread_sanitizer)
# endif // defined(__has_feature)

return NO;
}

# if defined(DEBUG) || defined(SENTRY_UI_TEST_SUPPORT) // Test support.

void
Expand Down
17 changes: 17 additions & 0 deletions Sources/Sentry/Profiling/SentryProfilingRuntime.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#import "SentryProfilingRuntime.h"

#if SENTRY_TARGET_PROFILING_SUPPORTED

# import "SentryCompiler.h"

BOOL
sentry_threadSanitizerIsPresent(void)
{
# if COMPILER_HAS_CLANG_FEATURE(thread_sanitizer)
return YES;
# else
return NO;
# endif
}

#endif // SENTRY_TARGET_PROFILING_SUPPORTED
13 changes: 6 additions & 7 deletions Sources/Sentry/SentryBacktrace.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@
# include "SentryAsyncSafeLog.h"
# include "SentryCompiler.h"
# include "SentryMachLogging.hpp"
# include "SentryMemory.h"
# include "SentryStackBounds.hpp"
# include "SentryStackFrame.hpp"
# include "SentryThreadHandle.hpp"
# include "SentryThreadMetadataCache.hpp"
# include "SentryThreadSnapshot.h"
# include "SentryThreadState.hpp"
# include "SentryThreadSuspension.h"
# include "SentryTime.h"
# include <cassert>
# include <cstring>
Expand Down Expand Up @@ -63,7 +62,7 @@ namespace profiling {
NOT_TAIL_CALLED NEVER_INLINE std::size_t
backtrace(const ThreadHandle &targetThread, const ThreadHandle &callingThread,
std::uintptr_t *addresses, const StackBounds &bounds, bool *reachedEndOfStackPtr,
std::size_t maxDepth, std::size_t skip) noexcept
std::size_t maxDepth, SentryProfilingMemoryReader memoryReader, std::size_t skip) noexcept
{
assert(addresses != nullptr);
if (UNLIKELY(maxDepth == 0 || !bounds.isValid())) {
Expand Down Expand Up @@ -109,7 +108,7 @@ namespace profiling {
bool reachedEndOfStack = false;
while (depth < maxDepth) {
const auto frame = reinterpret_cast<StackFrame *>(current);
if (!sentryMemoryIsReadable(frame, sizeof(StackFrame))) {
if (!memoryReader(frame, sizeof(StackFrame))) {
break;
}
if (LIKELY(skip == 0)) {
Expand All @@ -133,8 +132,8 @@ namespace profiling {
}

void
enumerateBacktracesForAllThreads(
const std::function<void(const Backtrace &)> &f, ThreadMetadataCache *cache)
enumerateBacktracesForAllThreads(const std::function<void(const Backtrace &)> &f,
ThreadMetadataCache *cache, SentryProfilingMemoryReader memoryReader)
{
const auto pair = ThreadHandle::allExcludingCurrent();
for (const auto &thread : pair.first) {
Expand Down Expand Up @@ -189,7 +188,7 @@ namespace profiling {
}

depth = backtrace(*thread, *pair.second, addresses, stackBounds, &reachedEndOfStack,
kMaxBacktraceDepth, 0);
kMaxBacktraceDepth, memoryReader, 0);

thread->resume();
}
Expand Down
6 changes: 6 additions & 0 deletions Sources/Sentry/SentryDefaultProfilerSDKBackend.m
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#import "SentryInternalDefines.h"
#import "SentryInternalSerializable.h"
#import "SentryLogC.h"
#import "SentryMemory.h"
#import "SentryProfilerCancellation.h"
#import "SentryProfilerConfigurationBridge.h"
#import "SentryProfilerDeliveryBridge.h"
Expand Down Expand Up @@ -52,6 +53,11 @@ @implementation SentryDefaultProfilerSDKBackend {
SentrySystemWrapper *_systemWrapper;
SentrySDKProfilingLogger *_profilingLogger;
}
- (SentryProfilingMemoryReader)memoryReader
{
return sentryMemoryIsReadable;
}

- (void)activate
{
_profilingLogger = [[SentrySDKProfilingLogger alloc] init];
Expand Down
15 changes: 7 additions & 8 deletions Sources/Sentry/SentryProfiler.mm
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
# import "SentryMetricProfiler.h"
# import "SentryProfilerSDKAdapter.h"
# import "SentryProfilerState+ObjCpp.h"
# import "SentryProfilerTestHelpers.h"
# import "SentryProfilingLog.h"
# import "SentryProfilingRuntime.h"
# import "SentrySamplingProfiler.hpp"
# import "SentryTime.h"

Expand Down Expand Up @@ -116,12 +116,11 @@ - (void)start
return;
}

// Pop the clang diagnostic to ignore unreachable code for TSAN runs
# if defined(__has_feature)
# if __has_feature(thread_sanitizer)
# pragma clang diagnostic pop
# endif // __has_feature(thread_sanitizer)
# endif // defined(__has_feature)
SentryProfilingMemoryReader memoryReader = [SentryProfilerSDKAdapter.shared memoryReader];
if (memoryReader == nullptr) {
SENTRY_PROFILING_LOG_WARN(@"Cannot start profiling without a memory reader.");
return;
}

SENTRY_PROFILING_LOG_DEBUG(@"Starting profiler.");

Expand All @@ -135,7 +134,7 @@ - (void)start
[state appendBacktrace:backtraceCopy];
}
},
kSentryProfilerFrequencyHz);
kSentryProfilerFrequencyHz, memoryReader);
_samplingProfiler->startSampling();
}

Expand Down
11 changes: 7 additions & 4 deletions Sources/Sentry/SentrySamplingProfiler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ namespace profiling {
mach_timespec_t delaySpec;
ThreadMetadataCache *cache;
std::function<void(const Backtrace &)> callback;
SentryProfilingMemoryReader memoryReader;
std::atomic_uint64_t &numSamples;
std::function<void()> onThreadStart;
};
Expand Down Expand Up @@ -65,7 +66,8 @@ namespace profiling {
}

params->numSamples.fetch_add(1, std::memory_order_relaxed);
enumerateBacktracesForAllThreads(params->callback, params->cache);
enumerateBacktracesForAllThreads(
params->callback, params->cache, params->memoryReader);
}
pthread_cleanup_pop(1);
pthread_cleanup_pop(1);
Expand All @@ -74,9 +76,10 @@ namespace profiling {

} // namespace

SamplingProfiler::SamplingProfiler(
std::function<void(const Backtrace &)> callback, std::uint32_t samplingRateHz)
SamplingProfiler::SamplingProfiler(std::function<void(const Backtrace &)> callback,
std::uint32_t samplingRateHz, SentryProfilingMemoryReader memoryReader)
: callback_(std::move(callback))
, memoryReader_(memoryReader)
, cache_(std::make_unique<ThreadMetadataCache>())
, isInitialized_(false)
, isSampling_(false)
Expand Down Expand Up @@ -140,7 +143,7 @@ namespace profiling {
}

const auto params = new SamplingThreadParams { port_, clock_, delaySpec_, cache_.get(),
callback_, std::ref(numSamples_), std::move(onThreadStart) };
callback_, memoryReader_, std::ref(numSamples_), std::move(onThreadStart) };
if (SENTRY_ASYNC_SAFE_LOG_ERRNO_RETURN(
pthread_create(&thread_, &attr, samplingThreadMain, params))
!= 0) {
Expand Down
19 changes: 0 additions & 19 deletions Sources/Sentry/SentryThreadSnapshot.c
Original file line number Diff line number Diff line change
@@ -1,23 +1,4 @@
#include "SentryThreadSnapshot.h"
#include <stdatomic.h>

// Coordinates the SDK's nonfatal bulk-inspection and profiler suspension paths. atomic_flag is
// guaranteed lock-free, so a contender can yield without waiting on an owner that may have
// suspended its thread.
static atomic_flag g_threadSuspensionAdmission = ATOMIC_FLAG_INIT;

bool
sentryThreadSuspensionTryAcquire(void)
{
return !atomic_flag_test_and_set_explicit(&g_threadSuspensionAdmission, memory_order_acquire);
}

void
sentryThreadSuspensionRelease(void)
{
atomic_flag_clear_explicit(&g_threadSuspensionAdmission, memory_order_release);
}

#include <string.h>

bool
Expand Down
10 changes: 7 additions & 3 deletions Sources/Sentry/include/SentryBacktrace.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

#if SENTRY_TARGET_PROFILING_SUPPORTED

# include "SentryProfilingMemory.h"
# include "SentryStackBounds.hpp"
# include "SentryThreadHandle.hpp"
# include "SentryThreadMetadataCache.hpp"
Expand Down Expand Up @@ -38,14 +39,16 @@ namespace profiling {
* additional frames that were not recorded because the `maxDepth` was too small.
* @param maxDepth The maximum number of addresses to collect, this should
* be less than or equal to the size of the buffer.
* @param memoryReader The async-safe C function used to validate each frame before reading it.
* @param skip An optional number of stack frames to skip at the beginning.
*
* @return The actual number of addresses collected. Returns 0 if a backtrace
* could not be collected.
*/
NOT_TAIL_CALLED NEVER_INLINE std::size_t backtrace(const ThreadHandle &targetThread,
const ThreadHandle &callingThread, std::uintptr_t *addresses, const StackBounds &bounds,
bool *reachedEndOfStackPtr, std::size_t maxDepth, std::size_t skip = 0) noexcept;
bool *reachedEndOfStackPtr, std::size_t maxDepth, SentryProfilingMemoryReader memoryReader,
std::size_t skip = 0) noexcept;

/**
* Attempts to collect backtraces for every thread in the process, except the
Expand All @@ -56,9 +59,10 @@ namespace profiling {
*
* @param f The function to call for each entry.
* @param cache The cache used to look up thread metadata.
* @param memoryReader The async-safe C function used to validate sampled memory.
*/
void enumerateBacktracesForAllThreads(
const std::function<void(const Backtrace &)> &f, ThreadMetadataCache *cache);
void enumerateBacktracesForAllThreads(const std::function<void(const Backtrace &)> &f,
ThreadMetadataCache *cache, SentryProfilingMemoryReader memoryReader);

} // namespace profiling
} // namespace sentry
Expand Down
Loading
Loading