From a0d9505134fd046aefa3296285fce1b124163937 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 14:34:03 +0000 Subject: [PATCH 1/5] iOS: retain the sign-in sheet's callback URL in CN1OidcBrowser.m CN1OidcBrowser.m was written for ARC, but the port compiles with CLANG_ENABLE_OBJC_ARC = NO. ASWebAuthenticationSession's completion handler stored [callbackURL absoluteString] -- autoreleased into the main thread's pool -- in a __block variable and signalled the waiting thread, which then called fromNSString on it after the pool had drained. That use-after-free raised EXC_BAD_ACCESS, which ParparVM's signal handler surfaces as a NullPointerException with no message, so SystemBrowser.authenticate and OidcClient.authorize failed on device after the person approved, with OidcException transport_error "Native sign-in sheet failed: null". Under manual reference counting: - the callback string is copied and the error retained on the main thread, and both are released by the waiting thread once it has read them; - the session and its presentation context, held at +1 from -alloc, are autoreleased when the flow clears them (inside the session's own completion handler, so the session outlives the handler's return) instead of being leaked. Found in a TestFlight build of an app that signs in with OidcClient: every sign-in failed with that transport_error until the generated project was patched the same way. --- Ports/iOSPort/nativeSources/CN1OidcBrowser.m | 47 ++++++++++++++------ 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/Ports/iOSPort/nativeSources/CN1OidcBrowser.m b/Ports/iOSPort/nativeSources/CN1OidcBrowser.m index dc0f06c8ea5..0b31c26646e 100644 --- a/Ports/iOSPort/nativeSources/CN1OidcBrowser.m +++ b/Ports/iOSPort/nativeSources/CN1OidcBrowser.m @@ -94,11 +94,22 @@ - (ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuth #endif // !TARGET_OS_WATCH // Single static slot to keep the session strongly referenced for the -// duration of a flow (ARC would otherwise deallocate it the moment the -// dispatch_async block returned). +// duration of a flow. The port compiles without ARC (CLANG_ENABLE_OBJC_ARC = +// NO), so these hold the +1 reference from -alloc, and cn1OidcClearSession() +// gives it up. static id g_cn1OidcCurrentSession = nil; static id g_cn1OidcCurrentContext = nil; +// Drops the flow's session and context. Autoreleased rather than released: +// this runs inside the session's own completion handler, and the session must +// outlive the handler's return. +static void cn1OidcClearSession(void) { + [g_cn1OidcCurrentSession autorelease]; + [g_cn1OidcCurrentContext autorelease]; + g_cn1OidcCurrentSession = nil; + g_cn1OidcCurrentContext = nil; +} + JAVA_BOOLEAN com_codename1_impl_ios_IOSNative_oidcSystemBrowserSupported___R_boolean( CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT me) { if (@available(iOS 12.0, watchOS 6.2, *)) { @@ -133,13 +144,17 @@ JAVA_OBJECT com_codename1_impl_ios_IOSNative_oidcStartAuthorization___java_lang_ [[ASWebAuthenticationSession alloc] initWithURL:url callbackURLScheme:redirectScheme completionHandler:^(NSURL * _Nullable callbackURL, NSError * _Nullable error) { + // Retained: absoluteString is autoreleased into the main + // thread's pool, which drains before the waiting thread reads + // it. Without the copy that read was a use-after-free, which + // ParparVM's signal handler surfaced as a NullPointerException + // (OidcException transport_error, "null"). if (callbackURL) { - result = [callbackURL absoluteString]; + result = [[callbackURL absoluteString] copy]; } else if (error) { - failure = error; + failure = [error retain]; } - g_cn1OidcCurrentSession = nil; - g_cn1OidcCurrentContext = nil; + cn1OidcClearSession(); dispatch_semaphore_signal(sem); }]; @@ -154,11 +169,10 @@ JAVA_OBJECT com_codename1_impl_ios_IOSNative_oidcStartAuthorization___java_lang_ #endif g_cn1OidcCurrentSession = session; if (![session start]) { - failure = [NSError errorWithDomain:@"com.codename1.io.oidc" - code:-1 - userInfo:@{NSLocalizedDescriptionKey: @"ASWebAuthenticationSession refused to start"}]; - g_cn1OidcCurrentSession = nil; - g_cn1OidcCurrentContext = nil; + failure = [[NSError errorWithDomain:@"com.codename1.io.oidc" + code:-1 + userInfo:@{NSLocalizedDescriptionKey: @"ASWebAuthenticationSession refused to start"}] retain]; + cn1OidcClearSession(); dispatch_semaphore_signal(sem); } }); @@ -167,10 +181,15 @@ JAVA_OBJECT com_codename1_impl_ios_IOSNative_oidcStartAuthorization___java_lang_ // sheet is ever held open indefinitely. dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3600 * NSEC_PER_SEC))); - if (failure != nil || result == nil) { - return JAVA_NULL; + // Both were retained on the main thread (above); release them here, once the + // flow is over. dispatch_semaphore_signal/wait order the writes before this. + JAVA_OBJECT answer = JAVA_NULL; + if (failure == nil && result != nil) { + answer = fromNSString(CN1_THREAD_GET_STATE_PASS_ARG result); } - return fromNSString(CN1_THREAD_GET_STATE_PASS_ARG result); + [result release]; + [failure release]; + return answer; } #else From ad72cfd95686fbad30ef25b1421988f673cd5554 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 15:50:23 +0000 Subject: [PATCH 2/5] iOS: keep CN1OidcBrowser.m valid under ARC as well The iOS native-source lint compiles with -fobjc-arc, where explicit retain/release/autorelease are errors. Guard them with __has_feature(objc_arc), so the file is correct both in the product build (ARC off) and under ARC. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SZMcbmatyXu26VSMeHqWHJ --- Ports/iOSPort/nativeSources/CN1OidcBrowser.m | 33 ++++++++++++++------ 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/Ports/iOSPort/nativeSources/CN1OidcBrowser.m b/Ports/iOSPort/nativeSources/CN1OidcBrowser.m index 0b31c26646e..31e46a0f6c2 100644 --- a/Ports/iOSPort/nativeSources/CN1OidcBrowser.m +++ b/Ports/iOSPort/nativeSources/CN1OidcBrowser.m @@ -95,17 +95,20 @@ - (ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuth // Single static slot to keep the session strongly referenced for the // duration of a flow. The port compiles without ARC (CLANG_ENABLE_OBJC_ARC = -// NO), so these hold the +1 reference from -alloc, and cn1OidcClearSession() -// gives it up. +// NO), so there these hold the +1 reference from -alloc, and +// cn1OidcClearSession() gives it up. Under ARC (the iOS native-source lint +// compiles with -fobjc-arc) the slots are strong and assigning nil is enough. static id g_cn1OidcCurrentSession = nil; static id g_cn1OidcCurrentContext = nil; -// Drops the flow's session and context. Autoreleased rather than released: -// this runs inside the session's own completion handler, and the session must -// outlive the handler's return. +// Drops the flow's session and context. Without ARC they are autoreleased +// rather than released: this runs inside the session's own completion +// handler, and the session must outlive the handler's return. static void cn1OidcClearSession(void) { +#if !__has_feature(objc_arc) [g_cn1OidcCurrentSession autorelease]; [g_cn1OidcCurrentContext autorelease]; +#endif g_cn1OidcCurrentSession = nil; g_cn1OidcCurrentContext = nil; } @@ -152,7 +155,11 @@ JAVA_OBJECT com_codename1_impl_ios_IOSNative_oidcStartAuthorization___java_lang_ if (callbackURL) { result = [[callbackURL absoluteString] copy]; } else if (error) { +#if __has_feature(objc_arc) + failure = error; +#else failure = [error retain]; +#endif } cn1OidcClearSession(); dispatch_semaphore_signal(sem); @@ -169,9 +176,12 @@ JAVA_OBJECT com_codename1_impl_ios_IOSNative_oidcStartAuthorization___java_lang_ #endif g_cn1OidcCurrentSession = session; if (![session start]) { - failure = [[NSError errorWithDomain:@"com.codename1.io.oidc" - code:-1 - userInfo:@{NSLocalizedDescriptionKey: @"ASWebAuthenticationSession refused to start"}] retain]; + failure = [NSError errorWithDomain:@"com.codename1.io.oidc" + code:-1 + userInfo:@{NSLocalizedDescriptionKey: @"ASWebAuthenticationSession refused to start"}]; +#if !__has_feature(objc_arc) + [failure retain]; +#endif cn1OidcClearSession(); dispatch_semaphore_signal(sem); } @@ -181,14 +191,17 @@ JAVA_OBJECT com_codename1_impl_ios_IOSNative_oidcStartAuthorization___java_lang_ // sheet is ever held open indefinitely. dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3600 * NSEC_PER_SEC))); - // Both were retained on the main thread (above); release them here, once the - // flow is over. dispatch_semaphore_signal/wait order the writes before this. + // Without ARC both were retained on the main thread (above); release them + // here, once the flow is over. dispatch_semaphore_signal/wait order the + // writes before this. JAVA_OBJECT answer = JAVA_NULL; if (failure == nil && result != nil) { answer = fromNSString(CN1_THREAD_GET_STATE_PASS_ARG result); } +#if !__has_feature(objc_arc) [result release]; [failure release]; +#endif return answer; } From 87645b7eaf8791252908cb0eb8fa7b76f43bd51f Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:33:38 +0200 Subject: [PATCH 3/5] iOS: own every object a block hands back through a __block variable The port builds without ARC. CN1OidcBrowser.m was not the only native that stored an autoreleased value into a __block variable from a block and read it after the block returned: - IOSNative.m: the audio recorders' error strings (freed by the block's own POOL_END before the IOException was built), openURL's string (retained under #ifdef CN1_USE_ARC -- backwards), the WKWebView snapshot image, and the watch screenshot's failure log. - CN1AR.m: createAnchorFromHit's anchor id; both anchor methods also leaked the ARAnchor. - CN1SmartHome.m: the mode-write key read in a later HomeKit completion, and the queued array walked after removeObjectForKey released it. - CN1WebAuthn.m: results alive only because the delegate leaks; now copied. How it passed: identity-stack.yml linted OIDC/AppleSignIn/WebAuthn with -fobjc-arc, the one model under which the code is correct. It now compiles them without ARC, as the target does. New gate scripts/check-ios-mrc-block-writes.py (source-gates.yml, with a unit test) reports an unowned store into a __block object variable inside a block that is read after the block. It flags master's CN1OidcBrowser.m. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/identity-stack.yml | 13 +- .github/workflows/source-gates.yml | 14 ++ Ports/iOSPort/nativeSources/CN1AR.m | 8 +- Ports/iOSPort/nativeSources/CN1OidcBrowser.m | 4 +- Ports/iOSPort/nativeSources/CN1SmartHome.m | 13 +- Ports/iOSPort/nativeSources/CN1WebAuthn.m | 46 ++-- Ports/iOSPort/nativeSources/IOSNative.m | 59 +++-- scripts/check-ios-mrc-block-writes.py | 252 +++++++++++++++++++ scripts/test_check_ios_mrc_block_writes.py | 96 +++++++ 9 files changed, 461 insertions(+), 44 deletions(-) create mode 100755 scripts/check-ios-mrc-block-writes.py create mode 100755 scripts/test_check_ios_mrc_block_writes.py diff --git a/.github/workflows/identity-stack.yml b/.github/workflows/identity-stack.yml index bf875810b16..9093cf9c8db 100644 --- a/.github/workflows/identity-stack.yml +++ b/.github/workflows/identity-stack.yml @@ -328,6 +328,16 @@ jobs: extra="-DCN1_INCLUDE_OIDC -DCN1_INCLUDE_APPLESIGNIN -DCN1_INCLUDE_WEBAUTHN" fi echo "::group::clang $sdk $label" + # -fno-objc-arc because the production target sets + # CLANG_ENABLE_OBJC_ARC = NO. This lint used to pass -fobjc-arc, + # so it checked these files under a memory model the app never + # builds with: CN1OidcBrowser.m handed an autoreleased callback + # URL across threads, which is correct under ARC and a + # use-after-free without it, and every sign-in on a device + # failed while this step stayed green. Same rule as + # call-vpn-native.yml. scripts/check-ios-mrc-block-writes.py + # catches that class of bug in every native. + # # -fmodules because the port's Metal sources use @import, and the # real build compiles with CLANG_ENABLE_MODULES=YES. The renderer # header used to be unreachable here -- CN1_USE_METAL was a @@ -342,7 +352,8 @@ jobs: -fmodules-cache-path="$STUB/modulecache" \ -target "$target" \ -isysroot "$SDK" \ - -fobjc-arc \ + -fno-objc-arc \ + -Werror=arc-bridge-casts-disallowed-in-nonarc \ -Werror=incompatible-pointer-types \ -Werror=objc-method-access \ -Wno-unused-parameter \ diff --git a/.github/workflows/source-gates.yml b/.github/workflows/source-gates.yml index 2277aa7ac06..09283c41d23 100644 --- a/.github/workflows/source-gates.yml +++ b/.github/workflows/source-gates.yml @@ -85,6 +85,20 @@ jobs: shell: bash run: scripts/check-android-gms-isolation.py + # The iOS port builds without ARC, so a block storing an autoreleased + # object into a __block variable hands the waiting thread a freed + # pointer. CN1OidcBrowser.m shipped that and broke every OIDC sign-in; + # no Xcode build or lint can see it. Absolute: no baseline. + - name: Unit-test the iOS __block ownership gate + if: ${{ !cancelled() }} + shell: bash + run: python3 scripts/test_check_ios_mrc_block_writes.py + + - name: iOS natives store only owned objects into __block variables + if: ${{ !cancelled() }} + shell: bash + run: scripts/check-ios-mrc-block-writes.py + # Unit-test the gate's classification boundaries before the scan, so a # broken gate is reported as a broken gate rather than as a clean tree. - name: Unit-test the 16 KB page alignment gate diff --git a/Ports/iOSPort/nativeSources/CN1AR.m b/Ports/iOSPort/nativeSources/CN1AR.m index 1bf82eb3bd2..902fbbe5427 100644 --- a/Ports/iOSPort/nativeSources/CN1AR.m +++ b/Ports/iOSPort/nativeSources/CN1AR.m @@ -213,6 +213,7 @@ - (NSString *)createAnchorTx:(float)tx ty:(float)ty tz:(float)tz cn1arRunOnMain(^{ [self.sceneView.session addAnchor:anchor]; }); + [anchor release]; return anchorId; } @@ -223,11 +224,14 @@ - (NSString *)createAnchorFromHit:(int)hitId { result = self.recentHits[@(hitId)]; if (result != nil) { ARAnchor *anchor = [[ARAnchor alloc] initWithTransform:result.worldTransform]; - anchorId = anchor.identifier.UUIDString; + // Copied: UUIDString is autoreleased into the main thread's pool, + // which can drain before the calling thread reads it. + anchorId = [anchor.identifier.UUIDString copy]; [self.sceneView.session addAnchor:anchor]; + [anchor release]; } }); - return anchorId; + return [anchorId autorelease]; } - (ARAnchor *)findAnchorById:(NSString *)anchorId { diff --git a/Ports/iOSPort/nativeSources/CN1OidcBrowser.m b/Ports/iOSPort/nativeSources/CN1OidcBrowser.m index 31e46a0f6c2..48ff5026293 100644 --- a/Ports/iOSPort/nativeSources/CN1OidcBrowser.m +++ b/Ports/iOSPort/nativeSources/CN1OidcBrowser.m @@ -96,8 +96,8 @@ - (ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuth // Single static slot to keep the session strongly referenced for the // duration of a flow. The port compiles without ARC (CLANG_ENABLE_OBJC_ARC = // NO), so there these hold the +1 reference from -alloc, and -// cn1OidcClearSession() gives it up. Under ARC (the iOS native-source lint -// compiles with -fobjc-arc) the slots are strong and assigning nil is enough. +// cn1OidcClearSession() gives it up. The objc_arc branches below keep the +// file correct if it is ever compiled with ARC. static id g_cn1OidcCurrentSession = nil; static id g_cn1OidcCurrentContext = nil; diff --git a/Ports/iOSPort/nativeSources/CN1SmartHome.m b/Ports/iOSPort/nativeSources/CN1SmartHome.m index 94996ff08ae..bf5301ee8b9 100644 --- a/Ports/iOSPort/nativeSources/CN1SmartHome.m +++ b/Ports/iOSPort/nativeSources/CN1SmartHome.m @@ -3025,12 +3025,17 @@ void com_codename1_impl_ios_IOSNative_homeRefresh___int( nil]])]; } if (releaseAfterMode != nil) { - NSArray *queued = [afterMode - objectForKey:releaseAfterMode]; + // Retained: removing the key releases the array, + // which is walked right after. + NSArray *queued = [[[afterMode + objectForKey:releaseAfterMode] + retain] autorelease]; [afterMode removeObjectForKey:releaseAfterMode]; for (void (^waiting)(BOOL) in queued) { waiting(!reported); } + [releaseAfterMode release]; + releaseAfterMode = nil; } finished++; if (finished == outstanding) { @@ -3076,7 +3081,9 @@ void com_codename1_impl_ios_IOSNative_homeRefresh___int( // keyed by THIS entry, so a second mode write in the same // batch releases nothing that was not waiting on it. Its own // answer is reported by writeParts as usual. - releaseAfterMode = [NSString stringWithFormat:@"%lu", + // Retained until the last part's completion reads it: that + // runs long after this pool has drained. Released there. + releaseAfterMode = [[NSString alloc] initWithFormat:@"%lu", (unsigned long) i]; } writeParts(); diff --git a/Ports/iOSPort/nativeSources/CN1WebAuthn.m b/Ports/iOSPort/nativeSources/CN1WebAuthn.m index 150a6bd0429..1b9e988ac35 100644 --- a/Ports/iOSPort/nativeSources/CN1WebAuthn.m +++ b/Ports/iOSPort/nativeSources/CN1WebAuthn.m @@ -315,9 +315,13 @@ JAVA_OBJECT com_codename1_impl_ios_IOSNative_webauthnCreate___java_lang_String_R CN1WebAuthnDelegate *del = [[CN1WebAuthnDelegate alloc] init]; del.completion = ^{ - finalResult = del.resultJson; - finalErrCode = del.errorCode; - finalErrMsg = del.errorMessage; + // Copied: the port builds without ARC, and these are read on the + // waiting thread after this block returns. They are alive today + // only because the delegate is never freed; copying does not + // depend on that. + finalResult = [del.resultJson copy]; + finalErrCode = [del.errorCode copy]; + finalErrMsg = [del.errorMessage copy]; dispatch_semaphore_signal(sem); }; @@ -336,14 +340,17 @@ JAVA_OBJECT com_codename1_impl_ios_IOSNative_webauthnCreate___java_lang_String_R g_cn1WebAuthnCurrentDelegate = nil; g_cn1WebAuthnCurrentController = nil; + JAVA_OBJECT answer = JAVA_NULL; if (finalErrCode != nil) { - return fromNSString(CN1_THREAD_GET_STATE_PASS_ARG + answer = fromNSString(CN1_THREAD_GET_STATE_PASS_ARG cn1WebAuthnErrorString(finalErrCode, finalErrMsg)); + } else if (finalResult != nil) { + answer = fromNSString(CN1_THREAD_GET_STATE_PASS_ARG finalResult); } - if (finalResult == nil) { - return JAVA_NULL; - } - return fromNSString(CN1_THREAD_GET_STATE_PASS_ARG finalResult); + [finalResult release]; + [finalErrCode release]; + [finalErrMsg release]; + return answer; } JAVA_OBJECT com_codename1_impl_ios_IOSNative_webauthnGet___java_lang_String_R_java_lang_String( @@ -414,9 +421,13 @@ JAVA_OBJECT com_codename1_impl_ios_IOSNative_webauthnGet___java_lang_String_R_ja CN1WebAuthnDelegate *del = [[CN1WebAuthnDelegate alloc] init]; del.completion = ^{ - finalResult = del.resultJson; - finalErrCode = del.errorCode; - finalErrMsg = del.errorMessage; + // Copied: the port builds without ARC, and these are read on the + // waiting thread after this block returns. They are alive today + // only because the delegate is never freed; copying does not + // depend on that. + finalResult = [del.resultJson copy]; + finalErrCode = [del.errorCode copy]; + finalErrMsg = [del.errorMessage copy]; dispatch_semaphore_signal(sem); }; @@ -434,14 +445,17 @@ JAVA_OBJECT com_codename1_impl_ios_IOSNative_webauthnGet___java_lang_String_R_ja g_cn1WebAuthnCurrentDelegate = nil; g_cn1WebAuthnCurrentController = nil; + JAVA_OBJECT answer = JAVA_NULL; if (finalErrCode != nil) { - return fromNSString(CN1_THREAD_GET_STATE_PASS_ARG + answer = fromNSString(CN1_THREAD_GET_STATE_PASS_ARG cn1WebAuthnErrorString(finalErrCode, finalErrMsg)); + } else if (finalResult != nil) { + answer = fromNSString(CN1_THREAD_GET_STATE_PASS_ARG finalResult); } - if (finalResult == nil) { - return JAVA_NULL; - } - return fromNSString(CN1_THREAD_GET_STATE_PASS_ARG finalResult); + [finalResult release]; + [finalErrCode release]; + [finalErrMsg release]; + return answer; } #else diff --git a/Ports/iOSPort/nativeSources/IOSNative.m b/Ports/iOSPort/nativeSources/IOSNative.m index 98f55ad31df..2c853261a1f 100644 --- a/Ports/iOSPort/nativeSources/IOSNative.m +++ b/Ports/iOSPort/nativeSources/IOSNative.m @@ -4390,9 +4390,13 @@ void com_codename1_impl_ios_IOSNative_execute___java_lang_String(CN1_THREAD_STAT }); #else #if !TARGET_OS_WATCH && !TARGET_OS_TV + // Retained for the main-queue block below: toNSString's result is + // autoreleased into this thread's pool, which may drain first. This was + // #ifdef CN1_USE_ARC, which is backwards -- the port builds without ARC. __block NSString* ns = toNSString(CN1_THREAD_STATE_PASS_ARG n1); -#ifdef CN1_USE_ARC +#ifndef CN1_USE_ARC [ns retain]; + NSString* retainedNs = ns; #endif dispatch_async(dispatch_get_main_queue(), ^{ POOL_BEGIN(); @@ -4415,8 +4419,9 @@ void com_codename1_impl_ios_IOSNative_execute___java_lang_String(CN1_THREAD_STAT [[UIApplication sharedApplication] openURL:url]; } } -#ifdef CN1_USE_ARC - [ns release]; +#ifndef CN1_USE_ARC + // ns may have been reassigned to an autoreleased substring above. + [retainedNs release]; #endif POOL_END(); }); @@ -9405,7 +9410,7 @@ static void cn1FileDialogDeliver(NSString *paths, JAVA_INT requestId) { NSError *copyError = nil; copied = [[NSFileManager defaultManager] copyItemAtURL:readURL toURL:destinationURL error:©Error]; if (!copied) { - error = copyError; + error = copyError; // mrr: the accessor runs synchronously, inside this function's pool } }]; if (coordError != nil && error == nil) { @@ -11759,7 +11764,9 @@ static BOOL cn1_renderViewIntoContext(CN1View *renderView, CN1View *rootView, CG __block BOOL snapshotComplete = NO; [webView takeSnapshotWithConfiguration:config completionHandler:^(CN1Image * _Nullable image, NSError * _Nullable error) { if (image != nil) { - snapshotImage = image; + // Retained: the handler runs from the run loop pumped + // below, whose pool may drain before the image is drawn. + snapshotImage = [image retain]; } else if (error != nil) { NSLog(@"WKWebView snapshot failed: %@", error); } @@ -11793,6 +11800,7 @@ static BOOL cn1_renderViewIntoContext(CN1View *renderView, CN1View *rootView, CG [snapshotImage drawInRect:CGRectMake(0, 0, localBounds.size.width, localBounds.size.height)]; drawn = YES; } + [snapshotImage release]; } } #endif @@ -12102,6 +12110,14 @@ void com_codename1_impl_ios_IOSNative_screenshot__(CN1_THREAD_STATE_MULTI_ARG JA #ifndef CN1_USE_ARC [wpng retain]; #endif + // Logged here, on the main thread: wimg is autoreleased into this + // thread's pool and must not be read after the block returns. + if (wpng == nil || [wpng length] == 0) { + int logicalW = wv != nil ? [wv logicalWidth] : -1; + int logicalH = wv != nil ? [wv logicalHeight] : -1; + NSLog(@"CN1SS:ERR:native watch screenshot failed renderingView=%@ image=%@ logical=%dx%d", + wv, wimg, logicalW, logicalH); + } }; // CN1SS screenshot requests originate from Java callbacks and are not // guaranteed to already be on the watch UI thread. @@ -12110,12 +12126,6 @@ void com_codename1_impl_ios_IOSNative_screenshot__(CN1_THREAD_STATE_MULTI_ARG JA } else { dispatch_sync(dispatch_get_main_queue(), captureWatchFrame); } - if (wpng == nil || [wpng length] == 0) { - int logicalW = wv != nil ? [wv logicalWidth] : -1; - int logicalH = wv != nil ? [wv logicalHeight] : -1; - NSLog(@"CN1SS:ERR:native watch screenshot failed renderingView=%@ image=%@ logical=%dx%d", - wv, wimg, logicalW, logicalH); - } JAVA_OBJECT wbyteArr = JAVA_NULL; if (wpng != nil && [wpng length] > 0) { int wlen = (int)[wpng length]; @@ -12913,7 +12923,7 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioUnit___java_lang_String_in [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err]; if(err){ CN1Log(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]); - exStr = [[err userInfo] description]; + exStr = [[[err userInfo] description] copy]; POOL_END(); return; } @@ -12921,7 +12931,7 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioUnit___java_lang_String_in [audioSession setActive:YES error:&err]; if(err){ CN1Log(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]); - exStr = [[err userInfo] description]; + exStr = [[[err userInfo] description] copy]; POOL_END(); return; } @@ -12933,7 +12943,7 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioUnit___java_lang_String_in if (granted) { recorder = [[CN1AudioUnit alloc] initWithPath:toNSString(CN1_THREAD_STATE_PASS_ARG path) channels:audioChannels sampleRate:sampleRate sampleBuffer:(JAVA_ARRAY)sampleBuffer]; } else { - exStr = @"Denied access to use the microphone"; + exStr = [@"Denied access to use the microphone" copy]; } POOL_END(); }]; @@ -12945,6 +12955,9 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioUnit___java_lang_String_in if (exStr != nil) { JAVA_OBJECT ex = __NEW_java_io_IOException(CN1_THREAD_STATE_PASS_SINGLE_ARG); java_io_IOException___INIT_____java_lang_String(CN1_THREAD_STATE_PASS_ARG ex, fromNSString(CN1_THREAD_GET_STATE_PASS_ARG exStr)); +#ifndef CN1_USE_ARC + [exStr release]; // copied on the main thread above +#endif throwException(threadStateData, ex); return (JAVA_LONG)0; } else { @@ -13025,7 +13038,7 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioRecorder___java_lang_Strin error:&error]; if (error != nil) { CN1Log(@"Error in recording: %@", [error localizedDescription]); - exStr = [error localizedDescription]; + exStr = [[error localizedDescription] copy]; POOL_END(); return; } @@ -13037,6 +13050,9 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioRecorder___java_lang_Strin JAVA_OBJECT ex = __NEW_java_io_IOException(CN1_THREAD_STATE_PASS_SINGLE_ARG); java_io_IOException___INIT_____java_lang_String(CN1_THREAD_STATE_PASS_ARG ex, fromNSString(CN1_THREAD_GET_STATE_PASS_ARG exStr)); +#ifndef CN1_USE_ARC + [exStr release]; // copied on the main thread above +#endif throwException(threadStateData, ex); return (JAVA_LONG)0; } @@ -13052,7 +13068,7 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioRecorder___java_lang_Strin [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err]; if(err){ CN1Log(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]); - exStr = [[err userInfo] description]; + exStr = [[[err userInfo] description] copy]; POOL_END(); return; } @@ -13060,7 +13076,7 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioRecorder___java_lang_Strin [audioSession setActive:YES error:&err]; if(err){ CN1Log(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]); - exStr = [[err userInfo] description]; + exStr = [[[err userInfo] description] copy]; POOL_END(); return; } @@ -13093,7 +13109,7 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioRecorder___java_lang_Strin error: &error]; if(error != nil) { CN1Log(@"Error in recording: %@", [error localizedDescription]); - exStr = [error localizedDescription]; + exStr = [[error localizedDescription] copy]; POOL_END(); return; } @@ -13101,7 +13117,7 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioRecorder___java_lang_Strin com_codename1_impl_ios_IOSImplementation_finishedCreatingAudioRecorder___java_io_IOException(CN1_THREAD_GET_STATE_PASS_ARG JAVA_NULL); } else { recorder = nil; - exStr = @"Permission to record was denied"; + exStr = [@"Permission to record was denied" copy]; } POOL_END(); @@ -13128,7 +13144,7 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioRecorder___java_lang_Strin error: &error]; if(error != nil) { CN1Log(@"Error in recording: %@", [error localizedDescription]); - exStr = [error localizedDescription]; + exStr = [[error localizedDescription] copy]; POOL_END(); return; } @@ -13139,6 +13155,9 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioRecorder___java_lang_Strin if (exStr != nil) { JAVA_OBJECT ex = __NEW_java_io_IOException(CN1_THREAD_STATE_PASS_SINGLE_ARG); java_io_IOException___INIT_____java_lang_String(CN1_THREAD_STATE_PASS_ARG ex, fromNSString(CN1_THREAD_GET_STATE_PASS_ARG exStr)); +#ifndef CN1_USE_ARC + [exStr release]; // copied on the main thread above +#endif throwException(threadStateData, ex); return (JAVA_LONG)0; } else { diff --git a/scripts/check-ios-mrc-block-writes.py b/scripts/check-ios-mrc-block-writes.py new file mode 100755 index 00000000000..767255d2b26 --- /dev/null +++ b/scripts/check-ios-mrc-block-writes.py @@ -0,0 +1,252 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2012-2026, Codename One and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Codename One designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Codename One through http://www.codenameone.com/ if you +# need additional information or have any questions. +"""Fail on an unowned object stored into a __block variable inside a block. + +The iOS port compiles without ARC (CLANG_ENABLE_OBJC_ARC = NO). There, a +`__block` object variable is a plain pointer: storing into it from a block +retains nothing. The blocks that do this are almost always the +completion-handler and main-queue blocks a native waits on, and the value is +read after the block returns -- on another thread, or after a POOL_END the +block ran itself. An autoreleased value has been freed by then. + +CN1OidcBrowser.m did exactly that with `[callbackURL absoluteString]`: correct +under ARC, a use-after-free without it, and every OIDC sign-in on a device +failed with a message-less NullPointerException. + +So in every native that is not compiled with ARC (a file that says +"requires ARC" is), an assignment to a `__block` object variable inside a +block must store something the variable owns: + +- the result of alloc/new/copy/mutableCopy/retain, or a CF Create/Copy call; +- nil, NULL or a string literal (immortal); +- or a value followed by `[var retain]` later in the same block. + +A variable nothing reads after the block returns is not reported. + +Anything else is reported. When the value really is kept alive by something +else (a peer the Java side holds, say), say so on the line with +`// mrr: `; the reason is required. + +There is no baseline: every finding is fixed or explained in place. +""" + +import os +import re +import subprocess +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +DEFAULT_DIRS = ["Ports/iOSPort/nativeSources"] + +DECL = re.compile( + r"(?:__block\s+(?P[A-Za-z_]\w*)(?:\s*<[^;=]*?>)?\s*\*\s*(?P[A-Za-z_]\w*)" + r"|(?P[A-Za-z_]\w*)(?:\s*<[^;=]*?>)?\s*\*\s*__block\s+(?P[A-Za-z_]\w*)" + r"|__block\s+id\s+(?P[A-Za-z_]\w*))\s*[=;]") +OWNED = re.compile( + r"^\s*(?:nil|NULL|0|@\"(?:[^\"\\]|\\.)*\")\s*$" + r"|\b(?:retain|copy|mutableCopy|alloc|new)\]" + r"|\b(?:copy|retain)\]\s*$" + r"|\b\w*(?:Create|Copy)\w*\s*\(") +ANNOTATION = re.compile(r"//\s*mrr:\s*\S") + + +def strip_comments_and_strings(src): + """Blank out comments and string/char literal contents, keeping offsets.""" + out = list(src) + i, n = 0, len(src) + while i < n: + c = src[i] + if src.startswith("//", i): + j = src.find("\n", i) + j = n if j < 0 else j + for k in range(i, j): + out[k] = " " + i = j + elif src.startswith("/*", i): + j = src.find("*/", i + 2) + j = n if j < 0 else j + 2 + for k in range(i, j): + if out[k] != "\n": + out[k] = " " + i = j + elif c in "\"'": + j = i + 1 + while j < n and src[j] != c and src[j] != "\n": + j += 2 if src[j] == "\\" else 1 + for k in range(i + 1, min(j, n)): + out[k] = " " + i = j + 1 + else: + i += 1 + return "".join(out) + + +ARC_IF = re.compile(r"^\s*#\s*(?:if\s+__has_feature\s*\(\s*objc_arc\s*\)|ifdef\s+CN1_USE_ARC)(?!\w)") +MRC_IF = re.compile(r"^\s*#\s*(?:if\s+!\s*__has_feature\s*\(\s*objc_arc\s*\)|ifndef\s+CN1_USE_ARC)(?!\w)") + + +def arc_only_lines(lines): + """1-based line numbers inside a branch compiled only under ARC. + + The port builds without ARC, so an `#if __has_feature(objc_arc)` / + `#ifdef CN1_USE_ARC` branch is not what ships; its plain store is right + for the compiler that would read it. + """ + stack, arc_only = [], set() + for number, line in enumerate(lines, 1): + if ARC_IF.match(line): + stack.append(True) + elif MRC_IF.match(line): + stack.append(False) + elif re.match(r"^\s*#\s*if", line): + stack.append(None) + elif re.match(r"^\s*#\s*(?:else|elif)\b", line) and stack: + stack[-1] = None if stack[-1] is None else not stack[-1] + elif re.match(r"^\s*#\s*endif\b", line) and stack: + stack.pop() + elif True in stack: + arc_only.add(number) + return arc_only + + +def matching_brace(code, open_at): + depth = 0 + for k in range(open_at, len(code)): + if code[k] == "{": + depth += 1 + elif code[k] == "}": + depth -= 1 + if depth == 0: + return k + return len(code) + + +def block_bodies(code): + """(start, end) of every block literal body: ^ [ (params) ] {""" + bodies = [] + for m in re.finditer(r"\^\s*(?:[A-Za-z_][\w\s\*<>,]*?)?\s*(?:\([^()]*(?:\([^()]*\)[^()]*)*\))?\s*\{", code): + start = m.end() - 1 + bodies.append((start, matching_brace(code, start))) + return bodies + + +def enclosing_scope_end(code, pos): + depth = 0 + for k in range(pos, len(code)): + if code[k] == "{": + depth += 1 + elif code[k] == "}": + if depth == 0: + return k + depth -= 1 + return len(code) + + +def is_object_type(name): + if name == "id": + return True + if re.fullmatch(r"[A-Z0-9_]+", name): # JAVA_ARRAY_INT, GLfloat-style C types + return False + return name[:1].isupper() and not name.endswith("Ref") + + +def check_file(path): + with open(path, "r", errors="replace") as handle: + src = handle.read() + if "requires ARC" in src: + return [] + code = strip_comments_and_strings(src) + lines = src.split("\n") + line_starts = [0] + for line in lines: + line_starts.append(line_starts[-1] + len(line) + 1) + + def line_of(pos): + lo, hi = 0, len(line_starts) - 1 + while lo < hi: + mid = (lo + hi + 1) // 2 + if line_starts[mid] <= pos: + lo = mid + else: + hi = mid - 1 + return lo + 1 + + bodies = block_bodies(code) + arc_only = arc_only_lines(lines) + findings = [] + for decl in DECL.finditer(code): + var = decl.group("v1") or decl.group("v2") or decl.group("v3") + typ = decl.group("t1") or decl.group("t2") or "id" + if not is_object_type(typ): + continue + scope_end = enclosing_scope_end(code, decl.end()) + assign = re.compile(r"(?&*])" + re.escape(var) + r"\s*=(?!=)\s*([^;]*);") + for m in assign.finditer(code, decl.end(), scope_end): + inside = [b for b in bodies if b[0] < m.start() < b[1] and b[0] > decl.start()] + if not inside: + continue + body_end = min(b[1] for b in inside) + value = m.group(1).strip() + if OWNED.search(value): + continue + if re.search(r"\[\s*" + re.escape(var) + r"\s+retain\s*\]", code[m.end():body_end]): + continue + # Only a value read once the block has returned can outlive its pool. + if not re.search(r"(?])" + re.escape(var) + r"\b", code[body_end:scope_end]): + continue + line_no = line_of(m.start()) + if line_no in arc_only or ANNOTATION.search(lines[line_no - 1]): + continue + findings.append("%s:%d: __block %s %s is assigned an unowned value inside a block: %s" + % (os.path.relpath(path, ROOT), line_no, typ, var, + " ".join(value.split())[:100])) + return findings + + +def tracked_sources(dirs): + out = subprocess.run(["git", "-C", ROOT, "ls-files", "--"] + dirs, + check=True, capture_output=True, text=True).stdout + return [os.path.join(ROOT, p) for p in out.splitlines() if p.endswith((".m", ".mm"))] + + +def main(argv): + paths = [os.path.abspath(p) for p in argv[1:]] or tracked_sources(DEFAULT_DIRS) + findings = [] + for path in paths: + findings.extend(check_file(path)) + findings = list(dict.fromkeys(findings)) # two #if branches can declare one name + for finding in findings: + print(finding) + if findings: + print("\n%d unowned __block store(s). The iOS port builds WITHOUT ARC: a block that\n" + "stores into a __block object variable must store an owned value (copy/retain,\n" + "released by the reader), or explain on the line with `// mrr: `.\n" + "See the header of %s." % (len(findings), os.path.relpath(__file__, ROOT))) + return 1 + print("check-ios-mrc-block-writes: %d file(s), no unowned __block stores" % len(paths)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/scripts/test_check_ios_mrc_block_writes.py b/scripts/test_check_ios_mrc_block_writes.py new file mode 100755 index 00000000000..bc1642e7178 --- /dev/null +++ b/scripts/test_check_ios_mrc_block_writes.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Pins what check-ios-mrc-block-writes.py reports and what it lets through. + +The first case is the bug that shipped: CN1OidcBrowser.m stored an +autoreleased string into a __block variable from a completion handler, and +read it on the waiting thread after the main thread's pool had drained. +""" + +import importlib.util +import os +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +spec = importlib.util.spec_from_file_location( + "gate", os.path.join(HERE, "check-ios-mrc-block-writes.py")) +gate = importlib.util.module_from_spec(spec) +spec.loader.exec_module(gate) + + +def findings(body): + with tempfile.NamedTemporaryFile("w", suffix=".m", delete=False) as handle: + handle.write(body) + path = handle.name + try: + return gate.check_file(path) + finally: + os.unlink(path) + + +WAIT = " dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);\n" + + +def native(store, after=" use(result);\n", decl=" __block NSString *result = nil;\n"): + return ("void f(void) {\n" + decl + + " dispatch_async(dispatch_get_main_queue(), ^{\n" + " " + store + "\n" + " dispatch_semaphore_signal(sem);\n" + " });\n" + WAIT + after + "}\n") + + +class MrcBlockWritesTest(unittest.TestCase): + + def test_the_oidc_bug_is_reported(self): + self.assertEqual(1, len(findings(native("result = [callbackURL absoluteString];")))) + + def test_trailing_star_declaration_is_reported(self): + self.assertEqual(1, len(findings(native( + "result = [x description];", decl=" NSString * __block result = nil;\n")))) + + def test_parameterised_completion_block_is_reported(self): + body = ("void f(void) {\n __block NSError *failure = nil;\n" + " [s startWithCompletion:^(NSURL * _Nullable u, NSError * _Nullable error) {\n" + " failure = error;\n }];\n" + WAIT + " use(failure);\n}\n") + self.assertEqual(1, len(findings(body))) + + def test_owned_values_pass(self): + for store in ("result = [[u absoluteString] copy];", "result = [s retain];", + "result = [[NSString alloc] initWithFormat:@\"%d\", 1];", + "result = nil;", "result = @\"literal\";", + "result = [s mutableCopy];"): + self.assertEqual([], findings(native(store)), store) + + def test_retained_later_in_the_block_passes(self): + self.assertEqual([], findings(native("result = [x description]; [result retain];"))) + + def test_not_read_after_the_block_passes(self): + self.assertEqual([], findings(native("result = [x description]; use(result);", after=""))) + + def test_arc_only_branch_passes_and_mrc_branch_does_not(self): + arc = "\n#if __has_feature(objc_arc)\n result = s;\n#else\n result = [s retain];\n#endif" + self.assertEqual([], findings(native(arc))) + mrc = "\n#ifndef CN1_USE_ARC\n result = s;\n#endif" + self.assertEqual(1, len(findings(native(mrc)))) + + def test_annotation_needs_a_reason(self): + self.assertEqual([], findings(native("result = s; // mrr: held by the peer"))) + self.assertEqual(1, len(findings(native("result = s; // mrr:")))) + + def test_arc_files_are_skipped(self): + body = '#if !__has_feature(objc_arc)\n#error "requires ARC"\n#endif\n' + self.assertEqual([], findings(body + native("result = [u absoluteString];"))) + + def test_comments_and_strings_do_not_count(self): + self.assertEqual(1, len(findings(native( + "/* result = [u copy]; */ result = [u description]; // [result retain]")))) + + def test_c_and_scalar_types_are_ignored(self): + body = native("data = CN1_ARRAY_DATA(arr);", after=" use(data);\n", + decl=" __block JAVA_ARRAY_INT *data = 0;\n") + self.assertEqual([], findings(body)) + + +if __name__ == "__main__": + sys.exit(0 if unittest.main(exit=False).result.wasSuccessful() else 1) From 2ef9de884aec89838846f5992d07134e95a434fa Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:55:32 +0200 Subject: [PATCH 4/5] iOS: settle the record permission before creating a recorder; no ARC in checks The audio recorders asked requestRecordPermission: from inside their main-queue block and returned before the asynchronous answer arrived, so a first prompt produced no recorder and a denial was never reported (the Java side then waited forever). The permission is now awaited on the calling thread, before the main-queue work, and a denial throws IOException. The __block gate also reports an unowned value stored outside a block that a later block reads (CN1SmartHome.m's shape), and fails any script or workflow that compiles with -fobjc-arc: every test, lint and bench now builds without ARC, as the app does. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/source-gates.yml | 2 +- CLAUDE.md | 21 +++ .../CodenameOne_GLViewController.m | 2 +- Ports/iOSPort/nativeSources/IOSNative.m | 170 +++++++++--------- .../run-apple-preview-tests.sh | 8 +- scripts/check-ios-mrc-block-writes.py | 56 +++++- scripts/crypto-gpu/batch-check.sh | 2 +- scripts/crypto-gpu/vectors.sh | 2 +- scripts/desktop-titlebar-tests/macos.py | 2 +- scripts/ios/text-input-state-tests/check.py | 2 +- scripts/test_check_ios_mrc_block_writes.py | 38 ++++ scripts/test_mac_native_font.py | 2 +- 12 files changed, 212 insertions(+), 95 deletions(-) diff --git a/.github/workflows/source-gates.yml b/.github/workflows/source-gates.yml index 09283c41d23..7a830c093cf 100644 --- a/.github/workflows/source-gates.yml +++ b/.github/workflows/source-gates.yml @@ -94,7 +94,7 @@ jobs: shell: bash run: python3 scripts/test_check_ios_mrc_block_writes.py - - name: iOS natives store only owned objects into __block variables + - name: iOS natives own their __block stores, and no check compiles them with ARC if: ${{ !cancelled() }} shell: bash run: scripts/check-ios-mrc-block-writes.py diff --git a/CLAUDE.md b/CLAUDE.md index faf0e526fcb..087f244f449 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -943,6 +943,27 @@ scripts/check-ios-private-api.py --sdk appletvos --project-dir <...-src> scripts/check-builder-define-toggles.py ``` +#### The port has no ARC, and a `__block` store can be a use-after-free + +Every Apple target builds the port with `CLANG_ENABLE_OBJC_ARC = NO`; only a +native that says "requires ARC" gets a per-file `-fobjc-arc`. Without ARC a +`__block` object variable retains nothing, so an autoreleased value a block +stores into one (a completion handler, a main-queue block ending in +`POOL_END()`) is freed before the waiting thread reads it. ParparVM turns the +crash into a NullPointerException with no message. `CN1OidcBrowser.m` shipped +exactly this, and `CN1SmartHome.m` did the reverse: an autoreleased key stored +outside a block and read in a later completion. + +It passed QA because `identity-stack.yml` linted those files with +`-fobjc-arc`, the one model under which the code is correct. + +`scripts/check-ios-mrc-block-writes.py` (`source-gates.yml`) gates both shapes: +store an owned value (`copy`, `retain`, `alloc`) and release it in the reader, +or explain on the line with `// mrr: `. It also fails any script or +workflow that compiles with `-fobjc-arc` across the board: tests, lints and +benches build with `-fno-objc-arc`, like the app. Choosing the flag per file +from the "requires ARC" marker is allowed. + ### Android compatibility: classic Android apps as Codename One apps An Android Studio module's `src/main` dropped into `common/src/main/android` diff --git a/Ports/iOSPort/nativeSources/CodenameOne_GLViewController.m b/Ports/iOSPort/nativeSources/CodenameOne_GLViewController.m index 1714948f3ea..0602b128bd0 100644 --- a/Ports/iOSPort/nativeSources/CodenameOne_GLViewController.m +++ b/Ports/iOSPort/nativeSources/CodenameOne_GLViewController.m @@ -842,7 +842,7 @@ void screenSizeChangedC(int width, int height) { dispatch_sync(dispatch_get_main_queue(), decodeImageData); } #else - img = CN1AppleImageWithDataCompat(nd); + img = CN1AppleImageWithDataCompat(nd); // mrr: no block in this branch; the watch-only block above is not compiled #endif if (img == nil) { #if TARGET_OS_WATCH diff --git a/Ports/iOSPort/nativeSources/IOSNative.m b/Ports/iOSPort/nativeSources/IOSNative.m index 2c853261a1f..6e6a0d9eaea 100644 --- a/Ports/iOSPort/nativeSources/IOSNative.m +++ b/Ports/iOSPort/nativeSources/IOSNative.m @@ -9414,7 +9414,7 @@ static void cn1FileDialogDeliver(NSString *paths, JAVA_INT requestId) { } }]; if (coordError != nil && error == nil) { - error = coordError; + error = coordError; // mrr: the accessor block already ran, synchronously } #if !__has_feature(objc_arc) [coordinator release]; @@ -12890,6 +12890,44 @@ void com_codename1_impl_ios_IOSNative_nsDataToByteArray___long_byte_1ARRAY(CN1_T } +#if defined(INCLUDE_MICROPHONE_USAGE) && !TARGET_OS_TV && !TARGET_OS_OSX +// Asks for (or reads) the record permission and waits for the answer. +// requestRecordPermission: answers asynchronously, on an arbitrary thread, so +// the recorders below used to ask from inside their main-queue block and +// return before the answer arrived: a first prompt produced no recorder, a +// denial was never reported, and createMediaRecorder waited forever for +// finishedCreatingAudioRecorder. Called from the Java thread that invoked the +// native, never the main thread -- the answer may be delivered there. +static BOOL cn1WaitForRecordPermission(void) { + if (!isIOS7()) { + return YES; + } + AVAudioSession *audioSession = [AVAudioSession sharedInstance]; + if ([NSThread isMainThread]) { + // Waiting here could deadlock; answer from the recorded decision. + return [audioSession recordPermission] == AVAudioSessionRecordPermissionGranted; + } + __block BOOL granted = NO; + dispatch_semaphore_t sem = dispatch_semaphore_create(0); + [audioSession requestRecordPermission:^(BOOL answer) { + granted = answer; + dispatch_semaphore_signal(sem); + }]; + dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); +#if !OS_OBJECT_USE_OBJC + dispatch_release(sem); +#endif + return granted; +} + +static void cn1ThrowIOException(CN1_THREAD_STATE_MULTI_ARG NSString *message) { + JAVA_OBJECT ex = __NEW_java_io_IOException(CN1_THREAD_STATE_PASS_SINGLE_ARG); + java_io_IOException___INIT_____java_lang_String(CN1_THREAD_STATE_PASS_ARG ex, + fromNSString(CN1_THREAD_GET_STATE_PASS_ARG message)); + throwException(threadStateData, ex); +} +#endif + JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioUnit___java_lang_String_int_float_float_1ARRAY_R_long(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_OBJECT path, JAVA_INT audioChannels, JAVA_FLOAT sampleRate, JAVA_OBJECT sampleBuffer) { #if defined(INCLUDE_MICROPHONE_USAGE) && TARGET_OS_OSX @@ -12914,6 +12952,10 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioUnit___java_lang_String_in #elif defined(INCLUDE_MICROPHONE_USAGE) && !TARGET_OS_TV && !TARGET_OS_WATCH __block CN1AudioUnit* recorder = nil; + if (!cn1WaitForRecordPermission()) { + cn1ThrowIOException(CN1_THREAD_STATE_PASS_ARG @"Denied access to use the microphone"); + return (JAVA_LONG)0; + } __block NSString *exStr = nil; dispatch_sync(dispatch_get_main_queue(), ^{ POOL_BEGIN(); @@ -12936,20 +12978,8 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioUnit___java_lang_String_in return; } - if (isIOS7()) { - CN1Log(@"Asking for record permission"); - [audioSession requestRecordPermission:^(BOOL granted) { - POOL_BEGIN(); - if (granted) { - recorder = [[CN1AudioUnit alloc] initWithPath:toNSString(CN1_THREAD_STATE_PASS_ARG path) channels:audioChannels sampleRate:sampleRate sampleBuffer:(JAVA_ARRAY)sampleBuffer]; - } else { - exStr = [@"Denied access to use the microphone" copy]; - } - POOL_END(); - }]; - } else { - recorder = [[CN1AudioUnit alloc] initWithPath:toNSString(CN1_THREAD_STATE_PASS_ARG path) channels:audioChannels sampleRate:sampleRate sampleBuffer:(JAVA_ARRAY)sampleBuffer]; - } + // Permission was settled before this block (cn1WaitForRecordPermission). + recorder = [[CN1AudioUnit alloc] initWithPath:toNSString(CN1_THREAD_STATE_PASS_ARG path) channels:audioChannels sampleRate:sampleRate sampleBuffer:(JAVA_ARRAY)sampleBuffer]; POOL_END(); }); if (exStr != nil) { @@ -13058,6 +13088,10 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioRecorder___java_lang_Strin } return (JAVA_LONG)((BRIDGE_CAST void*)recorder); #elif defined(INCLUDE_MICROPHONE_USAGE) && !TARGET_OS_TV + if (!cn1WaitForRecordPermission()) { + cn1ThrowIOException(CN1_THREAD_STATE_PASS_ARG @"Permission to record was denied"); + return (JAVA_LONG)0; + } __block AVAudioRecorder* recorder = nil; __block NSString *exStr = nil; @@ -13080,76 +13114,44 @@ JAVA_LONG com_codename1_impl_ios_IOSNative_createAudioRecorder___java_lang_Strin POOL_END(); return; } - if (isIOS7()) { - CN1Log(@"Asking for record permission"); - [audioSession requestRecordPermission:^(BOOL granted) { - POOL_BEGIN(); - if (granted) { - NSString * filePath = toNSString(CN1_THREAD_GET_STATE_PASS_ARG destinationFile); - - // cleanup older file if it exists in this location - NSFileManager* fm = [[NSFileManager alloc] init]; - NSString* ns = fixFilePath(filePath); - if([fm fileExistsAtPath:ns]) { - [fm removeItemAtPath:ns error:nil]; - } - - CN1Log(@"Recording audio to: %@", filePath); - - // Ignoring bit rate setting as ios doesn't have direct equivalent - // We only support the one mimetype for now also. - NSDictionary *recordSettings = [[NSDictionary alloc] initWithObjectsAndKeys: - [NSNumber numberWithFloat: (JAVA_FLOAT)sampleRate], AVSampleRateKey, - [NSNumber numberWithInt: kAudioFormatMPEG4AAC],AVFormatIDKey, - [NSNumber numberWithInt: channels], AVNumberOfChannelsKey, - nil]; - NSError *error = nil; - recorder = [[AVAudioRecorder alloc] initWithURL: [NSURL fileURLWithPath:ns] - settings: recordSettings - error: &error]; - if(error != nil) { - CN1Log(@"Error in recording: %@", [error localizedDescription]); - exStr = [[error localizedDescription] copy]; - POOL_END(); - return; - } - recorder.delegate = [CodenameOne_GLViewController instance]; - com_codename1_impl_ios_IOSImplementation_finishedCreatingAudioRecorder___java_io_IOException(CN1_THREAD_GET_STATE_PASS_ARG JAVA_NULL); - } else { - recorder = nil; - exStr = [@"Permission to record was denied" copy]; - - } - POOL_END(); - }]; - } else { - NSString * filePath = toNSString(CN1_THREAD_GET_STATE_PASS_ARG destinationFile); - - // cleanup older file if it exists in this location - NSFileManager* fm = [[NSFileManager alloc] init]; - NSString* ns = fixFilePath(filePath); - if([fm fileExistsAtPath:ns]) { - [fm removeItemAtPath:ns error:nil]; - } - - CN1Log(@"Recording audio to: %@", filePath); - NSDictionary *recordSettings = [[NSDictionary alloc] initWithObjectsAndKeys: - [NSNumber numberWithFloat: 16000.0], AVSampleRateKey, - [NSNumber numberWithInt: kAudioFormatMPEG4AAC],AVFormatIDKey, - [NSNumber numberWithInt: 1], AVNumberOfChannelsKey, - nil]; - NSError *error = nil; - recorder = [[AVAudioRecorder alloc] initWithURL: [NSURL fileURLWithPath:filePath] - settings: recordSettings - error: &error]; - if(error != nil) { - CN1Log(@"Error in recording: %@", [error localizedDescription]); - exStr = [[error localizedDescription] copy]; - POOL_END(); - return; - } - recorder.delegate = [CodenameOne_GLViewController instance]; + // Permission was settled before this block (cn1WaitForRecordPermission). + NSString * filePath = toNSString(CN1_THREAD_GET_STATE_PASS_ARG destinationFile); + + // cleanup older file if it exists in this location + NSFileManager* fm = [[NSFileManager alloc] init]; + NSString* ns = fixFilePath(filePath); + if([fm fileExistsAtPath:ns]) { + [fm removeItemAtPath:ns error:nil]; + } +#ifndef CN1_USE_ARC + [fm release]; +#endif + + CN1Log(@"Recording audio to: %@", filePath); + + // Ignoring bit rate setting as ios doesn't have direct equivalent + // We only support the one mimetype for now also. + NSDictionary *recordSettings = [[NSDictionary alloc] initWithObjectsAndKeys: + [NSNumber numberWithFloat: (JAVA_FLOAT)sampleRate], AVSampleRateKey, + [NSNumber numberWithInt: kAudioFormatMPEG4AAC],AVFormatIDKey, + [NSNumber numberWithInt: channels], AVNumberOfChannelsKey, + nil]; + NSError *error = nil; + recorder = [[AVAudioRecorder alloc] initWithURL: [NSURL fileURLWithPath:ns] + settings: recordSettings + error: &error]; +#ifndef CN1_USE_ARC + [recordSettings release]; +#endif + if(error != nil) { + CN1Log(@"Error in recording: %@", [error localizedDescription]); + exStr = [[error localizedDescription] copy]; + POOL_END(); + return; } + recorder.delegate = [CodenameOne_GLViewController instance]; + // finishedCreatingAudioRecorder is called once, on the Java thread, + // after this block returns. POOL_END(); }); if (exStr != nil) { diff --git a/scripts/camera-regression/run-apple-preview-tests.sh b/scripts/camera-regression/run-apple-preview-tests.sh index a03f040b888..5fb692e9973 100755 --- a/scripts/camera-regression/run-apple-preview-tests.sh +++ b/scripts/camera-regression/run-apple-preview-tests.sh @@ -15,8 +15,10 @@ end = s.index('@end', s.index('@implementation CN1CameraPreviewView')) + len('@e (target / 'PreviewProduction.inc').write_text(s[start:end]) PY SRC="$ROOT/scripts/camera-regression/apple/PreviewLayoutTest.m" -# Check both the manual ownership build and the ARC build. -for OWNERSHIP in -fno-objc-arc -fobjc-arc; do +# Manual reference counting only: the port builds with CLANG_ENABLE_OBJC_ARC = NO, +# and an ARC build checks a memory model the app never ships with +# (scripts/check-ios-mrc-block-writes.py --arc-flags enforces this). +for OWNERSHIP in -fno-objc-arc; do xcrun --sdk macosx clang "$OWNERSHIP" -Werror -Wno-deprecated-declarations \ -I "$TMP" -framework AppKit -framework AVFoundation -framework QuartzCore -framework CoreGraphics \ "$SRC" -o "$TMP/preview-test" @@ -25,7 +27,7 @@ done if [ -n "${1:-}" ]; then APP="$TMP/CameraPreviewTest.app" mkdir -p "$APP" - xcrun --sdk iphonesimulator clang -fobjc-arc -Werror -Wno-deprecated-declarations \ + xcrun --sdk iphonesimulator clang -fno-objc-arc -Werror -Wno-deprecated-declarations \ -target arm64-apple-ios15.0-simulator \ -isysroot "$(xcrun --sdk iphonesimulator --show-sdk-path)" \ -I "$TMP" -framework UIKit -framework AVFoundation -framework QuartzCore -framework CoreGraphics \ diff --git a/scripts/check-ios-mrc-block-writes.py b/scripts/check-ios-mrc-block-writes.py index 767255d2b26..473d9297de7 100755 --- a/scripts/check-ios-mrc-block-writes.py +++ b/scripts/check-ios-mrc-block-writes.py @@ -205,6 +205,21 @@ def line_of(pos): for m in assign.finditer(code, decl.end(), scope_end): inside = [b for b in bodies if b[0] < m.start() < b[1] and b[0] > decl.start()] if not inside: + # Stored outside any block: a problem only if a block that may + # run later -- a completion handler -- reads it. + value = m.group(1).strip() + if OWNED.search(value): + continue + readers = [b for b in bodies if b[0] > decl.end() and b[0] < scope_end + and re.search(r"(?])" + re.escape(var) + r"\b", code[b[0]:b[1]])] + if not readers: + continue + line_no = line_of(m.start()) + if line_no in arc_only or ANNOTATION.search(lines[line_no - 1]): + continue + findings.append("%s:%d: __block %s %s is assigned an unowned value a later block reads: %s" + % (os.path.relpath(path, ROOT), line_no, typ, var, + " ".join(value.split())[:100])) continue body_end = min(b[1] for b in inside) value = m.group(1).strip() @@ -230,9 +245,48 @@ def tracked_sources(dirs): return [os.path.join(ROOT, p) for p in out.splitlines() if p.endswith((".m", ".mm"))] +# Where a test, lint or bench could compile port sources. The builders are +# not here: IPhoneBuilder gives -fobjc-arc to a cn1lib pod that asks for it, +# which is how that code really ships. +ARC_FLAG_DIRS = ["scripts", ".github"] +# As an argument: a quoted list element, or a shell word followed by another +# argument, a line continuation or the end of the line. Prose that names the +# flag ("built with -fobjc-arc (%s)") is not a compile. +ARC_FLAG = re.compile(r"[\"']-fobjc-arc[\"']|(? Date: Tue, 1 Dec 2026 18:59:15 +0200 Subject: [PATCH 5/5] iOS: a late OIDC handler must not release a newer flow's session After the one-hour timeout Java can start a second sign-in; the first session's handler then fired and autoreleased the second's session and context, which its own handler released again. A handler now clears only its own session, and a new flow cancels any abandoned one first. The ARC flag check also catches a flag followed by a file name. Co-Authored-By: Claude Opus 5.5 --- Ports/iOSPort/nativeSources/CN1OidcBrowser.m | 14 ++++++++++++-- scripts/check-ios-mrc-block-writes.py | 2 +- scripts/test_check_ios_mrc_block_writes.py | 3 ++- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/Ports/iOSPort/nativeSources/CN1OidcBrowser.m b/Ports/iOSPort/nativeSources/CN1OidcBrowser.m index 48ff5026293..72723faadd4 100644 --- a/Ports/iOSPort/nativeSources/CN1OidcBrowser.m +++ b/Ports/iOSPort/nativeSources/CN1OidcBrowser.m @@ -143,7 +143,15 @@ JAVA_OBJECT com_codename1_impl_ios_IOSNative_oidcStartAuthorization___java_lang_ dispatch_semaphore_t sem = dispatch_semaphore_create(0); dispatch_async(dispatch_get_main_queue(), ^{ - ASWebAuthenticationSession *session = + // A flow abandoned by the timeout below still owns the globals; give + // them up here. Its handler may yet fire, which is why every handler + // clears only while the globals are still its own session's. + if (g_cn1OidcCurrentSession != nil) { + [(ASWebAuthenticationSession *)g_cn1OidcCurrentSession cancel]; + cn1OidcClearSession(); + } + __block ASWebAuthenticationSession *session = nil; + session = [[ASWebAuthenticationSession alloc] initWithURL:url callbackURLScheme:redirectScheme completionHandler:^(NSURL * _Nullable callbackURL, NSError * _Nullable error) { @@ -161,7 +169,9 @@ JAVA_OBJECT com_codename1_impl_ios_IOSNative_oidcStartAuthorization___java_lang_ failure = [error retain]; #endif } - cn1OidcClearSession(); + if (g_cn1OidcCurrentSession == session) { + cn1OidcClearSession(); + } dispatch_semaphore_signal(sem); }]; diff --git a/scripts/check-ios-mrc-block-writes.py b/scripts/check-ios-mrc-block-writes.py index 473d9297de7..974f6c39cad 100755 --- a/scripts/check-ios-mrc-block-writes.py +++ b/scripts/check-ios-mrc-block-writes.py @@ -252,7 +252,7 @@ def tracked_sources(dirs): # As an argument: a quoted list element, or a shell word followed by another # argument, a line continuation or the end of the line. Prose that names the # flag ("built with -fobjc-arc (%s)") is not a compile. -ARC_FLAG = re.compile(r"[\"']-fobjc-arc[\"']|(?