Path: blob/main/SignalServiceKit/Concurrency/Threading.m
1 views
//1// Copyright 2024 Signal Messenger, LLC2// SPDX-License-Identifier: AGPL-3.0-only3//45#import "Threading.h"6#import <SignalServiceKit/SignalServiceKit-Swift.h>7#import <pthread.h>89NS_ASSUME_NONNULL_BEGIN1011BOOL DispatchQueueIsCurrentQueue(dispatch_queue_t testQueue)12{13#pragma clang diagnostic push14#pragma clang diagnostic ignored "-Wdeprecated-declarations"15void *currentQueuePtr = (__bridge void *)dispatch_get_current_queue();16#pragma clang diagnostic pop17return (currentQueuePtr == (__bridge void *)testQueue);18}1920double _CurrentStackUsage(void)21{22#if TARGET_CPU_X86 || TARGET_CPU_X86_64 || TARGET_CPU_ARM || TARGET_CPU_ARM6423pthread_t _Nullable currentThread = pthread_self();24if (!currentThread) {25OWSCFailDebug(@"No current thread");26return NAN;27}2829size_t stackSize = pthread_get_stacksize_np(currentThread);30void *baseAddr = pthread_get_stackaddr_np(currentThread);3132// In all of our supported platforms, the stack grows towards down towards 0.33// The local var address should always be less than our stack base.34ptrdiff_t usedBytes = baseAddr - ((void *)&baseAddr);3536if (stackSize > 0 && baseAddr > 0 && usedBytes > 0 && (size_t)usedBytes < stackSize) {37double result = ((double)usedBytes / (double)stackSize);38return MAX(0.0, MIN(result, 1.0));39} else {40OWSCFailDebug(@"Unexpected stack format");41return NAN;42}43#else /* !x86(_64) && !arm(64) */44#error Double check this implementation to ensure it works for the platform45return NAN;46#endif47}4849NS_ASSUME_NONNULL_END505152