Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions bindings/dart/cnativeapi/hook/build.dart
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ void main(List<String> 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.
Expand All @@ -73,8 +75,12 @@ void main(List<String> 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])) {
Expand All @@ -88,6 +94,8 @@ void main(List<String> 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']);
Expand All @@ -106,6 +114,14 @@ void main(List<String> 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',
Expand All @@ -117,6 +133,11 @@ void main(List<String> 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,
Expand All @@ -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
Expand Down
10 changes: 10 additions & 0 deletions bindings/dart/cnativeapi/hook/cnativeapi.exports
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
global:
native_*;
free_c_*;
cnativeapi_*;
nativeapi_protocol_handler_host_*;
Java_dev_libnativeapi_nativeapi_ProtocolHandlerBridge_*;
local:
*;
};
6 changes: 6 additions & 0 deletions tools/codegen/capi/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
64 changes: 64 additions & 0 deletions tools/verify_native_exports.py
Original file line number Diff line number Diff line change
@@ -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()
Loading