diff --git a/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java b/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java index 5f0cfffe4f3..22b93d5287c 100644 --- a/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java +++ b/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java @@ -13284,6 +13284,24 @@ public AsyncResource requestIntegrityToken(String nonce) { return result; } + /// Requests a Google Play Integrity token through the Standard request flow, bound to the given + /// request hash. Only Android implements it; everywhere else the result completes with an error. + /// + /// #### Parameters + /// + /// - `requestHash`: a digest of the action being protected, bound into the verdict + /// + /// #### Returns + /// + /// an `AsyncResource` that completes with the opaque integrity token, or with an error + public AsyncResource requestStandardIntegrityToken(String requestHash) { + AsyncResource result = new AsyncResource(); + result.error(new UnsupportedOperationException( + "Standard Play Integrity requests are only supported on Android, with the " + + "android.playIntegrity and android.playIntegrity.cloudProjectNumber build hints.")); + return result; + } + /// Returns true if device-attestation (Play Integrity / App Attest) is available on this device and /// was bundled into the build. False on the base/unsupported implementation. public boolean isAttestationSupported() { diff --git a/CodenameOne/src/com/codename1/security/DeviceIntegrity.java b/CodenameOne/src/com/codename1/security/DeviceIntegrity.java index b9d8a710ab5..653c6027e96 100644 --- a/CodenameOne/src/com/codename1/security/DeviceIntegrity.java +++ b/CodenameOne/src/com/codename1/security/DeviceIntegrity.java @@ -124,6 +124,49 @@ public static AsyncResource requestIntegrityToken(String serverNonce) { return Display.getInstance().requestIntegrityToken(serverNonce); } + /// Requests a Google Play Integrity token through the **Standard** request flow. + /// + /// Play Integrity has two request types. [#requestIntegrityToken(String)] makes a *Classic* + /// request: every call goes to Google's servers and takes seconds, so it suits occasional + /// checks such as sign-in. A *Standard* request is what + /// Google recommends for checking individual actions: the token provider is prepared once, ahead + /// of time, and each request then answers in a few hundred milliseconds. Instead of a nonce the + /// verdict carries the `requestHash` you pass, typically a SHA-256 of the action's parameters + /// (the transfer's account, amount and a timestamp); your backend recomputes it and compares it + /// with the `requestDetails.requestHash` of the decoded verdict. + /// + /// Enable it with `android.playIntegrity=true` and + /// `android.playIntegrity.cloudProjectNumber=`. The provider is + /// prepared in the background when the application starts and prepared again when Google + /// reports it expired, so the first call does not pay for the warm-up. + /// + /// ```java + /// String transfer = "IL620108000000099999999|250.00|" + System.currentTimeMillis(); + /// String hash = Hash.toHex(Hash.sha256(StringUtil.getBytes(transfer))); + /// DeviceIntegrity.requestStandardIntegrityToken(hash).onResult((token, err) -> { + /// if (err != null) { + /// // attestation unavailable -- treat as untrusted / require step-up + /// return; + /// } + /// // POST token with the transfer; the backend decodes it and checks the hash + /// }); + /// ``` + /// + /// Standard requests exist only on Google Play. On iOS, the simulator and every other platform + /// the result completes with an error; use [#requestIntegrityToken(String)] there. + /// + /// #### Parameters + /// + /// - `requestHash`: a digest of the action being protected, at most 500 characters + /// + /// #### Returns + /// + /// an `AsyncResource` that completes with the opaque integrity token, or completes with an error + /// when Standard requests are unsupported, not configured, or the request fails + public static AsyncResource requestStandardIntegrityToken(String requestHash) { + return Display.getInstance().requestStandardIntegrityToken(requestHash); + } + /// Returns true when platform attestation (Play Integrity / App Attest) is available on this device /// and was bundled into the build via the relevant build hint. public static boolean isAttestationSupported() { diff --git a/CodenameOne/src/com/codename1/ui/Display.java b/CodenameOne/src/com/codename1/ui/Display.java index 37c140b6690..426fd317867 100644 --- a/CodenameOne/src/com/codename1/ui/Display.java +++ b/CodenameOne/src/com/codename1/ui/Display.java @@ -9490,6 +9490,20 @@ public AsyncResource requestIntegrityToken(String nonce) { return impl.requestIntegrityToken(nonce); } + /// Requests a Play Integrity token through the Standard request flow. See + /// `com.codename1.security.DeviceIntegrity#requestStandardIntegrityToken(String)`. + /// + /// #### Parameters + /// + /// - `requestHash`: a digest of the action being protected + /// + /// #### Returns + /// + /// an `AsyncResource` completing with the token or an error + public AsyncResource requestStandardIntegrityToken(String requestHash) { + return impl.requestStandardIntegrityToken(requestHash); + } + /// Returns true if device-attestation (Play Integrity / App Attest) is supported and bundled. public boolean isAttestationSupported() { return impl.isAttestationSupported(); diff --git a/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java b/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java index 1b47299a996..8b72e60af87 100644 --- a/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java +++ b/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java @@ -1843,6 +1843,9 @@ public void init(Object m) { setActivity(null); setContext((Context)m); } + // Standard Play Integrity requests answer fast only once the token provider is + // prepared; doing it now keeps the warm-up off the first protected action. + GoogleServices.prewarmStandardIntegrity(getContext()); // The nearby bridge is cached for the life of the process while // Android recreates the activity freely -- a configuration change, // or "Don't keep activities". An association chooser opened by the @@ -19087,6 +19090,13 @@ public AsyncResource requestIntegrityToken(final String nonce) { return result; } + @Override + public AsyncResource requestStandardIntegrityToken(final String requestHash) { + final AsyncResource result = new AsyncResource(); + GoogleServices.requestStandardIntegrityToken(getContext(), requestHash, result); + return result; + } + @Override public boolean isDeviceCompromised() { // Developer Options and USB debugging are switched on by plenty of ordinary users and diff --git a/Ports/Android/src/com/codename1/impl/android/GoogleServices.java b/Ports/Android/src/com/codename1/impl/android/GoogleServices.java index 253c26f2a96..d80e7de1075 100644 --- a/Ports/Android/src/com/codename1/impl/android/GoogleServices.java +++ b/Ports/Android/src/com/codename1/impl/android/GoogleServices.java @@ -273,4 +273,313 @@ public Object invoke(Object proxy, java.lang.reflect.Method method, Object[] arg result.error(t); } } + + /// The application meta-data key carrying the Google Cloud project number the + /// Standard flow needs. The builder writes it from the + /// `android.playIntegrity.cloudProjectNumber` hint, prefixed with + /// [#CLOUD_PROJECT_PREFIX]: a bare twelve digit value would be parsed by the + /// manifest as a number and overflow the int Android stores it in. + static final String CLOUD_PROJECT_META = "codename1.playIntegrity.cloudProjectNumber"; + + /// See [#CLOUD_PROJECT_META]. + static final String CLOUD_PROJECT_PREFIX = "p"; + + /// The error for a build whose Play Integrity SDK lacks the Standard API: either + /// the SDK is not bundled, or `android.playIntegrityVersion` pins one too old. + private static final String STANDARD_NOT_BUNDLED = "Standard Play Integrity requests are not available " + + "in this build. Enable the android.playIntegrity build hint, and if android.playIntegrityVersion " + + "is set, remove it or raise it to a version with StandardIntegrityManager."; + + /// Play Core's `StandardIntegrityErrorCode.INTEGRITY_TOKEN_PROVIDER_INVALID`: + /// the prepared provider expired and must be prepared again. + private static final int PROVIDER_INVALID = -19; + + /// The prepared `StandardIntegrityTokenProvider`, null until a prepare succeeds. + /// Touched only from Play Core's callbacks, which run on the main thread, and + /// from `requestStandardIntegrityToken`, which the port also posts there. + private static Object standardProvider; + + /// Requests waiting for the prepare in flight. + private static final java.util.ArrayList PENDING_PREPARE = new java.util.ArrayList(); + + /// Whether a prepare is in flight. + private static boolean preparing; + + /// Reads the configured Cloud project number, or 0 when the hint is not set. + /// + /// #### Parameters + /// + /// - `context`: any context of the application + /// + /// #### Returns + /// + /// the project number, or 0 + static long cloudProjectNumber(Context context) { + if (cachedCloudProject >= 0) { + return cachedCloudProject; + } + return readCloudProjectNumber(context); + } + + /// The project number once read, -1 before. It comes from the APK's manifest, + /// so it cannot change while the process lives. Only a successful read is + /// cached: a PackageManager failure is retried on the next call. + private static long cachedCloudProject = -1; + + private static long readCloudProjectNumber(Context context) { + try { + ApplicationInfo info = context.getPackageManager().getApplicationInfo( + context.getPackageName(), PackageManager.GET_META_DATA); + if (info.metaData == null) { + cachedCloudProject = 0; + return 0; + } + Object v = info.metaData.get(CLOUD_PROJECT_META); + if (v instanceof String) { + String str = (String) v; + if (str.startsWith(CLOUD_PROJECT_PREFIX)) { + str = str.substring(CLOUD_PROJECT_PREFIX.length()); + } + cachedCloudProject = Long.parseLong(str.trim()); + return cachedCloudProject; + } + cachedCloudProject = 0; + } catch(Throwable t) { + // Missing package info or a malformed number: the flow is not configured. + } + return 0; + } + + /// Prepares the Standard token provider in the background, so the first + /// request does not pay for the warm-up. Does nothing when the flow is not + /// configured, not bundled, or the Play Store is absent. + /// + /// #### Parameters + /// + /// - `context`: any context of the application + static void prewarmStandardIntegrity(final Context context) { + if (context == null || cloudProjectNumber(context) == 0 || !isPlayStoreInstalled(context)) { + return; + } + runOnMain(new Runnable() { + public void run() { + if (standardProvider == null) { + prepareStandard(context, null); + } + } + }); + } + + /// Requests a Play Integrity token through the Standard flow, bound to + /// `requestHash`, completing `result`. + /// + /// #### Parameters + /// + /// - `context`: any context of the application + /// - `requestHash`: the request hash bound into the verdict + /// - `result`: completed with the token or an error + static void requestStandardIntegrityToken(final Context context, final String requestHash, + final AsyncResource result) { + if (requestHash == null || requestHash.length() == 0 || requestHash.length() > 500) { + result.error(new IllegalArgumentException( + "requestHash must be between 1 and 500 characters")); + return; + } + if (context == null || cloudProjectNumber(context) == 0) { + result.error(new UnsupportedOperationException( + "Standard Play Integrity requests need the android.playIntegrity.cloudProjectNumber build hint")); + return; + } + if (!isPlayStoreInstalled(context)) { + result.error(new UnsupportedOperationException( + "Google Play Integrity needs the Google Play Store, which is not installed")); + return; + } + runOnMain(new Runnable() { + public void run() { + requestStandard(context, requestHash, result, true); + } + }); + } + + private static void runOnMain(Runnable r) { + new android.os.Handler(android.os.Looper.getMainLooper()).post(r); + } + + /// Requests with the prepared provider, preparing it first when needed. On + /// `PROVIDER_INVALID` the provider is dropped and, once, prepared again. + private static void requestStandard(final Context context, final String requestHash, + final AsyncResource result, final boolean retryOnInvalid) { + if (standardProvider == null) { + prepareStandard(context, new Runnable() { + public void run() { + if (standardProvider == null) { + result.error(lastPrepareError != null ? lastPrepareError + : new IllegalStateException("Play Integrity provider could not be prepared")); + } else { + requestStandard(context, requestHash, result, false); + } + } + }); + return; + } + try { + Class requestClass = Class.forName( + "com.google.android.play.core.integrity.StandardIntegrityManager$StandardIntegrityTokenRequest"); + Object builder = requestClass.getMethod("builder").invoke(null); + builder = builder.getClass().getMethod("setRequestHash", String.class).invoke(builder, requestHash); + Object request = builder.getClass().getMethod("build").invoke(builder); + Class providerClass = Class.forName( + "com.google.android.play.core.integrity.StandardIntegrityManager$StandardIntegrityTokenProvider"); + Object task = providerClass.getMethod("request", requestClass).invoke(standardProvider, request); + final Class tokenClass = Class.forName( + "com.google.android.play.core.integrity.StandardIntegrityManager$StandardIntegrityToken"); + listen(task, new Callback() { + public void success(Object response) { + try { + Object token = tokenClass.getMethod("token").invoke(response); + if (token instanceof String) { + result.complete((String) token); + } else { + result.error(new IllegalStateException("integrity token was not a string")); + } + } catch(Throwable t) { + result.error(t); + } + } + + public void failure(Throwable err) { + if (retryOnInvalid && errorCode(err) == PROVIDER_INVALID) { + standardProvider = null; + requestStandard(context, requestHash, result, false); + } else { + result.error(err); + } + } + }); + } catch(ClassNotFoundException notBundled) { + result.error(new UnsupportedOperationException( + STANDARD_NOT_BUNDLED)); + } catch(Throwable t) { + result.error(t); + } + } + + private static Throwable lastPrepareError; + + /// Starts preparing the provider, or joins a prepare in flight. `then` runs + /// on the main thread when the prepare ends, whatever its outcome. + private static void prepareStandard(Context context, Runnable then) { + if (then != null) { + PENDING_PREPARE.add(then); + } + if (preparing) { + return; + } + preparing = true; + try { + Class factory = Class.forName(INTEGRITY_FACTORY); + Object manager = factory.getMethod("createStandard", Context.class).invoke(null, context); + Class prepareClass = Class.forName( + "com.google.android.play.core.integrity.StandardIntegrityManager$PrepareIntegrityTokenRequest"); + Object builder = prepareClass.getMethod("builder").invoke(null); + builder = builder.getClass().getMethod("setCloudProjectNumber", long.class) + .invoke(builder, Long.valueOf(cloudProjectNumber(context))); + Object request = builder.getClass().getMethod("build").invoke(builder); + Class managerClass = Class.forName("com.google.android.play.core.integrity.StandardIntegrityManager"); + Object task = managerClass.getMethod("prepareIntegrityToken", prepareClass).invoke(manager, request); + listen(task, new Callback() { + public void success(Object provider) { + standardProvider = provider; + lastPrepareError = null; + finishPrepare(); + } + + public void failure(Throwable err) { + lastPrepareError = err; + finishPrepare(); + } + }); + } catch(ClassNotFoundException notBundled) { + lastPrepareError = new UnsupportedOperationException( + STANDARD_NOT_BUNDLED); + finishPrepare(); + } catch(Throwable t) { + lastPrepareError = t; + finishPrepare(); + } + } + + private static void finishPrepare() { + preparing = false; + Runnable[] waiting = PENDING_PREPARE.toArray(new Runnable[PENDING_PREPARE.size()]); + PENDING_PREPARE.clear(); + for (int i = 0; i < waiting.length; i++) { + waiting[i].run(); + } + } + + /// Play Core's `IntegrityServiceException.getErrorCode()`, or 0 for any other error. + private static int errorCode(Throwable err) { + try { + Object code = err.getClass().getMethod("getErrorCode").invoke(err); + if (code instanceof Integer) { + return ((Integer) code).intValue(); + } + } catch(Throwable t) { + // Not a Play Core exception. + } + return 0; + } + + private interface Callback { + void success(Object value); + + void failure(Throwable err); + } + + /// Answers `equals`, `hashCode` and `toString` on a listener proxy, which + /// must never be mistaken for the task completing. + private static Object objectMethod(Object proxy, java.lang.reflect.Method method, Object[] args) { + String name = method.getName(); + if ("equals".equals(name)) { + return Boolean.valueOf(args != null && args.length == 1 && args[0] == proxy); + } + if ("hashCode".equals(name)) { + return Integer.valueOf(System.identityHashCode(proxy)); + } + return "PlayIntegrityListener@" + Integer.toHexString(System.identityHashCode(proxy)); + } + + /// Attaches success and failure listeners to a Play services `Task` by name. + private static void listen(Object task, final Callback cb) throws Exception { + Class taskClass = Class.forName("com.google.android.gms.tasks.Task"); + Class onSuccessClass = Class.forName("com.google.android.gms.tasks.OnSuccessListener"); + Class onFailureClass = Class.forName("com.google.android.gms.tasks.OnFailureListener"); + Object successListener = java.lang.reflect.Proxy.newProxyInstance( + onSuccessClass.getClassLoader(), new Class[] { onSuccessClass }, + new java.lang.reflect.InvocationHandler() { + public Object invoke(Object proxy, java.lang.reflect.Method method, Object[] args) { + if (method.getDeclaringClass() == Object.class) { + return objectMethod(proxy, method, args); + } + cb.success(args != null && args.length > 0 ? args[0] : null); + return null; + } + }); + Object failureListener = java.lang.reflect.Proxy.newProxyInstance( + onFailureClass.getClassLoader(), new Class[] { onFailureClass }, + new java.lang.reflect.InvocationHandler() { + public Object invoke(Object proxy, java.lang.reflect.Method method, Object[] args) { + if (method.getDeclaringClass() == Object.class) { + return objectMethod(proxy, method, args); + } + cb.failure(args != null && args.length > 0 && args[0] instanceof Throwable + ? (Throwable) args[0] : new RuntimeException("Play Integrity request failed")); + return null; + } + }); + taskClass.getMethod("addOnSuccessListener", onSuccessClass).invoke(task, successListener); + taskClass.getMethod("addOnFailureListener", onFailureClass).invoke(task, failureListener); + } } diff --git a/docs/developer-guide/security.asciidoc b/docs/developer-guide/security.asciidoc index 5fea8248fc5..fecd27764bd 100644 --- a/docs/developer-guide/security.asciidoc +++ b/docs/developer-guide/security.asciidoc @@ -479,6 +479,14 @@ TIP: The block-the-transfer decision lives in *your backend*, gated on the verif `DeviceIntegrity` hands you the raw platform blob and leaves verification, policy, replay protection, key management and rotation to you. If you'd rather not build that, <> is the managed layer on top of exactly this API: the attestation is verified server-side against Apple and Google, evaluated against a policy you control, and turned into a short-lived signed token your backend checks with a few lines of middleware. Both remain available and this API keeps working unchanged. +===== Classic and Standard requests on Android + +Google Play Integrity has two request types, and Codename One supports both. `requestIntegrityToken(nonce)` makes a *Classic* request. Each call goes to Google and takes a few seconds, so use it for occasional checks such as sign-in. It's also the call that works on iOS. + +`DeviceIntegrity.requestStandardIntegrityToken(requestHash)` makes a *Standard* request, which Google recommends for checking individual actions such as a payment. Codename One prepares the token provider in the background when the app starts, so each request answers in a fraction of a second. Instead of a nonce you pass a request hash: a digest of the action, for example a hex SHA-256 of the account, amount and time of a transfer. Your backend decodes the token with the same Google endpoint, recomputes the hash and compares it with `requestDetails.requestHash` in the verdict. Google also guards Standard tokens against replay, so your server doesn't need to keep a list of used nonces. + +Enable it with `android.playIntegrity=true` plus `android.playIntegrity.cloudProjectNumber`, set to the number of the Google Cloud project linked to your app in the Play Console. Standard requests exist only on Google Play: on iOS, in the simulator and when the hint is missing, the call completes with an error, so fall back to `requestIntegrityToken()` there. + ==== Defending against accessibility-service abuse (Android) A common Android malware technique is to abuse the accessibility services API for overlays, remote control, and on-screen text extraction (including reading text destined for text-to-speech). Codename One lets you detect untrusted accessibility services and lock down sensitive screens. diff --git a/docs/website/data/port_status_supplement.json b/docs/website/data/port_status_supplement.json index 02573e74fe3..07d59375f16 100644 --- a/docs/website/data/port_status_supplement.json +++ b/docs/website/data/port_status_supplement.json @@ -42,6 +42,20 @@ } ] }, + { + "test": "TabsThemeScreenshotTest", + "reason": "A bottom tab bar is a phone and tablet pattern. On the round watch screen the glass tab bar has no room to lay out its tabs, so there is no meaningful baseline to capture.", + "platform_support": "Tabs has no watchOS-specific restriction; watch apps navigate with swipeable pages rather than a tab bar.", + "verification": "Every phone, desktop and browser leg renders the screen in both light and dark themes and compares it against stored goldens.", + "reason_codes": [ + { + "prefix": "tabs-on-watch", + "ports": [ + "watchos" + ] + } + ] + }, { "test": "LoadingPlaceholdersScreenshotTest", "reason": "The loading placeholders baseline is a phone-sized screen of skeletons, carousel and empty state. The watch form factor has no comparable layout to capture.", diff --git a/maven/build-engine/src/main/java/com/codename1/builders/AndroidGradleBuilder.java b/maven/build-engine/src/main/java/com/codename1/builders/AndroidGradleBuilder.java index 23e0002168f..86a2797e5c6 100644 --- a/maven/build-engine/src/main/java/com/codename1/builders/AndroidGradleBuilder.java +++ b/maven/build-engine/src/main/java/com/codename1/builders/AndroidGradleBuilder.java @@ -2753,6 +2753,7 @@ public boolean build(File sourceZip, final BuildRequest request) throws BuildExc } String googlePlayAdsMetaData = ""; + String playIntegrityMetaData = ""; String googlePlayAdsActivity = ""; String googlePlayObfuscation = ""; String googleAdUnitId = request.getArg("android.googleAdUnitId", request.getArg("google.adUnitId", null)); @@ -2851,11 +2852,29 @@ public boolean build(File sourceZip, final BuildRequest request) throws BuildExc if (playServicesAds) { minSDK = maxInt("21", minSDK); } + if (!playIntegrity && request.getArg("android.playIntegrity.cloudProjectNumber", "").trim().length() > 0) { + // Without the SDK the meta-data would be useless and the run-time error + // ("needs the cloudProjectNumber hint") would blame the hint that is set. + throw new BuildException("android.playIntegrity.cloudProjectNumber needs android.playIntegrity=true"); + } if (playIntegrity) { // com.google.android.play:integrity declares minSdk 21 in its own manifest, so // an application left at the default floor of 19 failed the manifest merger // ("uses-sdk:minSdkVersion 19 cannot be smaller than version 21"). minSDK = maxInt("21", minSDK); + // android.playIntegrity.cloudProjectNumber enables Standard requests + // (DeviceIntegrity.requestStandardIntegrityToken). The port reads it from + // application meta-data, prefixed with "p": a bare twelve digit value is + // parsed by the manifest as a number and overflows the int Android keeps. + String cloudProject = request.getArg("android.playIntegrity.cloudProjectNumber", "").trim(); + if (cloudProject.length() > 0) { + if (!cloudProject.matches("[0-9]+")) { + throw new BuildException("android.playIntegrity.cloudProjectNumber must be the numeric " + + "Google Cloud project number, got: " + cloudProject); + } + playIntegrityMetaData = ""; + } } if (rootCheck) { // rootbeer-lib 0.1.0 ships 4 KB aligned arm64/x86_64 natives, which Play @@ -6924,6 +6943,7 @@ && watchModuleName(request) != null && legacyGplayServicesMode) { + providerTag + usesLibrary + googlePlayAdsMetaData + + playIntegrityMetaData + " Old archives -- the ZBar {@code libzbar.a} shipped by the codescan and QR scanner + * cn1libs is the known case -- were written by tools that padded members to 2 bytes only. + * Some are misaligned inside the archive; the ZBar one is misaligned because its fat header + * places the 64-bit slices at offsets that are not multiples of 8. Xcode up to 26.3 linked them. The linker in Xcode 26.6 refuses them outright + * ("64-bit mach-o member 'codabar.o' not 8-byte aligned") and 27.x skips every such member, + * so the archive contributes nothing and the link fails on its symbols. The build server + * carries 26.6, 27.0 and 27.1 only, so no {@code ios.xcode_version} can avoid it, and the + * developer usually cannot rebuild a library that came inside someone else's cn1lib. + * + *

