### Install Protocol Interfaces Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_84.md Installs a set of protocol interfaces into the boot services environment. Requires a tuple of protocol GUIDs and interface pointers. ```zig pub fn installProtocolInterfaces( self: *BootServices, handle: ?Handle, interfaces: anytype, ) InstallProtocolInterfacesError!Handle { var hdl: ?Handle = handle; const args_tuple = protocolInterfaces(&hdl, interfaces); switch (@call( .auto, self._installMultipleProtocolInterfaces, args_tuple, )) { .success => return hdl.?, .already_started => return error.AlreadyStarted, .out_of_resources => return error.OutOfResources, .invalid_parameter => return error.InvalidParameter, else => |status| return uefi.unexpectedStatus(status), } } ``` -------------------------------- ### Get Install Build Step Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_139.md Retrieves the installation step from the build object. This step is typically associated with installing the project's artifacts. ```zig pub fn getInstallStep(b: *Build) *Step { return &b.install_tls.step; } ``` -------------------------------- ### installProtocolInterfaces Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_84.md Installs a set of protocol interfaces into the boot services environment. This function accepts a variable number of protocol GUIDs and interface pointers. ```APIDOC ## installProtocolInterfaces ### Description Installs a set of protocol interfaces into the boot services environment. This function accepts a variable number of protocol GUIDs and interface pointers. ### Method `installProtocolInterfaces(self: *BootServices, handle: ?Handle, interfaces: anytype) InstallProtocolInterfacesError!Handle` ### Parameters - `self` (*BootServices) - A pointer to the BootServices structure. - `handle` (?Handle) - An optional handle to associate the protocols with. - `interfaces` (anytype) - A tuple of protocol interfaces to install. Each element should be a pointer to a protocol structure that has a `guid` constant. ### Return Value - `InstallProtocolInterfacesError!Handle` - The handle to which the protocols were installed. Returns an error if the operation fails due to already started services, insufficient resources, or invalid parameters. ``` -------------------------------- ### Add Install File with Directory in Zig Build Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_139.md Creates an install file step, specifying the source, installation directory type, and relative destination path. Returns the created Step.InstallFile object. ```zig pub fn addInstallFileWithDir( b: *Build, source: LazyPath, install_dir: InstallDir, dest_rel_path: []const u8, ) *Step.InstallFile { return Step.InstallFile.create(b, source, install_dir, dest_rel_path); } ``` -------------------------------- ### addInstallFile Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_139.md Adds a file to be installed, relative to the installation prefix. This function returns the created `Step.InstallFile` object. ```APIDOC /// Adds a file to be installed relative to the prefix path. /// /// Parameters: /// - b: The build instance. /// - source: The source of the file (LazyPath). /// - dest_rel_path: The destination path relative to the install prefix. /// /// Returns: /// A pointer to the created `Step.InstallFile`. pub fn addInstallFile(b: *Build, source: LazyPath, dest_rel_path: []const u8) *Step.InstallFile ``` -------------------------------- ### Start WebServer Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_8.md Starts the WebServer by listening on the specified address and spawning a task to handle incoming connections. It logs the listening address and any potential errors during startup. ```zig pub fn start(ws: *WebServer) error{AlreadyReported}!void { assert(ws.tcp_server == null); assert(ws.serve_task == null); const io = ws.graph.io; ws.tcp_server = ws.listen_address.listen(io, .{ .reuse_address = true }) catch |err| { log.err("failed to listen to port {d}: {t}", .{ ws.listen_address.getPort(), err }); return error.AlreadyReported; }; ws.serve_task = io.concurrent(serve, .{ws}) catch |err| { log.err("unable to spawn web server thread: {t}", .{err}); ws.tcp_server.?.deinit(io); ws.tcp_server = null; return error.AlreadyReported; }; log.info("web interface listening at http://{f}/", .{ws.tcp_server.?.socket.address}); if (ws.listen_address.getPort() == 0) { log.info("hint: pass '--webui={f}' to use the same port next time", .{ws.tcp_server.?.socket.address}); } } ``` -------------------------------- ### Initialize LibCDirs with Installation Details Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_126.md Initializes the LibCDirs structure using details from a found LibCInstallation. Populates include and framework directory lists, handling potential redundancy. ```zig var list = try std.array_list.Managed([]const u8).initCapacity(arena, 5); var framework_list = std.array_list.Managed([]const u8).init(arena); list.appendAssumeCapacity(lci.include_dir.?); const is_redundant = std.mem.eql(u8, lci.sys_include_dir.?, lci.include_dir.?); if (!is_redundant) list.appendAssumeCapacity(lci.sys_include_dir.?); if (target.os.tag == .windows) { if (std.fs.path.dirname(lci.sys_include_dir.?) |sys_include_dir_parent|) { // This include path will only exist when the optional "Desktop development with C++" // is installed. It contains headers, .rc files, and resources. It is especially // necessary when working with Windows resources. const atlmfc_dir = try std.fs.path.join(arena, &[_][]const u8{ sys_include_dir_parent, "atlmfc", "include" }); list.appendAssumeCapacity(atlmfc_dir); } } ``` -------------------------------- ### POSIX Main Entry Point (posixCallMainAndExit) Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_159.md Handles the POSIX startup process, including argument and environment parsing, ELF auxiliary vector processing, PIE relocation, TLS initialization, stack expansion, and calling `__init_array` functions before exiting. ```zig fn posixCallMainAndExit(argc_argv_ptr: [*]usize) callconv(.c) noreturn { // We're not ready to panic until thread local storage is initialized. @setRuntimeSafety(false); // Code coverage instrumentation might try to use thread local variables. @disableInstrumentation(); const argc = argc_argv_ptr[0]; const argv: [*][*:0]u8 = @ptrCast(argc_argv_ptr + 1); const envp_optional: [*:null]?[*:0]u8 = @ptrCast(@alignCast(argv + argc + 1)); var envp_count: usize = 0; while (envp_optional[envp_count]) |_| : (envp_count += 1) {} const envp = envp_optional[0..envp_count :null]; // Find the beginning of the auxiliary vector const auxv: [*]elf.Auxv = @ptrCast(@alignCast(envp.ptr + envp_count + 1)); var at_hwcap: usize = 0; const phdrs = init: { var i: usize = 0; var at_phdr: usize = 0; var at_phnum: usize = 0; while (auxv[i].a_type != elf.AT_NULL) : (i += 1) { switch (auxv[i].a_type) { elf.AT_PHNUM => at_phnum = auxv[i].a_un.a_val, elf.AT_PHDR => at_phdr = auxv[i].a_un.a_val, elf.AT_HWCAP => at_hwcap = auxv[i].a_un.a_val, else => continue, } } break :init @as([*]elf.Phdr, @ptrFromInt(at_phdr))[0..at_phnum]; }; // Apply the initial relocations as early as possible in the startup process. We cannot // make calls yet on some architectures (e.g. MIPS) *because* they haven't been applied yet, // so this must be fully inlined. if (builtin.link_mode == .static and builtin.position_independent_executable) { @call(.always_inline, std.pie.relocate, .{phdrs}); } if (native_os == .linux) { // This must be done after PIE relocations have been applied or we may crash // while trying to access the global variable (happens on MIPS at least). std.os.linux.elf_aux_maybe = auxv; if (!builtin.single_threaded) { // ARMv6 targets (and earlier) have no support for TLS in hardware. // FIXME: Elide the check for targets >= ARMv7 when the target feature API // becomes less verbose (and more usable). if (comptime native_arch.isArm()) { if (at_hwcap & std.os.linux.HWCAP.TLS == 0) { // FIXME: Make __aeabi_read_tp call the kernel helper kuser_get_tls // For the time being use a simple trap instead of a @panic call to // keep the binary bloat under control. @trap(); } } // Initialize the TLS area. std.os.linux.tls.initStatic(phdrs); } // The way Linux executables represent stack size is via the PT_GNU_STACK // program header. However the kernel does not recognize it; it always gives 8 MiB. // Here we look for the stack size in our program headers and use setrlimit // to ask for more stack space. expandStackSize(phdrs); } const opt_init_array_start = @extern([*]const *const fn () callconv(.c) void, .{ .name = "__init_array_start", .linkage = .weak, }); const opt_init_array_end = @extern([*]const *const fn () callconv(.c) void, .{ .name = "__init_array_end", .linkage = .weak, }); if (opt_init_array_start) |init_array_start| { const init_array_end = opt_init_array_end.?; const slice = init_array_start[0 .. init_array_end - init_array_start]; for (slice) |func| func(); } std.process.exit(callMainWithArgs(argc, argv, envp)); } ``` -------------------------------- ### Get Token Start Byte Offset from AST Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_117.md Retrieves the starting byte offset of a token at a given index from the AST's token list. ```zig pub fn tokenStart(tree: *const Ast, token_index: TokenIndex) ByteOffset { return tree.tokens.items(.start)[token_index]; } ``` -------------------------------- ### Install Configuration Table in Zig Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_84.md Installs a configuration table with a specified GUID and data. Handles potential errors like invalid parameters or insufficient resources. ```zig pub fn installConfigurationTable( self: *BootServices, guid: *const Guid, table: *anyopaque, ) InstallConfigurationTableError!void { switch (self._installConfigurationTable( guid, table, )) { .success => {}, .invalid_parameter => return error.InvalidParameter, .out_of_resources => return error.OutOfResources, else => |status| return uefi.unexpectedStatus(status), } } ``` -------------------------------- ### Zig Build System Configuration with std.Build Source: https://context7.com/larkliy/zig-mcp/llms.txt Illustrates a basic `build.zig` file, showing how to define an executable, link system libraries, and set up 'run' and 'test' build steps. ```zig // build.zig const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); // Compile an executable const exe = b.addExecutable(.{ .name = "my-app", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); // Link a system library exe.linkSystemLibrary("c"); b.installArtifact(exe); // Add a run step: `zig build run` const run_cmd = b.addRunArtifact(exe); run_cmd.step.dependOn(b.getInstallStep()); const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); // Add a test step: `zig build test` const unit_tests = b.addTest(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&b.addRunArtifact(unit_tests).step); } ``` -------------------------------- ### ProtocolsPerHandle Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_84.md Retrieves a list of GUIDs for all protocols associated with a given handle. This function returns an array of `Guid` pointers, indicating all the protocols that have been installed or are managed by the specified handle. Returns an error if the operation fails. ```APIDOC ## ProtocolsPerHandle ### Description Retrieves a list of GUIDs for all protocols associated with a given handle. This function returns an array of `Guid` pointers, indicating all the protocols that have been installed or are managed by the specified handle. Returns an error if the operation fails. ### Parameters - **handle** (Handle) - The handle for which to retrieve the list of protocol GUIDs. ### Returns - `ProtocolsPerHandleError![]*const Guid` - An array of pointers to `Guid` structures representing the protocols on the handle, or `ProtocolsPerHandleError` on failure. ``` -------------------------------- ### Create InstallDir Step Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_4.md Initializes and returns a new InstallDir step. It allocates memory for the step, sets its ID, name, owner, and the `makeFn`. The options are duplicated to ensure they are owned by the build system. ```zig pub fn create(owner: *std.Build, options: Options) *InstallDir { const install_dir = owner.allocator.create(InstallDir) catch @panic("OOM"); install_dir.* = .{ .step = Step.init(.{ .id = base_id, .name = owner.fmt("install {s}/", .{"s"}), .owner = owner, .makeFn = make, }), .options = options.dupe(owner), }; options.source_dir.addStepDependencies(&install_dir.step); return install_dir; } ``` -------------------------------- ### Generic POSIX-like _start Function Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_159.md This is a low-level entry point for POSIX-like systems. It includes architecture-specific setup for stack pointers and unwind table information. ```zig fn _start() callconv(.naked) noreturn { // TODO set Top of Stack on non x86_64-plan9 if (native_os == .plan9 and native_arch == .x86_64) { // from /sys/src/libc/amd64/main9.s std.os.plan9.tos = asm volatile ("" \ : [tos] "={rax}" (-> *std.os.plan9.Tos) ); } // This is the first userspace frame. Prevent DWARF-based unwinders from unwinding further. We // prevent FP-based unwinders from unwinding further by zeroing the register below. if (builtin.unwind_tables != .none or !builtin.strip_debug_info) asm volatile (switch (native_arch) { .aarch64, .aarch64_be => ".cfi_undefined lr", .alpha => ".cfi_undefined $26", .arc, .arceb => ".cfi_undefined blink", .arm, .armeb, .thumb, .thumbeb => "", // https://github.com/llvm/llvm-project/issues/115891 .csky => ".cfi_undefined lr", .hexagon => ".cfi_undefined r31", .kvx => ".cfi_undefined r14", .loongarch32, .loongarch64 => ".cfi_undefined 1", .m68k => ".cfi_undefined %%pc", .microblaze, .microblazeel => ".cfi_undefined r15", .mips, .mipsel, .mips64, .mips64el => ".cfi_undefined $ra", .or1k => ".cfi_undefined r9", .powerpc, .powerpcle, .powerpc64, .powerpc64le => ".cfi_undefined lr", .riscv32, .riscv32be, .riscv64, .riscv64be => if (builtin.zig_backend == .stage2_riscv64) "" else ".cfi_undefined ra", .s390x => ".cfi_undefined %%r14", .sh, .sheb => ".cfi_undefined pr", .sparc, .sparc64 => ".cfi_undefined %%i7", .x86 => ".cfi_undefined %%eip", .x86_64 => ".cfi_undefined %%rip", else => @compileError("unsupported arch"), }); // Move this to the riscv prong below when this is resolved: https://github.com/ziglang/zig/issues/20918 if (builtin.cpu.arch.isRISCV() and builtin.zig_backend != .stage2_riscv64) asm volatile ( \ .weak __global_pointer$ \ .hidden __global_pointer$ \ .option push \ .option norelax \ lla gp, __global_pointer$ \ .option pop ); // Note that we maintain a very low level of trust with regards to ABI guarantees at this point. ``` -------------------------------- ### Get Start Index and Layer for Sift Up Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_157.md Calculates the starting index and layer type (min or max) for the sift-up operation. It checks if the child element needs to be swapped with its parent based on layer priority. ```zig fn getStartForSiftUp(self: *const Self, child: T, index: usize) StartIndexAndLayer { const child_index = index; const parent_index = parentIndex(child_index); const parent = self.items[parent_index]; const min_layer = self.nextIsMinLayer(); const order = compareFn(self.context, child, parent); if ((min_layer and order == .gt) or (!min_layer and order == .lt)) { // We must swap the item with it's parent if it is on the "wrong" layer self.items[parent_index] = child; self.items[child_index] = parent; return .{ .index = parent_index, .min_layer = !min_layer, }; } else { return .{ .index = child_index, .min_layer = min_layer, }; } } ``` -------------------------------- ### Get Null-Terminated String Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_126.md Retrieves a null-terminated string from the ErrorBundle's string bytes given a starting index. ```zig pub fn nullTerminatedString(eb: ErrorBundle, index: String) [:0]const u8 { const string_bytes = eb.string_bytes; var end: usize = index; while (string_bytes[end] != 0) { end += 1; } return string_bytes[index..end :0]; } ``` -------------------------------- ### addInstallDirectory Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_139.md Creates a directory installation step with the specified options. This function returns the created `Step.InstallDir` object. ```APIDOC /// Creates a directory installation step. /// /// Parameters: /// - b: The build instance. /// - options: The options for installing the directory. /// /// Returns: /// A pointer to the created `Step.InstallDir`. pub fn addInstallDirectory(b: *Build, options: Step.InstallDir.Options) *Step.InstallDir ``` -------------------------------- ### Start Build Process in WebServer Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_8.md Initiates the build process by resetting fuzzing state, clearing step status bits, and setting the build status to running. It then notifies any listeners of the update. ```zig pub fn startBuild(ws: *WebServer) void { if (ws.fuzz) |*fuzz| { fuzz.deinit(); ws.fuzz = null; } for (ws.step_status_bits) |*bits| @atomicStore(u8, bits, 0, .monotonic); ws.build_status.store(.running, .monotonic); ws.notifyUpdate(); } ``` -------------------------------- ### Get Uninstall Build Step Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_139.md Retrieves the uninstallation step from the build object. This step is used for cleaning up installed artifacts. ```zig pub fn getUninstallStep(b: *Build) *Step { return &b.uninstall_tls.step; } ``` -------------------------------- ### installConfigurationTable Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_84.md Installs a configuration table with a specified GUID and data into the UEFI system. Handles errors related to invalid parameters or insufficient resources. ```APIDOC ## installConfigurationTable ### Description Installs a configuration table with a given GUID and data. ### Parameters - **guid** (*const Guid) - The GUID of the configuration table. - **table** (*anyopaque) - A pointer to the configuration table data. ### Errors - **InstallConfigurationTableError** - **error.InvalidParameter** - **error.OutOfResources** ``` -------------------------------- ### Windows CRT Startup (wWinMainCRTStartup) Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_159.md Similar to `winMainCRTStartup`, this function sets up the Windows environment for console applications, handling FPU state, TLS, and signal handlers before executing the main entry point. ```zig fn wWinMainCRTStartup() callconv(.withStackAlign(.c, 1)) noreturn { // Switch from the x87 fpu state set by windows to the state expected by the gnu abi. if (builtin.cpu.arch.isX86() and builtin.abi == .gnu) asm volatile ("fninit"); if (!builtin.single_threaded and !builtin.link_libc) { _ = @import("os/windows/tls.zig"); } std.Thread.maybeAttachSignalStack(); std.debug.maybeEnableSegfaultHandler(); const result: std.os.windows.INT = call_wWinMain(); std.os.windows.ntdll.RtlExitUserProcess(@as(std.os.windows.UINT, @bitCast(result))); } ``` -------------------------------- ### Register Protocol Notification in Zig Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_84.md Registers a notification function to be called when a specific protocol is installed or uninstalled. Ensures the protocol has a 'guid' declaration. ```zig pub fn registerProtocolNotify( self: *BootServices, Protocol: type, event: Event, ) RegisterProtocolNotifyError!EventRegistration { if (!@hasDecl(Protocol, "guid")) @compileError("Protocol is missing guid"); var registration: EventRegistration = undefined; switch (self._registerProtocolNotify( &Protocol.guid, event, ®istration, )) { .success => return registration, .out_of_resources => return error.OutOfResources, .invalid_parameter => return error.InvalidParameter, else => |status| return uefi.unexpectedStatus(status), } } ``` -------------------------------- ### Create Directories, Files, and Symlinks Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_160.md Demonstrates creating nested directories, files, and symbolic links using Zig's testing utilities. Includes handling for Windows-specific symlink limitations. ```zig test "create file and symlink" { const io = testing.io; var root = testing.tmpDir(.{}); defer root.cleanup(); var file = try createDirAndFile(io, root.dir, "file1", .default_file); file.close(io); file = try createDirAndFile(io, root.dir, "a/b/c/file2", .default_file); file.close(io); createDirAndSymlink(io, root.dir, "a/b/c/file2", "symlink1") catch |err| switch (err) { // On Windows, symlinks require developer mode/admin privileges and the underlying filesystem must support symlinks error.AccessDenied, error.PermissionDenied, error.FileSystem => if (builtin.os.tag == .windows) return error.SkipZigTest else return err, else => return err, }; try createDirAndSymlink(io, root.dir, "../../../file1", "d/e/f/symlink2"); // Danglink symlnik, file created later try createDirAndSymlink(io, root.dir, "../../../g/h/i/file4", "j/k/l/symlink3"); file = try createDirAndFile(io, root.dir, "g/h/i/file4", .default_file); file.close(io); } ``` -------------------------------- ### Get Emitted Binary Path Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_3.md Retrieves the path to the generated executable, library, or object file. For executables, use `run` or an install step. ```zig pub fn getEmittedBin(compile: *Compile) LazyPath { return compile.getEmittedFileGeneric(&compile.generated_bin); } ``` -------------------------------- ### BitStack Initialization and Push Test in Zig Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_138.md Demonstrates the initialization of a BitStack and pushing bits onto it. Includes setup for testing with a dynamic allocator and deferred deinitialization. ```zig const testing = std.testing; test BitStack { var stack = BitStack.init(testing.allocator); defer stack.deinit(); try stack.push(1); try stack.push(0); try s ``` -------------------------------- ### Get Next Token (next) Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_71.md Advances the parser and returns the next JSON token. Handles whitespace, object/array starts, strings, numbers, and literals. ```zig pub fn next(self: *@This()) NextError!Token { state_loop: while (true) { switch (self.state) { .value => { switch (try self.skipWhitespaceExpectByte()) { // Object, Array '{' => { try self.stack.push(OBJECT_MODE); self.cursor += 1; self.state = .object_start; return .object_begin; }, '[' => { try self.stack.push(ARRAY_MODE); self.cursor += 1; self.state = .array_start; return .array_begin; }, // String '"' => { self.cursor += 1; self.value_start = self.cursor; self.state = .string; continue :state_loop; }, // Number '1'...'9' => { self.value_start = self.cursor; self.cursor += 1; self.state = .number_int; continue :state_loop; }, '0' => { self.value_start = self.cursor; self.cursor += 1; self.state = .number_leading_zero; continue :state_loop; }, '-' => { self.value_start = self.cursor; self.cursor += 1; self.state = .number_minus; continue :state_loop; }, // literal values 't' => { ``` -------------------------------- ### Web Server Initialization Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_8.md Initializes a WebServer with the provided options. This sets up the necessary components for serving build information over a web interface. ```zig pub fn init(opts: Options) WebServer { ``` -------------------------------- ### Get Fiber Result Bytes with Alignment in Zig Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_57.md Calculates the starting memory address for the result data within a Fiber, based on a specified alignment. ```zig fn resultBytes(f: *Fiber, alignment: Alignment) [*]u8 { return @ptrFromInt(alignment.forward(@intFromPtr(f) + @sizeOf(Fiber))); } ``` -------------------------------- ### Install File with Verbose and Error Handling Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_7.md Wraps `Io.Dir.updateFile` to include verbose logging and specific error handling for file installation. Use for copying files during the build process. ```zig /// Wrapper around `Io.Dir.updateFile` that handles verbose and error output. pub fn installFile(s: *Step, src_lazy_path: Build.LazyPath, dest_path: []const u8) !Io.Dir.PrevStatus { const b = s.owner; const io = b.graph.io; const src_path = src_lazy_path.getPath3(b, s); try handleVerbose(b, .inherit, &.{ "install", "-C", b.fmt("{f}", .{src_path}), dest_path }); return Io.Dir.updateFile(src_path.root_dir.handle, io, src_path.sub_path, .cwd(), dest_path, .{}) catch |err| return s.fail("unable to update file from '{f}' to '{s}': {t}", .{ src_path, dest_path, err }); } ``` -------------------------------- ### FuzzTestRunner Initialization and Execution Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_5.md Initializes and starts fuzz test instances, then enters a listening loop. This function orchestrates the setup and execution of fuzz tests. ```zig fn evalFuzzTest( run: *Run, spawn_options: process.SpawnOptions, options: Step.MakeOptions, fuzz_context: FuzzContext, ) !void { var f: FuzzTestRunner = try .init(run, fuzz_context, options.progress_node, spawn_options); defer f.deinit(); try f.startInstances(); try f.listen(); } ``` -------------------------------- ### NetBSD Linker Startup Objects in Zig Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_127.md Sets up linker startup objects for NetBSD, covering dynamic libraries, executables, and PIE builds, with specific object files for each mode. ```zig .netbsd => switch (mode) { .dynamic_lib => .{ .crti = "crti.o", .crtbegin = "crtbeginS.o", .crtend = "crtendS.o", .crtn = "crtn.o", }, .dynamic_exe => .{ .crt0 = "crt0.o", .crti = "crti.o", .crtbegin = "crtbegin.o", .crtend = "crtend.o", .crtn = "crtn.o", }, .dynamic_pie => .{ .crt0 = "crt0.o", .crti = "crti.o", .crtbegin = "crtbeginS.o", .crtend = "crtendS.o", .crtn = "crtn.o", }, }, ``` -------------------------------- ### Group Async Function Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_68.md Manages asynchronous group operations, handling potential errors during concurrent group setup by falling back to starting the task directly. ```zig fn groupAsync( userdata: ?*anyopaque, type_erased: *Io.Group, context: []const u8, context_alignment: Alignment, start: *const fn (context: *const anyopaque) void, ) void { const ev: *Evented = @ptrCast(@alignCast(userdata)); return groupConcurrent(ev, type_erased, context, context_alignment, start) catch { start(context.ptr); }; } ``` -------------------------------- ### ResolvConf Initialization Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_54.md Initializes the ResolvConf structure by parsing the system's resolv.conf file. If the file is not found or inaccessible, it defaults to using localhost as the nameserver. ```zig pub const ResolvConf = struct { attempts: u32, ndots: u32, timeout_seconds: u32, nameservers_buffer: [max_nameservers]IpAddress, nameservers_len: usize, search_buffer: [max_len]u8, search_len: usize, /// According to resolv.conf(5) there is a maximum of 3 nameservers in this /// file. pub const max_nameservers = 3; /// Returns `error.StreamTooLong` if a line is longer than 512 bytes. pub fn init(io: Io) !ResolvConf { var rc: ResolvConf = ફો.{ // Note: This is a placeholder for the actual struct initialization .nameservers_buffer = undefined, .nameservers_len = 0, .search_buffer = undefined, .search_len = 0, .ndots = 1, .timeout_seconds = 5, .attempts = 2, }; const file = Io.Dir.openFileAbsolute(io, "/etc/resolv.conf", .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.AccessDenied, => { try addNumeric(&rc, io, "127.0.0.1", 53); return rc; }, else => |e| return e, }; defer file.close(io); var line_buf: [512]u8 = undefined; var file_reader = file.reader(io, &line_buf); parse(&rc, io, &file_reader.interface) catch |err| switch (err) { error.ReadFailed => return file_reader.err.?, else => |e| return e, }; return rc; } const Directive = enum { options, nameserver, domain, search }; }; ``` -------------------------------- ### Get Entry Depth in Walker Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_54.md Calculates the depth of a file system entry relative to the starting directory. Depth is 1 for direct children, 2 for nested entries, and so on. ```zig pub fn depth(self: Walker.Entry) usize { return std.mem.countScalar(u8, self.path, path.sep) + 1; } ``` -------------------------------- ### registerProtocolNotify Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_84.md Registers a notification function to be called when a protocol is installed or uninstalled. It ensures the protocol has a GUID defined and handles potential errors like resource exhaustion or invalid parameters. ```APIDOC ## registerProtocolNotify ### Description Registers a notification function for protocol installation/uninstallation. ### Parameters - **Protocol** (type) - The protocol type to register for. - **event** (Event) - The event to trigger the notification. ### Returns - **EventRegistration** - A handle to the registered event. ### Errors - **error.OutOfResources** - **error.InvalidParameter** - **uefi.UnexpectedStatus** ``` -------------------------------- ### Server Initialization Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_128.md Initializes a new `Server` instance with the provided reader, writer, and Zig version information. ```APIDOC ## Server.init Function Initializes a `Server` instance. ### Signature ```zig pub fn init(options: Options) !Server ``` ### Parameters - **options** (`Options` struct): - **in** (`*Reader`): The input reader for server communication. - **out** (`*Writer`): The output writer for server communication. - **zig_version** (`[]const u8`): The Zig version string. ``` -------------------------------- ### Get Source Token Index for ZIR Context Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_124.md Retrieves the source token index associated with the current ZIR declaration node. This is the starting point for relative token calculations. ```zig fn srcToken(gz: GenZir) Ast.TokenIndex { return gz.astgen.tree.firstToken(gz.decl_node_index); } ``` -------------------------------- ### addInstallBinFile Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_139.md Adds a file to be installed, relative to the binary directory. This function returns the created `Step.InstallFile` object. ```APIDOC /// Adds a file to be installed relative to the bin path. /// /// Parameters: /// - b: The build instance. /// - source: The source of the file (LazyPath). /// - dest_rel_path: The destination path relative to the bin directory. /// /// Returns: /// A pointer to the created `Step.InstallFile`. pub fn addInstallBinFile(b: *Build, source: LazyPath, dest_rel_path: []const u8) *Step.InstallFile ``` -------------------------------- ### WaitGroup Implementation in Zig Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_67.md A WaitGroup synchronizes multiple goroutines or threads. Use `start` to increment the counter, `value` to get the current count, `wait` to block until the counter is zero, and `finish` to decrement the counter. ```zig const WaitGroup = struct { state: std.atomic.Value(usize), event: Io.Event, const init: WaitGroup = .{ .state = .{ .raw = 0 }, .event = .unset }; const is_waiting: usize = 1 << 0; const one_pending: usize = 1 << 1; fn start(wg: *WaitGroup) void { const prev_state = wg.state.fetchAdd(one_pending, .monotonic); assert((prev_state / one_pending) < (std.math.maxInt(usize) / one_pending)); } fn value(wg: *WaitGroup) usize { return wg.state.load(.monotonic) / one_pending; } fn wait(wg: *WaitGroup) void { const prev_state = wg.state.fetchAdd(is_waiting, .acquire); assert(prev_state & is_waiting == 0); if ((prev_state / one_pending) > 0) eventWait(&wg.event); } fn finish(wg: *WaitGroup) void { const state = wg.state.fetchSub(one_pending, .acq_rel); assert((state / one_pending) > 0); if (state == (one_pending | is_waiting)) { eventSet(&wg.event); } } }; ``` -------------------------------- ### Initialize io_uring_sqe for direct ACCEPT operation Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_78.md Prepares an SQE for a direct accept operation, which uses a fixed file descriptor for the accepted connection. This function calls `prep_accept` and then sets the target fixed file using `__io_uring_set_target_fixed_file`. ```zig pub fn prep_accept_direct( sqe: *linux.io_uring_sqe, fd: linux.fd_t, addr: ?*linux.sockaddr, addrlen: ?*linux.socklen_t, flags: u32, file_index: u32, ) void { prep_accept(sqe, fd, addr, addrlen, flags); __io_uring_set_target_fixed_file(sqe, file_index); } ``` -------------------------------- ### Zig MinHeap Shrink and Free Example Source: https://github.com/larkliy/zig-mcp/blob/main/zig-std-lib_part_157.md Demonstrates using `ensureTotalCapacity` to allocate memory, adding elements, and then using `shrinkAndFree` to reduce the capacity to the minimum required. Verifies element integrity after shrinking. ```zig test "shrinkAndFree" { const gpa = testing.allocator; var queue: MinHeap = .empty; defer queue.deinit(gpa); try queue.ensureTotalCapacity(gpa, 4); try expect(queue.capacity() >= 4); try queue.push(gpa, 1); try queue.push(gpa, 2); try queue.push(gpa, 3); try expect(queue.capacity() >= 4); try expectEqual(@as(usize, 3), queue.count()); queue.shrinkAndFree(gpa, 3); try expectEqual(@as(usize, 3), queue.capacity()); try expectEqual(@as(usize, 3), queue.count()); try expectEqual(@as(u32, 1), queue.pop()); try expectEqual(@as(u32, 2), queue.pop()); try expectEqual(@as(u32, 3), queue.pop()); try expect(queue.pop() == null); } ```