From fd61d9449d31321fe36c2f19a6c3f2dcdd253ce6 Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Sat, 5 Dec 2026 18:52:32 +0200 Subject: [PATCH 1/3] Device runtime: shrink the interpreter shims, compile them for size Every shim overrides every method its class inherits: about 104k overrides averaging 2.3 KB of machine code each, two thirds of the iOS executable, which exceeded the App Store's 500 MB limit once the interpreter bindings were on. Each override now calls a per-parameter-shape helper in a generated InterpCalls class that holds the argument array, the try/catch and the exception unwrapping; the override keeps only the sentinel test and its own super call. Behavior is unchanged case by case. The new ios.sizeOptimizedClasses build hint adds -Oz to the per-file compiler flags of the named classes in the generated Xcode project; the device runtime sets it for its shim package. Stripped device executable, same project: 579 MB -> 264 MB. Co-Authored-By: Claude Opus 5.5 --- .../com/codename1/builders/IPhoneBuilder.java | 18 ++ .../builders/XcodeSizeOptimizedSources.java | 143 +++++++++++ .../XcodeSizeOptimizedSourcesTest.java | 93 ++++++++ .../codename1/build/shared/BuildHintsIos.java | 10 + scripts/cn1-device-runtime/INTERNALS.asciidoc | 8 + .../common/codenameone_settings.properties | 3 + .../devruntime/tools/GenerateInterpShims.java | 222 +++++++++++++++--- 7 files changed, 460 insertions(+), 37 deletions(-) create mode 100644 maven/build-engine/src/main/java/com/codename1/builders/XcodeSizeOptimizedSources.java create mode 100644 maven/build-engine/src/test/java/com/codename1/builders/XcodeSizeOptimizedSourcesTest.java diff --git a/maven/build-engine/src/main/java/com/codename1/builders/IPhoneBuilder.java b/maven/build-engine/src/main/java/com/codename1/builders/IPhoneBuilder.java index 1274ecd40b0..e82b5ca1780 100644 --- a/maven/build-engine/src/main/java/com/codename1/builders/IPhoneBuilder.java +++ b/maven/build-engine/src/main/java/com/codename1/builders/IPhoneBuilder.java @@ -7385,6 +7385,24 @@ public void usesClassMethod(String cls, String method) { throw new BuildException("Failed to update infoplist file", ex); } + // ios.sizeOptimizedClasses: compile the named classes with -Oz. See + // XcodeSizeOptimizedSources for why; the cloud builder does the same. + java.util.List sizeOptimized = XcodeSizeOptimizedSources.filePrefixes( + request.getArg("ios.sizeOptimizedClasses", null)); + if (!sizeOptimized.isEmpty()) { + try { + java.nio.file.Path pbxPath = new File(tmpFile, "dist/" + request.getMainClass() + + ".xcodeproj/project.pbxproj").toPath(); + String before = new String(java.nio.file.Files.readAllBytes(pbxPath), "UTF-8"); + String after = XcodeSizeOptimizedSources.apply(before, sizeOptimized); + if (!after.equals(before)) { + java.nio.file.Files.write(pbxPath, after.getBytes("UTF-8")); + } + } catch (IOException ex) { + throw new BuildException("Failed to apply ios.sizeOptimizedClasses", ex); + } + } + try { normalizeAssetCatalogs(request); } catch (Exception ex) { diff --git a/maven/build-engine/src/main/java/com/codename1/builders/XcodeSizeOptimizedSources.java b/maven/build-engine/src/main/java/com/codename1/builders/XcodeSizeOptimizedSources.java new file mode 100644 index 00000000000..f614d0f02c5 --- /dev/null +++ b/maven/build-engine/src/main/java/com/codename1/builders/XcodeSizeOptimizedSources.java @@ -0,0 +1,143 @@ +/* + * 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 java.util.ArrayList; +import java.util.List; + +/// Compiles chosen translated classes for size (`-Oz`) while the rest of the +/// application keeps the project's speed optimization. +/// +/// The `ios.sizeOptimizedClasses` build hint names class-name prefixes. Each +/// translated class is one source file whose name is the class name with `.` +/// replaced by `_`, and its `PBXBuildFile` entry in the generated project gets +/// `-Oz` in its per-file `COMPILER_FLAGS`. Per-file flags come after the +/// target's own on the compile line, so the later `-Oz` wins over the +/// configuration's `-O3`. +/// +/// The device runtime is what this is for: its generated interpreter shims are +/// two thirds of its executable and only forward calls into an interpreter, so +/// faster code buys nothing there while the size pushes the app toward the App +/// Store's executable limit. Measured on that app, `-Oz` halves the shims' +/// machine code. +/// +/// Editing the project, rather than asking the translator, means it works with +/// whichever ParparVM produced the project. +final class XcodeSizeOptimizedSources { + static final String FLAG = "-Oz"; + + private XcodeSizeOptimizedSources() { + } + + /// The source file name prefixes the hint value names, or none for an empty + /// or absent value. + static List filePrefixes(String hint) { + List out = new ArrayList(); + if (hint == null) { + return out; + } + for (String p : hint.split(",")) { + String t = p.trim(); + if (t.length() > 0) { + out.add(t.replace('.', '_')); + } + } + return out; + } + + /// Returns the project text with `-Oz` added to the build file entry of + /// every C or Objective-C source whose name starts with one of the + /// prefixes. Anything else, and an entry that already carries the flag, is + /// left as it was, so applying it twice changes nothing. + static String apply(String pbx, List prefixes) { + if (prefixes.isEmpty()) { + return pbx; + } + StringBuilder out = new StringBuilder(pbx.length() + 4096); + int start = 0; + while (start < pbx.length()) { + int end = pbx.indexOf('\n', start); + end = end < 0 ? pbx.length() : end + 1; + out.append(rewrite(pbx.substring(start, end), prefixes)); + start = end; + } + return out.toString(); + } + + private static String rewrite(String line, List prefixes) { + if (line.indexOf("isa = PBXBuildFile;") < 0) { + return line; + } + int open = line.indexOf("/* "); + int close = open < 0 ? -1 : line.indexOf(" */", open + 3); + if (close < 0) { + return line; + } + String file = line.substring(open + 3, close); + if (!isCompiledSource(file) || !matches(file, prefixes)) { + return line; + } + String flagsKey = "COMPILER_FLAGS = \""; + int flags = line.indexOf(flagsKey); + if (flags >= 0) { + int valueStart = flags + flagsKey.length(); + int valueEnd = line.indexOf('"', valueStart); + if (valueEnd < 0) { + return line; + } + String value = line.substring(valueStart, valueEnd); + if ((" " + value + " ").indexOf(" " + FLAG + " ") >= 0) { + return line; + } + String joined = value.trim().length() == 0 ? FLAG : value + " " + FLAG; + return line.substring(0, valueStart) + joined + line.substring(valueEnd); + } + int settings = line.indexOf("settings = {"); + if (settings >= 0) { + int at = settings + "settings = {".length(); + return line.substring(0, at) + "COMPILER_FLAGS = \"" + FLAG + "\"; " + line.substring(at); + } + // An entry with no settings dictionary at all: give it one, just before + // the entry's closing brace. + int last = line.lastIndexOf("};"); + if (last < 0) { + return line; + } + return line.substring(0, last) + "settings = {COMPILER_FLAGS = \"" + FLAG + "\"; }; " + + line.substring(last); + } + + private static boolean isCompiledSource(String file) { + return file.endsWith(".m") || file.endsWith(".c") || file.endsWith(".mm") + || file.endsWith(".cpp"); + } + + private static boolean matches(String file, List prefixes) { + for (String p : prefixes) { + if (file.startsWith(p)) { + return true; + } + } + return false; + } +} diff --git a/maven/build-engine/src/test/java/com/codename1/builders/XcodeSizeOptimizedSourcesTest.java b/maven/build-engine/src/test/java/com/codename1/builders/XcodeSizeOptimizedSourcesTest.java new file mode 100644 index 00000000000..aedb6838b59 --- /dev/null +++ b/maven/build-engine/src/test/java/com/codename1/builders/XcodeSizeOptimizedSourcesTest.java @@ -0,0 +1,93 @@ +/* + * 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.assertTrue; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; + +class XcodeSizeOptimizedSourcesTest { + private static final List GEN = + XcodeSizeOptimizedSources.filePrefixes(" com.codenameone.devruntime.gen. , "); + + // The entry shapes ParparVM's project generator writes: no flags, and the + // -fno-objc-arc one with a weak-link attribute. + private static final String PLAIN = "\t\t0F6456DE18E9ABBC002F3D1D /* " + + "com_codenameone_devruntime_gen_Interp_ui_Form.m */ = {isa = PBXBuildFile; fileRef = " + + "0F6456DD18E9ABBC002F3D1D /* com_codenameone_devruntime_gen_Interp_ui_Form.m */;" + + "settings = { }; };\n"; + private static final String NO_ARC = "\t\t0A18E9ABBC002F3D1D /* com_codenameone_devruntime_gen_X.m */" + + " = {isa = PBXBuildFile; fileRef = 0B18E9ABBC002F3D1D /* com_codenameone_devruntime_gen_X.m */;" + + " settings = {COMPILER_FLAGS = \"-fno-objc-arc\"; ATTRIBUTES = (Weak, ); }; };\n"; + + @Test + void prefixesBecomeFileNamePrefixes() { + assertEquals(Collections.singletonList("com_codenameone_devruntime_gen_"), GEN); + assertTrue(XcodeSizeOptimizedSources.filePrefixes(null).isEmpty()); + assertTrue(XcodeSizeOptimizedSources.filePrefixes(" , ").isEmpty()); + } + + @Test + void addsTheFlagToAnEntryWithoutFlags() { + assertEquals(PLAIN.replace("settings = { }", "settings = {COMPILER_FLAGS = \"-Oz\"; }"), + XcodeSizeOptimizedSources.apply(PLAIN, GEN)); + } + + @Test + void appendsToExistingFlagsSoTheyStillApply() { + assertEquals(NO_ARC.replace("\"-fno-objc-arc\"", "\"-fno-objc-arc -Oz\""), + XcodeSizeOptimizedSources.apply(NO_ARC, GEN)); + } + + @Test + void leavesOtherSourcesHeadersAndReferencesAlone() { + String other = PLAIN.replace("com_codenameone_devruntime_gen_", "com_codename1_ui_"); + String header = PLAIN.replace("Form.m", "Form.h"); + String fileRef = "\t\t0F6456DD18E9ABBC002F3D1D /* com_codenameone_devruntime_gen_Interp_ui_Form.m */" + + " = {isa = PBXFileReference; path = \"com_codenameone_devruntime_gen_Interp_ui_Form.m\"; };\n"; + String project = other + header + fileRef; + assertEquals(project, XcodeSizeOptimizedSources.apply(project, GEN)); + } + + @Test + void applyingTwiceChangesNothingMore() { + String once = XcodeSizeOptimizedSources.apply(PLAIN + NO_ARC, GEN); + assertEquals(once, XcodeSizeOptimizedSources.apply(once, GEN)); + } + + @Test + void noPrefixesMeansNoChange() { + assertEquals(PLAIN, XcodeSizeOptimizedSources.apply(PLAIN, Collections.emptyList())); + } + + @Test + void anyOfSeveralPrefixesMatches() { + List two = XcodeSizeOptimizedSources.filePrefixes("com.other.,com.codenameone.devruntime.gen."); + assertEquals(Arrays.asList("com_other_", "com_codenameone_devruntime_gen_"), two); + assertTrue(XcodeSizeOptimizedSources.apply(PLAIN, two).contains("\"-Oz\"")); + } +} diff --git a/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsIos.java b/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsIos.java index d023e1f7d03..5658251ee5e 100644 --- a/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsIos.java +++ b/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsIos.java @@ -652,6 +652,16 @@ static void register(List h) { + "on-device interpreter app (scripts/cn1-device-runtime). A regular app " + "leaves this false and gets a smaller binary.")); + h.add(new Hint("ios.sizeOptimizedClasses") + .group(HintGroup.IOS) + .type(HintType.STRING) + .platform("ios") + .doc("Comma-separated class-name prefixes (com.example.gen.) whose translated " + + "sources are compiled for size (-Oz) instead of the project's speed " + + "optimization. Meant for large generated code off the hot paths, such " + + "as the device runtime's interpreter shims, where it halves the machine " + + "code and keeps the executable under the App Store's limit.")); + h.add(new Hint("ios.featureScanExclude") .group(HintGroup.IOS) .type(HintType.STRING) diff --git a/scripts/cn1-device-runtime/INTERNALS.asciidoc b/scripts/cn1-device-runtime/INTERNALS.asciidoc index 8bd8d34bb11..75eb91c8004 100644 --- a/scripts/cn1-device-runtime/INTERNALS.asciidoc +++ b/scripts/cn1-device-runtime/INTERNALS.asciidoc @@ -300,6 +300,14 @@ A generated shim overrides the framework method and asks the interpreter for it. That's what the `super_` bridges on every shim are for: `super.paint(g)` from interpreted code is dispatched to `super_paint`, which is the only path to the framework implementation. The same applies to any `super.` call on a host superclass. +=== Shim methods are a call, not a template + +Every shim overrides every method its class inherits, so the shims are most of the app: about 1,650 classes and 104,000 overrides. When each override carried its own argument array, its own `try`/`catch` and its own exception unwrapping, they averaged 2.3 KB of machine code each. Together they were two thirds of the executable and pushed it past the App Store's 500 MB limit. Each new framework method also grew every shim that inherits it. + +An override now calls a helper in the generated `InterpCalls` class, one helper per parameter shape (about 260 shapes cover the framework). It tests the result with `InterpCalls.miss` and calls `super` itself, because Java allows a `super` call only inside the subclass. Only a method that declares a checked exception keeps a handler, so that the exception reaches its caller by its own type. Keep new shim behavior in the helpers, not in the emitted method body. + +The device runtime also sets the `ios.sizeOptimizedClasses` build hint for the generated package, so the iOS build compiles the shims with `-Oz`. They only forward calls into the interpreter, where the speed difference doesn't show. The rest of the app keeps the project's optimization. Together these changes cut the shims' machine code from 396 MB to 86 MB. + === Pushing an application, not a file `cn1:push` sends the module's whole compiled tree with all of its source roots, diff --git a/scripts/cn1-device-runtime/common/codenameone_settings.properties b/scripts/cn1-device-runtime/common/codenameone_settings.properties index 2ea7edab2b0..4a1429e8c80 100644 --- a/scripts/cn1-device-runtime/common/codenameone_settings.properties +++ b/scripts/cn1-device-runtime/common/codenameone_settings.properties @@ -7,6 +7,9 @@ # builds; nothing here calls Play billing or FCM at runtime. codename1.arg.android.useAndroidX=true codename1.arg.ios.interpHost=true +# The interpreter shims are two thirds of the executable and only forward calls; +# compiled for size they stay well under the App Store executable limit. +codename1.arg.ios.sizeOptimizedClasses=com.codenameone.devruntime.gen. # A pushed program gets the native theme its own ios.themeMode / # ios.themeGeneration ask for, so every iOS native theme has to be in the # bundle; the builder otherwise ships only the one this app's mode loads. diff --git a/scripts/cn1-device-runtime/tools/src/main/java/com/codenameone/devruntime/tools/GenerateInterpShims.java b/scripts/cn1-device-runtime/tools/src/main/java/com/codenameone/devruntime/tools/GenerateInterpShims.java index 38231453969..f582c5c80a9 100644 --- a/scripts/cn1-device-runtime/tools/src/main/java/com/codenameone/devruntime/tools/GenerateInterpShims.java +++ b/scripts/cn1-device-runtime/tools/src/main/java/com/codenameone/devruntime/tools/GenerateInterpShims.java @@ -268,6 +268,7 @@ public static void main(String[] args) throws Exception { writeNativeCapabilities(outDir, frameworkJar); writeRegistry(outDir, generated, okClasses, ifaceShims, okInterfaces); + writeCallHelpers(outDir); System.out.println("generated " + generated.size() + " class shims, " + ifaceShims.size() + " interface shims, " + skipped + " skipped, " + skippedByExclusion + " excluded, into " + outDir); @@ -885,8 +886,8 @@ private static void emitInterfaceMethod(PrintWriter w, Method m, Class target } w.println(" public " + typeName(ret) + " " + m.getName() + "(" + sig + ")" + throwsClause(m) + " {"); - emitDispatch(w, m, "$runtime.dispatch($interp, \"" + m.getName() + "\", \"" - + descriptorOf(params, ret) + "\", new Object[]{" + boxed + "})"); + emitDispatch(w, m, helperCall("null", m.getName(), descriptorOf(params, ret), + params, boxed)); if (!m.isDefault()) { // A stopped program's peer is still held by whatever registered it. // Answering nothing is the point of detaching; throwing here would @@ -1594,8 +1595,8 @@ private static void emitObjectMethods(PrintWriter w, Set alreadyEmitted, if (!alreadyEmitted.contains("toString()") && !sealed(target, "toString")) { w.println(" @Override"); w.println(" public String toString() {"); - w.println(" Object $r = InterpRuntime.dispatchOrDeferred(this, $runtime, $interp,"); - w.println(" \"toString\", \"()Ljava/lang/String;\", new Object[]{});"); + w.println(" Object $r = " + helperCall("this", "toString", "()Ljava/lang/String;", + new Class[0], new StringBuilder()) + ";"); w.println(" if (" + MISS + ") {"); w.println(" return super.toString();"); w.println(" }"); @@ -1606,12 +1607,12 @@ private static void emitObjectMethods(PrintWriter w, Set alreadyEmitted, if (!alreadyEmitted.contains("hashCode()") && !sealed(target, "hashCode")) { w.println(" @Override"); w.println(" public int hashCode() {"); - w.println(" Object $r = InterpRuntime.dispatchOrDeferred(this, $runtime, $interp,"); - w.println(" \"hashCode\", \"()I\", new Object[]{});"); + w.println(" Object $r = " + helperCall("this", "hashCode", "()I", + new Class[0], new StringBuilder()) + ";"); w.println(" if (" + MISS + ") {"); w.println(" return super.hashCode();"); w.println(" }"); - w.println(" return $r == null ? 0 : ((Number)$r).intValue();"); + w.println(" return " + unbox(Integer.TYPE, "$r") + ";"); w.println(" }"); w.println(); } @@ -1619,12 +1620,12 @@ private static void emitObjectMethods(PrintWriter w, Set alreadyEmitted, && !sealed(target, "equals")) { w.println(" @Override"); w.println(" public boolean equals(Object a0) {"); - w.println(" Object $r = InterpRuntime.dispatchOrDeferred(this, $runtime, $interp,"); - w.println(" \"equals\", \"(Ljava/lang/Object;)Z\", new Object[]{a0});"); + w.println(" Object $r = " + helperCall("this", "equals", "(Ljava/lang/Object;)Z", + new Class[]{Object.class}, new StringBuilder("a0")) + ";"); w.println(" if (" + MISS + ") {"); w.println(" return super.equals(a0);"); w.println(" }"); - w.println(" return $r != null && ((Boolean)$r).booleanValue();"); + w.println(" return " + unbox(Boolean.TYPE, "$r") + ";"); w.println(" }"); w.println(); } @@ -1695,9 +1696,8 @@ private static void emitOverride(PrintWriter w, Method m, Map> // constructor pushes before super() runs; the object has no state // yet, exactly as Java dictates during that window, but the // override runs rather than being silently skipped. - emitDispatch(w, thrown, "InterpRuntime.dispatchOrDeferred(this, $runtime, $interp, \"" - + m.getName() + "\", \"" - + descriptorOf(params, ret) + "\", new Object[]{" + boxed + "})"); + emitDispatch(w, thrown, helperCall("this", m.getName(), descriptorOf(params, ret), + params, boxed)); if (abstractMethod) { // See zero(): a callback for a program that has been stopped. w.println(" if ($r == InterpRuntime.DETACHED) {"); @@ -1747,8 +1747,7 @@ private static void emitOverride(PrintWriter w, Method m, Map> * stopped. Both are handled by doing what the framework class would do on * its own, which for anything with a body is calling it.

