Explore the core architecture of the operating system, including the kernel, memory management, and process scheduling.

Post

Replies

Boosts

Views

Activity

Background Mode for BLE app
We have a BLE app and we are trying to get it to work in Background Mode consistently. Use case: RFID BLE reader is attached to a printer Person installs the iOS app on phone and enables Background Mode Person walks to the printer with phone iOS App connects to RFID BLE reader and authenticates to allow secure printing Current status/Problem: On several tests, we were able to connect to the BLE device, but with inconsistent results. For example, for 5 - 2 min tests - (1) we see 8 successful scans, (2) 1 successful scan, (3) 20 successful scans, (4) 15 successful scans, and (5) 11 successful scans. In the above tests, we were getting a scan every 3-4 secs and then it scanning stops. The objective is to maintain continuous scanning until user closes app or disables background mode. Why does scanning stop? How can we make scanning continuous? Any guidance you can provide is appreciated.
2
0
194
2w
Sign In With Apple on IPhone
Hello there, I have been facing an issue with apple sign in on react native app. I have been able to get the authorization and all codes in frontend part. The issue is on backend that is in php. We are firstly validating our identity token phone generated, and then we are creating a client secret and then trying to fetch the user info the issue relies in the api call of getAppleUser($authorizationCode, $clientId, $clientSecret);: function below where we are recieving error like: {"error":"invalid_grant","error_description":"client_id mismatch. The code was not issued to com.marchup.prod.AppSSO."} public function appleAuth($identityToken,$authorizationCode) { if (!$identityToken || !$authorizationCode) { return $this->returnError(400,'Missing identity token or authorization code'); } try { // Validate identity token $decodedToken = $this->validateAppleToken($identityToken); // Generate client secret $teamId = isset(Yii::$app->params['apple-auth']['teamId'])?Yii::$app->params['apple-auth']['teamId']:''; $clientId = isset(Yii::$app->params['apple-auth']['clientId'])?Yii::$app->params['apple-auth']['clientId']:''; $keyId = isset(Yii::$app->params['apple-auth']['keyId'])?Yii::$app->params['apple-auth']['keyId']:''; $privateKey = isset(Yii::$app->params['apple-auth']['privateKey'])?Yii::$app->params['apple-auth']['privateKey']:''; $clientSecret = $this->generateClientSecret($teamId, $clientId, $keyId, $privateKey); // Get user info from Apple $appleUser = $this->getAppleUser($authorizationCode, $clientId, $clientSecret); // Verify the authorization code is valid if (!isset($appleUser['id_token'])) { throw new \Exception('Invalid authorization code'); } // Extract user info from the identity token $userId = $decodedToken->sub; $email = $decodedToken->email ?? ''; // login or signup code need to know about object definition to add login and signup logic return $this->returnSuccess('Request successful',200,[ 'userId' => $userId, 'email' => $email ]); } catch (\Exception $e) { // Handle errors Yii::error('Error on apple login '.$e->getMessage()); return $this->returnError(500,'Server Error'); } } **This function is where i am creating a clientSecret as per apples guidelines: ** function createClientSecret($teamId, $clientId, $keyId, $privateKey) { // $key = file_get_contents($privateKeyPath); $key=$privateKey; $headers = [ 'kid' => $keyId, 'alg' => 'ES256' ]; $claims = [ 'iss' => $teamId, 'iat' => time(), 'exp' => time() + 86400 * 180, 'aud' => 'https://appleid.apple.com', 'sub' => $clientId ]; return JWT::encode($claims, $key, 'ES256', $headers['kid']); } **This is the validate Apple Token that is not giving me error: ** function validateAppleToken($identityToken) { $client = new Client(); $response = $client->get('https://appleid.apple.com/auth/keys'); $keys = json_decode($response->getBody(), true)['keys']; $header = JWT::urlsafeB64Decode(explode('.', $identityToken)[0]); $headerData = json_decode($header, true); $kid = $headerData['kid']; $publicKey = null; foreach ($keys as $key) { if ($key['kid'] === $kid) { $publicKey = JWK::parseKey($key); break; } } if (!$publicKey) { throw new \Exception('Public key not found'); } try { $decoded = JWT::decode($identityToken, $publicKey, ['RS256']); return $decoded; } catch (\Exception $e) { throw new \Exception('Token validation failed: ' . $e->getMessage()); } } The response i got was : { aud: "com.abc" auth_time: 1718017883 c_hash: "HSNFJSBdut5vk84QyK0xHA" exp: 1718104283 iat: 1718017883 iss: "https://appleid.apple.com" nonce:"2878cd1ac1fa121f75250f453edaac47365f5144f2e605e8b526a29cb62c83da" nonce_supported: true sub: "001703.2a52ec72cb874a93986522fa35742bd4.1219" } After that we are mainly getting error as {"error":"invalid_grant","error_description":"client_id mismatch. The code was not issued to com.marchup.prod.AppSSO."} in this function: function getAppleUser($authorizationCode, $clientId, $clientSecret) { try { $client = new Client(); $response = $client->post('https://appleid.apple.com/auth/token', [ 'form_params' => [ 'client_id' => $clientId, 'client_secret' => $clientSecret, 'code' => $authorizationCode, 'grant_type' => 'authorization_code' ] ]); if ($response->getStatusCode() !== 200) { throw new \Exception('Failed to get user information from Apple. Status code: ' . $response->getStatusCode()); } $data = json_decode($response->getBody(), true); // Check if the response contains the expected data if (!isset($data['access_token']) || !isset($data['id_token'])) { throw new \Exception('Invalid response from Apple. Missing access token or ID token.'); } // Return the decoded data return $data; } catch (\Exception $e) { // Log any other unexpected errors Yii::error('Unexpected error: ' . $e->getMessage()); // Re-throw the exception to propagate it further throw $e; } } Assumptions: bundleId = com.marchup serviceId i created as client_id= com.marchup.prod.AppSSO team ID= as usual keyId= is the id i created in apple developer consonsole. And the private key is the key inside the private key file. Can anyone please answer. What is mismatched here
0
0
105
2w
bluetooth control
I am learning about endpoint security and other system extensions, while I was handling ES_EVENT_TYPE_AUTH_IOKIT_OPEN event I realized that I cannot auth deny any bluetooth events. I tried to deny any open or execute events related to com.apple.bluetoothd but it did not work. I searched google and found out that I can use CoreBluetooth to control bluetooth. But when I get connected to bluetooth keyboard or mouse, didConnectPeripheral dose not get called or when I call [central cancelPeripheralConnection:peripheral] disconnection never happens. Is there any recommendation for handling or controlling events related to bluetooth connection?
3
0
196
2w
open (1) fails with fnfErr while open (2) succeeds on custom filesystem
Hello, I have developed a custom filesystem in golang, that relies on macFUSE. High-level apps on osx (TextEdit, Numbers, Preview) rely on syscall.renamex_np with the flag RENAME_SWAP in order to save edits. In golang, the sys call renamex_np and renameat2 are not supported, thus I had to implement the logic for it it. The discussion opened on the google group for macFUSE can be followed here: https://groups.google.com/g/osxfuse-group/c/Kh0qVRGIVv4 On my mounted filesystem, edits work and performing system calls work. However after I perform a series of edits in TextEdit, and completely exit TextEdit. When I call open (1) on the file I get the following error: The application cannot be opened for an unexpected reason, error=Error Domain=NSOSStatusErrorDomain Code=-43 "fnfErr: File not found" UserInfo={_LSLine=4129, _LSFunction=_LSOpenStuffCallLocal} From the logs of my app, there is no open (2) called on the file. I have tried to (trace) dtruss the open call for Numbers/TextEdit, but when I perform the above scenario, my Mac system freezes and the piped output from dtruss is 0 bytes after rebooting my system. How can I debug my issue? Where can I find more documentation of the order of system calls for open (1)? I couldn't find the source code for renamex_np thus my implementation relied on the linux kernel implementation of renameat2, does renamex_np do something different? I note that, if I open TextEdit for example, and then open my file, there is no problem. Also calling cat for example on the terminal it displays the content correctly. The problem seems to be from open (1). Furthermore, if I perform a rename of the file, open (1) succeeds in opening the file, until I perform at least another edit from a high-level app (that calls rename with the swap flag). Also if I unmount my filesystem and mount it again, open (1) behaves correctly. How can I understand what open (1) is doing under the hood? For the high-level apps I could trace the system calls and figure out why they didn't work, but now I reached a point (scenario) where I can't trace the system calls for open (1) due to my whole system freezing. Any input is appreciated.
8
0
200
2w
NSFilePresenter Does Not Seem to Work on watchOS on Device
Hi, I submitted a Feedback Report (FB13820685) but I thought I would ask here as well because maybe I am using the framework wrong. I am using NSFilePresenter to monitor changes to a folder. On macOS, iOS (simulator), iOS (device), and watchOS (simulator) it works fine. However when running on watchOS 10.5 on device, it does not appear to work at all. I created a sample project that reproduces this problem. Am I doing something wrong? It seems like this is too basic of a problem for it to be actually broken on all Apple Watches. https://github.com/jeffreybergier/NSFilePresenterBugSampleProject
0
0
168
3w
Clarification on Where Application Code and Static Libraries Are Stored in Memory
Hello, I’m seeking some clarity regarding the memory storage of application code and static libraries. I understand the basic memory layout in terms of the code (text) segment, data segment, heap, and stack: • Code Segment (Text Segment): Typically stores the compiled program code. • Data Segment: Stores global and static variables. • Heap: Dynamically allocated memory during runtime. • Stack: Stores local variables and function call information. However, I’ve come across some conflicting information: 1. Official Documentation: In an illustration from Apple’s official documentation, it appeared as though application code might be stored in the heap. This seemed unusual given my understanding that compiled code is generally stored in the code segment. from document archive 2. Blog Posts: Several blogs mention that the source code for static libraries is stored in the heap. This also contradicts my understanding since static libraries, after being linked, should be part of the application’s executable code, thus residing in the code segment. Given these points, my understanding is that: • Application Code: After compilation, the executable code should be stored in the code segment. • Static Libraries: Once linked, the code from static libraries should also be part of the code segment. Could you please clarify: • Where exactly is the application code stored in memory? • Is the claim that static libraries’ source code is stored in the heap correct, or is it a misunderstanding? Thank you!
1
0
188
3w
sem_t in sandbox app
Hello, For educational purpose, I try to use a POSIX semaphore sem_t instead of a dispatch_semaphore_t in a sandbox macOS Obj-C app. When using sandbox, the semaphore code creation : sem_t * _unixSemaphore; char nameSemaphore[64] = {0}; snprintf(nameSemaphore, 22, "/UnixSemaphore_sample"); _unixSemaphore = sem_open(nameSemaphore, O_CREAT, 0644, 0); fails, receiving SEM_FAILED and the errno is 78 (not implemented) However, the sem_t _unixSemaphore is created and works fine when I disable sandbox I my entitlements. Is there a way to fix this? Thank you in advance Jean Marie
4
0
258
3w
NSFileProviderReplicatedExtension copy hooks?
My company has developed a desktop-Mac FileProvider extension which presents a user with shared encrypted folders; it's working well except for one issue. While we can handle moving an encrypted folder, there seems to be no way to detect that an encrypted folder has been copied or duplicated. Is there any equivalent to the Windows shell extension copy-hook handler, which can allow NSReplicatedFileProviderExtension (or some other portion of the system) to detect that a folder is being copied?
2
0
228
3w
FileHandle over XPC failure?
2024-06-04 15:17:59.618853+0100 ProxyAgent[20233:29237510] [xpc.exceptions] <NSXPCConnection: 0x60000331cb40> connection from pid 20227 on anonymousListener or serviceListener: Exception caught during decoding of received selector newFlowWithIdentifier:to:type:metadata:socket:, dropping incoming message. Exception: Exception while decoding argument 4 (#6 of invocation): <NSInvocation: 0x600001778780> return value: {v} void target: {@} 0x0 selector: {:} null argument 2: {@} 0x6000017787c0 argument 3: {@} 0x60000002d170 argument 4: {q} 1 argument 5: {@} 0x600001746600 argument 6: {@} 0x0 Exception: decodeObjectForKey: Object of class "NSFileHandle" returned nil from -initWithCoder: while being decoded for key <no key> The extension is in Swift; the recipient is in ObjC (wheeeeee). Based on the extension's logging, the FileHandle is not nil. I am trying to pass a FileHandle based on a socketpair up to the user-land code. The sockets are created happily. Any ideas what's going wrong here?
5
0
205
3w
Prevent authorisation prompt during deactivationRequest
By calling the deactivationRequest from the main app bundle, we see Privacy & Security prompts for TouchID to deactivate the System Extension. We want to know if there's way to avoid that prompt. And also need know why the prompt pops up to deactivate our own app's System Extension component. We even tried to call the deactivate request from Daemon which contain the root access. We still see the prompt. https://developer.apple.com/documentation/systemextensions/ossystemextensionrequest/deactivationrequest(forextensionwithidentifier:queue:)
1
0
210
3w
iOS 17.5.1 dyld watchdog
Hello, I get a lot of crashlogs from MetricKit watchdog on iOS 17.5.1 all related to dyld. Does anybody has the same issue or any idea what could be the problem? Attached is the watchdog log. wathchdog exhausted real (wall clock) time allowance of 30.00 seconds ProcessVisibility: Background ProcessState: Running WatchdogEvent: process-launch. crash in dyld process Following error is shown: 0 Thread 0 1 dyld objc::findhash(dyld3::OverflowSafeArray<objc::bstuff, 4294967295ull>&, unsigned int*, unsigned long long*, unsigned int*, unsigned int, dyld3::OverflowSafeArray<objc::PerfectHash::key, 4294967295ull>&) + 584 2 dyld objc::PerfectHash::make_perfect(dyld3::OverflowSafeArray<objc::PerfectHash::key, 4294967295ull>&, objc::PerfectHash&) + 124 3 dyld objc::PerfectHash::make_perfect(dyld3::OverflowSafeArray<char const*, 4294967295ull> const&, objc::PerfectHash&) + 152 4 dyld dyld4::PrebuiltObjC::generateHashTables(dyld4::RuntimeState&) + 128 5 dyld dyld4::PrebuiltObjC::make(Diagnostics&, dyld4::RuntimeState&) + 2968 6 dyld dyld4::PrebuiltLoaderSet::makeLaunchSet(Diagnostics&, dyld4::RuntimeState&, dyld4::MissingPaths const&) + 468 7 dyld dyld4::prepare(dyld4::APIs&, dyld3::MachOAnalyzer const*) + 2920 8 dyld start + 1724 MetricKitLog.txt diagnostic.json
1
0
289
3w
IPadOS/iOS
How do I switch a thread in my app to use ARM’s big endian mode? The thread code is complied in with the app using Xcode; however other ways of compiling/linking such as libraries, support threads or even cooperative apps might work. Open to ideas. I need to get the iPad processor into big endian mode. Please feel free to ask for any additional information. Best, BR.
1
0
212
3w
Hide global mouse cursor on macOS dock
I'm working on a macOS background app which hide mouse cursor for all apps. I use eventTap to listen keystroke, then call CGDisplayHideCursor and SetsCursorInBackground trick to hide cursor when specific key is down. It works on most case, except one - when mouse hover on dock. I'm not sure why mouse cursor can't be hidden when over dock, maybe some kind of elevated privilege? Is there a way to hide it? Thanks.
1
0
189
May ’24
FileDescriptor writing to an unexpected file
I'm using a file descriptor to write into a file. I've encountered a problem where if the underlying file is removed or recreated, the file descriptor becomes unstable. I have no reliable way to confirm if it's writing on the expected file. let url = URL(fileURLWithPath: "/path/") try FileManager.default.removeItem(at: url) FileManager.default.createFile(atPath: url.path, contents: .empty) let filePath = FilePath(url.path) var fileDescriptor = try FileDescriptor.open(filePath, .readWrite) // The file is recreated - may be done from a different process. try FileManager.default.removeItem(at: url) // L9 FileManager.default.createFile(atPath: url.path, contents: .empty) // L10 let dataToWrite = Data([1,1,1,1]) try fileDescriptor.writeAll(dataToWrite) // L13 let dataWritten = try Data(contentsOf: url) print(dataToWrite == dataWritten) // false I would expect L13 to result in an error. Given it doesn't: Is there a way to determine where fileDescriptor is writing? Is there a way to ensure that fileDescriptor is writing the content in the expected filePath?
8
0
373
May ’24
`listener failed to activate: xpc_error=[1: Operation not permitted]`
Hi :wave: I started a new project to experiment with EndpointSecurity framework. It seems to have been worked, but when I try to add XPC I face some troubles. I am not able to send XPC message from my app to my system extension. No runtime error, but when I'm inspecting logs: That correspond to this code: https://github.com/tony-go/TestES/blob/main/Extension/main.swift#L21-L30 Full project: https://github.com/tony-go/TestES/ I thought at first that it could come from a missing @objc somehere but it does not seems ... I also wonder why I cannot catch this error at runtime ?
12
0
349
May ’24
Dualboot monterey/ventura, monterey part has wrong SystemVersion after Ventura update
My MBP 2019 with i9T2Chip was working with a DualBoot Monterey (on MacintoshHD) and Ventura (on other partition) and after installing the latest Ventura Update on that partition, the main Monterey Partition won't start up, and as a dive in shows, figures now with Sonoma 14.5 SystemVersion.plist I can't figure out what happened, 4 days ago I updated Monterey to 12.7.5, today I booted, read some news during breakfast and then switched partition to update the Ventura OS to it's latest update. After trying to switch back to monterey the monterey partition is in an endless boot-loop. It forwards a little then the screen flickers, the mouse appears, the boot bar jumps to the end and then black screen and later showing recovery asking for internet conection to verify the disk. Fortunately the Ventura Partition allows still to boot, so I started up, Diskutilities did not help, NVRAM reset, SMC reset, startup in diagnose mode, all with no result. I tried to reinstall Monterey over internet: preflight error 21, made a usb installer, chose monterey partition with error "Cannot downgrade"... That made me wonder: why downgrade? it's the same system version, but the startup disk menu indicated 14.5 for the monterey partition... So I deep dived into /System/Library/CoreServices/SystemVersion.plist and there it was the monterey SystemVersion became somehow Sonoma, even if sonoma is not installed, and was not installed nor installing... It was a clean reboot from Monterey into Sonoma. My only guess is that the Ventura update messed up something, but how and why???? no clue. Can anyone help me on how I could reset the systemVersion to Monterey so that I can make a clean install? I have a one month old TimeMachine Backup, and off course I could upgrade to sonoma, but I'd prefere to have Monterey or Ventura on that Partition, as the other one is for DAW compatibility tests... <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>BuildID</key> <string>4805124E-0C37-11EF-BC27-82EAA8E0F66E</string> <key>ProductBuildVersion</key> <string>23F79</string> <key>ProductCopyright</key> <string>1983-2024 Apple Inc.</string> <key>ProductName</key> <string>macOS</string> <key>ProductUserVisibleVersion</key> <string>14.5</string> <key>ProductVersion</key> <string>14.5</string> <key>iOSSupportVersion</key> <string>17.5</string> </dict> </plist>
0
0
161
May ’24
Skip FileProvider folders without metadata
I want to traverse my local Google Drive folder to calculate the size of all the files on my drive. I'm not interested in files or directories that are not present locally. I use getattrlistbulk for traversing and it takes way too much time. I think it is because FileProvider tries to download metadata for the directories that are not yet materialised. Is there a way to skip non-materialised directories?
2
0
257
May ’24