authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-03-02 22:38:07-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-03-15 10:48:13-07:00
logdcec4d55e36f48e459f4e8f218b8619d9be925db
tree0064e09c25715650b4e1ac641d5a33ec91245be1
parent9bf63b09963ca6ea1179dfaa9142498556bfac9d

eliminate stderr usage in std.Build make() functions

* Eliminate all uses of `std.debug.print` in make() functions, instead properly using the step failure reporting mechanism. * Introduce the concept of skipped build steps. These do not cause the build to fail, and they do allow their dependants to run. * RunStep gains a new flag, `skip_foreign_checks` which causes the RunStep to be skipped if stdio mode is `check` and the binary cannot be executed due to it being a foreign executable. - RunStep is improved to automatically use known interpreters to execute binaries if possible (integrating with flags such as -fqemu and -fwasmtime). It only does this after attempting a native execution and receiving a "exec file format" error. - Update RunStep to use an ArrayList for the checks rather than this ad-hoc reallocation/copying mechanism. - `expectStdOutEqual` now also implicitly adds an exit_code==0 check if there is not already an expected termination. This matches previously expected behavior from older API and can be overridden by directly setting the checks array. * Add `dest_sub_path` to `InstallArtifactStep` which allows choosing an arbitrary subdirectory relative to the prefix, as well as overriding the basename. - Delete the custom InstallWithRename step that I found deep in the test/ directory. * WriteFileStep will now update its step display name after the first file is added. * Add missing stdout checks to various standalone test case build scripts.

20 files changed, 513 insertions(+), 312 deletions(-)

