-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathApk.zig
More file actions
1184 lines (1043 loc) · 51.5 KB
/
Copy pathApk.zig
File metadata and controls
1184 lines (1043 loc) · 51.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const Allocator = std.mem.Allocator;
const Target = std.Target;
const Step = std.Build.Step;
const ResolvedTarget = std.Build.ResolvedTarget;
const LazyPath = std.Build.LazyPath;
const ArrayList = std.ArrayListUnmanaged;
const builtin = @import("builtin");
const androidbuild = @import("androidbuild.zig");
const ApiLevel = androidbuild.ApiLevel;
const getAndroidTriple = androidbuild.getAndroidTriple;
const runNameContext = androidbuild.runNameContext;
const printErrorsAndExit = androidbuild.printErrorsAndExit;
const BuildTools = @import("BuildTools.zig");
const BuiltinOptionsUpdate = @import("BuiltinOptionsUpdate.zig");
const D8Glob = @import("D8Glob.zig");
const DirectoryFileInput = @import("DirectoryFileInput.zig");
const Ndk = @import("Ndk.zig");
const Sdk = @import("tools.zig");
const KeyStore = Sdk.KeyStore;
pub const Resource = union(enum) {
// file: File,
directory: Directory,
// pub const File = struct {
// source: LazyPath,
// };
pub const Directory = struct {
source: LazyPath,
};
};
b: *std.Build,
/// APK file output name, ie. "{name}.apk"
name: []const u8,
sdk: *Sdk,
/// Path to Native Development Kit, this includes various C-code headers, libraries, and more.
/// ie. $ANDROID_HOME/ndk/29.0.13113456
ndk: Ndk,
/// Paths to Build Tools such as aapt2, zipalign
/// ie. $ANDROID_HOME/build-tools/35.0.0
build_tools: BuildTools,
/// API Level is the target Android API Level
/// ie. .android15 = 35 (android 15 uses API version 35)
api_level: ApiLevel,
key_store: ?KeyStore,
android_manifest: ?LazyPath,
artifacts: ArrayList(*Step.Compile),
/// Precompiled library files can be added to the APK to support features like Vulkan validation layers
/// ie. https://developer.android.com/ndk/guides/graphics/validation-layer
precompiled_library_files: ArrayList(PrecompiledLibraryFile),
java_files: ArrayList(LazyPath),
resources: ArrayList(Resource),
assets: ArrayList(Resource),
pub const Options = struct {
/// APK file output name, ie. "{name}.apk"
name: []const u8,
/// "37.0.0" will use "$ANDROID_HOME/build-tools/37.0.0" which contains tools like:
/// "aapt2", "zipalign", "apksigner", "d8"
build_tools_version: []const u8,
/// "27.0.12077973" will is used to access:
/// - Include headers: $ANDROID_HOME/ndk/27.0.12077973/toolchains/llvm/prebuilt/YOUR_HOST_OS_HERE/sysroot/usr/include
/// - System libraries: $ANDROID_HOME/ndk/27.0.12077973/toolchains/llvm/prebuilt/YOUR_HOST_OS_HERE/sysroot/usr/lib
ndk_version: []const u8,
/// .android15 = 35 (android 15 uses API version 35) decides on:
/// - System libraries: $ANDROID_HOME/ndk/$NDK_VERSION/toolchains/llvm/prebuilt/$HOST_OS/sysroot/usr/lib/$TARGET_ARCH/$ANDROID_API_LEVEL
/// - Platform tool jar: $ANDROID_HOME/platforms/android-ANDROID_API_LEVEL
api_level: ApiLevel,
};
pub fn create(sdk: *Sdk, options: Options) *Apk {
const b = sdk.b;
var errors = std.ArrayListUnmanaged([]const u8).empty;
defer errors.deinit(b.allocator);
const build_tools = BuildTools.init(b, sdk.android_sdk_path, options.build_tools_version, &errors) catch |err| switch (err) {
error.BuildToolFailed => BuildTools.empty, // fallthruogh and print all errors below
error.OutOfMemory => @panic("OOM"),
};
const ndk = Ndk.init(b, sdk.android_sdk_path, options.ndk_version, &errors) catch |err| switch (err) {
error.NdkFailed => Ndk.empty, // fallthrough and print all errors below
error.OutOfMemory => @panic("OOM"),
};
if (ndk.path.len != 0) {
// Only do additional NDK validation if ndk is not set to Ndk.empty
// ie. "ndk_version" isn't installed
ndk.validateApiLevel(b, options.api_level, &errors);
}
if (errors.items.len > 0) {
printErrorsAndExit(sdk.b, "unable to find required Android installation", errors.items);
}
const apk: *Apk = b.allocator.create(Apk) catch @panic("OOM");
apk.* = .{
.b = b,
.name = options.name,
.sdk = sdk,
.ndk = ndk,
.build_tools = build_tools,
.api_level = options.api_level,
.key_store = null,
.android_manifest = null,
.precompiled_library_files = .empty,
.artifacts = .empty,
.java_files = .empty,
.resources = .empty,
.assets = .empty,
};
return apk;
}
/// Set the AndroidManifest.xml file to use
pub fn setAndroidManifest(apk: *Apk, path: LazyPath) void {
apk.android_manifest = path;
}
/// Set the directory of your Android /res/ folder.
/// ie.
/// - values/strings.xml
/// - mipmap-hdpi/ic_launcher.png
/// - mipmap-mdpi/ic_launcher.png
/// - etc
pub fn addResourceDirectory(apk: *Apk, dir: LazyPath) void {
const b = apk.b;
apk.resources.append(b.allocator, Resource{
.directory = .{
.source = dir,
},
}) catch @panic("OOM");
}
pub fn addAssetDirectory(apk: *Apk, dir: LazyPath) void {
const b = apk.b;
apk.assets.append(b.allocator, Resource{
.directory = .{
.source = dir,
},
}) catch @panic("OOM");
}
/// Add artifact to the Android build, this should be a shared library (*.so)
/// that targets x86, x86_64, aarch64, etc
pub fn addArtifact(apk: *Apk, compile: *std.Build.Step.Compile) void {
const b = apk.b;
apk.artifacts.append(b.allocator, compile) catch @panic("OOM");
}
pub const AddJavaSourceFileOption = struct {
file: LazyPath,
// NOTE(jae): 2024-09-17
// Consider adding flags to define/declare the target Java version for this file.
// Not sure what we'll need in the future.
// flags: []const []const u8 = &.{},
};
/// Add Java file to be transformed into DEX bytecode and packaged into a classes.dex file in the root
/// of your APK.
pub fn addJavaSourceFile(apk: *Apk, options: AddJavaSourceFileOption) void {
const b = apk.b;
const java_file = if (builtin.zig_version.major == 0 and builtin.zig_version.minor <= 16)
// Deprecated: Just uses Build
options.file.dupe(b)
else
options.file.dupe(b.graph);
apk.java_files.append(b.allocator, java_file) catch @panic("OOM");
}
pub const AddJavaSourceFilesOptions = struct {
root: LazyPath,
files: []const []const u8,
};
pub fn addJavaSourceFiles(apk: *Apk, options: AddJavaSourceFilesOptions) void {
const b = apk.b;
for (options.files) |path| {
apk.addJavaSourceFile(.{ .file = options.root.path(b, path) });
}
}
/// Set the keystore file used to sign the APK file
/// This is required run on an Android device.
///
/// If you want to just use a temporary key for local development, do something like this:
/// - apk.setKeyStore(android_sdk.createKeyStore(.example);
pub fn setKeyStore(apk: *Apk, key_store: KeyStore) void {
apk.key_store = key_store;
}
/// Add precompiled library files
///
/// This is useful for when you want to consume vendors compiled library files such as the Vulkan Validation layers
/// ie. https://developer.android.com/ndk/guides/graphics/validation-layer
pub fn addLibraryFile(apk: *Apk, android_target: androidbuild.AndroidTarget, path: LazyPath) void {
const b = apk.b;
apk.precompiled_library_files.append(b.allocator, .{
.target = android_target.target(b),
.path = path,
}) catch @panic("OOM");
}
pub fn installApk(apk: *Apk) void {
const b = apk.b;
const install_apk = apk.addInstallApk();
b.getInstallStep().dependOn(&install_apk.step);
}
pub fn addInstallApk(apk: *Apk) *Step.InstallFile {
return apk.doInstallApk() catch |err| switch (err) {
error.OutOfMemory => @panic("OOM"),
};
}
fn doInstallApk(apk: *Apk) Allocator.Error!*Step.InstallFile {
const b = apk.b;
const key_store: KeyStore = apk.key_store orelse .empty;
// validate
{
var errors = std.ArrayListUnmanaged([]const u8).empty;
defer errors.deinit(b.allocator);
if (key_store.password.len == 0) {
try errors.append(b.allocator, "Keystore not configured with password, must be setup with setKeyStore");
}
if (apk.android_manifest == null) {
try errors.append(b.allocator, "AndroidManifest.xml not configured, must be set with setAndroidManifest");
}
if (apk.artifacts.items.len == 0) {
try errors.append(b.allocator, "Must add at least one artifact targeting a valid Android CPU architecture: aarch64, x86_64, x86, etc");
} else {
for (apk.artifacts.items, 0..) |artifact, i| {
if (artifact.kind == .exe) {
try errors.append(b.allocator, b.fmt("artifact[{}]: must make Android artifacts be created with addSharedLibrary, not addExecutable", .{i}));
} else {
if (artifact.linkage) |linkage| {
if (linkage != .dynamic) {
try errors.append(b.allocator, b.fmt("artifact[{}]: invalid linkage, expected it to be created via addSharedLibrary", .{i}));
}
} else {
try errors.append(b.allocator, b.fmt("artifact[{}]: unable to get linkage from artifact, expected it to be created via addSharedLibrary", .{i}));
}
}
if (artifact.root_module.resolved_target) |target| {
if (!target.result.abi.isAndroid()) {
try errors.append(b.allocator, b.fmt("artifact[{}]: must be targetting Android abi", .{i}));
continue;
}
} else {
try errors.append(b.allocator, b.fmt("artifact[{}]: unable to get resolved target from artifact", .{i}));
}
}
}
// NOTE(jae): 2025-05-06
// This validation rule has been removed because if you have `android:hasCode="false"` in your AndroidManifest.xml file
// then you can have no Java files.
//
// If you do not provide Java files AND android:hasCode="false" isn't set, then you may get the following error on "adb install"
// - Scanning Failed.: Package /data/app/base.apk code is missing]
//
// Ideally we may want to do something where we can utilize "aapt2 dump X" to determine if "hasCode" is set and if it isn't, throw
// an error at compilation time. Similar to how we use it to extract the package name from AndroidManifest.xml below (ie. "aapt2 dump packagename")
// if (apk.java_files.items.len == 0) {
// try errors.append(b.fmt("must add at least one Java file to build OR you must setup your AndroidManifest.xml to have 'android:hasCode=false'", .{}));
// }
if (errors.items.len > 0) {
printErrorsAndExit(apk.b, "misconfigured Android APK", errors.items);
}
}
// Setup AndroidManifest.xml
const android_manifest_file: LazyPath = apk.android_manifest orelse {
@panic("call setAndroidManifestFile and point to your AndroidManifest.xml file");
};
// NOTE(jae): 2024-10-01
// Consider adding option where you can explicitly set an optional release mode with like:
// - setMode(.debug)
//
// If that value ISN'T set then we can just infer based on optimization level.
const debug_apk: bool = blk: {
for (apk.artifacts.items) |root_artifact| {
if (root_artifact.root_module.optimize) |optimize| {
if (optimize == .Debug) {
break :blk true;
}
}
}
break :blk false;
};
// ie. "$ANDROID_HOME/Sdk/platforms/android-{api_level}/android.jar"
const root_jar: LazyPath = .{
.cwd_relative = b.pathResolve(&[_][]const u8{
apk.sdk.android_sdk_path,
"platforms",
b.fmt("android-{d}", .{@intFromEnum(apk.api_level)}),
"android.jar",
}),
};
// Make resources.apk from:
// - resources.flat.zip (created from "aapt2 compile")
// - res/values/strings.xml -> values_strings.arsc.flat
// - AndroidManifest.xml
//
// This also validates your AndroidManifest.xml and can catch configuration errors
// which "aapt" was not capable of.
// See: https://developer.android.com/tools/aapt2#aapt2_element_hierarchy
// Snapshot: http://web.archive.org/web/20241001070128/https://developer.android.com/tools/aapt2#aapt2_element_hierarchy
const resources_apk: LazyPath = blk: {
const aapt2link = b.addSystemCommand(&[_][]const u8{
apk.build_tools.aapt2,
"link",
});
aapt2link.setName(runNameContext("aapt2 link"));
// Add '-I android_sdk/platforms/android_version/android.jar'
aapt2link.addArg("-I");
aapt2link.addFileArg(root_jar);
if (builtin.zig_version.major == 0 and builtin.zig_version.minor <= 16) {
// Deprecated: b.verbose no longer exists
if (b.verbose) {
aapt2link.addArg("-v");
}
}
// Inserts android:debuggable="true" in to the application node of the manifest,
// making the application debuggable even on production devices.
if (debug_apk) {
aapt2link.addArg("--debug-mode");
}
// full path to AndroidManifest.xml to include in APK
// ie. --manifest AndroidManifest.xml
aapt2link.addArg("--manifest");
aapt2link.addFileArg(android_manifest_file);
aapt2link.addArgs(&[_][]const u8{
"--target-sdk-version",
b.fmt("{d}", .{@intFromEnum(apk.api_level)}),
});
// NOTE(jae): 2024-10-02
// Explored just outputting to dir but it gets errors like:
// - error: failed to write res/mipmap-mdpi-v4/ic_launcher.png to archive:
// The system cannot find the file specified. (2).
//
// So... I'll stick with the creating an APK and extracting it approach.
// aapt2link.addArg("--output-to-dir"); // Requires: Android SDK Build Tools 28.0.0 or higher
// aapt2link.addArg("-o");
// const resources_apk_dir = aapt2link.addOutputDirectoryArg("resources");
aapt2link.addArg("-o");
const resources_apk_file = aapt2link.addOutputFileArg("resources.apk");
// Add assets
for (apk.assets.items) |asset| {
switch (asset) {
.directory => |asset_dir_path| {
aapt2link.addArg("-A");
aapt2link.addDirectoryArg(asset_dir_path.source);
DirectoryFileInput.create(b, aapt2link, asset_dir_path.source);
},
}
}
// Add resource files
for (apk.resources.items) |resource| {
const resources_flat_zip = resblk: {
// Make zip of compiled resource files, ie.
// - res/values/strings.xml -> values_strings.arsc.flat
// - mipmap/ic_launcher.png -> mipmap-ic_launcher.png.flat
switch (resource) {
.directory => |resource_directory| {
const aapt2compile = b.addSystemCommand(&[_][]const u8{
apk.build_tools.aapt2,
"compile",
});
aapt2compile.setName(runNameContext("aapt2 compile [dir]"));
// add directory
aapt2compile.addArg("--dir");
aapt2compile.addDirectoryArg(resource_directory.source);
DirectoryFileInput.create(b, aapt2compile, resource_directory.source);
aapt2compile.addArg("-o");
const resources_flat_zip_file = aapt2compile.addOutputFileArg("resource_dir.flat.zip");
break :resblk resources_flat_zip_file;
},
}
};
// Add resources.flat.zip
aapt2link.addFileArg(resources_flat_zip);
}
break :blk resources_apk_file;
};
const package_name_file: LazyPath = blk: {
const aapt2packagename = b.addSystemCommand(&[_][]const u8{
apk.build_tools.aapt2,
"dump",
"packagename",
});
aapt2packagename.setName(runNameContext("aapt2 dump packagename"));
aapt2packagename.addFileArg(resources_apk);
const aapt2_package_name_file = if (builtin.zig_version.major == 0 and builtin.zig_version.minor <= 15)
aapt2packagename.captureStdOut()
else
aapt2packagename.captureStdOut(.{ .trim_whitespace = .trailing });
break :blk aapt2_package_name_file;
};
const android_builtin_options = BuiltinOptionsUpdate.create(b, package_name_file);
const android_builtin_mod = android_builtin_options.createModule();
// We could also use that information to create easy to use Zig step like
// - zig build adb-uninstall (adb uninstall "com.zig.sdl2")
// - zig build adb-logcat
// - Works if process isn't running anymore/crashed: Powershell: adb logcat | Select-String com.zig.sdl2:
// - Only works if process is running: adb logcat --pid=`adb shell pidof -s com.zig.sdl2`
//
// ADB install doesn't require the package name however.
// - zig build adb-install (adb install ./zig-out/bin/minimal.apk)
// These are files that belong in root like:
// - lib/x86_64/libmain.so
// - lib/x86_64/libSDL2.so
// - lib/x86/libmain.so
// - classes.dex
const apk_files = b.addWriteFiles();
// Add support for adding compiled library files (Vulkan Validation layers)
// ie. https://developer.android.com/ndk/guides/graphics/validation-layer
for (apk.precompiled_library_files.items) |precompiled_library| {
const so_dir = androidbuild.getTargetLibDir(b, precompiled_library.target);
// NOTE(jae): 2026-04-12
// Can likely just change to "precompiled_library.path.basename()" in the future if this breaks
const precompiled_lib_basename = std.fs.path.basename(switch (precompiled_library.path) {
.src_path => |sp| sp.sub_path,
.cwd_relative => |sub_path| sub_path,
.generated => @panic("invalid precompiled library, cannot be generated"),
.dependency => |dep| dep.sub_path,
// TODO(jae): 2026-06-29: Handle .relative in Zig 0.17.X
// .relative => @panic("UNHANDLED: invalid relative path"),
});
_ = apk_files.addCopyFile(precompiled_library.path, b.fmt("lib/{s}/{s}", .{ so_dir, precompiled_lib_basename }));
}
// These files belong in root and *must not* be compressed
// - resources.arsc
const apk_files_not_compressed = b.addWriteFiles();
// Add build artifacts, usually a shared library targetting:
// - aarch64-linux-android
// - arm-linux-androideabi
// - i686-linux-android
// - x86_64-linux-android
for (apk.artifacts.items, 0..) |artifact, artifact_index| {
if (artifact.root_module.resolved_target == null) {
@panic(b.fmt("artifact[{d}] has no 'target' set", .{artifact_index}));
}
// Add libraries *and* this artifact (exe) to collected libraries
//
// As of Zig 0.15.2 the order looks like
// - your_app_name
// - SDL3
// - freetype
// - imgui
const compile_dep_list = apk.getCompileDependencies(artifact, true);
for (compile_dep_list) |compile_dep| {
const graph = apk.getGraph(compile_dep.root_module);
// Update android_builtin
for (graph.modules) |module| {
if (module.import_table.get("android_builtin")) |prev_module| {
if (prev_module != android_builtin_mod) {
module.addImport("android_builtin", android_builtin_mod);
compile_dep.step.dependOn(&android_builtin_options.options.step);
}
}
}
// Update translate-c module
for (graph.modules) |module| {
const root_source_file = module.root_source_file orelse continue;
const c_translate_target = module.resolved_target orelse continue;
if (!c_translate_target.result.abi.isAndroid()) continue;
switch (root_source_file) {
.generated => |gen| {
const step: *std.Build.Step = if (builtin.zig_version.major == 0 and builtin.zig_version.minor <= 16)
// Deprecated: Zig 0.16.X, used to get Step directly
gen.file.step
else
b.graph.generated_files.items[@intFromEnum(gen.index)];
const tag = if (builtin.zig_version.major == 0 and builtin.zig_version.minor <= 16)
// Deprecated: Zig 0.16.X, renamed to tag in later versions
step.id
else
step.tag;
switch (tag) {
.translate_c => {
// Detect if using Translate-C vendored version
//
// NOTE(jae): 2026-04-29
// Longterm this will deprecated from Zig
const translate_c: *std.Build.Step.TranslateC = @fieldParentPtr("step", step);
translate_c.addIncludePath(.{ .cwd_relative = apk.ndk.include_path });
translate_c.addSystemIncludePath(.{ .cwd_relative = apk.getSystemIncludePath(c_translate_target) });
// NOTE(jae): 2026-06-14 - Zig 0.16.0
// Patch Aro/Translate-C to fix issues with SDL3 using translate-c.
// - _Nullable not working
// - _Nonnull not working
// - Force _FORTIFY_SOURCE to 0 to avoid references to missing functions
//
// Possibly related: https://github.com/Vexu/arocc/issues/989
translate_c.defineCMacro("_Nullable", "");
translate_c.defineCMacro("_Nonnull", "");
translate_c.defineCMacro("_FORTIFY_SOURCE", "0");
translate_c.defineCMacro("__ANDROID_API__", b.fmt("{}", .{@intFromEnum(apk.api_level)}));
},
.run => {
// Detect if using Translate-C external dependency and make assumptions about the flags
// we can pass into it such as "isystem" and "-I"
//
// Name: https://codeberg.org/ziglang/translate-c/src/commit/71642ad0084d433f14b091a7b2b109f0be915dbb/build/Translator.zig#L89
// Imports: https://codeberg.org/ziglang/translate-c/src/commit/71642ad0084d433f14b091a7b2b109f0be915dbb/build/Translator.zig#L103-L104
if (std.mem.startsWith(u8, step.name, "translate-c ") and
(module.import_table.contains("c_builtins") and module.import_table.contains("helpers")))
{
const run: *std.Build.Step.Run = @fieldParentPtr("step", step);
const ndk_include_path: LazyPath = .{ .cwd_relative = apk.ndk.include_path };
const system_include_path: LazyPath = .{ .cwd_relative = apk.getSystemIncludePath(c_translate_target) };
// Exposes the system include path `path` to both translate-c and to `t.mod`.
// https://codeberg.org/ziglang/translate-c/src/commit/71642ad0084d433f14b091a7b2b109f0be915dbb/build/Translator.zig#L207-L211
module.addSystemIncludePath(system_include_path);
run.addPrefixedDirectoryArg("-isystem", system_include_path);
// Exposes the include path `path` to both translate-c and to `t.mod`.
// https://codeberg.org/ziglang/translate-c/src/commit/71642ad0084d433f14b091a7b2b109f0be915dbb/build/Translator.zig#L203-L206
module.addIncludePath(ndk_include_path);
run.addPrefixedDirectoryArg("-I", ndk_include_path);
}
},
else => continue,
}
},
else => continue,
}
}
// update linked libraries that use C or C++ to:
// - use Android LibC file
// - add Android NDK library paths. (libandroid, liblog, etc)
switch (compile_dep.kind) {
.lib => {
// if (compile_dep.linkage.? == .static) {
// if (compile_dep.root_module.pic == null) {
// compile_dep.root_module.pic = true;
// }
// }
// Update updateSharedLibraryOptions, libCFile
apk.updateArtifact(compile_dep, apk_files);
// Apply workaround for Zig 0.14.0 and Zig 0.15.X
apk.applyLibLinkCppWorkaroundIssue19(compile_dep);
},
else => continue,
}
}
// Add module
// - If a module has no `root_source_file` (e.g you're only compiling C files using `addCSourceFiles`)
// then adding an import module will cause a build error (as of Zig 0.15.1).
if (artifact.root_module.root_source_file != null) {
const module = artifact.root_module;
if (module.import_table.get("android_builtin")) |prev_module| {
if (prev_module != android_builtin_mod) {
artifact.root_module.addImport("android_builtin", android_builtin_mod);
}
}
}
// update artifact to:
// - Be configured to work correctly on Android
// - To know where C header /lib files are via setLibCFile and linkLibC
// - Provide path to additional libraries to link to
{
if (artifact.root_module.link_libc == null) {
artifact.root_module.link_libc = true;
}
apk.updateArtifact(artifact, apk_files);
// Apply workaround for Zig 0.14.0 stable
//
// This *must* occur after apk.updateArtifact (apk.updateLinkObjects) for the root package otherwise
// you may get an error like: "unable to find dynamic system library 'c++abi_zig_workaround'"
apk.applyLibLinkCppWorkaroundIssue19(artifact);
}
}
// Add *.jar files
// - Even if java_files.items.len == 0, we still always add the root_jar
if (apk.java_files.items.len > 0) {
// https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html
const javac_cmd = b.addSystemCommand(&[_][]const u8{
apk.sdk.java_tools.javac,
// NOTE(jae): 2024-09-22
// Force encoding to be "utf8", this fixes the following error occuring in Windows:
// error: unmappable character (0x8F) for encoding windows-1252
// Source: https://github.com/libsdl-org/SDL/blob/release-2.30.7/android-project/app/src/main/java/org/libsdl/app/SDLActivity.java#L2045
"-encoding",
"utf8",
});
javac_cmd.setName(runNameContext("javac"));
// Add root jar
javac_cmd.addArg("-cp");
javac_cmd.addFileArg(root_jar);
if (builtin.zig_version.major == 0 and builtin.zig_version.minor <= 16) {
// NOTE(jae): 2026-03-01
// If we have verbose logging on, telling us about deprecated Java files
if (b.verbose) {
javac_cmd.addArg("-Xlint:deprecation");
}
}
// Output directory
javac_cmd.addArg("-d");
const java_classes_output_dir = javac_cmd.addOutputDirectoryArg("android_classes");
// Add Java files
for (apk.java_files.items) |java_file| {
javac_cmd.addFileArg(java_file);
}
// From d8.bat
// call "%java_exe%" %javaOpts% -cp "%jarpath%" com.android.tools.r8.D8 %params%
const d8 = b.addSystemCommand(&[_][]const u8{
apk.build_tools.d8,
});
d8.setName(runNameContext("d8"));
// Add JDK bin path so d8 can always find "java", etc
try apk.updatePathWithJdk(d8);
// NOTE(jae): 2024-09-22
// As per documentation for d8, we may want to specific the minimum API level we want
// to support. Not sure how to test or expose this yet. See: https://developer.android.com/tools/d8
// d8.addArg("--min-api");
// d8.addArg(number_as_string);
// add each output *.class file
if (builtin.zig_version.major == 0 and builtin.zig_version.minor <= 16) {
D8Glob.create(b, d8, java_classes_output_dir, root_jar);
} else {
// TODO(jae): 2026-06-29: Update D8Glob to collect files as seperate Run artifact
@compileError("TODO: Rewrite D8Glob to use Step.Run");
}
// ie. android_sdk/platforms/android-{api-level}/android.jar
d8.addArg("--lib");
d8.addFileArg(root_jar);
d8.addArg("--output");
const dex_output_dir = d8.addOutputDirectoryArg("android_dex");
const dex_file = dex_output_dir.path(b, "classes.dex");
// Append classes.dex to apk
_ = apk_files.addCopyFile(dex_file, "classes.dex");
}
// Extract compiled resources.apk and add contents to the folder we'll zip with "jar" below
// See: https://musteresel.github.io/posts/2019/07/build-android-app-bundle-on-command-line.html
{
const jar = b.addSystemCommand(&[_][]const u8{
apk.sdk.java_tools.jar,
});
jar.setName(runNameContext("jar (unzip resources.apk)"));
if (builtin.zig_version.major == 0 and builtin.zig_version.minor <= 16 and b.verbose) {
jar.addArg("--verbose");
}
// Extract *.apk file created with "aapt2 link"
jar.addArg("--extract");
jar.addPrefixedFileArg("--file=", resources_apk);
// NOTE(jae): 2024-09-30
// Extract to directory of resources_apk and force add that to the overall apk files.
// This currently has an issue where because we can't use "addOutputDirectoryArg" this
// step will always be executed.
const extracted_apk_dir = resources_apk.dirname();
jar.setCwd(extracted_apk_dir);
_ = apk_files.addCopyDirectory(extracted_apk_dir, "", .{
.exclude_extensions = &.{
// ignore the *.apk that exists in this directory
".apk",
// ignore resources.arsc as Android 30+ APIs does not supporting
// compressing this in the zip file
".arsc",
},
});
apk_files.step.dependOn(&jar.step);
// Setup directory of additional files that should not be compressed
// NOTE(jae): 2025-03-23 - https://github.com/silbinarywolf/zig-android-sdk/issues/23
// We apply resources.arsc seperately to the zip file to avoid compressing it, otherwise we get the following
// error when we "adb install"
// - "Targeting R+ (version 30 and above) requires the resources.arsc of installed APKs to be stored uncompressed and aligned on a 4-byte boundary"
_ = apk_files_not_compressed.addCopyFile(extracted_apk_dir.path(b, "resources.arsc"), "resources.arsc");
apk_files_not_compressed.step.dependOn(&jar.step);
}
// Create zip via "jar" as it's cross-platform and aapt2 can't zip *.so or *.dex files.
// - lib/**/*.so
// - classes.dex
// - {directory with all resource files like: AndroidManifest.xml, res/values/strings.xml}
const zip_file: LazyPath = blk: {
const jar = b.addSystemCommand(&[_][]const u8{
apk.sdk.java_tools.jar,
});
jar.setName(runNameContext("jar (zip compress apk)"));
const directory_to_zip = apk_files.getDirectory();
jar.setCwd(directory_to_zip);
// NOTE(jae): 2024-09-30
// Hack to ensure this side-effect re-triggers zipping this up
jar.addFileInput(directory_to_zip.path(b, "AndroidManifest.xml"));
// Written as-is from running "jar --help"
// -c, --create = Create the archive. When the archive file name specified
// -u, --update = Update an existing jar archive
// -f, --file=FILE = The archive file name. When omitted, either stdin or
// -M, --no-manifest = Do not create a manifest file for the entries
// -0, --no-compress = Store only; use no ZIP compression
const compress_zip_arg = "-cfM";
if (builtin.zig_version.major == 0 and builtin.zig_version.minor <= 16 and b.verbose) jar.addArg(compress_zip_arg ++ "v") else jar.addArg(compress_zip_arg);
const output_zip_file = jar.addOutputFileArg("compiled_code.zip");
jar.addArg(".");
break :blk output_zip_file;
};
// Update zip with files that are not compressed (ie. resources.arsc)
const update_zip: *Step = blk: {
const jar = b.addSystemCommand(&[_][]const u8{
apk.sdk.java_tools.jar,
});
jar.setName(runNameContext("jar (update zip with uncompressed files)"));
const directory_to_zip = apk_files_not_compressed.getDirectory();
jar.setCwd(directory_to_zip);
// NOTE(jae): 2025-03-23
// Hack to ensure this side-effect re-triggers zipping this up
jar.addFileInput(apk_files_not_compressed.getDirectory().path(b, "resources.arsc"));
// Written as-is from running "jar --help"
// -c, --create = Create the archive. When the archive file name specified
// -u, --update = Update an existing jar archive
// -f, --file=FILE = The archive file name. When omitted, either stdin or
// -M, --no-manifest = Do not create a manifest file for the entries
// -0, --no-compress = Store only; use no ZIP compression
const update_zip_arg = "-ufM0";
if (builtin.zig_version.major == 0 and builtin.zig_version.minor <= 16 and b.verbose)
jar.addArg(update_zip_arg ++ "v")
else
jar.addArg(update_zip_arg);
jar.addFileArg(zip_file);
jar.addArg(".");
break :blk &jar.step;
};
// NOTE(jae): 2024-09-28 - https://github.com/silbinarywolf/zig-android-sdk/issues/8
// Experimented with using "lint" but it didn't actually catch the issue described
// in the above Github, ie. having "<category android:name="org.khronos.openxr.intent.category.IMMERSIVE_HMD" />"
// outside of an <intent-filter>
//
// const lint = b.addSystemCommand(&[_][]const u8{
// apk.tools.commandline_tools.lint,
// });
// lint.setEnvironmentVariable("PATH", b.pathJoin(&.{ apk.tools.jdk_path, "bin" }));
// lint.setEnvironmentVariable("JAVA_HOME", apk.tools.jdk_path);
// lint.addFileArg(android_manifest_file);
// Align contents of .apk (zip)
const aligned_apk_file: LazyPath = blk: {
var zipalign = b.addSystemCommand(&[_][]const u8{
apk.build_tools.zipalign,
});
zipalign.setName(runNameContext("zipalign"));
// If you use apksigner, zipalign must be used before the APK file has been signed.
// If you sign your APK using apksigner and make further changes to the APK, its signature is invalidated.
// Source: https://developer.android.com/tools/zipalign (10th Sept, 2024)
//
// Example: "zipalign -P 16 -f -v 4 infile.apk outfile.apk"
if (builtin.zig_version.major == 0 and builtin.zig_version.minor <= 16 and b.verbose) {
zipalign.addArg("-v");
}
zipalign.addArgs(&.{
"-P", // aligns uncompressed .so files to the specified page size in KiB...
"16", // ... align to 16kb
"-f", // overwrite existing files
// "-z", // recompresses using Zopfli. (very very slow)
"4",
});
// Depend on zip file and the additional update to it
zipalign.addFileArg(zip_file);
zipalign.step.dependOn(update_zip);
const apk_file = zipalign.addOutputFileArg(b.fmt("aligned-{s}.apk", .{apk.name}));
break :blk apk_file;
};
// Sign apk
const signed_apk_file: LazyPath = blk: {
const apksigner = b.addSystemCommand(&[_][]const u8{
apk.build_tools.apksigner,
"sign",
});
try apk.updatePathWithJdk(apksigner);
apksigner.setName(runNameContext("apksigner"));
apksigner.addArg("--ks"); // ks = keystore
apksigner.addFileArg(key_store.file);
apksigner.addArgs(&.{ "--ks-pass", b.fmt("pass:{s}", .{key_store.password}) });
apksigner.addArg("--out");
const signed_output_apk_file = apksigner.addOutputFileArg("signed-and-aligned-apk.apk");
apksigner.addFileArg(aligned_apk_file);
break :blk signed_output_apk_file;
};
const install_apk = b.addInstallBinFile(signed_apk_file, b.fmt("{s}.apk", .{apk.name}));
return install_apk;
}
fn getSystemIncludePath(apk: *Apk, target: ResolvedTarget) []const u8 {
const b = apk.b;
const system_target = getAndroidTriple(target) catch |err| @panic(@errorName(err));
return b.fmt("{s}/{s}", .{ apk.ndk.include_path, system_target });
}
fn setLibCFile(apk: *Apk, compile: *Step.Compile) void {
const tools = apk.sdk;
const android_libc_path = tools.createOrGetLibCFile(compile, apk.api_level, apk.ndk.sysroot_path, apk.ndk.version);
android_libc_path.addStepDependencies(&compile.step);
compile.setLibCFile(android_libc_path);
}
/// Copy-paste of "lib/std/Build/Module.zig" but it doesn't cache via GetGraph and won't potentially break the
/// Zig build system.
///
/// Return the full set of `Step.Compile` which `start` depends on, recursively. `start` itself is
/// always returned as the first element. If `chase_dynamic` is `false`, then dynamic libraries are
/// not included, and their dependencies are not considered; if `chase_dynamic` is `true`, dynamic
/// libraries are treated the same as other linked `Compile`s.
fn getCompileDependencies(apk: *Apk, start: *Step.Compile, chase_dynamic: bool) []const *Step.Compile {
const arena = start.step.owner.graph.arena;
var compiles: std.AutoArrayHashMapUnmanaged(*Step.Compile, void) = .empty;
var next_idx: usize = 0;
compiles.putNoClobber(arena, start, {}) catch @panic("OOM");
while (next_idx < compiles.count()) {
const compile = compiles.keys()[next_idx];
next_idx += 1;
for (apk.getGraph(compile.root_module).modules) |mod| {
for (mod.link_objects.items) |lo| {
switch (lo) {
.other_step => |other_compile| {
if (!chase_dynamic and other_compile.isDynamicLibrary()) continue;
compiles.put(arena, other_compile, {}) catch @panic("OOM");
},
else => {},
}
}
}
}
return compiles.keys();
}
const Graph = struct {
modules: []const *std.Build.Module,
names: []const []const u8,
};
/// Copy-paste of "lib/std/Build/Module.zig" but it doesn't cache and won't potentially break the
/// Zig build system.
///
/// Given that `root` is the root `Module` of a compilation, return all `Module`s
/// in the module graph, including `root` itself. `root` is guaranteed to be the
/// first module in the returned slice.
fn getGraph(apk: *Apk, root: *std.Build.Module) Graph {
const arena = apk.b.graph.arena;
var modules: std.AutoArrayHashMapUnmanaged(*std.Build.Module, []const u8) = .empty;
var next_idx: usize = 0;
modules.putNoClobber(arena, root, "root") catch @panic("OOM");
while (next_idx < modules.count()) {
const mod = modules.keys()[next_idx];
next_idx += 1;
modules.ensureUnusedCapacity(arena, mod.import_table.count()) catch @panic("OOM");
for (mod.import_table.keys(), mod.import_table.values()) |import_name, other_mod| {
modules.putAssumeCapacity(other_mod, import_name);
}
}
const result: Graph = .{
.modules = modules.keys(),
.names = modules.values(),
};
return result;
}
fn updateArtifact(apk: *Apk, artifact: *Step.Compile, raw_top_level_apk_files: *Step.WriteFile) void {
const b = apk.b;
// Set page size to 16KB-aligned binaries by default
//
// For Android NDK r27 onwards, Android recommends the following setting by default
// Source: https://developer.android.com/guide/practices/page-sizes#compile-r27
//
// NOTE(jae): 2026-04-23
// Zig 0.16.0 stable does not do this by default and without this line, there is a pop-up
// warning when testing on Pixel 10, Android 17 VM device.
// Screenshot is on Github issue here: https://github.com/silbinarywolf/zig-android-sdk/issues/87
if (artifact.link_z_max_page_size == null) {
artifact.link_z_max_page_size = 16384;
}
// If you have a library that is being built as an *.so then install it
// alongside your library.
//
// This was initially added to support building SDL2 with Zig.
if (artifact.linkage) |linkage| {
if (linkage == .dynamic) {
updateSharedLibraryOptions(artifact);
// https://developer.android.com/ndk/guides/abis#native-code-in-app-packages
const target = artifact.root_module.resolved_target orelse unreachable;
const so_dir = androidbuild.getTargetLibDir(b, target);
_ = raw_top_level_apk_files.addCopyFile(artifact.getEmittedBin(), b.fmt("lib/{s}/lib{s}.so", .{ so_dir, artifact.name }));
}
}
// NOTE(jae): 2026-02-01
// If not explicitly set in users build, default to using LLVM and LLD for Android builds
// as that's the same toolchain that the Android SDK uses.
//
// This also can resolve issues with Zigs linker not yet supporting certain compression schemes/etc
if (artifact.use_lld == null) {
artifact.use_lld = true;
}
if (artifact.use_llvm == null) {
artifact.use_llvm = true;
}
// If library is built using C or C++ then setLibCFile
if (artifact.root_module.link_libc == true or
artifact.root_module.link_libcpp == true)
{
apk.setLibCFile(artifact);
}
// Add library paths to find "android", "log", etc
{
const module = artifact.root_module;
const target: ResolvedTarget = module.resolved_target orelse {
@panic(b.fmt("no 'target' set on Android module", .{}));
};
const system_target = getAndroidTriple(target) catch |err| @panic(@errorName(err));
// NOTE(jae): 2024-09-11
// These *must* be in order of API version, then architecture, then non-arch specific otherwise
// when starting an *.so from Android or an emulator you can get an error message like this:
// - "java.lang.UnsatisfiedLinkError: dlopen failed: TLS symbol "_ZZN8gwp_asan15getThreadLocalsEvE6Locals" in dlopened"