diff --git a/bindings/dart/cnativeapi/hook/build.dart b/bindings/dart/cnativeapi/hook/build.dart index b917ae00..a6b3c801 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']); @@ -106,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', @@ -117,6 +133,11 @@ void main(List args) async { flags: flags, language: Language.cpp, std: 'c++17', + // MSVC's /Os is only a size preference, unlike Clang/GCC's -Os. Keep + // the existing /O2 optimization on Windows. + optimizationLevel: targetOS == OS.windows + ? OptimizationLevel.o3 + : 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 +161,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/bindings/dart/cnativeapi/hook/cnativeapi.exports b/bindings/dart/cnativeapi/hook/cnativeapi.exports new file mode 100644 index 00000000..0cc94ed1 --- /dev/null +++ b/bindings/dart/cnativeapi/hook/cnativeapi.exports @@ -0,0 +1,10 @@ +{ + global: + native_*; + free_c_*; + cnativeapi_*; + nativeapi_protocol_handler_host_*; + Java_dev_libnativeapi_nativeapi_ProtocolHandlerBridge_*; + local: + *; +}; diff --git a/core b/core index 59a20f38..6b179a95 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit 59a20f38fcfc36b1a3412b841139816a77c26ac4 +Subproject commit 6b179a953976b36eab33a5f03165cb8a1edee927 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(); diff --git a/tools/verify_native_exports.py b/tools/verify_native_exports.py new file mode 100644 index 00000000..66ea1b66 --- /dev/null +++ b/tools/verify_native_exports.py @@ -0,0 +1,64 @@ +#!/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([A-Za-z_]\w*)\s*\(' + for header in (ROOT / 'core/src/capi').glob('*.h'): + 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', '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}' + 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()