build.zig+1-2
......@@ -385,7 +385,7 @@ pub fn build(b: *std.Build) !void {
385385 const optimization_modes = chosen_opt_modes_buf[0..chosen_mode_index];
386386
387387 const fmt_include_paths = &.{ "doc", "lib", "src", "test", "tools", "build.zig" };
388 const fmt_exclude_paths = &.{ "test/cases" };
388 const fmt_exclude_paths = &.{"test/cases"};
389389 const check_fmt = b.addFmt(.{
390390 .paths = fmt_include_paths,
391391 .exclude_paths = fmt_exclude_paths,
......@@ -402,7 +402,6 @@ pub fn build(b: *std.Build) !void {
402402 const do_fmt_step = b.step("fmt", "Modify source files in place to have conforming formatting");
403403 do_fmt_step.dependOn(&do_fmt.step);
404404
405
406405 test_step.dependOn(tests.addPkgTests(
407406 b,
408407 test_filter,
lib/build_runner.zig+23-12
......@@ -357,6 +357,7 @@ fn runStepNames(
357357 }
358358
359359 var success_count: usize = 0;
360 var skipped_count: usize = 0;
360361 var failure_count: usize = 0;
361362 var pending_count: usize = 0;
362363 var total_compile_errors: usize = 0;
......@@ -379,6 +380,7 @@ fn runStepNames(
379380 },
380381 .dependency_failure => pending_count += 1,
381382 .success => success_count += 1,
383 .skipped => skipped_count += 1,
382384 .failure => {
383385 failure_count += 1;
384386 const compile_errors_len = s.result_error_bundle.errorMessageCount();
......@@ -395,13 +397,13 @@ fn runStepNames(
395397 if (failure_count == 0 and enable_summary != true) return cleanExit();
396398
397399 if (enable_summary != false) {
398 const total_count = success_count + failure_count + pending_count;
400 const total_count = success_count + failure_count + pending_count + skipped_count;
399401 ttyconf.setColor(stderr, .Cyan) catch {};
400402 stderr.writeAll("Build Summary:") catch {};
401403 ttyconf.setColor(stderr, .Reset) catch {};
402 stderr.writer().print(" {d}/{d} steps succeeded; {d} failed", .{
403 success_count, total_count, failure_count,
404 }) catch {};
404 stderr.writer().print(" {d}/{d} steps succeeded", .{ success_count, total_count }) catch {};
405 if (skipped_count > 0) stderr.writer().print("; {d} skipped", .{skipped_count}) catch {};
406 if (failure_count > 0) stderr.writer().print("; {d} failed", .{failure_count}) catch {};
405407
406408 if (enable_summary == null) {
407409 ttyconf.setColor(stderr, .Dim) catch {};
......@@ -503,6 +505,12 @@ fn printTreeStep(
503505 try ttyconf.setColor(stderr, .Reset);
504506 },
505507
508 .skipped => {
509 try ttyconf.setColor(stderr, .Yellow);
510 try stderr.writeAll(" skipped\n");
511 try ttyconf.setColor(stderr, .Reset);
512 },
513
506514 .failure => {
507515 try ttyconf.setColor(stderr, .Red);
508516 if (s.result_error_bundle.errorMessageCount() > 0) {
......@@ -569,6 +577,7 @@ fn checkForDependencyLoop(
569577 .running => unreachable,
570578 .success => unreachable,
571579 .failure => unreachable,
580 .skipped => unreachable,
572581 }
573582}
574583
......@@ -587,7 +596,7 @@ fn workerMakeOneStep(
587596 // queue this step up again when dependencies are met.
588597 for (s.dependencies.items) |dep| {
589598 switch (@atomicLoad(Step.State, &dep.state, .SeqCst)) {
590 .success => continue,
599 .success, .skipped => continue,
591600 .failure, .dependency_failure => {
592601 @atomicStore(Step.State, &s.state, .dependency_failure, .SeqCst);
593602 return;
......@@ -639,13 +648,15 @@ fn workerMakeOneStep(
639648 }
640649 }
641650
642 make_result catch |err| {
643 assert(err == error.MakeFailed);
644 @atomicStore(Step.State, &s.state, .failure, .SeqCst);
645 return;
646 };
647
648 @atomicStore(Step.State, &s.state, .success, .SeqCst);
651 if (make_result) |_| {
652 @atomicStore(Step.State, &s.state, .success, .SeqCst);
653 } else |err| switch (err) {
654 error.MakeFailed => {
655 @atomicStore(Step.State, &s.state, .failure, .SeqCst);
656 return;
657 },
658 error.MakeSkipped => @atomicStore(Step.State, &s.state, .skipped, .SeqCst),
659 }
649660
650661 // Successful completion of a step, so we queue up its dependants as well.
651662 for (s.dependants.items) |dep| {
lib/std/Build/CheckFileStep.zig+3-4
......@@ -42,15 +42,14 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
4242
4343 for (self.expected_matches) |expected_match| {
4444 if (mem.indexOf(u8, contents, expected_match) == null) {
45 std.debug.print(
45 return step.fail(
4646 \\
47 \\========= Expected to find: ===================
47 \\========= expected to find: ===================
4848 \\{s}
49 \\========= But file does not contain it: =======
49 \\========= but file does not contain it: =======
5050 \\{s}
5151 \\
5252 , .{ expected_match, contents });
53 return error.TestFailed;
5453 }
5554 }
5655}
lib/std/Build/CheckObjectStep.zig+65-73
......@@ -133,7 +133,8 @@ const Action = struct {
133133 /// Will return true if the `phrase` is correctly parsed into an RPN program and
134134 /// its reduced, computed value compares using `op` with the expected value, either
135135 /// a literal or another extracted variable.
136 fn computeCmp(act: Action, gpa: Allocator, global_vars: anytype) !bool {
136 fn computeCmp(act: Action, step: *Step, global_vars: anytype) !bool {
137 const gpa = step.owner.allocator;
137138 var op_stack = std.ArrayList(enum { add, sub, mod, mul }).init(gpa);
138139 var values = std.ArrayList(u64).init(gpa);
139140
......@@ -150,11 +151,11 @@ const Action = struct {
150151 } else {
151152 const val = std.fmt.parseInt(u64, next, 0) catch blk: {
152153 break :blk global_vars.get(next) orelse {
153 std.debug.print(
154 try step.addError(
154155 \\
155 \\========= Variable was not extracted: ===========
156 \\========= variable was not extracted: ===========
156157 \\{s}
157 \\
158 \\=================================================
158159 , .{next});
159160 return error.UnknownVariable;
160161 };
......@@ -186,11 +187,11 @@ const Action = struct {
186187
187188 const exp_value = switch (act.expected.?.value) {
188189 .variable => |name| global_vars.get(name) orelse {
189 std.debug.print(
190 try step.addError(
190191 \\
191 \\========= Variable was not extracted: ===========
192 \\========= variable was not extracted: ===========
192193 \\{s}
193 \\
194 \\=================================================
194195 , .{name});
195196 return error.UnknownVariable;
196197 },
......@@ -323,14 +324,12 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
323324 );
324325
325326 const output = switch (self.obj_format) {
326 .macho => try MachODumper.parseAndDump(contents, .{
327 .gpa = gpa,
327 .macho => try MachODumper.parseAndDump(step, contents, .{
328328 .dump_symtab = self.dump_symtab,
329329 }),
330330 .elf => @panic("TODO elf parser"),
331331 .coff => @panic("TODO coff parser"),
332 .wasm => try WasmDumper.parseAndDump(contents, .{
333 .gpa = gpa,
332 .wasm => try WasmDumper.parseAndDump(step, contents, .{
334333 .dump_symtab = self.dump_symtab,
335334 }),
336335 else => unreachable,
......@@ -346,54 +345,50 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
346345 while (it.next()) |line| {
347346 if (try act.match(line, &vars)) break;
348347 } else {
349 std.debug.print(
348 return step.fail(
350349 \\
351 \\========= Expected to find: ==========================
350 \\========= expected to find: ==========================
352351 \\{s}
353 \\========= But parsed file does not contain it: =======
352 \\========= but parsed file does not contain it: =======
354353 \\{s}
355 \\
354 \\======================================================
356355 , .{ act.phrase, output });
357 return error.TestFailed;
358356 }
359357 },
360358 .not_present => {
361359 while (it.next()) |line| {
362360 if (try act.match(line, &vars)) {
363 std.debug.print(
361 return step.fail(
364362 \\
365 \\========= Expected not to find: ===================
363 \\========= expected not to find: ===================
366364 \\{s}
367 \\========= But parsed file does contain it: ========
365 \\========= but parsed file does contain it: ========
368366 \\{s}
369 \\
367 \\===================================================
370368 , .{ act.phrase, output });
371 return error.TestFailed;
372369 }
373370 }
374371 },
375372 .compute_cmp => {
376 const res = act.computeCmp(gpa, vars) catch |err| switch (err) {
373 const res = act.computeCmp(step, vars) catch |err| switch (err) {
377374 error.UnknownVariable => {
378 std.debug.print(
379 \\========= From parsed file: =====================
375 return step.fail(
376 \\========= from parsed file: =====================
380377 \\{s}
381 \\
378 \\=================================================
382379 , .{output});
383 return error.TestFailed;
384380 },
385381 else => |e| return e,
386382 };
387383 if (!res) {
388 std.debug.print(
384 return step.fail(
389385 \\
390 \\========= Comparison failed for action: ===========
386 \\========= comparison failed for action: ===========
391387 \\{s} {}
392 \\========= From parsed file: =======================
388 \\========= from parsed file: =======================
393389 \\{s}
394 \\
390 \\===================================================
395391 , .{ act.phrase, act.expected.?, output });
396 return error.TestFailed;
397392 }
398393 },
399394 }
......@@ -402,7 +397,6 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
402397}
403398
404399const Opts = struct {
405 gpa: ?Allocator = null,
406400 dump_symtab: bool = false,
407401};
408402
......@@ -410,8 +404,8 @@ const MachODumper = struct {
410404 const LoadCommandIterator = macho.LoadCommandIterator;
411405 const symtab_label = "symtab";
412406
413 fn parseAndDump(bytes: []align(@alignOf(u64)) const u8, opts: Opts) ![]const u8 {
414 const gpa = opts.gpa orelse unreachable; // MachO dumper requires an allocator
407 fn parseAndDump(step: *Step, bytes: []align(@alignOf(u64)) const u8, opts: Opts) ![]const u8 {
408 const gpa = step.owner.allocator;
415409 var stream = std.io.fixedBufferStream(bytes);
416410 const reader = stream.reader();
417411
......@@ -693,8 +687,8 @@ const MachODumper = struct {
693687const WasmDumper = struct {
694688 const symtab_label = "symbols";
695689
696 fn parseAndDump(bytes: []const u8, opts: Opts) ![]const u8 {
697 const gpa = opts.gpa orelse unreachable; // Wasm dumper requires an allocator
690 fn parseAndDump(step: *Step, bytes: []const u8, opts: Opts) ![]const u8 {
691 const gpa = step.owner.allocator;
698692 if (opts.dump_symtab) {
699693 @panic("TODO: Implement symbol table parsing and dumping");
700694 }
......@@ -715,20 +709,24 @@ const WasmDumper = struct {
715709 const writer = output.writer();
716710
717711 while (reader.readByte()) |current_byte| {
718 const section = std.meta.intToEnum(std.wasm.Section, current_byte) catch |err| {
719 std.debug.print("Found invalid section id '{d}'\n", .{current_byte});
720 return err;
712 const section = std.meta.intToEnum(std.wasm.Section, current_byte) catch {
713 return step.fail("Found invalid section id '{d}'", .{current_byte});
721714 };
722715
723716 const section_length = try std.leb.readULEB128(u32, reader);
724 try parseAndDumpSection(section, bytes[fbs.pos..][0..section_length], writer);
717 try parseAndDumpSection(step, section, bytes[fbs.pos..][0..section_length], writer);
725718 fbs.pos += section_length;
726719 } else |_| {} // reached end of stream
727720
728721 return output.toOwnedSlice();
729722 }
730723
731 fn parseAndDumpSection(section: std.wasm.Section, data: []const u8, writer: anytype) !void {
724 fn parseAndDumpSection(
725 step: *Step,
726 section: std.wasm.Section,
727 data: []const u8,
728 writer: anytype,
729 ) !void {
732730 var fbs = std.io.fixedBufferStream(data);
733731 const reader = fbs.reader();
734732
......@@ -751,7 +749,7 @@ const WasmDumper = struct {
751749 => {
752750 const entries = try std.leb.readULEB128(u32, reader);
753751 try writer.print("\nentries {d}\n", .{entries});
754 try dumpSection(section, data[fbs.pos..], entries, writer);
752 try dumpSection(step, section, data[fbs.pos..], entries, writer);
755753 },
756754 .custom => {
757755 const name_length = try std.leb.readULEB128(u32, reader);
......@@ -760,7 +758,7 @@ const WasmDumper = struct {
760758 try writer.print("\nname {s}\n", .{name});
761759
762760 if (mem.eql(u8, name, "name")) {
763 try parseDumpNames(reader, writer, data);
761 try parseDumpNames(step, reader, writer, data);
764762 } else if (mem.eql(u8, name, "producers")) {
765763 try parseDumpProducers(reader, writer, data);
766764 } else if (mem.eql(u8, name, "target_features")) {
......@@ -776,7 +774,7 @@ const WasmDumper = struct {
776774 }
777775 }
778776
779 fn dumpSection(section: std.wasm.Section, data: []const u8, entries: u32, writer: anytype) !void {
777 fn dumpSection(step: *Step, section: std.wasm.Section, data: []const u8, entries: u32, writer: anytype) !void {
780778 var fbs = std.io.fixedBufferStream(data);
781779 const reader = fbs.reader();
782780
......@@ -786,19 +784,18 @@ const WasmDumper = struct {
786784 while (i < entries) : (i += 1) {
787785 const func_type = try reader.readByte();
788786 if (func_type != std.wasm.function_type) {
789 std.debug.print("Expected function type, found byte '{d}'\n", .{func_type});
790 return error.UnexpectedByte;
787 return step.fail("expected function type, found byte '{d}'", .{func_type});
791788 }
792789 const params = try std.leb.readULEB128(u32, reader);
793790 try writer.print("params {d}\n", .{params});
794791 var index: u32 = 0;
795792 while (index < params) : (index += 1) {
796 try parseDumpType(std.wasm.Valtype, reader, writer);
793 try parseDumpType(step, std.wasm.Valtype, reader, writer);
797794 } else index = 0;
798795 const returns = try std.leb.readULEB128(u32, reader);
799796 try writer.print("returns {d}\n", .{returns});
800797 while (index < returns) : (index += 1) {
801 try parseDumpType(std.wasm.Valtype, reader, writer);
798 try parseDumpType(step, std.wasm.Valtype, reader, writer);
802799 }
803800 }
804801 },
......@@ -812,9 +809,8 @@ const WasmDumper = struct {
812809 const name = data[fbs.pos..][0..name_len];
813810 fbs.pos += name_len;
814811
815 const kind = std.meta.intToEnum(std.wasm.ExternalKind, try reader.readByte()) catch |err| {
816 std.debug.print("Invalid import kind\n", .{});
817 return err;
812 const kind = std.meta.intToEnum(std.wasm.ExternalKind, try reader.readByte()) catch {
813 return step.fail("invalid import kind", .{});
818814 };
819815
820816 try writer.print(
......@@ -831,11 +827,11 @@ const WasmDumper = struct {
831827 try parseDumpLimits(reader, writer);
832828 },
833829 .global => {
834 try parseDumpType(std.wasm.Valtype, reader, writer);
830 try parseDumpType(step, std.wasm.Valtype, reader, writer);
835831 try writer.print("mutable {}\n", .{0x01 == try std.leb.readULEB128(u32, reader)});
836832 },
837833 .table => {
838 try parseDumpType(std.wasm.RefType, reader, writer);
834 try parseDumpType(step, std.wasm.RefType, reader, writer);
839835 try parseDumpLimits(reader, writer);
840836 },
841837 }
......@@ -850,7 +846,7 @@ const WasmDumper = struct {
850846 .table => {
851847 var i: u32 = 0;
852848 while (i < entries) : (i += 1) {
853 try parseDumpType(std.wasm.RefType, reader, writer);
849 try parseDumpType(step, std.wasm.RefType, reader, writer);
854850 try parseDumpLimits(reader, writer);
855851 }
856852 },
......@@ -863,9 +859,9 @@ const WasmDumper = struct {
863859 .global => {
864860 var i: u32 = 0;
865861 while (i < entries) : (i += 1) {
866 try parseDumpType(std.wasm.Valtype, reader, writer);
862 try parseDumpType(step, std.wasm.Valtype, reader, writer);
867863 try writer.print("mutable {}\n", .{0x01 == try std.leb.readULEB128(u1, reader)});
868 try parseDumpInit(reader, writer);
864 try parseDumpInit(step, reader, writer);
869865 }
870866 },
871867 .@"export" => {
......@@ -875,9 +871,8 @@ const WasmDumper = struct {
875871 const name = data[fbs.pos..][0..name_len];
876872 fbs.pos += name_len;
877873 const kind_byte = try std.leb.readULEB128(u8, reader);
878 const kind = std.meta.intToEnum(std.wasm.ExternalKind, kind_byte) catch |err| {
879 std.debug.print("invalid export kind value '{d}'\n", .{kind_byte});
880 return err;
874 const kind = std.meta.intToEnum(std.wasm.ExternalKind, kind_byte) catch {
875 return step.fail("invalid export kind value '{d}'", .{kind_byte});
881876 };
882877 const index = try std.leb.readULEB128(u32, reader);
883878 try writer.print(
......@@ -892,7 +887,7 @@ const WasmDumper = struct {
892887 var i: u32 = 0;
893888 while (i < entries) : (i += 1) {
894889 try writer.print("table index {d}\n", .{try std.leb.readULEB128(u32, reader)});
895 try parseDumpInit(reader, writer);
890 try parseDumpInit(step, reader, writer);
896891
897892 const function_indexes = try std.leb.readULEB128(u32, reader);
898893 var function_index: u32 = 0;
......@@ -908,7 +903,7 @@ const WasmDumper = struct {
908903 while (i < entries) : (i += 1) {
909904 const index = try std.leb.readULEB128(u32, reader);
910905 try writer.print("memory index 0x{x}\n", .{index});
911 try parseDumpInit(reader, writer);
906 try parseDumpInit(step, reader, writer);
912907 const size = try std.leb.readULEB128(u32, reader);
913908 try writer.print("size {d}\n", .{size});
914909 try reader.skipBytes(size, .{}); // we do not care about the content of the segments
......@@ -918,11 +913,10 @@ const WasmDumper = struct {
918913 }
919914 }
920915
921 fn parseDumpType(comptime WasmType: type, reader: anytype, writer: anytype) !void {
916 fn parseDumpType(step: *Step, comptime WasmType: type, reader: anytype, writer: anytype) !void {
922917 const type_byte = try reader.readByte();
923 const valtype = std.meta.intToEnum(WasmType, type_byte) catch |err| {
924 std.debug.print("Invalid wasm type value '{d}'\n", .{type_byte});
925 return err;
918 const valtype = std.meta.intToEnum(WasmType, type_byte) catch {
919 return step.fail("Invalid wasm type value '{d}'", .{type_byte});
926920 };
927921 try writer.print("type {s}\n", .{@tagName(valtype)});
928922 }
......@@ -937,11 +931,10 @@ const WasmDumper = struct {
937931 }
938932 }
939933
940 fn parseDumpInit(reader: anytype, writer: anytype) !void {
934 fn parseDumpInit(step: *Step, reader: anytype, writer: anytype) !void {
941935 const byte = try std.leb.readULEB128(u8, reader);
942 const opcode = std.meta.intToEnum(std.wasm.Opcode, byte) catch |err| {
943 std.debug.print("invalid wasm opcode '{d}'\n", .{byte});
944 return err;
936 const opcode = std.meta.intToEnum(std.wasm.Opcode, byte) catch {
937 return step.fail("invalid wasm opcode '{d}'", .{byte});
945938 };
946939 switch (opcode) {
947940 .i32_const => try writer.print("i32.const {x}\n", .{try std.leb.readILEB128(i32, reader)}),
......@@ -953,14 +946,13 @@ const WasmDumper = struct {
953946 }
954947 const end_opcode = try std.leb.readULEB128(u8, reader);
955948 if (end_opcode != std.wasm.opcode(.end)) {
956 std.debug.print("expected 'end' opcode in init expression\n", .{});
957 return error.MissingEndOpcode;
949 return step.fail("expected 'end' opcode in init expression", .{});
958950 }
959951 }
960952
961 fn parseDumpNames(reader: anytype, writer: anytype, data: []const u8) !void {
953 fn parseDumpNames(step: *Step, reader: anytype, writer: anytype, data: []const u8) !void {
962954 while (reader.context.pos < data.len) {
963 try parseDumpType(std.wasm.NameSubsection, reader, writer);
955 try parseDumpType(step, std.wasm.NameSubsection, reader, writer);
964956 const size = try std.leb.readULEB128(u32, reader);
965957 const entries = try std.leb.readULEB128(u32, reader);
966958 try writer.print(
lib/std/Build/CompileStep.zig+1-2
......@@ -538,8 +538,7 @@ pub fn run(cs: *CompileStep) *RunStep {
538538}
539539
540540pub fn checkObject(self: *CompileStep, obj_format: std.Target.ObjectFormat) *CheckObjectStep {
541 const b = self.step.owner;
542 return CheckObjectStep.create(b, self.getOutputSource(), obj_format);
541 return CheckObjectStep.create(self.step.owner, self.getOutputSource(), obj_format);
543542}
544543
545544pub fn setLinkerScriptPath(self: *CompileStep, source: FileSource) void {
lib/std/Build/ConfigHeaderStep.zig+13-10
......@@ -192,13 +192,13 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
192192 try output.appendSlice(c_generated_line);
193193 const src_path = file_source.getPath(b);
194194 const contents = try std.fs.cwd().readFileAlloc(gpa, src_path, self.max_bytes);
195 try render_autoconf(contents, &output, self.values, src_path);
195 try render_autoconf(step, contents, &output, self.values, src_path);
196196 },
197197 .cmake => |file_source| {
198198 try output.appendSlice(c_generated_line);
199199 const src_path = file_source.getPath(b);
200200 const contents = try std.fs.cwd().readFileAlloc(gpa, src_path, self.max_bytes);
201 try render_cmake(contents, &output, self.values, src_path);
201 try render_cmake(step, contents, &output, self.values, src_path);
202202 },
203203 .blank => {
204204 try output.appendSlice(c_generated_line);
......@@ -234,8 +234,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
234234 output_dir;
235235
236236 var dir = std.fs.cwd().makeOpenPath(sub_dir_path, .{}) catch |err| {
237 std.debug.print("unable to make path {s}: {s}\n", .{ output_dir, @errorName(err) });
238 return err;
237 return step.fail("unable to make path '{s}': {s}", .{ output_dir, @errorName(err) });
239238 };
240239 defer dir.close();
241240
......@@ -247,6 +246,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
247246}
248247
249248fn render_autoconf(
249 step: *Step,
250250 contents: []const u8,
251251 output: *std.ArrayList(u8),
252252 values: std.StringArrayHashMap(Value),
......@@ -273,7 +273,7 @@ fn render_autoconf(
273273 }
274274 const name = it.rest();
275275 const kv = values_copy.fetchSwapRemove(name) orelse {
276 std.debug.print("{s}:{d}: error: unspecified config header value: '{s}'\n", .{
276 try step.addError("{s}:{d}: error: unspecified config header value: '{s}'", .{
277277 src_path, line_index + 1, name,
278278 });
279279 any_errors = true;
......@@ -283,15 +283,17 @@ fn render_autoconf(
283283 }
284284
285285 for (values_copy.keys()) |name| {
286 std.debug.print("{s}: error: config header value unused: '{s}'\n", .{ src_path, name });
286 try step.addError("{s}: error: config header value unused: '{s}'", .{ src_path, name });
287 any_errors = true;
287288 }
288289
289290 if (any_errors) {
290 return error.HeaderConfigFailed;
291 return error.MakeFailed;
291292 }
292293}
293294
294295fn render_cmake(
296 step: *Step,
295297 contents: []const u8,
296298 output: *std.ArrayList(u8),
297299 values: std.StringArrayHashMap(Value),
......@@ -317,14 +319,14 @@ fn render_cmake(
317319 continue;
318320 }
319321 const name = it.next() orelse {
320 std.debug.print("{s}:{d}: error: missing define name\n", .{
322 try step.addError("{s}:{d}: error: missing define name", .{
321323 src_path, line_index + 1,
322324 });
323325 any_errors = true;
324326 continue;
325327 };
326328 const kv = values_copy.fetchSwapRemove(name) orelse {
327 std.debug.print("{s}:{d}: error: unspecified config header value: '{s}'\n", .{
329 try step.addError("{s}:{d}: error: unspecified config header value: '{s}'", .{
328330 src_path, line_index + 1, name,
329331 });
330332 any_errors = true;
......@@ -334,7 +336,8 @@ fn render_cmake(
334336 }
335337
336338 for (values_copy.keys()) |name| {
337 std.debug.print("{s}: error: config header value unused: '{s}'\n", .{ src_path, name });
339 try step.addError("{s}: error: config header value unused: '{s}'", .{ src_path, name });
340 any_errors = true;
338341 }
339342
340343 if (any_errors) {
lib/std/Build/InstallArtifactStep.zig+7-1
......@@ -12,6 +12,9 @@ artifact: *CompileStep,
1212dest_dir: InstallDir,
1313pdb_dir: ?InstallDir,
1414h_dir: ?InstallDir,
15/// If non-null, adds additional path components relative to dest_dir, and
16/// overrides the basename of the CompileStep.
17dest_sub_path: ?[]const u8,
1518
1619pub fn create(owner: *std.Build, artifact: *CompileStep) *InstallArtifactStep {
1720 if (artifact.install_step) |s| return s;
......@@ -40,6 +43,7 @@ pub fn create(owner: *std.Build, artifact: *CompileStep) *InstallArtifactStep {
4043 }
4144 } else null,
4245 .h_dir = if (artifact.kind == .lib and artifact.emit_h) .header else null,
46 .dest_sub_path = null,
4347 };
4448 self.step.dependOn(&artifact.step);
4549 artifact.install_step = self;
......@@ -71,7 +75,9 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
7175 const self = @fieldParentPtr(InstallArtifactStep, "step", step);
7276 const dest_builder = self.dest_builder;
7377
74 const full_dest_path = dest_builder.getInstallPath(self.dest_dir, self.artifact.out_filename);
78 const dest_sub_path = if (self.dest_sub_path) |sub_path| sub_path else self.artifact.out_filename;
79 const full_dest_path = dest_builder.getInstallPath(self.dest_dir, dest_sub_path);
80
7581 try src_builder.updateFile(
7682 self.artifact.getOutputSource().getPath(src_builder),
7783 full_dest_path,
lib/std/Build/ObjCopyStep.zig+1-2
......@@ -95,8 +95,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
9595 const full_dest_path = try b.cache_root.join(b.allocator, &.{ "o", &digest, self.basename });
9696 const cache_path = "o" ++ fs.path.sep_str ++ digest;
9797 b.cache_root.handle.makePath(cache_path) catch |err| {
98 std.debug.print("unable to make path {s}: {s}\n", .{ cache_path, @errorName(err) });
99 return err;
98 return step.fail("unable to make path {s}: {s}", .{ cache_path, @errorName(err) });
10099 };
101100
102101 var argv = std.ArrayList([]const u8).init(b.allocator);
lib/std/Build/RunStep.zig+267-105
......@@ -10,6 +10,7 @@ const ArrayList = std.ArrayList;
1010const EnvMap = process.EnvMap;
1111const Allocator = mem.Allocator;
1212const ExecError = std.Build.ExecError;
13const assert = std.debug.assert;
1314
1415const RunStep = @This();
1516
......@@ -54,6 +55,8 @@ rename_step_with_output_arg: bool = true,
5455/// Command-line arguments such as -fqemu and -fwasmtime may affect whether a
5556/// binary is detected as foreign, as well as system configuration such as
5657/// Rosetta (macOS) and binfmt_misc (Linux).
58/// If this RunStep is considered to have side-effects, then this flag does
59/// nothing.
5760skip_foreign_checks: bool = false,
5861
5962/// If stderr or stdout exceeds this amount, the child process is killed and
......@@ -79,7 +82,7 @@ pub const StdIo = union(enum) {
7982 /// conditions.
8083 /// Note that an explicit check for exit code 0 needs to be added to this
8184 /// list if such a check is desireable.
82 check: []const Check,
85 check: std.ArrayList(Check),
8386
8487 pub const Check = union(enum) {
8588 expect_stderr_exact: []const u8,
......@@ -214,14 +217,20 @@ pub fn setEnvironmentVariable(self: *RunStep, key: []const u8, value: []const u8
214217 env_map.put(b.dupe(key), b.dupe(value)) catch @panic("unhandled error");
215218}
216219
220/// Adds a check for exact stderr match. Does not add any other checks.
217221pub fn expectStdErrEqual(self: *RunStep, bytes: []const u8) void {
218222 const new_check: StdIo.Check = .{ .expect_stderr_exact = self.step.owner.dupe(bytes) };
219223 self.addCheck(new_check);
220224}
221225
226/// Adds a check for exact stdout match as well as a check for exit code 0, if
227/// there is not already an expected termination check.
222228pub fn expectStdOutEqual(self: *RunStep, bytes: []const u8) void {
223229 const new_check: StdIo.Check = .{ .expect_stdout_exact = self.step.owner.dupe(bytes) };
224230 self.addCheck(new_check);
231 if (!self.hasTermCheck()) {
232 self.expectExitCode(0);
233 }
225234}
226235
227236pub fn expectExitCode(self: *RunStep, code: u8) void {
......@@ -229,19 +238,21 @@ pub fn expectExitCode(self: *RunStep, code: u8) void {
229238 self.addCheck(new_check);
230239}
231240
241pub fn hasTermCheck(self: RunStep) bool {
242 for (self.stdio.check.items) |check| switch (check) {
243 .expect_term => return true,
244 else => continue,
245 };
246 return false;
247}
248
232249pub fn addCheck(self: *RunStep, new_check: StdIo.Check) void {
233 const arena = self.step.owner.allocator;
234250 switch (self.stdio) {
235251 .infer_from_args => {
236 const list = arena.create([1]StdIo.Check) catch @panic("OOM");
237 list.* = .{new_check};
238 self.stdio = .{ .check = list };
239 },
240 .check => |checks| {
241 const new_list = arena.alloc(StdIo.Check, checks.len + 1) catch @panic("OOM");
242 std.mem.copy(StdIo.Check, new_list, checks);
243 new_list[checks.len] = new_check;
252 self.stdio = .{ .check = std.ArrayList(StdIo.Check).init(self.step.owner.allocator) };
253 self.stdio.check.append(new_check) catch @panic("OOM");
244254 },
255 .check => |*checks| checks.append(new_check) catch @panic("OOM"),
245256 else => @panic("illegal call to addCheck: conflicting helper method calls. Suggest to directly set stdio field of RunStep instead"),
246257 }
247258}
......@@ -298,14 +309,15 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
298309 _ = prog_node;
299310
300311 const b = step.owner;
312 const arena = b.allocator;
301313 const self = @fieldParentPtr(RunStep, "step", step);
302314 const has_side_effects = self.hasSideEffects();
303315
304 var argv_list = ArrayList([]const u8).init(b.allocator);
316 var argv_list = ArrayList([]const u8).init(arena);
305317 var output_placeholders = ArrayList(struct {
306318 index: usize,
307319 output: Arg.Output,
308 }).init(b.allocator);
320 }).init(arena);
309321
310322 var man = b.cache.obtain();
311323 defer man.deinit();
......@@ -357,7 +369,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
357369 const digest = man.final();
358370 for (output_placeholders.items) |placeholder| {
359371 placeholder.output.generated_file.path = try b.cache_root.join(
360 b.allocator,
372 arena,
361373 &.{ "o", &digest, placeholder.output.basename },
362374 );
363375 }
......@@ -367,30 +379,21 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
367379 const digest = man.final();
368380
369381 for (output_placeholders.items) |placeholder| {
370 const output_path = try b.cache_root.join(
371 b.allocator,
372 &.{ "o", &digest, placeholder.output.basename },
373 );
374 const output_dir = fs.path.dirname(output_path).?;
375 fs.cwd().makePath(output_dir) catch |err| {
376 std.debug.print("unable to make path {s}: {s}\n", .{ output_dir, @errorName(err) });
377 return err;
382 const output_components = .{ "o", &digest, placeholder.output.basename };
383 const output_sub_path = try fs.path.join(arena, &output_components);
384 const output_sub_dir_path = fs.path.dirname(output_sub_path).?;
385 b.cache_root.handle.makePath(output_sub_dir_path) catch |err| {
386 return step.fail("unable to make path '{}{s}': {s}", .{
387 b.cache_root, output_sub_dir_path, @errorName(err),
388 });
378389 };
379
390 const output_path = try b.cache_root.join(arena, &output_components);
380391 placeholder.output.generated_file.path = output_path;
381392 argv_list.items[placeholder.index] = output_path;
382393 }
383394 }
384395
385 try runCommand(
386 step,
387 self.cwd,
388 argv_list.items,
389 self.env_map,
390 self.stdio,
391 has_side_effects,
392 self.max_stdio_size,
393 );
396 try runCommand(self, argv_list.items, has_side_effects);
394397
395398 if (!has_side_effects) {
396399 try man.writeManifest();
......@@ -442,92 +445,150 @@ fn termMatches(expected: ?std.ChildProcess.Term, actual: std.ChildProcess.Term)
442445 };
443446}
444447
445fn runCommand(
446 step: *Step,
447 opt_cwd: ?[]const u8,
448 argv: []const []const u8,
449 env_map: ?*EnvMap,
450 stdio: StdIo,
451 has_side_effects: bool,
452 max_stdio_size: usize,
453) !void {
448fn runCommand(self: *RunStep, argv: []const []const u8, has_side_effects: bool) !void {
449 const step = &self.step;
454450 const b = step.owner;
455451 const arena = b.allocator;
456 const cwd = if (opt_cwd) |cwd| b.pathFromRoot(cwd) else b.build_root.path;
457452
458 try step.handleChildProcUnsupported(opt_cwd, argv);
459 try Step.handleVerbose(step.owner, opt_cwd, argv);
460
461 var child = std.ChildProcess.init(argv, arena);
462 child.cwd = cwd;
463 child.env_map = env_map orelse b.env_map;
464
465 child.stdin_behavior = switch (stdio) {
466 .infer_from_args => if (has_side_effects) .Inherit else .Ignore,
467 .inherit => .Inherit,
468 .check => .Close,
469 };
470 child.stdout_behavior = switch (stdio) {
471 .infer_from_args => if (has_side_effects) .Inherit else .Ignore,
472 .inherit => .Inherit,
473 .check => |checks| if (checksContainStdout(checks)) .Pipe else .Ignore,
474 };
475 child.stderr_behavior = switch (stdio) {
476 .infer_from_args => if (has_side_effects) .Inherit else .Pipe,
477 .inherit => .Inherit,
478 .check => .Pipe,
479 };
480
481 child.spawn() catch |err| return step.fail("unable to spawn {s}: {s}", .{
482 argv[0], @errorName(err),
483 });
453 try step.handleChildProcUnsupported(self.cwd, argv);
454 try Step.handleVerbose(step.owner, self.cwd, argv);
484455
485456 var stdout_bytes: ?[]const u8 = null;
486457 var stderr_bytes: ?[]const u8 = null;
487458
488 if (child.stdout) |stdout| {
489 if (child.stderr) |stderr| {
490 var poller = std.io.poll(arena, enum { stdout, stderr }, .{
491 .stdout = stdout,
492 .stderr = stderr,
493 });
494 defer poller.deinit();
459 const term = spawnChildAndCollect(self, argv, &stdout_bytes, &stderr_bytes, has_side_effects) catch |err| term: {
460 if (err == error.InvalidExe) interpret: {
461 // TODO: learn the target from the binary directly rather than from
462 // relying on it being a CompileStep. This will make this logic
463 // work even for the edge case that the binary was produced by a
464 // third party.
465 const exe = switch (self.argv.items[0]) {
466 .artifact => |exe| exe,
467 else => break :interpret,
468 };
469 if (exe.kind != .exe) break :interpret;
470
471 var interp_argv = std.ArrayList([]const u8).init(b.allocator);
472 defer interp_argv.deinit();
473
474 const need_cross_glibc = exe.target.isGnuLibC() and exe.is_linking_libc;
475 switch (b.host.getExternalExecutor(exe.target_info, .{
476 .qemu_fixes_dl = need_cross_glibc and b.glibc_runtimes_dir != null,
477 .link_libc = exe.is_linking_libc,
478 })) {
479 .native, .rosetta => {
480 if (self.stdio == .check and self.skip_foreign_checks)
481 return error.MakeSkipped;
482
483 break :interpret;
484 },
485 .wine => |bin_name| {
486 if (b.enable_wine) {
487 try interp_argv.append(bin_name);
488 } else {
489 return failForeign(self, "-fwine", argv[0], exe);
490 }
491 },
492 .qemu => |bin_name| {
493 if (b.enable_qemu) {
494 const glibc_dir_arg = if (need_cross_glibc)
495 b.glibc_runtimes_dir orelse return
496 else
497 null;
498
499 try interp_argv.append(bin_name);
500
501 if (glibc_dir_arg) |dir| {
502 // TODO look into making this a call to `linuxTriple`. This
503 // needs the directory to be called "i686" rather than
504 // "x86" which is why we do it manually here.
505 const fmt_str = "{s}" ++ fs.path.sep_str ++ "{s}-{s}-{s}";
506 const cpu_arch = exe.target.getCpuArch();
507 const os_tag = exe.target.getOsTag();
508 const abi = exe.target.getAbi();
509 const cpu_arch_name: []const u8 = if (cpu_arch == .x86)
510 "i686"
511 else
512 @tagName(cpu_arch);
513 const full_dir = try std.fmt.allocPrint(b.allocator, fmt_str, .{
514 dir, cpu_arch_name, @tagName(os_tag), @tagName(abi),
515 });
516
517 try interp_argv.append("-L");
518 try interp_argv.append(full_dir);
519 }
520 } else {
521 return failForeign(self, "-fqemu", argv[0], exe);
522 }
523 },
524 .darling => |bin_name| {
525 if (b.enable_darling) {
526 try interp_argv.append(bin_name);
527 } else {
528 return failForeign(self, "-fdarling", argv[0], exe);
529 }
530 },
531 .wasmtime => |bin_name| {
532 if (b.enable_wasmtime) {
533 try interp_argv.append(bin_name);
534 try interp_argv.append("--dir=.");
535 } else {
536 return failForeign(self, "-fwasmtime", argv[0], exe);
537 }
538 },
539 .bad_dl => |foreign_dl| {
540 if (self.stdio == .check and self.skip_foreign_checks)
541 return error.MakeSkipped;
542
543 const host_dl = b.host.dynamic_linker.get() orelse "(none)";
495544
496 while (try poller.poll()) {
497 if (poller.fifo(.stdout).count > max_stdio_size)
498 return error.StdoutStreamTooLong;
499 if (poller.fifo(.stderr).count > max_stdio_size)
500 return error.StderrStreamTooLong;
545 return step.fail(
546 \\the host system is unable to execute binaries from the target
547 \\ because the host dynamic linker is '{s}',
548 \\ while the target dynamic linker is '{s}'.
549 \\ consider setting the dynamic linker or enabling skip_foreign_checks in the Run step
550 , .{ host_dl, foreign_dl });
551 },
552 .bad_os_or_cpu => {
553 if (self.stdio == .check and self.skip_foreign_checks)
554 return error.MakeSkipped;
555
556 const host_name = try b.host.target.zigTriple(b.allocator);
557 const foreign_name = try exe.target.zigTriple(b.allocator);
558
559 return step.fail("the host system ({s}) is unable to execute binaries from the target ({s})", .{
560 host_name, foreign_name,
561 });
562 },
501563 }
502564
503 stdout_bytes = try poller.fifo(.stdout).toOwnedSlice();
504 stderr_bytes = try poller.fifo(.stderr).toOwnedSlice();
505 } else {
506 stdout_bytes = try stdout.reader().readAllAlloc(arena, max_stdio_size);
507 }
508 } else if (child.stderr) |stderr| {
509 stderr_bytes = try stderr.reader().readAllAlloc(arena, max_stdio_size);
510 }
565 if (exe.target.isWindows()) {
566 // On Windows we don't have rpaths so we have to add .dll search paths to PATH
567 RunStep.addPathForDynLibsInternal(&self.step, b, exe);
568 }
511569
512 if (stderr_bytes) |stderr| if (stderr.len > 0) {
513 const stderr_is_diagnostic = switch (stdio) {
514 .check => |checks| !checksContainStderr(checks),
515 else => true,
516 };
517 if (stderr_is_diagnostic) {
518 try step.result_error_msgs.append(arena, stderr);
570 try interp_argv.append(argv[0]);
571
572 try Step.handleVerbose(step.owner, self.cwd, interp_argv.items);
573
574 assert(stdout_bytes == null);
575 assert(stderr_bytes == null);
576 break :term spawnChildAndCollect(self, interp_argv.items, &stdout_bytes, &stderr_bytes, has_side_effects) catch |inner_err| {
577 return step.fail("unable to spawn {s}: {s}", .{
578 interp_argv.items[0], @errorName(inner_err),
579 });
580 };
519581 }
520 };
521582
522 const term = child.wait() catch |err| {
523 return step.fail("unable to wait for {s}: {s}", .{ argv[0], @errorName(err) });
583 return step.fail("unable to spawn {s}: {s}", .{ argv[0], @errorName(err) });
524584 };
525585
526 switch (stdio) {
527 .check => |checks| for (checks) |check| switch (check) {
586 switch (self.stdio) {
587 .check => |checks| for (checks.items) |check| switch (check) {
528588 .expect_stderr_exact => |expected_bytes| {
529589 if (!mem.eql(u8, expected_bytes, stderr_bytes.?)) {
530590 return step.fail(
591 \\
531592 \\========= expected this stderr: =========
532593 \\{s}
533594 \\========= but found: ====================
......@@ -537,13 +598,14 @@ fn runCommand(
537598 , .{
538599 expected_bytes,
539600 stderr_bytes.?,
540 try Step.allocPrintCmd(arena, opt_cwd, argv),
601 try Step.allocPrintCmd(arena, self.cwd, argv),
541602 });
542603 }
543604 },
544605 .expect_stderr_match => |match| {
545606 if (mem.indexOf(u8, stderr_bytes.?, match) == null) {
546607 return step.fail(
608 \\
547609 \\========= expected to find in stderr: =========
548610 \\{s}
549611 \\========= but stderr does not contain it: =====
......@@ -553,13 +615,14 @@ fn runCommand(
553615 , .{
554616 match,
555617 stderr_bytes.?,
556 try Step.allocPrintCmd(arena, opt_cwd, argv),
618 try Step.allocPrintCmd(arena, self.cwd, argv),
557619 });
558620 }
559621 },
560622 .expect_stdout_exact => |expected_bytes| {
561623 if (!mem.eql(u8, expected_bytes, stdout_bytes.?)) {
562624 return step.fail(
625 \\
563626 \\========= expected this stdout: =========
564627 \\{s}
565628 \\========= but found: ====================
......@@ -569,13 +632,14 @@ fn runCommand(
569632 , .{
570633 expected_bytes,
571634 stdout_bytes.?,
572 try Step.allocPrintCmd(arena, opt_cwd, argv),
635 try Step.allocPrintCmd(arena, self.cwd, argv),
573636 });
574637 }
575638 },
576639 .expect_stdout_match => |match| {
577640 if (mem.indexOf(u8, stdout_bytes.?, match) == null) {
578641 return step.fail(
642 \\
579643 \\========= expected to find in stdout: =========
580644 \\{s}
581645 \\========= but stdout does not contain it: =====
......@@ -585,7 +649,7 @@ fn runCommand(
585649 , .{
586650 match,
587651 stdout_bytes.?,
588 try Step.allocPrintCmd(arena, opt_cwd, argv),
652 try Step.allocPrintCmd(arena, self.cwd, argv),
589653 });
590654 }
591655 },
......@@ -594,17 +658,89 @@ fn runCommand(
594658 return step.fail("the following command {} (expected {}):\n{s}", .{
595659 fmtTerm(term),
596660 fmtTerm(expected_term),
597 try Step.allocPrintCmd(arena, opt_cwd, argv),
661 try Step.allocPrintCmd(arena, self.cwd, argv),
598662 });
599663 }
600664 },
601665 },
602666 else => {
603 try step.handleChildProcessTerm(term, opt_cwd, argv);
667 try step.handleChildProcessTerm(term, self.cwd, argv);
604668 },
605669 }
606670}
607671
672fn spawnChildAndCollect(
673 self: *RunStep,
674 argv: []const []const u8,
675 stdout_bytes: *?[]const u8,
676 stderr_bytes: *?[]const u8,
677 has_side_effects: bool,
678) !std.ChildProcess.Term {
679 const b = self.step.owner;
680 const arena = b.allocator;
681 const cwd = if (self.cwd) |cwd| b.pathFromRoot(cwd) else b.build_root.path;
682
683 var child = std.ChildProcess.init(argv, arena);
684 child.cwd = cwd;
685 child.env_map = self.env_map orelse b.env_map;
686
687 child.stdin_behavior = switch (self.stdio) {
688 .infer_from_args => if (has_side_effects) .Inherit else .Ignore,
689 .inherit => .Inherit,
690 .check => .Close,
691 };
692 child.stdout_behavior = switch (self.stdio) {
693 .infer_from_args => if (has_side_effects) .Inherit else .Ignore,
694 .inherit => .Inherit,
695 .check => |checks| if (checksContainStdout(checks.items)) .Pipe else .Ignore,
696 };
697 child.stderr_behavior = switch (self.stdio) {
698 .infer_from_args => if (has_side_effects) .Inherit else .Pipe,
699 .inherit => .Inherit,
700 .check => .Pipe,
701 };
702
703 child.spawn() catch |err| return self.step.fail("unable to spawn {s}: {s}", .{
704 argv[0], @errorName(err),
705 });
706
707 if (child.stdout) |stdout| {
708 if (child.stderr) |stderr| {
709 var poller = std.io.poll(arena, enum { stdout, stderr }, .{
710 .stdout = stdout,
711 .stderr = stderr,
712 });
713 defer poller.deinit();
714
715 while (try poller.poll()) {
716 if (poller.fifo(.stdout).count > self.max_stdio_size)
717 return error.StdoutStreamTooLong;
718 if (poller.fifo(.stderr).count > self.max_stdio_size)
719 return error.StderrStreamTooLong;
720 }
721
722 stdout_bytes.* = try poller.fifo(.stdout).toOwnedSlice();
723 stderr_bytes.* = try poller.fifo(.stderr).toOwnedSlice();
724 } else {
725 stdout_bytes.* = try stdout.reader().readAllAlloc(arena, self.max_stdio_size);
726 }
727 } else if (child.stderr) |stderr| {
728 stderr_bytes.* = try stderr.reader().readAllAlloc(arena, self.max_stdio_size);
729 }
730
731 if (stderr_bytes.*) |stderr| if (stderr.len > 0) {
732 const stderr_is_diagnostic = switch (self.stdio) {
733 .check => |checks| !checksContainStderr(checks.items),
734 else => true,
735 };
736 if (stderr_is_diagnostic) {
737 try self.step.result_error_msgs.append(arena, stderr);
738 }
739 };
740
741 return child.wait();
742}
743
608744fn addPathForDynLibs(self: *RunStep, artifact: *CompileStep) void {
609745 addPathForDynLibsInternal(&self.step, self.step.owner, artifact);
610746}
......@@ -624,3 +760,29 @@ pub fn addPathForDynLibsInternal(step: *Step, builder: *std.Build, artifact: *Co
624760 }
625761 }
626762}
763
764fn failForeign(
765 self: *RunStep,
766 suggested_flag: []const u8,
767 argv0: []const u8,
768 exe: *CompileStep,
769) error{ MakeFailed, MakeSkipped, OutOfMemory } {
770 switch (self.stdio) {
771 .check => {
772 if (self.skip_foreign_checks)
773 return error.MakeSkipped;
774
775 const b = self.step.owner;
776 const host_name = try b.host.target.zigTriple(b.allocator);
777 const foreign_name = try exe.target.zigTriple(b.allocator);
778
779 return self.step.fail(
780 \\unable to spawn foreign binary '{s}' ({s}) on host system ({s})
781 \\ consider using {s} or enabling skip_foreign_checks in the Run step
782 , .{ argv0, foreign_name, host_name, suggested_flag });
783 },
784 else => {
785 return self.step.fail("unable to spawn foreign binary '{s}'", .{argv0});
786 },
787 }
788}
lib/std/Build/Step.zig+16-7
......@@ -26,6 +26,9 @@ pub const State = enum {
2626 dependency_failure,
2727 success,
2828 failure,
29 /// This state indicates that the step did not complete, however, it also did not fail,
30 /// and it is safe to continue executing its dependencies.
31 skipped,
2932};
3033
3134pub const Id = enum {
......@@ -106,13 +109,15 @@ pub fn init(options: Options) Step {
106109/// If the Step's `make` function reports `error.MakeFailed`, it indicates they
107110/// have already reported the error. Otherwise, we add a simple error report
108111/// here.
109pub fn make(s: *Step, prog_node: *std.Progress.Node) error{MakeFailed}!void {
110 return s.makeFn(s, prog_node) catch |err| {
111 if (err != error.MakeFailed) {
112pub fn make(s: *Step, prog_node: *std.Progress.Node) error{ MakeFailed, MakeSkipped }!void {
113 return s.makeFn(s, prog_node) catch |err| switch (err) {
114 error.MakeFailed => return error.MakeFailed,
115 error.MakeSkipped => return error.MakeSkipped,
116 else => {
112117 const gpa = s.dependencies.allocator;
113118 s.result_error_msgs.append(gpa, @errorName(err)) catch @panic("OOM");
114 }
115 return error.MakeFailed;
119 return error.MakeFailed;
120 },
116121 };
117122}
118123
......@@ -192,10 +197,14 @@ pub fn evalChildProcess(s: *Step, argv: []const []const u8) !void {
192197}
193198
194199pub fn fail(step: *Step, comptime fmt: []const u8, args: anytype) error{ OutOfMemory, MakeFailed } {
200 try step.addError(fmt, args);
201 return error.MakeFailed;
202}
203
204pub fn addError(step: *Step, comptime fmt: []const u8, args: anytype) error{OutOfMemory}!void {
195205 const arena = step.owner.allocator;
196206 const msg = try std.fmt.allocPrint(arena, fmt, args);
197207 try step.result_error_msgs.append(arena, msg);
198 return error.MakeFailed;
199208}
200209
201210/// Assumes that argv contains `--listen=-` and that the process being spawned
......@@ -398,5 +407,5 @@ fn failWithCacheError(s: *Step, man: *const std.Build.Cache.Manifest, err: anyer
398407 const i = man.failed_file_index orelse return err;
399408 const pp = man.files.items[i].prefixed_path orelse return err;
400409 const prefix = man.cache.prefixes()[pp.prefix].path orelse "";
401 return s.fail("{s}: {s}/{s}\n", .{ @errorName(err), prefix, pp.sub_path });
410 return s.fail("{s}: {s}/{s}", .{ @errorName(err), prefix, pp.sub_path });
402411}
lib/std/Build/WriteFileStep.zig+86-28
......@@ -37,7 +37,7 @@ pub fn init(owner: *std.Build) WriteFileStep {
3737 return .{
3838 .step = Step.init(.{
3939 .id = .write_file,
40 .name = "writefile",
40 .name = "WriteFile",
4141 .owner = owner,
4242 .makeFn = make,
4343 }),
......@@ -56,6 +56,8 @@ pub fn add(wf: *WriteFileStep, sub_path: []const u8, bytes: []const u8) void {
5656 .contents = .{ .bytes = b.dupe(bytes) },
5757 };
5858 wf.files.append(gpa, file) catch @panic("OOM");
59
60 wf.maybeUpdateName();
5961}
6062
6163/// Place the file into the generated directory within the local cache,
......@@ -75,6 +77,8 @@ pub fn addCopyFile(wf: *WriteFileStep, source: std.Build.FileSource, sub_path: [
7577 .contents = .{ .copy = source },
7678 };
7779 wf.files.append(gpa, file) catch @panic("OOM");
80
81 wf.maybeUpdateName();
7882}
7983
8084/// A path relative to the package root.
......@@ -101,6 +105,15 @@ pub fn getFileSource(wf: *WriteFileStep, sub_path: []const u8) ?std.Build.FileSo
101105 return null;
102106}
103107
108fn maybeUpdateName(wf: *WriteFileStep) void {
109 if (wf.files.items.len == 1) {
110 // First time adding a file; update name.
111 if (std.mem.eql(u8, wf.step.name, "WriteFile")) {
112 wf.step.name = wf.step.owner.fmt("WriteFile {s}", .{wf.files.items[0].sub_path});
113 }
114 }
115}
116
104117fn make(step: *Step, prog_node: *std.Progress.Node) !void {
105118 _ = prog_node;
106119 const b = step.owner;
......@@ -110,14 +123,39 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
110123 // WriteFileStep - arguably it should be a different step. But anyway here
111124 // it is, it happens unconditionally and does not interact with the other
112125 // files here.
126 var any_miss = false;
113127 for (wf.output_source_files.items) |output_source_file| {
114 const basename = fs.path.basename(output_source_file.sub_path);
115128 if (fs.path.dirname(output_source_file.sub_path)) |dirname| {
116 var dir = try b.build_root.handle.makeOpenPath(dirname, .{});
117 defer dir.close();
118 try writeFile(wf, dir, output_source_file.contents, basename);
119 } else {
120 try writeFile(wf, b.build_root.handle, output_source_file.contents, basename);
129 b.build_root.handle.makePath(dirname) catch |err| {
130 return step.fail("unable to make path '{}{s}': {s}", .{
131 b.build_root, dirname, @errorName(err),
132 });
133 };
134 }
135 switch (output_source_file.contents) {
136 .bytes => |bytes| {
137 b.build_root.handle.writeFile(output_source_file.sub_path, bytes) catch |err| {
138 return step.fail("unable to write file '{}{s}': {s}", .{
139 b.build_root, output_source_file.sub_path, @errorName(err),
140 });
141 };
142 any_miss = true;
143 },
144 .copy => |file_source| {
145 const source_path = file_source.getPath(b);
146 const prev_status = fs.Dir.updateFile(
147 fs.cwd(),
148 source_path,
149 b.build_root.handle,
150 output_source_file.sub_path,
151 .{},
152 ) catch |err| {
153 return step.fail("unable to update file from '{s}' to '{}{s}': {s}", .{
154 source_path, b.build_root, output_source_file.sub_path, @errorName(err),
155 });
156 };
157 any_miss = any_miss or prev_status == .stale;
158 },
121159 }
122160 }
123161
......@@ -164,19 +202,52 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
164202 const cache_path = "o" ++ fs.path.sep_str ++ digest;
165203
166204 var cache_dir = b.cache_root.handle.makeOpenPath(cache_path, .{}) catch |err| {
167 std.debug.print("unable to make path {s}: {s}\n", .{ cache_path, @errorName(err) });
168 return err;
205 return step.fail("unable to make path '{}{s}': {s}", .{
206 b.cache_root, cache_path, @errorName(err),
207 });
169208 };
170209 defer cache_dir.close();
171210
172211 for (wf.files.items) |file| {
173 const basename = fs.path.basename(file.sub_path);
174212 if (fs.path.dirname(file.sub_path)) |dirname| {
175 var dir = try b.cache_root.handle.makeOpenPath(dirname, .{});
176 defer dir.close();
177 try writeFile(wf, dir, file.contents, basename);
178 } else {
179 try writeFile(wf, cache_dir, file.contents, basename);
213 cache_dir.makePath(dirname) catch |err| {
214 return step.fail("unable to make path '{}{s}{c}{s}': {s}", .{
215 b.cache_root, cache_path, fs.path.sep, dirname, @errorName(err),
216 });
217 };
218 }
219 switch (file.contents) {
220 .bytes => |bytes| {
221 cache_dir.writeFile(file.sub_path, bytes) catch |err| {
222 return step.fail("unable to write file '{}{s}{c}{s}': {s}", .{
223 b.cache_root, cache_path, fs.path.sep, file.sub_path, @errorName(err),
224 });
225 };
226 },
227 .copy => |file_source| {
228 const source_path = file_source.getPath(b);
229 const prev_status = fs.Dir.updateFile(
230 fs.cwd(),
231 source_path,
232 cache_dir,
233 file.sub_path,
234 .{},
235 ) catch |err| {
236 return step.fail("unable to update file from '{s}' to '{}{s}{c}{s}': {s}", .{
237 source_path,
238 b.cache_root,
239 cache_path,
240 fs.path.sep,
241 file.sub_path,
242 @errorName(err),
243 });
244 };
245 // At this point we already will mark the step as a cache miss.
246 // But this is kind of a partial cache hit since individual
247 // file copies may be avoided. Oh well, this information is
248 // discarded.
249 _ = prev_status;
250 },
180251 }
181252
182253 file.generated_file.path = try b.cache_root.join(
......@@ -188,19 +259,6 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
188259 try man.writeManifest();
189260}
190261
191fn writeFile(wf: *WriteFileStep, dir: fs.Dir, contents: Contents, basename: []const u8) !void {
192 const b = wf.step.owner;
193 // TODO after landing concurrency PR, improve error reporting here
194 switch (contents) {
195 .bytes => |bytes| return dir.writeFile(basename, bytes),
196 .copy => |file_source| {
197 const source_path = file_source.getPath(b);
198 const prev_status = try fs.Dir.updateFile(fs.cwd(), source_path, dir, basename, .{});
199 _ = prev_status; // TODO logging (affected by open PR regarding concurrency)
200 },
201 }
202}
203
204262const std = @import("../std.zig");
205263const Step = std.Build.Step;
206264const fs = std.fs;
lib/std/child_process.zig-1
......@@ -185,7 +185,6 @@ pub const ChildProcess = struct {
185185 }
186186
187187 /// Blocks until child process terminates and then cleans up all resources.
188 /// TODO: set the pid to undefined in this function.
189188 pub fn wait(self: *ChildProcess) !Term {
190189 const term = if (builtin.os.tag == .windows)
191190 try self.waitWindows()
test/link/macho/bugs/13457/build.zig+3-1
......@@ -13,6 +13,8 @@ pub fn build(b: *std.Build) void {
1313 .target = target,
1414 });
1515
16 const run = exe.runEmulatable();
16 const run = b.addRunArtifact(exe);
17 run.skip_foreign_checks = true;
18 run.expectStdOutEqual("");
1719 test_step.dependOn(&run.step);
1820}
test/link/macho/empty/build.zig+2-1
......@@ -16,7 +16,8 @@ pub fn build(b: *std.Build) void {
1616 exe.addCSourceFile("empty.c", &[0][]const u8{});
1717 exe.linkLibC();
1818
19 const run_cmd = std.Build.EmulatableRunStep.create(b, "run", exe);
19 const run_cmd = b.addRunArtifact(exe);
20 run_cmd.skip_foreign_checks = true;
2021 run_cmd.expectStdOutEqual("Hello!\n");
2122 test_step.dependOn(&run_cmd.step);
2223}
test/link/macho/needed_library/build.zig+1
......@@ -36,5 +36,6 @@ pub fn build(b: *std.Build) void {
3636 check.checkNext("name @rpath/liba.dylib");
3737
3838 const run_cmd = check.runAndCompare();
39 run_cmd.expectStdOutEqual("");
3940 test_step.dependOn(&run_cmd.step);
4041}
test/link/macho/objc/build.zig+3-1
......@@ -17,6 +17,8 @@ pub fn build(b: *std.Build) void {
1717 // populate paths to the sysroot here.
1818 exe.linkFramework("Foundation");
1919
20 const run_cmd = std.Build.EmulatableRunStep.create(b, "run", exe);
20 const run_cmd = b.addRunArtifact(exe);
21 run_cmd.skip_foreign_checks = true;
22 run_cmd.expectStdOutEqual("");
2123 test_step.dependOn(&run_cmd.step);
2224}
test/link/macho/search_strategy/build.zig+2-1
......@@ -27,7 +27,8 @@ pub fn build(b: *std.Build) void {
2727 const exe = createScenario(b, optimize, target);
2828 exe.search_strategy = .paths_first;
2929
30 const run = std.Build.EmulatableRunStep.create(b, "run", exe);
30 const run = b.addRunArtifact(exe);
31 run.skip_foreign_checks = true;
3132 run.cwd = b.pathFromRoot(".");
3233 run.expectStdOutEqual("Hello world");
3334 test_step.dependOn(&run.step);
test/link/macho/stack_size/build.zig+1
......@@ -21,5 +21,6 @@ pub fn build(b: *std.Build) void {
2121 check_exe.checkNext("stacksize 100000000");
2222
2323 const run = check_exe.runAndCompare();
24 run.expectStdOutEqual("");
2425 test_step.dependOn(&run.step);
2526}
test/link/macho/uuid/build.zig+16-60
......@@ -1,5 +1,4 @@
11const std = @import("std");
2const Builder = std.Build.Builder;
32const CompileStep = std.Build.CompileStep;
43const FileSource = std.Build.FileSource;
54const Step = std.Build.Step;
......@@ -38,13 +37,15 @@ fn testUuid(
3837 // stay the same across builds.
3938 {
4039 const dylib = simpleDylib(b, optimize, target);
41 const install_step = installWithRename(dylib, "test1.dylib");
40 const install_step = b.addInstallArtifact(dylib);
41 install_step.dest_sub_path = "test1.dylib";
4242 install_step.step.dependOn(&dylib.step);
4343 }
4444 {
4545 const dylib = simpleDylib(b, optimize, target);
4646 dylib.strip = true;
47 const install_step = installWithRename(dylib, "test2.dylib");
47 const install_step = b.addInstallArtifact(dylib);
48 install_step.dest_sub_path = "test2.dylib";
4849 install_step.step.dependOn(&dylib.step);
4950 }
5051
......@@ -68,70 +69,23 @@ fn simpleDylib(
6869 return dylib;
6970}
7071
71fn installWithRename(cs: *CompileStep, name: []const u8) *InstallWithRename {
72 const step = InstallWithRename.create(cs.builder, cs.getOutputSource(), name);
73 cs.builder.getInstallStep().dependOn(&step.step);
74 return step;
75}
76
77const InstallWithRename = struct {
78 pub const base_id = .custom;
79
80 step: Step,
81 builder: *Builder,
82 source: FileSource,
83 name: []const u8,
84
85 pub fn create(
86 builder: *Builder,
87 source: FileSource,
88 name: []const u8,
89 ) *InstallWithRename {
90 const self = builder.allocator.create(InstallWithRename) catch @panic("OOM");
91 self.* = InstallWithRename{
92 .builder = builder,
93 .step = Step.init(builder.allocator, .{
94 .id = .custom,
95 .name = builder.fmt("install and rename: {s} -> {s}", .{
96 source.getDisplayName(), name,
97 }),
98 .makeFn = make,
99 }),
100 .source = source,
101 .name = builder.dupe(name),
102 };
103 return self;
104 }
105
106 fn make(step: *Step) anyerror!void {
107 const self = @fieldParentPtr(InstallWithRename, "step", step);
108 const source_path = self.source.getPath(self.builder);
109 const target_path = self.builder.getInstallPath(.lib, self.name);
110 self.builder.updateFile(source_path, target_path) catch |err| {
111 std.log.err("Unable to rename: {s} -> {s}", .{ source_path, target_path });
112 return err;
113 };
114 }
115};
116
11772const CompareUuid = struct {
11873 pub const base_id = .custom;
11974
12075 step: Step,
121 builder: *Builder,
12276 lhs: []const u8,
12377 rhs: []const u8,
12478
125 pub fn create(builder: *Builder, lhs: []const u8, rhs: []const u8) *CompareUuid {
126 const self = builder.allocator.create(CompareUuid) catch @panic("OOM");
79 pub fn create(owner: *std.Build, lhs: []const u8, rhs: []const u8) *CompareUuid {
80 const self = owner.allocator.create(CompareUuid) catch @panic("OOM");
12781 self.* = CompareUuid{
128 .builder = builder,
129 .step = Step.init(builder.allocator, .{
130 .id = .custom,
131 .name = builder.fmt("compare uuid: {s} and {s}", .{
82 .step = Step.init(.{
83 .id = base_id,
84 .name = owner.fmt("compare uuid: {s} and {s}", .{
13285 lhs,
13386 rhs,
13487 }),
88 .owner = owner,
13589 .makeFn = make,
13690 }),
13791 .lhs = lhs,
......@@ -140,16 +94,18 @@ const CompareUuid = struct {
14094 return self;
14195 }
14296
143 fn make(step: *Step) anyerror!void {
97 fn make(step: *Step, prog_node: *std.Progress.Node) anyerror!void {
98 _ = prog_node;
99 const b = step.owner;
144100 const self = @fieldParentPtr(CompareUuid, "step", step);
145 const gpa = self.builder.allocator;
101 const gpa = b.allocator;
146102
147103 var lhs_uuid: [16]u8 = undefined;
148 const lhs_path = self.builder.getInstallPath(.lib, self.lhs);
104 const lhs_path = b.getInstallPath(.lib, self.lhs);
149105 try parseUuid(gpa, lhs_path, &lhs_uuid);
150106
151107 var rhs_uuid: [16]u8 = undefined;
152 const rhs_path = self.builder.getInstallPath(.lib, self.rhs);
108 const rhs_path = b.getInstallPath(.lib, self.rhs);
153109 try parseUuid(gpa, rhs_path, &rhs_uuid);
154110
155111 try std.testing.expectEqualStrings(&lhs_uuid, &rhs_uuid);
test/link/wasm/extern/build.zig+2-1
......@@ -11,7 +11,8 @@ pub fn build(b: *std.Build) void {
1111 exe.use_llvm = false;
1212 exe.use_lld = false;
1313
14 const run = exe.runEmulatable();
14 const run = b.addRunArtifact(exe);
15 run.skip_foreign_checks = true;
1516 run.expectStdOutEqual("Result: 30");
1617
1718 const test_step = b.step("test", "Run linker test");