From cf15ce2c7e1e3777ece3b097dbe724f80d3d2a57 Mon Sep 17 00:00:00 2001 From: LiJianying Date: Fri, 20 Nov 2026 08:18:44 +0800 Subject: [PATCH 1/3] Reduce cnativeapi shared library size via hidden visibility, section GC, and -Os --- bindings/dart/cnativeapi/hook/build.dart | 27 ++++++++++++++++++++++++ core | 2 +- tools/codegen/capi/src/generator.rs | 6 ++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/bindings/dart/cnativeapi/hook/build.dart b/bindings/dart/cnativeapi/hook/build.dart index b917ae00..f5285af4 100644 --- a/bindings/dart/cnativeapi/hook/build.dart +++ b/bindings/dart/cnativeapi/hook/build.dart @@ -59,6 +59,8 @@ void main(List args) async { switch (targetOS) { case OS.macOS: flags.addAll(_objectiveCpp); + flags.addAll(_sizeAndVisibilityFlags); + flags.addAll(_appleLinkerStripFlags); // SMAppService is macOS 13+, so link ServiceManagement weakly. With a // normal link dyld refuses to load the whole library on macOS 12, // even when the app never calls launch-at-login. @@ -73,8 +75,12 @@ void main(List args) async { ]; case OS.iOS: flags.addAll(_objectiveCpp); + flags.addAll(_sizeAndVisibilityFlags); + flags.addAll(_appleLinkerStripFlags); frameworks = ['UIKit', 'Foundation', 'CoreGraphics']; case OS.linux: + flags.addAll(_sizeAndVisibilityFlags); + flags.addAll(_elfLinkerStripFlags); flags.addAll(await _pkgConfig(['--cflags', ..._linuxPackages])); // Libraries go after the sources, where --as-needed keeps them. for (final flag in await _pkgConfig(['--libs', ..._linuxPackages])) { @@ -88,6 +94,8 @@ void main(List args) async { } flags.add('-pthread'); case OS.android: + flags.addAll(_sizeAndVisibilityFlags); + flags.addAll(_elfLinkerStripFlags); libraries.addAll(['log', 'android']); case OS.windows: flags.addAll(['/EHsc', '/utf-8']); @@ -117,6 +125,7 @@ void main(List args) async { flags: flags, language: Language.cpp, std: 'c++17', + optimizationLevel: OptimizationLevel.oS, // Native assets package this one library; no Gradle CMake target supplies // libc++_shared.so. Keep the NDK runtime inside our Android library. cppLinkStdLib: targetOS == OS.android ? 'c++_static' : null, @@ -140,6 +149,24 @@ const _objectiveCpp = [ '-DOBJC_OLD_DISPATCH_PROTOTYPES=0', ]; +/// Hide internal C++ symbols so only FFI_PLUGIN_EXPORT / CNATIVEAPI_EXPORT / +/// host-bridge entry points are exported, and place functions/data in separate +/// sections so the linker can dead-strip unused code. +const _sizeAndVisibilityFlags = [ + '-fvisibility=hidden', + '-fvisibility-inlines-hidden', + '-ffunction-sections', + '-fdata-sections', +]; + +const _elfLinkerStripFlags = [ + '-Wl,--gc-sections', + '-Wl,--exclude-libs,ALL', + '-Wl,--strip-all', +]; + +const _appleLinkerStripFlags = ['-Wl,-dead_strip', '-Wl,-x']; + const _linuxPackages = ['gtk+-3.0', 'x11', 'xi']; /// The core sources: a published package carries a copy in cxx_impl/ (vendored diff --git a/core b/core index e8446f68..2ab064d2 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit e8446f68556d39708e6a38735e0dfa42f762f62b +Subproject commit 2ab064d2ff5021448ad5ea530c620e3d7ec13e9a diff --git a/tools/codegen/capi/src/generator.rs b/tools/codegen/capi/src/generator.rs index 62edfe89..3cf0fec7 100644 --- a/tools/codegen/capi/src/generator.rs +++ b/tools/codegen/capi/src/generator.rs @@ -612,6 +612,12 @@ fn render_cpp_converters(out: &mut String, header: &Header, capi_out: &Path, pre fn write_export_macro(out: &mut String) { writeln!(out, "#if _WIN32").unwrap(); writeln!(out, "#define FFI_PLUGIN_EXPORT __declspec(dllexport)").unwrap(); + writeln!(out, "#elif defined(__GNUC__) || defined(__clang__)").unwrap(); + writeln!( + out, + "#define FFI_PLUGIN_EXPORT __attribute__((visibility(\"default\")))" + ) + .unwrap(); writeln!(out, "#else").unwrap(); writeln!(out, "#define FFI_PLUGIN_EXPORT").unwrap(); writeln!(out, "#endif").unwrap(); From dcd571dc83e54c5021e979d1d5cb2c1eb5d7dfc8 Mon Sep 17 00:00:00 2001 From: LiJianying Date: Sun, 22 Nov 2026 07:49:53 +0800 Subject: [PATCH 2/3] Restrict ELF exports to public FFI and host entry points --- bindings/dart/cnativeapi/hook/build.dart | 8 +++ .../dart/cnativeapi/hook/cnativeapi.exports | 9 +++ tools/verify_native_exports.py | 62 +++++++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 bindings/dart/cnativeapi/hook/cnativeapi.exports create mode 100644 tools/verify_native_exports.py diff --git a/bindings/dart/cnativeapi/hook/build.dart b/bindings/dart/cnativeapi/hook/build.dart index fb75b773..a6b3c801 100644 --- a/bindings/dart/cnativeapi/hook/build.dart +++ b/bindings/dart/cnativeapi/hook/build.dart @@ -114,6 +114,14 @@ void main(List args) async { ]); } + if (targetOS == OS.linux || targetOS == OS.android) { + // libstdc++ marks some template instantiations default-visible even + // with -fvisibility=hidden. Keep the ELF export table to the C contract. + final exportMap = input.packageRoot.resolve('hook/cnativeapi.exports'); + flags.add('-Wl,--version-script=${exportMap.toFilePath()}'); + output.dependencies.add(exportMap); + } + final builder = CBuilder.library( name: 'cnativeapi', assetName: 'cnativeapi.dart', diff --git a/bindings/dart/cnativeapi/hook/cnativeapi.exports b/bindings/dart/cnativeapi/hook/cnativeapi.exports new file mode 100644 index 00000000..3c3fe221 --- /dev/null +++ b/bindings/dart/cnativeapi/hook/cnativeapi.exports @@ -0,0 +1,9 @@ +{ + global: + native_*; + cnativeapi_*; + nativeapi_protocol_handler_host_*; + Java_dev_libnativeapi_nativeapi_ProtocolHandlerBridge_*; + local: + *; +}; diff --git a/tools/verify_native_exports.py b/tools/verify_native_exports.py new file mode 100644 index 00000000..0330f479 --- /dev/null +++ b/tools/verify_native_exports.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""Check that a stripped cnativeapi library still exports the complete C API. + +Build with `dart run bindings/dart/nativeapi/example/nativeapi_example.dart`, +then run this script (or pass --library to inspect a particular build). +""" +import argparse +import ctypes +import gzip +import json +from pathlib import Path +import re +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[1] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--library', type=Path) + parser.add_argument('--allow-internal', action='store_true', help='Measure an unhidden baseline build') + args = parser.parse_args() + path = args.library + if path is None: + candidates = [p for p in (ROOT / '.dart_tool/hooks_runner/shared/cnativeapi/build').glob('*/*') + if p.name in ('libcnativeapi.so', 'libcnativeapi.dylib', 'cnativeapi.dll')] + if not candidates: + parser.error('Build cnativeapi first, or supply --library') + path = max(candidates, key=lambda p: p.stat().st_mtime) + path = path.resolve() + expected = set() + pattern = r'\bFFI_PLUGIN_EXPORT\s+[^;{}#]*?\b(native_\w+)\s*\(' + for header in (ROOT / 'core/src/capi').glob('*.h'): + expected.update(re.findall(pattern, header.read_text())) + shim = (ROOT / 'bindings/dart/cnativeapi/src/event_loop.h').read_text() + expected.update(re.findall(r'\bCNATIVEAPI_EXPORT\s+[^;{}#]*?\b(cnativeapi_\w+)\s*\(', shim)) + expected.update(('nativeapi_protocol_handler_host_attach', 'nativeapi_protocol_handler_host_deliver')) + assert {'native_window_create', 'native_handle_finalize'} <= expected, 'C API headers were not parsed' + library = ctypes.CDLL(str(path)) + missing = sorted(name for name in expected if not hasattr(library, name)) + assert not missing, f'Missing public exports: {missing}' + exported = None + internal = None + if sys.platform == 'darwin' or sys.platform.startswith('linux'): + command = (['nm', '-gU', str(path)] if sys.platform == 'darwin' else + ['nm', '-D', '--defined-only', str(path)]) + symbols = subprocess.check_output(command, text=True).splitlines() + names = [line.split()[-1] for line in symbols if line.split()] + internal = sum(name.startswith(('_Z', '__Z')) for name in names) + assert args.allow_internal or internal == 0, 'Internal C++ symbols are exported' + exported = len(names) + data = path.read_bytes() + print(json.dumps({'library': str(path), 'bytes': len(data), + 'gzipBytes': len(gzip.compress(data, mtime=0)), + 'requiredExports': len(expected), 'exportedSymbols': exported, + 'internalCppSymbols': internal, + 'missingExports': missing}, indent=2)) + + +if __name__ == '__main__': + main() From 31bc5c347bbc4037fd9a68fed838f1339b06dff5 Mon Sep 17 00:00:00 2001 From: LiJianying Date: Sun, 22 Nov 2026 07:58:19 +0800 Subject: [PATCH 3/3] Preserve legacy C string exports in the ELF allowlist --- bindings/dart/cnativeapi/hook/cnativeapi.exports | 1 + tools/verify_native_exports.py | 8 +++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/bindings/dart/cnativeapi/hook/cnativeapi.exports b/bindings/dart/cnativeapi/hook/cnativeapi.exports index 3c3fe221..0cc94ed1 100644 --- a/bindings/dart/cnativeapi/hook/cnativeapi.exports +++ b/bindings/dart/cnativeapi/hook/cnativeapi.exports @@ -1,6 +1,7 @@ { global: native_*; + free_c_*; cnativeapi_*; nativeapi_protocol_handler_host_*; Java_dev_libnativeapi_nativeapi_ProtocolHandlerBridge_*; diff --git a/tools/verify_native_exports.py b/tools/verify_native_exports.py index 0330f479..66ea1b66 100644 --- a/tools/verify_native_exports.py +++ b/tools/verify_native_exports.py @@ -30,13 +30,15 @@ def main(): path = max(candidates, key=lambda p: p.stat().st_mtime) path = path.resolve() expected = set() - pattern = r'\bFFI_PLUGIN_EXPORT\s+[^;{}#]*?\b(native_\w+)\s*\(' + pattern = r'\bFFI_PLUGIN_EXPORT\s+[^;{}#]*?\b([A-Za-z_]\w*)\s*\(' for header in (ROOT / 'core/src/capi').glob('*.h'): - expected.update(re.findall(pattern, header.read_text())) + source = re.sub(r'^\s*#.*$', '', header.read_text(), flags=re.M) + source = re.sub(r'/\*.*?\*/|//[^\n]*', '', source, flags=re.S) + expected.update(re.findall(pattern, source)) shim = (ROOT / 'bindings/dart/cnativeapi/src/event_loop.h').read_text() expected.update(re.findall(r'\bCNATIVEAPI_EXPORT\s+[^;{}#]*?\b(cnativeapi_\w+)\s*\(', shim)) expected.update(('nativeapi_protocol_handler_host_attach', 'nativeapi_protocol_handler_host_deliver')) - assert {'native_window_create', 'native_handle_finalize'} <= expected, 'C API headers were not parsed' + assert {'native_window_create', 'native_handle_finalize', 'free_c_str'} <= expected, 'C API headers were not parsed' library = ctypes.CDLL(str(path)) missing = sorted(name for name in expected if not hasattr(library, name)) assert not missing, f'Missing public exports: {missing}'