Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
signalapp
GitHub Repository: signalapp/Signal-iOS
Path: blob/main/SignalServiceKit/Concurrency/Threading.m
1 views
1
//
2
// Copyright 2024 Signal Messenger, LLC
3
// SPDX-License-Identifier: AGPL-3.0-only
4
//
5
6
#import "Threading.h"
7
#import <SignalServiceKit/SignalServiceKit-Swift.h>
8
#import <pthread.h>
9
10
NS_ASSUME_NONNULL_BEGIN
11
12
BOOL DispatchQueueIsCurrentQueue(dispatch_queue_t testQueue)
13
{
14
#pragma clang diagnostic push
15
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
16
void *currentQueuePtr = (__bridge void *)dispatch_get_current_queue();
17
#pragma clang diagnostic pop
18
return (currentQueuePtr == (__bridge void *)testQueue);
19
}
20
21
double _CurrentStackUsage(void)
22
{
23
#if TARGET_CPU_X86 || TARGET_CPU_X86_64 || TARGET_CPU_ARM || TARGET_CPU_ARM64
24
pthread_t _Nullable currentThread = pthread_self();
25
if (!currentThread) {
26
OWSCFailDebug(@"No current thread");
27
return NAN;
28
}
29
30
size_t stackSize = pthread_get_stacksize_np(currentThread);
31
void *baseAddr = pthread_get_stackaddr_np(currentThread);
32
33
// In all of our supported platforms, the stack grows towards down towards 0.
34
// The local var address should always be less than our stack base.
35
ptrdiff_t usedBytes = baseAddr - ((void *)&baseAddr);
36
37
if (stackSize > 0 && baseAddr > 0 && usedBytes > 0 && (size_t)usedBytes < stackSize) {
38
double result = ((double)usedBytes / (double)stackSize);
39
return MAX(0.0, MIN(result, 1.0));
40
} else {
41
OWSCFailDebug(@"Unexpected stack format");
42
return NAN;
43
}
44
#else /* !x86(_64) && !arm(64) */
45
#error Double check this implementation to ensure it works for the platform
46
return NAN;
47
#endif
48
}
49
50
NS_ASSUME_NONNULL_END
51
52