Detection is plain Java over the archive bytes. The repair extracts every member of + * every slice itself (unique file names, because an archive may hold two members of one + * name and {@code ar -x} would let one overwrite the other), rebuilds each slice with + * {@code libtool -static}, which aligns members and writes a fresh symbol table, and joins + * the slices again with {@code lipo}. Slices are cut out by offset rather than with + * {@code lipo -thin}, which reports a misaligned 64-bit slice as an empty archive. + */ +final class StaticLibraryAlignment { + private static final byte[] AR_MAGIC = "!\n".getBytes(StandardCharsets.US_ASCII); + private static final int AR_HEADER = 60; + + private StaticLibraryAlignment() { + } + + /** One architecture slice: where it starts in the file and how long it is. */ + static final class Slice { + final String label; + final int offset; + final int size; + + Slice(String label, int offset, int size) { + this.label = label; + this.offset = offset; + this.size = size; + } + } + + /** One archive member's name and data, relative to the whole file. */ + static final class Member { + final String name; + final int dataOffset; + final int dataSize; + + Member(String name, int dataOffset, int dataSize) { + this.name = name; + this.dataOffset = dataOffset; + this.dataSize = dataSize; + } + } + + /** The slices of a fat or thin static library, or null if it is not one we understand. */ + static List slices(byte[] b) { + List out = new ArrayList(); + if (startsWith(b, 0, AR_MAGIC)) { + out.add(new Slice("thin", 0, b.length)); + return out; + } + if (b.length < 8) { + return null; + } + long magic = be32(b, 0); + boolean fat64; + if (magic == 0xCAFEBABEL) { + fat64 = false; + } else if (magic == 0xCAFEBABFL) { + fat64 = true; + } else { + return null; + } + long n = be32(b, 4); + int entry = fat64 ? 32 : 20; + if (n <= 0 || n > 64 || 8 + n * entry > b.length) { + return null; + } + for (int i = 0; i < n; i++) { + int p = 8 + i * entry; + long off = fat64 ? be64(b, p + 8) : be32(b, p + 8); + long size = fat64 ? be64(b, p + 16) : be32(b, p + 12); + if (off < 0 || size <= 0 || off + size > b.length) { + return null; + } + out.add(new Slice("slice" + i, (int) off, (int) size)); + } + return out; + } + + /** The members of the archive in one slice, symbol tables excluded; null if malformed. */ + static List members(byte[] b, Slice s) { + if (!startsWith(b, s.offset, AR_MAGIC)) { + return null; + } + List out = new ArrayList(); + int end = s.offset + s.size; + int p = s.offset + AR_MAGIC.length; + while (p + AR_HEADER <= end) { + String rawName = new String(b, p, 16, StandardCharsets.US_ASCII).trim(); + long size; + try { + size = Long.parseLong(new String(b, p + 48, 10, StandardCharsets.US_ASCII).trim()); + } catch (NumberFormatException ex) { + return null; + } + int data = p + AR_HEADER; + if (size < 0 || data + size > end) { + return null; + } + String name = rawName; + int nameLen = 0; + if (rawName.startsWith("#1/")) { + try { + nameLen = Integer.parseInt(rawName.substring(3).trim()); + } catch (NumberFormatException ex) { + return null; + } + if (nameLen < 0 || nameLen > size) { + return null; + } + name = new String(b, data, nameLen, StandardCharsets.US_ASCII); + int nul = name.indexOf('\0'); + if (nul >= 0) { + name = name.substring(0, nul); + } + } else if (name.endsWith("/")) { + name = name.substring(0, name.length() - 1); + } + if (!name.startsWith("__.SYMDEF") && !name.equals("") && !name.equals("/") && !name.equals("//")) { + out.add(new Member(name, data + nameLen, (int) (size - nameLen))); + } + p = data + (int) size; + if ((p & 1) != 0) { + p++; + } + } + return out; + } + + /** + * True if any 64-bit Mach-O member does not start on an 8-byte boundary OF THE FILE. + * + *

The file offset is what the linker checks, not the offset within the slice: the + * ZBar library's members are aligned inside their slice, but its fat header puts the + * arm64 slice at byte 2575268, four bytes off, which misaligns every member in it. + */ + static boolean hasMisalignedMembers(byte[] b) { + List slices = slices(b); + if (slices == null) { + return false; + } + for (Slice s : slices) { + List members = members(b, s); + if (members == null) { + continue; + } + for (Member m : members) { + if (isMachO64(b, m.dataOffset, m.dataSize) && (m.dataOffset & 7) != 0) { + return true; + } + } + } + return false; + } + + private static boolean isMachO64(byte[] b, int p, int size) { + if (size < 4) { + return false; + } + // MH_MAGIC_64 is 0xfeedfacf; little-endian objects store it as cf fa ed fe. + return (b[p] & 0xff) == 0xcf && (b[p + 1] & 0xff) == 0xfa + && (b[p + 2] & 0xff) == 0xed && (b[p + 3] & 0xff) == 0xfe; + } + + /** + * Rewrites {@code lib} in place when it has misaligned 64-bit members. + * + * @return true if the library was rewritten + */ + static boolean realignIfNeeded(File lib, File workRoot, Executor ex) throws Exception { + byte[] b = Files.readAllBytes(lib.toPath()); + if (!hasMisalignedMembers(b)) { + return false; + } + List slices = slices(b); + File work = new File(workRoot, "realign-" + lib.getName() + "-" + System.nanoTime()); + if (!work.mkdirs()) { + throw new IOException("Could not create " + work); + } + List rebuilt = new ArrayList(); + for (Slice s : slices) { + List members = members(b, s); + if (members == null || members.isEmpty()) { + throw new IOException("Cannot read slice " + s.label + " of " + lib.getName()); + } + File dir = new File(work, s.label); + if (!dir.mkdirs()) { + throw new IOException("Could not create " + dir); + } + List cmd = new ArrayList(); + cmd.add("xcrun"); + cmd.add("libtool"); + cmd.add("-static"); + cmd.add("-no_warning_for_no_symbols"); + cmd.add("-o"); + File out = new File(work, s.label + ".a"); + cmd.add(out.getAbsolutePath()); + int i = 0; + for (Member m : members) { + // Index prefix keeps two members of one name apart and keeps the order. + File f = new File(dir, String.format("%04d_%s", i++, safeName(m.name))); + try (OutputStream os = new FileOutputStream(f)) { + os.write(b, m.dataOffset, m.dataSize); + } + cmd.add(f.getAbsolutePath()); + } + if (!ex.exec(work, cmd.toArray(new String[0])) || !out.isFile()) { + throw new IOException("libtool could not rebuild slice " + s.label + " of " + lib.getName()); + } + rebuilt.add(out.getAbsolutePath()); + } + File result = new File(work, "result.a"); + if (rebuilt.size() == 1 && "thin".equals(slices.get(0).label)) { + Files.copy(new File(rebuilt.get(0)).toPath(), result.toPath()); + } else { + List cmd = new ArrayList(); + cmd.add("xcrun"); + cmd.add("lipo"); + cmd.add("-create"); + cmd.addAll(rebuilt); + cmd.add("-output"); + cmd.add(result.getAbsolutePath()); + if (!ex.exec(work, cmd.toArray(new String[0])) || !result.isFile()) { + throw new IOException("lipo could not join the rebuilt slices of " + lib.getName()); + } + } + if (hasMisalignedMembers(Files.readAllBytes(result.toPath()))) { + throw new IOException("The rebuilt " + lib.getName() + " is still misaligned"); + } + Files.copy(result.toPath(), lib.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING); + return true; + } + + private static String safeName(String name) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < name.length(); i++) { + char c = name.charAt(i); + sb.append(Character.isLetterOrDigit(c) || c == '.' || c == '_' || c == '-' ? c : '_'); + } + return sb.length() == 0 ? "member.o" : sb.toString(); + } + + private static boolean startsWith(byte[] b, int p, byte[] prefix) { + if (p < 0 || p + prefix.length > b.length) { + return false; + } + for (int i = 0; i < prefix.length; i++) { + if (b[p + i] != prefix[i]) { + return false; + } + } + return true; + } + + private static long be32(byte[] b, int p) { + return ((long) (b[p] & 0xff) << 24) | ((b[p + 1] & 0xff) << 16) | ((b[p + 2] & 0xff) << 8) | (b[p + 3] & 0xff); + } + + private static long be64(byte[] b, int p) { + return (be32(b, p) << 32) | be32(b, p + 4); + } +} diff --git a/maven/build-engine/src/test/java/com/codename1/builders/StaticLibraryAlignmentTest.java b/maven/build-engine/src/test/java/com/codename1/builders/StaticLibraryAlignmentTest.java new file mode 100644 index 00000000000..d3fa09f5f9c --- /dev/null +++ b/maven/build-engine/src/test/java/com/codename1/builders/StaticLibraryAlignmentTest.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 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. + */ +package com.codename1.builders; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + +/** + * Detection of static libraries current Xcode linkers refuse. Synthetic bytes rather than a + * committed binary: the shape that matters is a 64-bit Mach-O member at an offset that is + * not a multiple of 8, which is what the old ZBar library has. + */ +public class StaticLibraryAlignmentTest { + + /** A BSD archive with one long-named 64-bit object member. */ + private static byte[] archive(String memberName) throws Exception { + ByteArrayOutputStream o = new ByteArrayOutputStream(); + o.write("!\n".getBytes(StandardCharsets.US_ASCII)); + byte[] name = memberName.getBytes(StandardCharsets.US_ASCII); + byte[] body = new byte[32]; + body[0] = (byte) 0xcf; + body[1] = (byte) 0xfa; + body[2] = (byte) 0xed; + body[3] = (byte) 0xfe; + String header = pad("#1/" + name.length, 16) + pad("0", 12) + pad("0", 6) + pad("0", 6) + + pad("100644", 8) + pad(String.valueOf(name.length + body.length), 10) + "`\n"; + o.write(header.getBytes(StandardCharsets.US_ASCII)); + o.write(name); + o.write(body); + return o.toByteArray(); + } + + private static String pad(String s, int n) { + StringBuilder sb = new StringBuilder(s); + while (sb.length() < n) { + sb.append(' '); + } + return sb.toString(); + } + + /** A fat file holding {@code slice} at {@code offset}. */ + private static byte[] fat(byte[] slice, int offset) { + byte[] b = new byte[offset + slice.length]; + int[] words = {0xCAFEBABE, 1, 0x0100000C, 0, offset, slice.length, 3}; + for (int i = 0; i < words.length; i++) { + int w = words[i]; + b[i * 4] = (byte) (w >>> 24); + b[i * 4 + 1] = (byte) (w >>> 16); + b[i * 4 + 2] = (byte) (w >>> 8); + b[i * 4 + 3] = (byte) w; + } + System.arraycopy(slice, 0, b, offset, slice.length); + return b; + } + + @Test + public void memberMisalignedInsideAThinArchiveIsFound() throws Exception { + // 8 + 60 + 6 = 74: the object starts four bytes off. + assertTrue(StaticLibraryAlignment.hasMisalignedMembers(archive("ab.o\0\0"))); + } + + @Test + public void alignedThinArchiveIsLeftAlone() throws Exception { + // 8 + 60 + 12 = 80. + assertFalse(StaticLibraryAlignment.hasMisalignedMembers(archive("config.o\0\0\0\0"))); + } + + @Test + public void sliceAtAnOffsetThatIsNotAMultipleOfEightIsFound() throws Exception { + // Aligned inside its archive, but the fat header puts the slice four bytes off -- + // exactly the ZBar library, whose arm64 slice starts at byte 2575268. + byte[] aligned = archive("config.o\0\0\0\0"); + assertFalse(StaticLibraryAlignment.hasMisalignedMembers(fat(aligned, 4096))); + assertTrue(StaticLibraryAlignment.hasMisalignedMembers(fat(aligned, 4100))); + } + + @Test + public void symbolTableAndNonObjectsAreIgnored() throws Exception { + byte[] b = archive("__.SYMDEF\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); + assertEquals(0, StaticLibraryAlignment.members(b, + StaticLibraryAlignment.slices(b).get(0)).size()); + assertFalse(StaticLibraryAlignment.hasMisalignedMembers("not an archive".getBytes(StandardCharsets.US_ASCII))); + } +} diff --git a/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsAndroid.java b/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsAndroid.java index 8f416d76bce..1e7bdae67da 100644 --- a/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsAndroid.java +++ b/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsAndroid.java @@ -859,6 +859,11 @@ static void register(List h) { .type(HintType.STRING) .platform("android")); + h.add(new Hint("android.playIntegrity.cloudProjectNumber") + .group(HintGroup.ANDROID) + .type(HintType.STRING) + .platform("android")); + h.add(new Hint("android.playIntegrityVersion") .group(HintGroup.ANDROID) .type(HintType.VERSION) diff --git a/maven/core-unittests/src/test/java/com/codename1/ui/util/UtilCoverageTest.java b/maven/core-unittests/src/test/java/com/codename1/ui/util/UtilCoverageTest.java index 2a581864dd0..f83a99c64c9 100644 --- a/maven/core-unittests/src/test/java/com/codename1/ui/util/UtilCoverageTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/ui/util/UtilCoverageTest.java @@ -456,28 +456,40 @@ public void paint(Graphics g) { /// The test thread is the EDT, so the first wait enters showOn's modal loop /// and gets control back only once that dialog closes. A dispose queued /// once -- or re-queued by a loop out here -- can run before the dialog is - /// current and then nothing ever closes it: the loop never runs again and - /// the test times out (both build-test legs on master). The closer - /// therefore re-queues ITSELF, so it keeps firing from inside the modal - /// loop until showOn has returned. + /// current and then nothing ever closes it. The closer therefore re-queues + /// ITSELF, so it keeps firing from inside the modal loop until showOn has + /// returned. It has no wall-clock deadline: a 4 s deadline inside the 5 s + /// test timeout made a slow runner stop closing just before the dialog was + /// current, and the test hung (build-test (21) on master). It stops when + /// showOn returns, or when the test abandons it through `stop`. private static void closeDialogUntil(final boolean[] finished) { - final long deadline = System.currentTimeMillis() + 4000; + // A dialog backed by a native window is never Display.getCurrent(), so + // the closer below could not find it; a test that leaves the default + // native mode on would hang this one. Pin it off for the showing. + final boolean nativeMode = Dialog.isDefaultNativeWindowMode(); + Dialog.setDefaultNativeWindowMode(false); + final boolean[] stop = new boolean[1]; CN.callSerially(new Runnable() { public void run() { - // Stops at the deadline too, so a failed test cannot leave it - // spinning into the next one. - if (finished[0] || System.currentTimeMillis() > deadline) { + if (finished[0] || stop[0]) { return; } + // Re-queue BEFORE touching the dialog: an exception from + // dispose() would otherwise end the chain with the dialog open. + CN.callSerially(this); Form current = Display.getInstance().getCurrent(); if (current instanceof Dialog) { ((Dialog) current).dispose(); } - CN.callSerially(this); } }); - while (!finished[0] && System.currentTimeMillis() < deadline) { - TestUtils.waitFor(20); + try { + while (!finished[0]) { + TestUtils.waitFor(20); + } + } finally { + stop[0] = true; + Dialog.setDefaultNativeWindowMode(nativeMode); } } } diff --git a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/TabsThemeScreenshotTest.java b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/TabsThemeScreenshotTest.java index 25eb617c41c..608a096151e 100644 --- a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/TabsThemeScreenshotTest.java +++ b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/TabsThemeScreenshotTest.java @@ -1,5 +1,28 @@ +/* + * Copyright (c) 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. + */ package com.codenameone.examples.hellocodenameone.tests; +import com.codename1.ui.CN; import com.codename1.ui.Button; import com.codename1.ui.Container; import com.codename1.ui.FontImage; @@ -10,6 +33,20 @@ import com.codename1.ui.layouts.Layout; public class TabsThemeScreenshotTest extends DualAppearanceBaseTest { + // cn1ss-skip: watchos -- captures nothing on these ports (the guard below); + // scripts/ci/cn1ss-golden-plan.py expects a golden everywhere else. + // A tab bar is not a watch UI; the glass tab bar collapses its labels into + // one spot on the round watch layout, which no watch app would ship. + @Override + public boolean runTest() { + if (CN.isWatch()) { + System.out.println("CN1SS:INFO:test=TabsThemeScreenshotTest status=SKIPPED reason=tabs-on-watch"); + skipAppearances(); + return true; + } + return super.runTest(); + } + @Override protected String baseName() { return "TabsTheme"; diff --git a/scripts/ios/screenshots-watch/AppReviewDialog.png b/scripts/ios/screenshots-watch/AppReviewDialog.png index c76dbc11168..e0860399700 100644 Binary files a/scripts/ios/screenshots-watch/AppReviewDialog.png and b/scripts/ios/screenshots-watch/AppReviewDialog.png differ diff --git a/scripts/ios/screenshots-watch/TabsTheme_dark.png b/scripts/ios/screenshots-watch/TabsTheme_dark.png deleted file mode 100644 index b74cb986dc8..00000000000 Binary files a/scripts/ios/screenshots-watch/TabsTheme_dark.png and /dev/null differ diff --git a/scripts/ios/screenshots-watch/TabsTheme_light.png b/scripts/ios/screenshots-watch/TabsTheme_light.png deleted file mode 100644 index 9a7de90d5c8..00000000000 Binary files a/scripts/ios/screenshots-watch/TabsTheme_light.png and /dev/null differ diff --git a/scripts/ios/screenshots-watch/ValidatorLightweightPicker.png b/scripts/ios/screenshots-watch/ValidatorLightweightPicker.png index aa538fe4454..c9a81c69eda 100644 Binary files a/scripts/ios/screenshots-watch/ValidatorLightweightPicker.png and b/scripts/ios/screenshots-watch/ValidatorLightweightPicker.png differ diff --git a/vm/selfhost/perf-baseline/pr/6392.json b/vm/selfhost/perf-baseline/pr/6392.json new file mode 100644 index 00000000000..9d1e8de9d3c --- /dev/null +++ b/vm/selfhost/perf-baseline/pr/6392.json @@ -0,0 +1,60 @@ +{ + "pr": 6392, + "rebaseline": { + "linux-x64@amd-epyc-9v45-96-core-processor": { + "translator": { + "all": { + "from": { + "memory": 0.548, + "time": 0.641, + "tolerance": { + "time": 0.2 + } + }, + "memory": 0.744, + "reason": "Stale single-run memory rows: translator RAM on EPYC 9V45 measured 0.57x on master e48c30ea70 and 0.74x here with identical VM code; EPYC 9V74's 0.46x row (Oct 14) is below every December run (0.58-0.66x, master 26ce12b7ca included); Windows arm64 D84's hello row (0.41x, one run, Oct 23) is half of D49's 0.75x and master measured 0.84x there. This PR changes no VM or translator code.", + "runs": 1, + "time": 0.641 + } + } + }, + "linux-x64@amd-epyc-9v74-80-core-processor": { + "translator": { + "all": { + "from": { + "memory": 0.463, + "time": 0.628, + "tolerance": { + "time": 0.2 + } + }, + "memory": 0.584, + "reason": "Stale single-run memory rows: translator RAM on EPYC 9V45 measured 0.57x on master e48c30ea70 and 0.74x here with identical VM code; EPYC 9V74's 0.46x row (Oct 14) is below every December run (0.58-0.66x, master 26ce12b7ca included); Windows arm64 D84's hello row (0.41x, one run, Oct 23) is half of D49's 0.75x and master measured 0.84x there. This PR changes no VM or translator code.", + "runs": 1, + "time": 0.628 + } + } + }, + "windows-arm64@armv8-64-bit-family-8-model-d84-microsoft-corporation": { + "hello": { + "all": { + "from": { + "memory": 0.407, + "time": 1.217, + "tolerance": { + "memory": 0.2, + "time": 0.5 + } + }, + "memory": 0.664, + "reason": "Stale single-run memory rows: translator RAM on EPYC 9V45 measured 0.57x on master e48c30ea70 and 0.74x here with identical VM code; EPYC 9V74's 0.46x row (Oct 14) is below every December run (0.58-0.66x, master 26ce12b7ca included); Windows arm64 D84's hello row (0.41x, one run, Oct 23) is half of D49's 0.75x and master measured 0.84x there. This PR changes no VM or translator code.", + "runs": 1, + "time": 1.217, + "tolerance": { + "time": 0.5 + } + } + } + } + } +}