*/ - private static final String MISS = - "$r == InterpRuntime.NOT_OVERRIDDEN || $r == InterpRuntime.DETACHED"; + private static final String MISS = "InterpCalls.miss($r)"; /** * The value a method returns when a callback arrives for a program that has @@ -1771,14 +1770,16 @@ private static String zero(Class t) { } private static String unbox(Class t, String expr) { - if (t == Boolean.TYPE) return "$r == null ? false : ((Boolean)" + expr + ").booleanValue()"; - if (t == Byte.TYPE) return "$r == null ? (byte)0 : ((Number)" + expr + ").byteValue()"; - if (t == Character.TYPE) return "$r == null ? (char)0 : ((Character)" + expr + ").charValue()"; - if (t == Short.TYPE) return "$r == null ? (short)0 : ((Number)" + expr + ").shortValue()"; - if (t == Integer.TYPE) return "$r == null ? 0 : ((Number)" + expr + ").intValue()"; - if (t == Long.TYPE) return "$r == null ? 0L : ((Number)" + expr + ").longValue()"; - if (t == Float.TYPE) return "$r == null ? 0f : ((Number)" + expr + ").floatValue()"; - if (t == Double.TYPE) return "$r == null ? 0d : ((Number)" + expr + ").doubleValue()"; + // The null and wrapper handling lives once in the helper class; inline + // it was a branch and a cast per override, 104k times over. + if (t == Boolean.TYPE) return CALLS + ".z(" + expr + ")"; + if (t == Byte.TYPE) return CALLS + ".b(" + expr + ")"; + if (t == Character.TYPE) return CALLS + ".c(" + expr + ")"; + if (t == Short.TYPE) return CALLS + ".s(" + expr + ")"; + if (t == Integer.TYPE) return CALLS + ".i(" + expr + ")"; + if (t == Long.TYPE) return CALLS + ".j(" + expr + ")"; + if (t == Float.TYPE) return CALLS + ".f(" + expr + ")"; + if (t == Double.TYPE) return CALLS + ".d(" + expr + ")"; return "(" + typeName(t) + ")" + expr; } @@ -1841,30 +1842,29 @@ private static void emitDispatch(PrintWriter w, Class[] declared, String call checked.add(e); } } + // The helper already rethrows an unchecked host throwable by its own + // type and anything else as the carrier, so a method that declares no + // checked exception needs no handler of its own -- which is nearly + // every method, and the try/catch was most of each override's code. + if (checked.isEmpty()) { + w.println(" Object $r = " + call + ";"); + return; + } + // A declared checked exception is thrown by its own type, so an + // interpreted Row.getString() throwing IOException reaches the + // caller's catch (IOException). hostThrowable, not getThrown: a pushed + // exception class arrives as an InterpObject whose peer is the host + // exception, and only the peer can match a catch clause. w.println(" Object $r;"); w.println(" try {"); w.println(" $r = " + call + ";"); w.println(" } catch (com.codename1.impl.interp.InterpThrowable $t) {"); - // hostThrowable, not getThrown: a pushed exception class arrives as an - // InterpObject whose peer is the host exception, and only the peer can - // match a catch clause. w.println(" Throwable $thrown = $t.hostThrowable();"); for (Class e : checked) { w.println(" if ($thrown instanceof " + typeName(e) + ") {"); w.println(" throw (" + typeName(e) + ") $thrown;"); w.println(" }"); } - // Unchecked ones need no throws clause to travel, and framework code - // around a callback catches them by their own type: a pushed - // `MyIllegalArgumentException extends IllegalArgumentException` has a - // peer that *is* an IllegalArgumentException, and letting the - // interpreter's carrier escape instead means that catch never runs. - w.println(" if ($thrown instanceof RuntimeException) {"); - w.println(" throw (RuntimeException) $thrown;"); - w.println(" }"); - w.println(" if ($thrown instanceof Error) {"); - w.println(" throw (Error) $thrown;"); - w.println(" }"); w.println(" throw $t;"); w.println(" }"); } @@ -2015,6 +2015,154 @@ private static String descriptorOf(Class c) { * and every interpreted {@code new} and every host call through a peer goes * through here.

*/ + /** The generated class every shim method dispatches through. */ + private static final String CALLS = "InterpCalls"; + + /** + * Every parameter shape a shim method has used, by helper name. Sorted so + * that generating twice writes the same file. + */ + private static final java.util.TreeMap[]> SHAPES = + new java.util.TreeMap[]>(); + + /** + * One letter per parameter: the primitive's descriptor, or {@code L} for + * any reference. References share a helper whatever their type, since the + * helper only boxes them into the argument array. + */ + private static char shapeCode(Class p) { + if (!p.isPrimitive()) { + return 'L'; + } + return descriptorOf(p).charAt(0); + } + + /** + * The call a shim method makes to ask the interpreter, recording the + * helper it needs. + * + *

Every override used to carry its own argument array, its own + * try/catch and its own rethrow chain: 2.3 KB of machine code each, and + * one override per inherited method per shim -- 104k of them, two thirds + * of the executable. A helper per parameter shape holds all of that once + * (a few hundred shapes cover the whole framework), so an override is a + * call, a sentinel test and its own super call -- the one part Java only + * allows inside the subclass itself.

+ * + * @param shim {@code "this"} for a class shim, which has to reach the + * interpreter during its superclass constructor and so goes + * through {@code dispatchOrDeferred}; {@code "null"} for an + * interface shim, which calls {@code dispatch} directly as it + * always did. + */ + private static String helperCall(String shim, String name, String descriptor, + Class[] params, CharSequence args) { + StringBuilder key = new StringBuilder("d_"); + Class[] erased = new Class[params.length]; + for (int i = 0; i < params.length; i++) { + char code = shapeCode(params[i]); + key.append(code); + erased[i] = code == 'L' ? Object.class : params[i]; + } + String helper = key.toString(); + if (!SHAPES.containsKey(helper)) { + SHAPES.put(helper, erased); + } + return CALLS + "." + helper + "(" + shim + ", $runtime, $interp, \"" + name + "\", \"" + + descriptor + "\"" + (args.length() == 0 ? "" : ", " + args) + ")"; + } + + /** + * Writes {@code InterpCalls}: the per-shape helpers {@link #helperCall} + * recorded, and the conversions every shim shares. + * + *

It only uses what the runtime has always offered a shim -- + * {@code dispatchOrDeferred}, {@code dispatch}, the two sentinels and + * {@code InterpThrowable.hostThrowable} -- so shims generated this way run + * on a framework built before it existed.

+ */ + private static void writeCallHelpers(File dir) throws Exception { + PrintWriter w = new PrintWriter(new File(dir, CALLS + ".java"), "UTF-8"); + try { + header(w); + w.println("package com.codenameone.devruntime.gen;"); + w.println(); + w.println("import com.codename1.impl.interp.InterpObject;"); + w.println("import com.codename1.impl.interp.InterpRuntime;"); + w.println("import com.codename1.impl.interp.InterpThrowable;"); + w.println(); + w.println("/** What every generated shim method shares: asking the interpreter. */"); + w.println("public final class " + CALLS + " {"); + w.println(" private " + CALLS + "() {"); + w.println(" }"); + w.println(); + w.println(" /** The interpreter did not answer: not overridden, or the program is stopped. */"); + w.println(" public static boolean miss(Object r) {"); + w.println(" return r == InterpRuntime.NOT_OVERRIDDEN || r == InterpRuntime.DETACHED;"); + w.println(" }"); + w.println(); + w.println(" /**"); + w.println(" * Runs the interpreted method. An unchecked host throwable is rethrown by"); + w.println(" * its own type, so framework code catching it by type still does; anything"); + w.println(" * else travels as the carrier, for the caller to unwrap what it declares."); + w.println(" */"); + w.println(" public static Object call(Object shim, InterpRuntime rt, InterpObject io,"); + w.println(" String name, String descriptor, Object[] args) {"); + w.println(" try {"); + w.println(" return shim == null ? rt.dispatch(io, name, descriptor, args)"); + w.println(" : InterpRuntime.dispatchOrDeferred(shim, rt, io, name, descriptor, args);"); + w.println(" } catch (InterpThrowable t) {"); + w.println(" Throwable thrown = t.hostThrowable();"); + w.println(" if (thrown instanceof RuntimeException) {"); + w.println(" throw (RuntimeException) thrown;"); + w.println(" }"); + w.println(" if (thrown instanceof Error) {"); + w.println(" throw (Error) thrown;"); + w.println(" }"); + w.println(" throw t;"); + w.println(" }"); + w.println(" }"); + w.println(); + String[][] unboxers = { + {"z", "boolean", "r != null && ((Boolean) r).booleanValue()"}, + {"b", "byte", "r == null ? (byte) 0 : ((Number) r).byteValue()"}, + {"c", "char", "r == null ? (char) 0 : ((Character) r).charValue()"}, + {"s", "short", "r == null ? (short) 0 : ((Number) r).shortValue()"}, + {"i", "int", "r == null ? 0 : ((Number) r).intValue()"}, + {"j", "long", "r == null ? 0L : ((Number) r).longValue()"}, + {"f", "float", "r == null ? 0f : ((Number) r).floatValue()"}, + {"d", "double", "r == null ? 0d : ((Number) r).doubleValue()"}, + }; + for (String[] u : unboxers) { + w.println(" public static " + u[1] + " " + u[0] + "(Object r) {"); + w.println(" return " + u[2] + ";"); + w.println(" }"); + w.println(); + } + for (Map.Entry[]> e : SHAPES.entrySet()) { + Class[] params = e.getValue(); + StringBuilder sig = new StringBuilder(); + StringBuilder args = new StringBuilder(); + for (int i = 0; i < params.length; i++) { + sig.append(", ").append(typeName(params[i])).append(" a").append(i); + if (i > 0) { + args.append(", "); + } + args.append("a").append(i); + } + w.println(" public static Object " + e.getKey() + + "(Object shim, InterpRuntime rt, InterpObject io, String name, String descriptor" + + sig + ") {"); + w.println(" return call(shim, rt, io, name, descriptor, new Object[]{" + args + "});"); + w.println(" }"); + w.println(); + } + w.println("}"); + } finally { + w.close(); + } + } + private static void writeRegistry(File dir, List shims, List> classes, List ifaceShims, List> interfaces) throws Exception { From d8a714a83ee57fadf8e0a94ff8d37dfd7384e055 Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Sat, 5 Dec 2026 20:14:47 +0200 Subject: [PATCH 2/3] JavaSE: compile the foldable-skin generator for Java 8 The module is built on JDK 8 and on JDK 17, and ant skips an up-to-date class, so a JDK 17 build followed by a JDK 8 one ran GenerateFoldableSkins from version-61 class files and failed build-skins with UnsupportedClassVersionError -- which took the Hugo build, Maven verify and the quality report down with it in scripts/pre-push-gates.sh --full. Co-Authored-By: Claude Opus 5.5 --- maven/javase/pom.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/maven/javase/pom.xml b/maven/javase/pom.xml index 83c27978d0e..79ba262899b 100644 --- a/maven/javase/pom.xml +++ b/maven/javase/pom.xml @@ -358,9 +358,17 @@ time from the iPhoneX.skin theme. --> Generating foldable skins + From 6f12cea7c9377f0eaf4fc231611a5134c4691acd Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Sat, 5 Dec 2026 21:55:50 +0200 Subject: [PATCH 3/3] Device runtime: compile the whole release build for size ios.optimizationLevel replaces ios.sizeOptimizedClasses: one clang level for the optimized configurations instead of -Oz on chosen classes. Simpler, and it shrinks the rest of the executable too; the slower code does not matter for a development tool. Co-Authored-By: Claude Opus 5.5 --- .../com/codename1/builders/IPhoneBuilder.java | 18 ++- .../builders/XcodeOptimizationLevel.java | 72 +++++++++ .../builders/XcodeSizeOptimizedSources.java | 143 ------------------ .../builders/XcodeOptimizationLevelTest.java | 68 +++++++++ .../XcodeSizeOptimizedSourcesTest.java | 93 ------------ .../codename1/build/shared/BuildHintsIos.java | 11 +- scripts/cn1-device-runtime/INTERNALS.asciidoc | 2 +- .../common/codenameone_settings.properties | 6 +- 8 files changed, 160 insertions(+), 253 deletions(-) create mode 100644 maven/build-engine/src/main/java/com/codename1/builders/XcodeOptimizationLevel.java delete mode 100644 maven/build-engine/src/main/java/com/codename1/builders/XcodeSizeOptimizedSources.java create mode 100644 maven/build-engine/src/test/java/com/codename1/builders/XcodeOptimizationLevelTest.java delete mode 100644 maven/build-engine/src/test/java/com/codename1/builders/XcodeSizeOptimizedSourcesTest.java diff --git a/maven/build-engine/src/main/java/com/codename1/builders/IPhoneBuilder.java b/maven/build-engine/src/main/java/com/codename1/builders/IPhoneBuilder.java index e82b5ca1780..7ec1855bc21 100644 --- a/maven/build-engine/src/main/java/com/codename1/builders/IPhoneBuilder.java +++ b/maven/build-engine/src/main/java/com/codename1/builders/IPhoneBuilder.java @@ -7385,21 +7385,25 @@ public void usesClassMethod(String cls, String method) { throw new BuildException("Failed to update infoplist file", ex); } - // ios.sizeOptimizedClasses: compile the named classes with -Oz. See - // XcodeSizeOptimizedSources for why; the cloud builder does the same. - java.util.List sizeOptimized = XcodeSizeOptimizedSources.filePrefixes( - request.getArg("ios.sizeOptimizedClasses", null)); - if (!sizeOptimized.isEmpty()) { + // ios.optimizationLevel: the clang level of the optimized configurations. + // See XcodeOptimizationLevel; the cloud builder does the same. + String optimizationLevel = request.getArg("ios.optimizationLevel", null); + if (optimizationLevel != null && optimizationLevel.trim().length() > 0) { + optimizationLevel = optimizationLevel.trim(); + if (!XcodeOptimizationLevel.isValid(optimizationLevel)) { + throw new BuildException("ios.optimizationLevel must be one of 0, 1, 2, 3, s, z or fast, not " + + optimizationLevel); + } try { java.nio.file.Path pbxPath = new File(tmpFile, "dist/" + request.getMainClass() + ".xcodeproj/project.pbxproj").toPath(); String before = new String(java.nio.file.Files.readAllBytes(pbxPath), "UTF-8"); - String after = XcodeSizeOptimizedSources.apply(before, sizeOptimized); + String after = XcodeOptimizationLevel.apply(before, optimizationLevel); if (!after.equals(before)) { java.nio.file.Files.write(pbxPath, after.getBytes("UTF-8")); } } catch (IOException ex) { - throw new BuildException("Failed to apply ios.sizeOptimizedClasses", ex); + throw new BuildException("Failed to apply ios.optimizationLevel", ex); } } diff --git a/maven/build-engine/src/main/java/com/codename1/builders/XcodeOptimizationLevel.java b/maven/build-engine/src/main/java/com/codename1/builders/XcodeOptimizationLevel.java new file mode 100644 index 00000000000..24b3465965a --- /dev/null +++ b/maven/build-engine/src/main/java/com/codename1/builders/XcodeOptimizationLevel.java @@ -0,0 +1,72 @@ +/* + * 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; + +/// The `ios.optimizationLevel` build hint: the clang optimization level of the +/// generated project's optimized configurations. +/// +/// Every `GCC_OPTIMIZATION_LEVEL` the project sets to something other than `0` +/// is replaced, so Release (and any other optimized configuration) changes +/// while Debug stays unoptimized. `z` is the one that matters in practice: the +/// device runtime, whose thousands of generated interpreter shims pushed its +/// executable past the App Store's 500 MB limit, builds with it. It is slower +/// code, which an app that spends its time elsewhere never notices. +/// +/// Editing the project, rather than asking the translator, means it works with +/// whichever ParparVM produced the project. +final class XcodeOptimizationLevel { + private static final String KEY = "GCC_OPTIMIZATION_LEVEL = "; + + private XcodeOptimizationLevel() { + } + + /// The levels clang accepts as `-O`. + static boolean isValid(String level) { + return "0".equals(level) || "1".equals(level) || "2".equals(level) || "3".equals(level) + || "s".equals(level) || "z".equals(level) || "fast".equals(level); + } + + /// Returns the project text with every non-zero `GCC_OPTIMIZATION_LEVEL` + /// set to `level`. + static String apply(String pbx, String level) { + StringBuilder out = new StringBuilder(pbx.length()); + int from = 0; + while (true) { + int at = pbx.indexOf(KEY, from); + if (at < 0) { + out.append(pbx, from, pbx.length()); + return out.toString(); + } + int valueStart = at + KEY.length(); + int valueEnd = pbx.indexOf(';', valueStart); + if (valueEnd < 0) { + out.append(pbx, from, pbx.length()); + return out.toString(); + } + String value = pbx.substring(valueStart, valueEnd).trim(); + out.append(pbx, from, valueStart); + out.append("0".equals(value) ? value : level); + from = valueEnd; + } + } +} diff --git a/maven/build-engine/src/main/java/com/codename1/builders/XcodeSizeOptimizedSources.java b/maven/build-engine/src/main/java/com/codename1/builders/XcodeSizeOptimizedSources.java deleted file mode 100644 index f614d0f02c5..00000000000 --- a/maven/build-engine/src/main/java/com/codename1/builders/XcodeSizeOptimizedSources.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * 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 java.util.ArrayList; -import java.util.List; - -/// Compiles chosen translated classes for size (`-Oz`) while the rest of the -/// application keeps the project's speed optimization. -/// -/// The `ios.sizeOptimizedClasses` build hint names class-name prefixes. Each -/// translated class is one source file whose name is the class name with `.` -/// replaced by `_`, and its `PBXBuildFile` entry in the generated project gets -/// `-Oz` in its per-file `COMPILER_FLAGS`. Per-file flags come after the -/// target's own on the compile line, so the later `-Oz` wins over the -/// configuration's `-O3`. -/// -/// The device runtime is what this is for: its generated interpreter shims are -/// two thirds of its executable and only forward calls into an interpreter, so -/// faster code buys nothing there while the size pushes the app toward the App -/// Store's executable limit. Measured on that app, `-Oz` halves the shims' -/// machine code. -/// -/// Editing the project, rather than asking the translator, means it works with -/// whichever ParparVM produced the project. -final class XcodeSizeOptimizedSources { - static final String FLAG = "-Oz"; - - private XcodeSizeOptimizedSources() { - } - - /// The source file name prefixes the hint value names, or none for an empty - /// or absent value. - static List filePrefixes(String hint) { - List out = new ArrayList(); - if (hint == null) { - return out; - } - for (String p : hint.split(",")) { - String t = p.trim(); - if (t.length() > 0) { - out.add(t.replace('.', '_')); - } - } - return out; - } - - /// Returns the project text with `-Oz` added to the build file entry of - /// every C or Objective-C source whose name starts with one of the - /// prefixes. Anything else, and an entry that already carries the flag, is - /// left as it was, so applying it twice changes nothing. - static String apply(String pbx, List prefixes) { - if (prefixes.isEmpty()) { - return pbx; - } - StringBuilder out = new StringBuilder(pbx.length() + 4096); - int start = 0; - while (start < pbx.length()) { - int end = pbx.indexOf('\n', start); - end = end < 0 ? pbx.length() : end + 1; - out.append(rewrite(pbx.substring(start, end), prefixes)); - start = end; - } - return out.toString(); - } - - private static String rewrite(String line, List prefixes) { - if (line.indexOf("isa = PBXBuildFile;") < 0) { - return line; - } - int open = line.indexOf("/* "); - int close = open < 0 ? -1 : line.indexOf(" */", open + 3); - if (close < 0) { - return line; - } - String file = line.substring(open + 3, close); - if (!isCompiledSource(file) || !matches(file, prefixes)) { - return line; - } - String flagsKey = "COMPILER_FLAGS = \""; - int flags = line.indexOf(flagsKey); - if (flags >= 0) { - int valueStart = flags + flagsKey.length(); - int valueEnd = line.indexOf('"', valueStart); - if (valueEnd < 0) { - return line; - } - String value = line.substring(valueStart, valueEnd); - if ((" " + value + " ").indexOf(" " + FLAG + " ") >= 0) { - return line; - } - String joined = value.trim().length() == 0 ? FLAG : value + " " + FLAG; - return line.substring(0, valueStart) + joined + line.substring(valueEnd); - } - int settings = line.indexOf("settings = {"); - if (settings >= 0) { - int at = settings + "settings = {".length(); - return line.substring(0, at) + "COMPILER_FLAGS = \"" + FLAG + "\"; " + line.substring(at); - } - // An entry with no settings dictionary at all: give it one, just before - // the entry's closing brace. - int last = line.lastIndexOf("};"); - if (last < 0) { - return line; - } - return line.substring(0, last) + "settings = {COMPILER_FLAGS = \"" + FLAG + "\"; }; " - + line.substring(last); - } - - private static boolean isCompiledSource(String file) { - return file.endsWith(".m") || file.endsWith(".c") || file.endsWith(".mm") - || file.endsWith(".cpp"); - } - - private static boolean matches(String file, List prefixes) { - for (String p : prefixes) { - if (file.startsWith(p)) { - return true; - } - } - return false; - } -} diff --git a/maven/build-engine/src/test/java/com/codename1/builders/XcodeOptimizationLevelTest.java b/maven/build-engine/src/test/java/com/codename1/builders/XcodeOptimizationLevelTest.java new file mode 100644 index 00000000000..15af907210b --- /dev/null +++ b/maven/build-engine/src/test/java/com/codename1/builders/XcodeOptimizationLevelTest.java @@ -0,0 +1,68 @@ +/* + * 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 org.junit.jupiter.api.Test; + +class XcodeOptimizationLevelTest { + private static final String PROJECT = "\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n" + + "\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = \"DEBUG=1\";\n" + + "\t\t\t\tGCC_OPTIMIZATION_LEVEL = 3;\n" + + "\t\t\t\tGCC_OPTIMIZATION_LEVEL = s;\n"; + + @Test + void optimizedConfigurationsTakeTheLevelAndDebugStaysUnoptimized() { + assertEquals("\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n" + + "\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = \"DEBUG=1\";\n" + + "\t\t\t\tGCC_OPTIMIZATION_LEVEL = z;\n" + + "\t\t\t\tGCC_OPTIMIZATION_LEVEL = z;\n", + XcodeOptimizationLevel.apply(PROJECT, "z")); + } + + @Test + void applyingTwiceChangesNothing() { + String once = XcodeOptimizationLevel.apply(PROJECT, "z"); + assertEquals(once, XcodeOptimizationLevel.apply(once, "z")); + } + + @Test + void aProjectWithoutTheSettingIsUnchanged() { + String pbx = "\t\t\t\tSDKROOT = iphoneos;\n"; + assertEquals(pbx, XcodeOptimizationLevel.apply(pbx, "z")); + } + + @Test + void onlyClangLevelsAreValid() { + assertTrue(XcodeOptimizationLevel.isValid("z")); + assertTrue(XcodeOptimizationLevel.isValid("s")); + assertTrue(XcodeOptimizationLevel.isValid("3")); + assertTrue(XcodeOptimizationLevel.isValid("fast")); + assertFalse(XcodeOptimizationLevel.isValid("Oz")); + assertFalse(XcodeOptimizationLevel.isValid("4")); + assertFalse(XcodeOptimizationLevel.isValid("")); + } +} diff --git a/maven/build-engine/src/test/java/com/codename1/builders/XcodeSizeOptimizedSourcesTest.java b/maven/build-engine/src/test/java/com/codename1/builders/XcodeSizeOptimizedSourcesTest.java deleted file mode 100644 index aedb6838b59..00000000000 --- a/maven/build-engine/src/test/java/com/codename1/builders/XcodeSizeOptimizedSourcesTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * 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.assertTrue; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import org.junit.jupiter.api.Test; - -class XcodeSizeOptimizedSourcesTest { - private static final List GEN = - XcodeSizeOptimizedSources.filePrefixes(" com.codenameone.devruntime.gen. , "); - - // The entry shapes ParparVM's project generator writes: no flags, and the - // -fno-objc-arc one with a weak-link attribute. - private static final String PLAIN = "\t\t0F6456DE18E9ABBC002F3D1D /* " - + "com_codenameone_devruntime_gen_Interp_ui_Form.m */ = {isa = PBXBuildFile; fileRef = " - + "0F6456DD18E9ABBC002F3D1D /* com_codenameone_devruntime_gen_Interp_ui_Form.m */;" - + "settings = { }; };\n"; - private static final String NO_ARC = "\t\t0A18E9ABBC002F3D1D /* com_codenameone_devruntime_gen_X.m */" - + " = {isa = PBXBuildFile; fileRef = 0B18E9ABBC002F3D1D /* com_codenameone_devruntime_gen_X.m */;" - + " settings = {COMPILER_FLAGS = \"-fno-objc-arc\"; ATTRIBUTES = (Weak, ); }; };\n"; - - @Test - void prefixesBecomeFileNamePrefixes() { - assertEquals(Collections.singletonList("com_codenameone_devruntime_gen_"), GEN); - assertTrue(XcodeSizeOptimizedSources.filePrefixes(null).isEmpty()); - assertTrue(XcodeSizeOptimizedSources.filePrefixes(" , ").isEmpty()); - } - - @Test - void addsTheFlagToAnEntryWithoutFlags() { - assertEquals(PLAIN.replace("settings = { }", "settings = {COMPILER_FLAGS = \"-Oz\"; }"), - XcodeSizeOptimizedSources.apply(PLAIN, GEN)); - } - - @Test - void appendsToExistingFlagsSoTheyStillApply() { - assertEquals(NO_ARC.replace("\"-fno-objc-arc\"", "\"-fno-objc-arc -Oz\""), - XcodeSizeOptimizedSources.apply(NO_ARC, GEN)); - } - - @Test - void leavesOtherSourcesHeadersAndReferencesAlone() { - String other = PLAIN.replace("com_codenameone_devruntime_gen_", "com_codename1_ui_"); - String header = PLAIN.replace("Form.m", "Form.h"); - String fileRef = "\t\t0F6456DD18E9ABBC002F3D1D /* com_codenameone_devruntime_gen_Interp_ui_Form.m */" - + " = {isa = PBXFileReference; path = \"com_codenameone_devruntime_gen_Interp_ui_Form.m\"; };\n"; - String project = other + header + fileRef; - assertEquals(project, XcodeSizeOptimizedSources.apply(project, GEN)); - } - - @Test - void applyingTwiceChangesNothingMore() { - String once = XcodeSizeOptimizedSources.apply(PLAIN + NO_ARC, GEN); - assertEquals(once, XcodeSizeOptimizedSources.apply(once, GEN)); - } - - @Test - void noPrefixesMeansNoChange() { - assertEquals(PLAIN, XcodeSizeOptimizedSources.apply(PLAIN, Collections.emptyList())); - } - - @Test - void anyOfSeveralPrefixesMatches() { - List two = XcodeSizeOptimizedSources.filePrefixes("com.other.,com.codenameone.devruntime.gen."); - assertEquals(Arrays.asList("com_other_", "com_codenameone_devruntime_gen_"), two); - assertTrue(XcodeSizeOptimizedSources.apply(PLAIN, two).contains("\"-Oz\"")); - } -} diff --git a/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsIos.java b/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsIos.java index 5658251ee5e..40376c34242 100644 --- a/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsIos.java +++ b/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsIos.java @@ -652,15 +652,14 @@ static void register(List h) { + "on-device interpreter app (scripts/cn1-device-runtime). A regular app " + "leaves this false and gets a smaller binary.")); - h.add(new Hint("ios.sizeOptimizedClasses") + h.add(new Hint("ios.optimizationLevel") .group(HintGroup.IOS) .type(HintType.STRING) .platform("ios") - .doc("Comma-separated class-name prefixes (com.example.gen.) whose translated " - + "sources are compiled for size (-Oz) instead of the project's speed " - + "optimization. Meant for large generated code off the hot paths, such " - + "as the device runtime's interpreter shims, where it halves the machine " - + "code and keeps the executable under the App Store's limit.")); + .doc("The clang optimization level of the release build: 0, 1, 2, 3, s, z or fast. " + + "Debug builds stay unoptimized. Set z for an app whose executable is too " + + "large, such as the device runtime: the code is smaller and somewhat " + + "slower.")); h.add(new Hint("ios.featureScanExclude") .group(HintGroup.IOS) diff --git a/scripts/cn1-device-runtime/INTERNALS.asciidoc b/scripts/cn1-device-runtime/INTERNALS.asciidoc index 75eb91c8004..1a92bfcfd80 100644 --- a/scripts/cn1-device-runtime/INTERNALS.asciidoc +++ b/scripts/cn1-device-runtime/INTERNALS.asciidoc @@ -306,7 +306,7 @@ Every shim overrides every method its class inherits, so the shims are most of t An override now calls a helper in the generated `InterpCalls` class, one helper per parameter shape (about 260 shapes cover the framework). It tests the result with `InterpCalls.miss` and calls `super` itself, because Java allows a `super` call only inside the subclass. Only a method that declares a checked exception keeps a handler, so that the exception reaches its caller by its own type. Keep new shim behavior in the helpers, not in the emitted method body. -The device runtime also sets the `ios.sizeOptimizedClasses` build hint for the generated package, so the iOS build compiles the shims with `-Oz`. They only forward calls into the interpreter, where the speed difference doesn't show. The rest of the app keeps the project's optimization. Together these changes cut the shims' machine code from 396 MB to 86 MB. +The device runtime also sets the `ios.optimizationLevel=z` build hint, so the whole iOS release build is compiled for size. The code is somewhat slower, which a development tool can afford. === Pushing an application, not a file diff --git a/scripts/cn1-device-runtime/common/codenameone_settings.properties b/scripts/cn1-device-runtime/common/codenameone_settings.properties index 4a1429e8c80..2077b938a83 100644 --- a/scripts/cn1-device-runtime/common/codenameone_settings.properties +++ b/scripts/cn1-device-runtime/common/codenameone_settings.properties @@ -7,9 +7,9 @@ # builds; nothing here calls Play billing or FCM at runtime. codename1.arg.android.useAndroidX=true codename1.arg.ios.interpHost=true -# The interpreter shims are two thirds of the executable and only forward calls; -# compiled for size they stay well under the App Store executable limit. -codename1.arg.ios.sizeOptimizedClasses=com.codenameone.devruntime.gen. +# Compiled for size: the interpreter shims are two thirds of the executable, and +# at the default speed optimization it passed the App Store's 500 MB limit. +codename1.arg.ios.optimizationLevel=z # A pushed program gets the native theme its own ios.themeMode / # ios.themeGeneration ask for, so every iOS native theme has to be in the # bundle; the builder otherwise ships only the one this app's mode loads.