Skip to content

Commit 10515af

Browse files
authored
[native_toolchain_c] Do not pass linker flags when compiling static libraries (#3731)
1 parent a2a6179 commit 10515af

5 files changed

Lines changed: 162 additions & 25 deletions

File tree

‎pkgs/code_assets/example/host_name/lib/src/third_party/unix.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,4 @@
2222
import 'dart:ffi' as ffi;
2323

2424
@ffi.Native<ffi.Int Function(ffi.Pointer<ffi.Char>, ffi.Size)>()
25-
external int gethostname(ffi.Pointer<ffi.Char> __name, int __len);
25+
external int gethostname(ffi.Pointer<ffi.Char> arg0, int __namelen);

‎pkgs/native_toolchain_c/CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
pass an `/INCLUDE:` flag per symbol in addition to the generated
66
module-definition file, which exceeded the Windows command-line length limit.
77
The generated module-definition file also no longer names the DLL `MyDLL`.
8+
- Do not pass linker flags (`-Wl,-encryptable`, `-Wl,-z,max-page-size=16384`,
9+
`-framework`, and C++ standard library link flags) when compiling object files
10+
for static libraries (`-c`).
811

912
## 0.19.5
1013

‎pkgs/native_toolchain_c/lib/src/cbuilder/run_cbuilder.dart‎

Lines changed: 28 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -346,30 +346,34 @@ class RunCBuilder {
346346
if (language == .cpp) ...[
347347
'-x',
348348
'c++',
349-
// On Android with c++_static, use -Bstatic/-Bdynamic to force
350-
// static resolution of -lc++. This picks up the NDK's libc++.a
351-
// linker script which expands to INPUT(-lc++_static -lc++abi),
352-
// ensuring libc++abi is also linked. Passing -l c++_static directly
353-
// would miss libc++abi. See:
354-
// https://android.googlesource.com/platform/ndk/+show/refs/heads/main/docs/BuildSystemMaintainers.md
355-
if (codeConfig.targetOS == .android &&
356-
(cppLinkStdLib ?? defaultCppLinkStdLib[codeConfig.targetOS]!) ==
357-
'c++_static') ...[
358-
'-Wl,-Bstatic',
359-
'-l',
360-
'c++',
361-
'-Wl,-Bdynamic',
362-
] else ...[
363-
'-l',
364-
cppLinkStdLib ?? defaultCppLinkStdLib[codeConfig.targetOS]!,
349+
if (executable != null || dynamicLibrary != null) ...[
350+
// On Android with c++_static, use -Bstatic/-Bdynamic to force
351+
// static resolution of -lc++. This picks up the NDK's libc++.a
352+
// linker script which expands to INPUT(-lc++_static -lc++abi),
353+
// ensuring libc++abi is also linked. Passing -l c++_static directly
354+
// would miss libc++abi. See:
355+
// https://android.googlesource.com/platform/ndk/+show/refs/heads/main/docs/BuildSystemMaintainers.md
356+
if (codeConfig.targetOS == .android &&
357+
(cppLinkStdLib ?? defaultCppLinkStdLib[codeConfig.targetOS]!) ==
358+
'c++_static') ...[
359+
'-Wl,-Bstatic',
360+
'-l',
361+
'c++',
362+
'-Wl,-Bdynamic',
363+
] else ...[
364+
'-l',
365+
cppLinkStdLib ?? defaultCppLinkStdLib[codeConfig.targetOS]!,
366+
],
365367
],
366368
],
367369
if (optimizationLevel != .unspecified) optimizationLevel.clangFlag(),
368-
// Support Android 15 page size by default, can be overridden by
369-
// passing [flags].
370-
if (codeConfig.targetOS == .android) '-Wl,-z,max-page-size=16384',
371-
if (codeConfig.targetOS == .iOS || codeConfig.targetOS == .macOS)
372-
'-Wl,-encryptable',
370+
if (executable != null || dynamicLibrary != null) ...[
371+
// Support Android 15 page size by default, can be overridden by
372+
// passing [flags].
373+
if (codeConfig.targetOS == .android) '-Wl,-z,max-page-size=16384',
374+
if (codeConfig.targetOS == .iOS || codeConfig.targetOS == .macOS)
375+
'-Wl,-encryptable',
376+
],
373377
...flags,
374378
for (final MapEntry(key: name, :value) in defines.entries)
375379
if (value == null) '-D$name' else '-D$name=$value',
@@ -386,9 +390,6 @@ class RunCBuilder {
386390
)
387391
else
388392
...sourceFiles,
389-
if (codeConfig.targetOS case .iOS || .macOS) ...[
390-
for (final framework in frameworks) ...['-framework', framework],
391-
],
392393
if (executable != null) ...[
393394
'-o',
394395
toolPath(outDir.resolveUri(executable!)),
@@ -402,6 +403,9 @@ class RunCBuilder {
402403
toolPath(outFile!),
403404
],
404405
if (executable != null || dynamicLibrary != null) ...[
406+
if (codeConfig.targetOS case .iOS || .macOS) ...[
407+
for (final framework in frameworks) ...['-framework', framework],
408+
],
405409
if (codeConfig.targetOS case .android || .linux)
406410
// During bundling code assets are all placed in the same directory.
407411
// Setting this rpath allows the binary to find other code assets

‎pkgs/native_toolchain_c/test/cbuilder/cbuilder_cross_ios_test.dart‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,9 @@ void main() {
137137
final buildInput = buildInputBuilder.build();
138138
final buildOutput = BuildOutputBuilder();
139139

140+
final logMessages = <String>[];
141+
final logger = createCapturingLogger(logMessages);
142+
140143
final cbuilder = CBuilder.library(
141144
name: name,
142145
assetName: name,
@@ -152,6 +155,17 @@ void main() {
152155
logger: logger,
153156
);
154157

158+
final compilerInvocation = logMessages.singleWhere(
159+
(message) => message.contains(sourceUri.toFilePath()),
160+
);
161+
if (linkMode == DynamicLoadingBundled()) {
162+
expect(compilerInvocation, contains('-Wl,-encryptable'));
163+
expect(compilerInvocation, contains('-framework Foundation'));
164+
} else {
165+
expect(compilerInvocation, isNot(contains('-Wl,-encryptable')));
166+
expect(compilerInvocation, isNot(contains('-framework')));
167+
}
168+
155169
final libUri = buildInput.outputDirectory.resolve(libName);
156170
final objdumpResult = await runProcess(
157171
executable: Uri.file('objdump'),

‎pkgs/native_toolchain_c/test/cbuilder/cbuilder_unit_test.dart‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,4 +140,120 @@ void main() {
140140
endsWith(targetOS.libraryFileName(name, DynamicLoadingBundled())),
141141
);
142142
});
143+
144+
test(
145+
'CBuilder static library does not pass linker flags to clang -c',
146+
() async {
147+
final fileSystem = MemoryFileSystem(
148+
style: Platform.isWindows
149+
? FileSystemStyle.windows
150+
: FileSystemStyle.posix,
151+
);
152+
153+
final outputDirectoryShared = await tempDirForTest();
154+
final packageRoot = await tempDirForTest();
155+
156+
const name = 'mylib';
157+
const targetOS = OS.android;
158+
const targetArchitecture = Architecture.arm64;
159+
160+
final ccUri = packageRoot.resolve(OS.current.executableFileName('clang'));
161+
final arUri = packageRoot.resolve(
162+
OS.current.executableFileName('llvm-ar'),
163+
);
164+
final ldUri = packageRoot.resolve(
165+
OS.current.executableFileName('ld.lld'),
166+
);
167+
for (final toolUri in [ccUri, arUri, ldUri]) {
168+
fileSystem.file(toolUri)
169+
..createSync(recursive: true)
170+
..writeAsStringSync('');
171+
}
172+
173+
final sourceUri = packageRoot.resolve('src.cc');
174+
fileSystem.file(sourceUri)
175+
..createSync(recursive: true)
176+
..writeAsStringSync('int foo() { return 0; }\n');
177+
178+
final ccPath = ccUri.toFilePath();
179+
final arPath = arUri.toFilePath();
180+
181+
const versionStdout = 'clang version 14.0.0\n';
182+
const arVersionStdout = 'LLVM version 14.0.0\n';
183+
final fakeProcessManager = FakeProcessManager([
184+
FakeCommand(command: [ccPath, '--version'], stdout: versionStdout),
185+
FakeCommand(command: [ccPath, '--version'], stdout: versionStdout),
186+
FakeCommand(command: [arPath, '--version'], stdout: arVersionStdout),
187+
FakeCommand(
188+
onRun: (command) {
189+
final outIndex = command.indexOf('-o');
190+
expect(outIndex, greaterThanOrEqualTo(0));
191+
fileSystem.file(command[outIndex + 1]).createSync(recursive: true);
192+
},
193+
),
194+
FakeCommand(
195+
onRun: (command) {
196+
fileSystem.file(command[2]).createSync(recursive: true);
197+
},
198+
),
199+
]);
200+
201+
final buildInputBuilder = BuildInputBuilder()
202+
..setupShared(
203+
packageName: name,
204+
packageRoot: packageRoot,
205+
outputFile: outputDirectoryShared.resolve('output.json'),
206+
outputDirectoryShared: outputDirectoryShared,
207+
)
208+
..config.setupBuild(linkingEnabled: false)
209+
..addExtension(
210+
CodeAssetExtension(
211+
targetOS: targetOS,
212+
targetArchitecture: targetArchitecture,
213+
android: AndroidCodeConfig(targetNdkApi: 21),
214+
linkModePreference: LinkModePreference.static,
215+
cCompiler: CCompilerConfig(
216+
archiver: arUri,
217+
compiler: ccUri,
218+
linker: ldUri,
219+
),
220+
),
221+
);
222+
final buildInput = buildInputBuilder.build();
223+
final buildOutput = BuildOutputBuilder();
224+
225+
final cbuilder = CBuilder.library(
226+
name: name,
227+
assetName: name,
228+
sources: [sourceUri.toFilePath()],
229+
language: .cpp,
230+
cppLinkStdLib: 'c++_static',
231+
libraries: ['bar'],
232+
libraryDirectories: ['baz'],
233+
);
234+
235+
await cbuilder.run(
236+
input: buildInput,
237+
output: buildOutput,
238+
logger: logger,
239+
processManager: fakeProcessManager,
240+
fileSystem: fileSystem,
241+
);
242+
243+
expect(fakeProcessManager.allCommandsConsumed, true);
244+
final invocations = fakeProcessManager.invocations;
245+
expect(invocations.length, 5);
246+
247+
final compileCommand = invocations[3].command;
248+
expect(compileCommand.first, ccPath);
249+
expect(compileCommand, contains('-c'));
250+
expect(compileCommand, containsAllInOrder(['-x', 'c++']));
251+
expect(compileCommand, isNot(contains('-Wl,-z,max-page-size=16384')));
252+
expect(compileCommand, isNot(contains('-Wl,-Bstatic')));
253+
expect(compileCommand, isNot(contains('-Wl,-Bdynamic')));
254+
expect(compileCommand, isNot(contains('-l')));
255+
expect(compileCommand, isNot(contains('-Wl,-rpath,\$ORIGIN')));
256+
expect(compileCommand, isNot(contains('-lbar')));
257+
},
258+
);
143259
}

0 commit comments

Comments
 (0)