code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const mem = std.mem; usingnamespace @import("primitive_types.zig"); const PrimitiveReader = @import("primitive/reader.zig").PrimitiveReader; const testing = @import("testing.zig"); pub const GlobalTableSpec = struct { keyspace: []const u8, table: []const u8, }; fn readOptionID(pr: *PrimitiveReader) !OptionID { return @intToEnum(OptionID, try pr.readInt(u16)); } pub const ColumnSpec = struct { const Self = @This(); option: OptionID, keyspace: ?[]const u8 = null, table: ?[]const u8 = null, name: []const u8 = "", // TODO(vincent): not a fan of this but for now it's fine. listset_element_type_option: ?OptionID = null, map_key_type_option: ?OptionID = null, map_value_type_option: ?OptionID = null, custom_class_name: ?[]const u8 = null, pub fn deinit(self: Self, allocator: *mem.Allocator) void { if (self.keyspace) |str| allocator.free(str); if (self.table) |str| allocator.free(str); allocator.free(self.name); if (self.custom_class_name) |str| allocator.free(str); } pub fn read(allocator: *mem.Allocator, pr: *PrimitiveReader, has_global_table_spec: bool) !Self { var spec = Self{ .keyspace = null, .table = null, .name = undefined, .option = undefined, .listset_element_type_option = null, .map_key_type_option = null, .map_value_type_option = null, .custom_class_name = null, }; if (!has_global_table_spec) { spec.keyspace = try pr.readString(allocator); spec.table = try pr.readString(allocator); } spec.name = try pr.readString(allocator); spec.option = try readOptionID(pr); switch (spec.option) { .Tuple => unreachable, .UDT => unreachable, .Custom => { spec.custom_class_name = try pr.readString(allocator); }, .List, .Set => { const option = try readOptionID(pr); spec.listset_element_type_option = option; if (option == .Custom) { spec.custom_class_name = try pr.readString(allocator); } }, .Map => { spec.map_key_type_option = try readOptionID(pr); spec.map_value_type_option = try readOptionID(pr); }, else => {}, } return spec; } }; /// Described in the protocol spec at §4.2.5.2. pub const RowsMetadata = struct { const Self = @This(); paging_state: ?[]const u8, new_metadata_id: ?[]const u8, global_table_spec: ?GlobalTableSpec, /// Store the column count as well as the column specs because /// with FlagNoMetadata the specs are empty columns_count: usize, column_specs: []const ColumnSpec, const FlagGlobalTablesSpec = 0x0001; const FlagHasMorePages = 0x0002; const FlagNoMetadata = 0x0004; const FlagMetadataChanged = 0x0008; pub fn deinit(self: *Self, allocator: *mem.Allocator) void { if (self.paging_state) |ps| allocator.free(ps); if (self.new_metadata_id) |id| allocator.free(id); if (self.global_table_spec) |spec| { allocator.free(spec.keyspace); allocator.free(spec.table); } for (self.column_specs) |spec| { spec.deinit(allocator); } allocator.free(self.column_specs); } pub fn read(allocator: *mem.Allocator, protocol_version: ProtocolVersion, pr: *PrimitiveReader) !Self { var metadata = Self{ .paging_state = null, .new_metadata_id = null, .global_table_spec = null, .columns_count = 0, .column_specs = undefined, }; const flags = try pr.readInt(u32); metadata.columns_count = @as(usize, try pr.readInt(u32)); if (flags & FlagHasMorePages == FlagHasMorePages) { metadata.paging_state = try pr.readBytes(allocator); } if (protocol_version.is(5)) { if (flags & FlagMetadataChanged == FlagMetadataChanged) { metadata.new_metadata_id = try pr.readShortBytes(allocator); } } if (flags & FlagNoMetadata == FlagNoMetadata) { return metadata; } if (flags & FlagGlobalTablesSpec == FlagGlobalTablesSpec) { const spec = GlobalTableSpec{ .keyspace = try pr.readString(allocator), .table = try pr.readString(allocator), }; metadata.global_table_spec = spec; } var column_specs = try allocator.alloc(ColumnSpec, metadata.columns_count); var i: usize = 0; while (i < metadata.columns_count) : (i += 1) { column_specs[i] = try ColumnSpec.read(allocator, pr, metadata.global_table_spec != null); } metadata.column_specs = column_specs; return metadata; } }; /// PreparedMetadata in the protocol spec at §4.2.5.4. pub const PreparedMetadata = struct { const Self = @This(); global_table_spec: ?GlobalTableSpec, pk_indexes: []const u16, column_specs: []const ColumnSpec, const FlagGlobalTablesSpec = 0x0001; const FlagNoMetadata = 0x0004; pub fn deinit(self: *const Self, allocator: *mem.Allocator) void { if (self.global_table_spec) |spec| { allocator.free(spec.keyspace); allocator.free(spec.table); } allocator.free(self.pk_indexes); for (self.column_specs) |spec| { spec.deinit(allocator); } allocator.free(self.column_specs); } pub fn read(allocator: *mem.Allocator, protocol_version: ProtocolVersion, pr: *PrimitiveReader) !Self { var metadata = Self{ .global_table_spec = null, .pk_indexes = undefined, .column_specs = undefined, }; const flags = try pr.readInt(u32); const columns_count = @as(usize, try pr.readInt(u32)); if (protocol_version.isAtLeast(4)) { const pk_count = @as(usize, try pr.readInt(u32)); // Read the partition key indexes var pk_indexes = try allocator.alloc(u16, pk_count); errdefer allocator.free(pk_indexes); var i: usize = 0; while (i < pk_count) : (i += 1) { pk_indexes[i] = try pr.readInt(u16); } metadata.pk_indexes = pk_indexes; } // Next are the table spec and column spec if (flags & FlagGlobalTablesSpec == FlagGlobalTablesSpec) { const spec = GlobalTableSpec{ .keyspace = try pr.readString(allocator), .table = try pr.readString(allocator), }; metadata.global_table_spec = spec; } // Read the column specs var column_specs = try allocator.alloc(ColumnSpec, columns_count); errdefer allocator.free(column_specs); var i: usize = 0; while (i < columns_count) : (i += 1) { column_specs[i] = try ColumnSpec.read(allocator, pr, metadata.global_table_spec != null); } metadata.column_specs = column_specs; return metadata; } }; test "column spec: deinit" { const allocator = testing.allocator; const column_spec = ColumnSpec{ .keyspace = try mem.dupe(allocator, u8, "keyspace"), .table = try mem.dupe(allocator, u8, "table"), .name = try mem.dupe(allocator, u8, "name"), .option = .Set, .listset_element_type_option = .Inet, .map_key_type_option = .Varchar, .map_value_type_option = .Varint, .custom_class_name = try mem.dupe(allocator, u8, "custom_class_name"), }; column_spec.deinit(allocator); } test "prepared metadata: deinit" { const allocator = testing.allocator; const column_spec = ColumnSpec{ .keyspace = try mem.dupe(allocator, u8, "keyspace"), .table = try mem.dupe(allocator, u8, "table"), .name = try mem.dupe(allocator, u8, "name"), .option = .Set, .listset_element_type_option = .Inet, .map_key_type_option = .Varchar, .map_value_type_option = .Varint, .custom_class_name = try mem.dupe(allocator, u8, "custom_class_name"), }; var metadata: PreparedMetadata = undefined; metadata.global_table_spec = GlobalTableSpec{ .keyspace = try mem.dupe(allocator, u8, "global_keyspace"), .table = try mem.dupe(allocator, u8, "global_table"), }; metadata.pk_indexes = try mem.dupe(allocator, u16, &[_]u16{ 0xde, 0xad, 0xbe, 0xef }); metadata.column_specs = try mem.dupe(allocator, ColumnSpec, &[_]ColumnSpec{column_spec}); metadata.deinit(allocator); } test "rows metadata: deinit" { const allocator = testing.allocator; const column_spec = ColumnSpec{ .keyspace = try mem.dupe(allocator, u8, "keyspace"), .table = try mem.dupe(allocator, u8, "table"), .name = try mem.dupe(allocator, u8, "name"), .option = .Set, .listset_element_type_option = .Inet, .map_key_type_option = .Varchar, .map_value_type_option = .Varint, .custom_class_name = try mem.dupe(allocator, u8, "custom_class_name"), }; var metadata: RowsMetadata = undefined; metadata.paging_state = try mem.dupe(allocator, u8, "\xbb\xbc\xde\xfe"); metadata.new_metadata_id = try mem.dupe(allocator, u8, "\xac\xbd\xde\xad"); metadata.global_table_spec = GlobalTableSpec{ .keyspace = try mem.dupe(allocator, u8, "global_keyspace"), .table = try mem.dupe(allocator, u8, "global_table"), }; metadata.column_specs = try mem.dupe(allocator, ColumnSpec, &[_]ColumnSpec{column_spec}); metadata.deinit(allocator); }
src/metadata.zig
const std = @import("std"); const kernel = @import("root"); const printk = kernel.printk; const lib = kernel.lib; const logger = @TypeOf(@import("../x86.zig").logger).childOf(@typeName(@This())){}; const mm = kernel.mm; const PhysicalAddress = kernel.mm.PhysicalAddress; const RSDP = extern struct { // "RSD PTR " signature: [8]u8, // Includes only 0-19 bytes, summing to zero checksum: u8, // OEM identifier oemid: [6]u8, // Revision of the structure, current value 2 revision: u8, // Physical address of the RSDT rsdt_address: u32, length: u32, xsdt_address: u64, extended_checksum: u8, // zig compiler workaound reserveda: [3]u8, pub fn get_rsdt(self: @This()) PhysicalAddress { std.debug.assert(self.signature_ok()); std.debug.assert(self.checksum_ok()); return PhysicalAddress.new(self.rsdt_address); } pub fn signature_ok(self: @This()) bool { return std.mem.eql(u8, self.signature[0..], "RSD PTR "); } fn sum_field(self: @This(), comptime field: []const u8) u8 { var total: u8 = 0; const bytes = std.mem.asBytes(&@field(self, field)); for (bytes) |c| { total = total +% c; } return total; } pub fn checksum_ok(self: @This()) bool { return self.calc_checksum() == 0; } pub fn calc_checksum(self: @This()) u8 { var total: u8 = 0; total = total +% self.sum_field("signature"); total = total +% self.sum_field("checksum"); total = total +% self.sum_field("oemid"); total = total +% self.sum_field("revision"); total = total +% self.sum_field("rsdt_address"); return total; } }; comptime { const Struct = RSDP; // Zig compiler is a little broken for packed structs :< //std.debug.assert(@sizeOf(Struct) == 36); std.debug.assert(@offsetOf(Struct, "signature") == 0); std.debug.assert(@offsetOf(Struct, "checksum") == 8); std.debug.assert(@offsetOf(Struct, "oemid") == 9); std.debug.assert(@offsetOf(Struct, "revision") == 15); std.debug.assert(@offsetOf(Struct, "rsdt_address") == 16); std.debug.assert(@offsetOf(Struct, "length") == 20); } const SDTHeader = packed struct { signature: [4]u8, length: u32, revision: u8, checksum: u8, // Zig compiler bug workaround - fields can only have a power of 2 size oemid_a: [4]u8, oemid_b: [2]u8, oemtableid: [8]u8, oemrevision: u32, creatorid: u32, creatorrevision: u32, }; comptime { const Struct = SDTHeader; std.debug.assert(@sizeOf(Struct) == 36); std.debug.assert(@offsetOf(Struct, "signature") == 0); std.debug.assert(@offsetOf(Struct, "length") == 4); std.debug.assert(@offsetOf(Struct, "revision") == 8); std.debug.assert(@offsetOf(Struct, "checksum") == 9); std.debug.assert(@offsetOf(Struct, "oemid_a") == 10); std.debug.assert(@offsetOf(Struct, "oemtableid") == 16); std.debug.assert(@offsetOf(Struct, "oemrevision") == 24); std.debug.assert(@offsetOf(Struct, "creatorid") == 28); std.debug.assert(@offsetOf(Struct, "creatorrevision") == 32); } const FADTData = packed struct { firmware_ctrl: u32, dsdt: u32, reserved: u8, preferred_pm_profile: u8, sci_int: u16, smi_cmd: u32, acpi_enable: u8, acpi_disable: u8, s4bios_req: u8, pstate_cnt: u8, pm1a_evt_blk: u32, pm1b_evt_blk: u32, pm1a_cnt_blk: u32, pm1b_cnt_blk: u32, pm2_cnt_blk: u32, pm2_tmr_blk: u32, gpe0_blk: u32, gpe1_blk: u32, pm1_evt_len: u8, pm1_cnt_len: u8, pm2_cnt_len: u8, pm_tmr_len: u8, gpe0_blk_len: u8, gpe1_blk_len: u8, gpe1_base: u8, cst_cnt: u8, p_lvl2_lat: u16, p_lvl3_lat: u16, flush_size: u16, flush_stride: u16, duty_offset: u8, duty_width: u8, day_alrm: u8, mon_alrm: u8, century: u8, iapc_boot_arch: u16, reserved_: u8, flags: u32, // Zig bug workaround reset_reg_low: u64, reset_reg_high: u32, reset_value: u8, arm_boot_arch: u16, fadt_minor_version: u8, x_firmware_ctrl: u64, x_dsdt: u64, // TODO rest }; fn find_rsdp() ?*RSDP { var base = PhysicalAddress.new(0); const limit = PhysicalAddress.new(lib.MiB(2)); // Use correct method (?) while (base.lt(limit)) : (base = base.add(16)) { //logger.log("Searching... {}", .{base}); const candidate = mm.directMapping().to_virt(base).into_pointer(*RSDP); if (candidate.signature_ok()) { if (candidate.checksum_ok()) { return candidate; } logger.log("{*} signature OK, checksum mismatch\n", .{candidate}); } } return null; } const MCFGEntry = packed struct { base_address: u64, pci_segment_group: u16, start_bus: u8, end_bus: u8, reserved: u32, }; pub const MCFGIterator = struct { data: []const u8, pub fn empty() MCFGIterator { return .{ .data = &[_]u8{} }; } pub fn next(self: *@This()) ?*const MCFGEntry { if (self.data.len < @sizeOf(MCFGEntry)) return null; const entry = @ptrCast(*const MCFGEntry, self.data); self.data = self.data[@sizeOf(MCFGEntry)..]; return entry; } pub fn init(header: *SDTHeader) MCFGIterator { const data_length = header.length - @sizeOf(SDTHeader) - 8; var data = @intToPtr([*]u8, @ptrToInt(header) + @sizeOf(SDTHeader) + 8)[0..data_length]; return .{ .data = data }; } }; pub const MADTLapicEntry = packed struct { madt_header: MADTHeader, processor_uid: u8, apic_id: u8, flags: u32, }; pub const MADTEntryType = enum(u8) { LocalApic = 0, IoApic = 1, InterruptSourceOverrride = 2, NmiSource = 3, LocalApicNmi = 4, LocalApicAddressOverride = 5, IoSapic = 6, LocalSapic = 7, PlatformInterruptSources = 8, ProcessorLocalx2Apic = 9, Localx2ApicNmi = 0xa, _, }; const MADTInfo = packed struct { lapic_address: u32, // The 8259 vectors must be disabled (that is, masked) when // enabling the ACPI APIC operation. flags: u32, }; const MADTHeader = packed struct { entry_type: u8, record_length: u8, }; pub const MADTLapic = packed struct { header: MADTHeader, acpi_processor_uid: u8, apic_uid: u8, flags: u32, }; pub const MADTIterator = struct { data: []const u8, pub fn next(self: *@This()) ?*const MADTHeader { if (self.data.len >= @sizeOf(MADTHeader)) { const madt_header = @ptrCast(*const MADTHeader, self.data.ptr); self.data = self.data[madt_header.record_length..]; return madt_header; } return null; } pub fn empty() MADTIterator { return .{ .data = &[_]u8{} }; } pub fn init(header: *SDTHeader) MADTIterator { const data_length = header.length - @sizeOf(SDTHeader); var data = @intToPtr([*]u8, @ptrToInt(header) + @sizeOf(SDTHeader))[0..data_length]; var entry_data = data[@sizeOf(MADTInfo)..]; return .{ .data = entry_data }; } }; pub fn iterMADT() MADTIterator { if (getTable("APIC")) |table| { return MADTIterator.init(table); } return MADTIterator.empty(); } pub fn iterMCFG() MCFGIterator { if (getTable("MCFG")) |table| { return MCFGIterator.init(table); } return MCFGIterator.empty(); } const SDTIterator = struct { data: []const u8, pub fn next(self: *@This()) ?*SDTHeader { const PointerType = u32; const pointerSize = @sizeOf(PointerType); if (self.data.len >= pointerSize) { const addr = PhysicalAddress.new(std.mem.readIntSliceNative( PointerType, self.data[0..pointerSize], )); self.data = self.data[pointerSize..]; return mm.directMapping().to_virt(addr).into_pointer(*SDTHeader); } return null; } pub fn init(rsdt: *SDTHeader) SDTIterator { return .{ .data = @ptrCast([*]u8, rsdt)[@sizeOf(SDTHeader)..rsdt.length] }; } }; pub fn iterSDT() SDTIterator { if (rsdt_root) |root| { return SDTIterator.init(root); } return SDTIterator{ .data = &[_]u8{} }; } pub fn getTable(name: []const u8) ?*SDTHeader { logger.log("Getting table {s}\n", .{name}); var sdt_it = iterSDT(); while (sdt_it.next()) |table| { if (std.mem.eql(u8, name, &table.signature)) { return table; } } return null; } var rsdt_root: ?*SDTHeader = null; pub fn init() void { logger.log("Initializing ACPI\n", .{}); const rsdp = find_rsdp(); if (rsdp == null) { logger.log("Failed to find a RSDP\n", .{}); return; } logger.log("Valid RSDP found\n", .{}); rsdt_root = mm.directMapping().to_virt(rsdp.?.get_rsdt()).into_pointer(*SDTHeader); var sdt_it = iterSDT(); while (sdt_it.next()) |table| { logger.info("Found table {e}\n", .{std.fmt.fmtSliceEscapeLower(&table.signature)}); } }
kernel/arch/x86/acpi.zig
const std = @import("std"); const math = std.math; const log = std.log; const fs = std.fs; const os = std.os; const proc = @import("./proc.zig"); const match = @import("./glob.zig").globMatch; const l2 = @import("./missing_syscalls.zig"); // Constants obtained from RF Jakob's earlyoom. const ram_fill_rate = 6000; const swap_fill_rate = 800; // Statistics about memory, in MB. pub const MemoryStats = struct { free_ram: f64, free_swap: f64, total_ram: f64, total_swap: f64, free_ram_percent: f64, free_swap_percent: f64, pub fn fromSysInfo(sysinf: l2.SysInfo) MemoryStats { const free_ram = @intToFloat(f64, (sysinf.freeram * @bitCast(c_uint, sysinf.mem_unit)) / (math.pow(u32, 1024, 2))); const free_swap = @intToFloat(f64, (sysinf.freeswap * @bitCast(c_uint, sysinf.mem_unit)) / (math.pow(u32, 1024, 2))); const total_ram = @intToFloat(f64, (sysinf.totalram * @bitCast(c_uint, sysinf.mem_unit)) / (math.pow(u32, 1024, 2))); const total_swap = @intToFloat(f64, (sysinf.totalswap * @bitCast(c_uint, sysinf.mem_unit)) / (math.pow(u32, 1024, 2))); return MemoryStats{ // above .free_ram = free_ram, .free_swap = free_swap, .total_ram = total_ram, .total_swap = total_swap, // percents .free_ram_percent = 100 * free_ram / total_ram, .free_swap_percent = 100 * free_swap / total_swap, }; } }; pub const VictimQueryError = error{ CantReadProc, ProcNotFound }; pub const Killer = struct { timer: std.time.Timer, terminal_ram_percent: f64, terminal_swap_percent: f64, terminal_psi: f32, do_not_kill: []const u8, kill_pgroup: bool, // Based on RF Jakob's earlyoom (https://github.com/rfjakob/earlyoom/blob/dea92ae67997fcb1a0664489c13d49d09d472d40/main.c#L365) pub fn calculateSleepTime(self: *Killer, mem: MemoryStats) u64 { // How much space left until limits are reached (in KiB) const ram_headroom_kib = math.max(0, (mem.free_ram_percent - self.terminal_ram_percent) * 10 * mem.total_ram); const swap_headroom_kib = math.max(0, (mem.free_swap_percent - self.terminal_swap_percent) * 10 * mem.total_swap); // Using those constants, how much we can sleep without missing am OOM const time_to_fill = math.min(ram_headroom_kib / ram_fill_rate, swap_headroom_kib / swap_fill_rate); return @floatToInt(u64, math.clamp(time_to_fill, 100, 1000)); } pub fn poll(self: *Killer, mem: MemoryStats) bool { var i = proc.getMemoryPressure() catch return true; return (i.Some.avg10 > self.terminal_psi) and (mem.free_ram_percent < self.terminal_ram_percent); } pub fn queryVictim(self: *Killer) VictimQueryError!proc.ProcEntry { log.info("Querying for victims after {}s.", .{self.timer.lap() / 1000000000}); // Reopen /proc and iterate on its contents var proc_dir = fs.cwd().openDir("/proc", .{ .iterate = true }) catch return error.CantReadProc; defer proc_dir.close(); var proc_it = proc_dir.iterate(); // Initialize stats monitoring var cur_proc: ?proc.ProcEntry = null; loop_proc: while (proc_it.next() catch return error.CantReadProc) |proc_entry| { if (proc_entry.kind != .Directory) continue; // non pid folders can be ignore const pid = std.fmt.parseInt(os.pid_t, proc_entry.name, 10) catch continue; var this_proc = proc.ProcEntry.init(pid, proc_dir) catch |err| switch (err) { error.AccessDenied => { log.warn("Skipping PID {} since it belongs to another user.", .{pid}); continue; }, // root process we can't kill error.FileNotFound => { log.warn("Skipping PID {} (died while were scanning /proc).", .{pid}); continue; }, // Process died halfway on event loop. else => return error.CantReadProc, }; defer this_proc.deinit(); // The kernel wouldn't kill them either if (this_proc.oom_score_adj == -1000) continue; var do_not_kill_it = std.mem.tokenize(u8, self.do_not_kill, "|"); while (do_not_kill_it.next()) |pat| { if (match(pat, this_proc.exe[0..])) { log.warn("Skipping PID {} {s} due it matching {s}", .{ this_proc.pid, this_proc.exe, pat }); continue :loop_proc; } } if (cur_proc) |previous| { if (this_proc.oom_score < previous.oom_score) continue; // less evil if (this_proc.vm_rss < previous.vm_rss) continue; // eats less ram } cur_proc = this_proc; } if (cur_proc == null) return error.ProcNotFound; // Found a victim. return cur_proc.?; } pub fn trigger(self: *Killer) !void { // Start gentle. var cur_proc = try self.queryVictim(); const pid = if (self.kill_pgroup) -cur_proc.pid else cur_proc.pid; try os.kill(pid, os.SIG.TERM); log.info("Sent SIGTERM to PID {} (exe: {s} | oom_score {}) in {}ns", .{ cur_proc.pid, cur_proc.exe, cur_proc.oom_score, self.timer.lap(), }); // sleep for 0.5s os.nanosleep(0, 500000000); // error = killed with success, return const new_oom = cur_proc.slurpInt(u16, "oom_score") catch return; if (new_oom + 200 < cur_proc.oom_score ) { log.info("OOM score dropped from {} to {} (delta > 200), not escalating to SIGKILL.", .{ new_oom, cur_proc.oom_score }); return; } try os.kill(pid, os.SIG.KILL); log.info("Escalated to SIGKILL after {}ns.", .{ self.timer.lap() }); } pub fn dryRun(self: *Killer) VictimQueryError!void { const cur_proc = try self.queryVictim(); log.info("Simulated victim: PID {} (exe {s} | oom_score {}). Spotted in {}s", .{ cur_proc.pid, cur_proc.exe, cur_proc.oom_score, self.timer.lap(), }); } };
src/killer.zig
const std = @import("std"); const common = @import("../common/data.zig"); const DEBUG = @import("../common/debug.zig").print; const options = @import("../common/options.zig"); const protocol = @import("../common/protocol.zig"); const rng = @import("../common/rng.zig"); const data = @import("data.zig"); const helpers = @import("helpers.zig"); const ArrayList = std.ArrayList; const assert = std.debug.assert; const stream = std.io.fixedBufferStream; const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const expectEqualSlices = std.testing.expectEqualSlices; const Player = common.Player; const Result = common.Result; const Choice = common.Choice; const showdown = options.showdown; const trace = options.trace; const ArgType = protocol.ArgType; const FixedLog = protocol.FixedLog; const Log = protocol.Log; const Move = data.Move; const Species = data.Species; const Status = data.Status; const Type = data.Type; const Types = data.Types; const Battle = helpers.Battle; const EXP = helpers.EXP; const move = helpers.move; const Pokemon = helpers.Pokemon; const Side = helpers.Side; const swtch = helpers.swtch; const OPTIONS_SIZE = data.OPTIONS_SIZE; const U = if (showdown) u32 else u8; const MIN: U = 0; const MAX: U = std.math.maxInt(U); const NOP = MIN; const HIT = MIN; const CRIT = MIN; const MIN_DMG = if (showdown) MIN else 179; const MAX_DMG = MAX; // TODO: inline Status.init(...) when Zig no longer causes SIGBUS const BRN = 0b10000; const PAR = 0b1000000; comptime { assert(showdown or std.math.rotr(u8, MIN_DMG, 1) == 217); assert(showdown or std.math.rotr(u8, MAX_DMG, 1) == 255); } fn ranged(comptime n: u8, comptime d: u9) U { return if (showdown) @as(U, n) * (@as(u64, 0x100000000) / @as(U, d)) else n; } const P1 = Player.P1; const P2 = Player.P2; var choices: [OPTIONS_SIZE]Choice = undefined; // General test "start (first fainted)" { if (showdown) return; var t = Test(.{}).init( &.{ .{ .species = .Pikachu, .hp = 0, .moves = &.{.ThunderShock} }, .{ .species = .Bulbasaur, .moves = &.{.Tackle} }, }, &.{ .{ .species = .Charmander, .hp = 0, .moves = &.{.Scratch} }, .{ .species = .Squirtle, .moves = &.{.Tackle} }, }, ); defer t.deinit(); try t.log.expected.switched(P1.ident(2), t.expected.p1.get(2)); try t.log.expected.switched(P2.ident(2), t.expected.p2.get(2)); try t.log.expected.turn(1); try expectEqual(Result.Default, try t.battle.actual.update(.{}, .{}, t.log.actual)); try t.verify(); } test "start (all fainted)" { if (showdown) return; // Win { var t = Test(.{}).init( &.{.{ .species = .Bulbasaur, .moves = &.{.Tackle} }}, &.{.{ .species = .Charmander, .hp = 0, .moves = &.{.Scratch} }}, ); defer t.deinit(); try expectEqual(Result.Win, try t.battle.actual.update(.{}, .{}, t.log.actual)); try t.verify(); } // Lose { var t = Test(.{}).init( &.{.{ .species = .Bulbasaur, .hp = 0, .moves = &.{.Tackle} }}, &.{.{ .species = .Charmander, .moves = &.{.Scratch} }}, ); defer t.deinit(); try expectEqual(Result.Lose, try t.battle.actual.update(.{}, .{}, t.log.actual)); try t.verify(); } // Tie { var t = Test(.{}).init( &.{.{ .species = .Bulbasaur, .hp = 0, .moves = &.{.Tackle} }}, &.{.{ .species = .Charmander, .hp = 0, .moves = &.{.Scratch} }}, ); defer t.deinit(); try expectEqual(Result.Tie, try t.battle.actual.update(.{}, .{}, t.log.actual)); try t.verify(); } } test "switching (order)" { var battle = Battle.init( 0x12345678, &[_]Pokemon{.{ .species = .Abra, .moves = &.{.Teleport} }} ** 6, &[_]Pokemon{.{ .species = .Gastly, .moves = &.{.Lick} }} ** 6, ); battle.turn = 1; const p1 = battle.side(.P1); const p2 = battle.side(.P2); try expectEqual(Result.Default, try battle.update(swtch(3), swtch(2), null)); try expectOrder(p1, &.{ 3, 2, 1, 4, 5, 6 }, p2, &.{ 2, 1, 3, 4, 5, 6 }); try expectEqual(Result.Default, try battle.update(swtch(5), swtch(5), null)); try expectOrder(p1, &.{ 5, 2, 1, 4, 3, 6 }, p2, &.{ 5, 1, 3, 4, 2, 6 }); try expectEqual(Result.Default, try battle.update(swtch(6), swtch(3), null)); try expectOrder(p1, &.{ 6, 2, 1, 4, 3, 5 }, p2, &.{ 3, 1, 5, 4, 2, 6 }); try expectEqual(Result.Default, try battle.update(swtch(3), swtch(3), null)); try expectOrder(p1, &.{ 1, 2, 6, 4, 3, 5 }, p2, &.{ 5, 1, 3, 4, 2, 6 }); try expectEqual(Result.Default, try battle.update(swtch(2), swtch(4), null)); try expectOrder(p1, &.{ 2, 1, 6, 4, 3, 5 }, p2, &.{ 4, 1, 3, 5, 2, 6 }); var expected_buf: [22]u8 = undefined; var actual_buf: [22]u8 = undefined; var expected = FixedLog{ .writer = stream(&expected_buf).writer() }; var actual = FixedLog{ .writer = stream(&actual_buf).writer() }; try expected.switched(P1.ident(3), p1.pokemon[2]); try expected.switched(P2.ident(2), p2.pokemon[1]); try expected.turn(7); try expectEqual(Result.Default, try battle.update(swtch(5), swtch(5), actual)); try expectOrder(p1, &.{ 3, 1, 6, 4, 2, 5 }, p2, &.{ 2, 1, 3, 5, 4, 6 }); try expectLog(&expected_buf, &actual_buf); } fn expectOrder(p1: anytype, o1: []const u8, p2: anytype, o2: []const u8) !void { try expectEqualSlices(u8, o1, &p1.order); try expectEqualSlices(u8, o2, &p2.order); } test "switching (reset)" { var t = Test(.{}).init( &.{.{ .species = .Abra, .moves = &.{.Teleport} }}, &.{ .{ .species = .Charmander, .moves = &.{.Scratch} }, .{ .species = .Squirtle, .moves = &.{.Tackle} }, }, ); defer t.deinit(); try t.start(); var p1 = &t.actual.p1.active; p1.volatiles.Reflect = true; t.actual.p2.last_used_move = .Scratch; var p2 = &t.actual.p2.active; p2.boosts.atk = 1; p2.volatiles.LightScreen = true; t.actual.p2.get(1).status = Status.init(.PAR); try t.log.expected.switched(P2.ident(2), t.expected.p2.get(2)); try t.log.expected.move(P1.ident(1), Move.Teleport, P1.ident(1), null); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), swtch(2))); try expect(p1.volatiles.Reflect); try expectEqual(data.Volatiles{}, p2.volatiles); try expectEqual(data.Boosts{}, p2.boosts); try expectEqual(@as(u8, 0), t.actual.p2.get(1).status); try expectEqual(Status.init(.PAR), t.actual.p2.get(2).status); try expectEqual(Move.Teleport, t.actual.p1.last_used_move); try expectEqual(Move.None, t.actual.p2.last_used_move); try t.verify(); } test "switching (brn/par)" { var t = Test(.{}).init( &.{ .{ .species = .Pikachu, .moves = &.{.ThunderShock} }, .{ .species = .Bulbasaur, .status = BRN, .moves = &.{.Tackle} }, }, &.{ .{ .species = .Charmander, .moves = &.{.Scratch} }, .{ .species = .Squirtle, .status = PAR, .moves = &.{.Tackle} }, }, ); defer t.deinit(); try t.log.expected.switched(P1.ident(2), t.expected.p1.get(2)); t.expected.p1.get(2).hp -= 18; try t.log.expected.damage(P1.ident(2), t.expected.p1.get(2), .Burn); try t.log.expected.switched(P2.ident(2), t.expected.p2.get(2)); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(swtch(2), swtch(2))); try expectEqual(@as(u16, 98), t.actual.p1.active.stats.atk); try expectEqual(@as(u16, 196), t.actual.p1.stored().stats.atk); try expectEqual(@as(u16, 46), t.actual.p2.active.stats.spe); try expectEqual(@as(u16, 184), t.actual.p2.stored().stats.spe); try t.verify(); } test "turn order (priority)" { var t = Test( // zig fmt: off if (showdown) .{ NOP, NOP, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, NOP, NOP, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, NOP, NOP, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, NOP, NOP, NOP, HIT, ~CRIT, MIN_DMG, HIT, } else .{ ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, HIT, } // zig fmt: on ).init( &.{.{ .species = .Raticate, .moves = &.{ .Tackle, .QuickAttack, .Counter } }}, &.{.{ .species = .Chansey, .moves = &.{ .Tackle, .QuickAttack, .Counter } }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Tackle, P2.ident(1), null); t.expected.p2.get(1).hp -= 91; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.Tackle, P1.ident(1), null); t.expected.p1.get(1).hp -= 20; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.turn(2); // Raticate > Chansey try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.move(P2.ident(1), Move.QuickAttack, P1.ident(1), null); t.expected.p1.get(1).hp -= 22; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.move(P1.ident(1), Move.Tackle, P2.ident(1), null); t.expected.p2.get(1).hp -= 91; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.turn(3); // Chansey > Raticate try expectEqual(Result.Default, try t.update(move(1), move(2))); try t.log.expected.move(P1.ident(1), Move.QuickAttack, P2.ident(1), null); t.expected.p2.get(1).hp -= 104; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.QuickAttack, P1.ident(1), null); t.expected.p1.get(1).hp -= 22; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.turn(4); // Raticate > Chansey try expectEqual(Result.Default, try t.update(move(2), move(2))); try t.log.expected.move(P2.ident(1), Move.Tackle, P1.ident(1), null); t.expected.p1.get(1).hp -= 20; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.move(P1.ident(1), Move.Counter, P2.ident(1), null); t.expected.p2.get(1).hp -= 40; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.turn(5); // Chansey > Raticate try expectEqual(Result.Default, try t.update(move(3), move(1))); try t.verify(); } test "turn order (basic speed tie)" { return error.SkipZigTest; } test "turn order (complex speed tie)" { return error.SkipZigTest; } test "turn order (switch vs. move)" { var t = Test(if (showdown) (.{ NOP, HIT, ~CRIT, MIN_DMG, NOP, HIT, ~CRIT, MIN_DMG }) else (.{ ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT })).init( &.{ .{ .species = .Raticate, .moves = &.{.QuickAttack} }, .{ .species = .Rattata, .moves = &.{.QuickAttack} }, }, &.{ .{ .species = .Ninetales, .moves = &.{.QuickAttack} }, .{ .species = .Vulpix, .moves = &.{.QuickAttack} }, }, ); defer t.deinit(); try t.log.expected.switched(P2.ident(2), t.expected.p2.get(2)); try t.log.expected.move(P1.ident(1), Move.QuickAttack, P2.ident(2), null); t.expected.p2.get(2).hp -= 64; try t.log.expected.damage(P2.ident(2), t.expected.p2.get(2), .None); try t.log.expected.turn(2); // Switch > Quick Attack try expectEqual(Result.Default, try t.update(move(1), swtch(2))); try t.log.expected.switched(P1.ident(2), t.expected.p1.get(2)); try t.log.expected.move(P2.ident(2), Move.QuickAttack, P1.ident(2), null); t.expected.p1.get(2).hp -= 32; try t.log.expected.damage(P1.ident(2), t.expected.p1.get(2), .None); try t.log.expected.turn(3); // Switch > Quick Attack try expectEqual(Result.Default, try t.update(swtch(2), move(1))); try t.verify(); } test "PP deduction" { var t = Test(.{}).init( &.{.{ .species = .Alakazam, .moves = &.{.Teleport} }}, &.{.{ .species = .Abra, .moves = &.{.Teleport} }}, ); defer t.deinit(); try t.start(); try expectEqual(@as(u8, 32), t.actual.p1.active.move(1).pp); try expectEqual(@as(u8, 32), t.actual.p1.stored().move(1).pp); try expectEqual(@as(u8, 32), t.actual.p2.active.move(1).pp); try expectEqual(@as(u8, 32), t.actual.p2.stored().move(1).pp); try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(@as(u8, 31), t.actual.p1.active.move(1).pp); try expectEqual(@as(u8, 31), t.actual.p1.stored().move(1).pp); try expectEqual(@as(u8, 31), t.actual.p2.active.move(1).pp); try expectEqual(@as(u8, 31), t.actual.p2.stored().move(1).pp); try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(@as(u8, 30), t.actual.p1.active.move(1).pp); try expectEqual(@as(u8, 30), t.actual.p1.stored().move(1).pp); try expectEqual(@as(u8, 30), t.actual.p2.active.move(1).pp); try expectEqual(@as(u8, 30), t.actual.p2.stored().move(1).pp); } test "accuracy (normal)" { const hit = comptime ranged(85 * 255 / 100, 256) - 1; const miss = hit + 1; var t = Test(if (showdown) (.{ NOP, NOP, hit, CRIT, MAX_DMG, miss }) else (.{ CRIT, MAX_DMG, hit, ~CRIT, MIN_DMG, miss })).init( &.{.{ .species = .Hitmonchan, .moves = &.{.MegaPunch} }}, &.{.{ .species = .Machamp, .moves = &.{.MegaPunch} }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.MegaPunch, P2.ident(1), null); try t.log.expected.crit(P2.ident(1)); t.expected.p2.get(1).hp -= 159; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.MegaPunch, P1.ident(1), null); try t.log.expected.lastmiss(); try t.log.expected.miss(P2.ident(1)); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.verify(); } test "damage calc" { const NO_BRN = MAX; var t = Test( // zig fmt: off if (showdown) .{ NOP, NOP, HIT, ~CRIT, MIN_DMG, HIT, CRIT, MAX_DMG, NO_BRN, NOP, NOP, HIT, ~CRIT, MIN_DMG } else .{ ~CRIT, MIN_DMG, HIT, CRIT, MAX_DMG, HIT, NO_BRN, ~CRIT, HIT, ~CRIT, MIN_DMG, HIT } // zig fmt: on ).init( &.{.{ .species = .Starmie, .moves = &.{ .WaterGun, .Thunderbolt } }}, &.{.{ .species = .Golem, .moves = &.{ .FireBlast, .Strength } }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.WaterGun, P2.ident(1), null); try t.log.expected.supereffective(P2.ident(1)); t.expected.p2.get(1).hp -= 248; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.FireBlast, P1.ident(1), null); try t.log.expected.crit(P1.ident(1)); try t.log.expected.resisted(P1.ident(1)); t.expected.p1.get(1).hp -= 70; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.turn(2); // STAB super effective non-critical min damage vs. non-STAB resisted critical max damage try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.move(P1.ident(1), Move.Thunderbolt, P2.ident(1), null); try t.log.expected.immune(P2.ident(1), .None); try t.log.expected.move(P2.ident(1), Move.Strength, P1.ident(1), null); t.expected.p1.get(1).hp -= 68; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.turn(3); // immune vs. normal try expectEqual(Result.Default, try t.update(move(2), move(2))); try t.verify(); } test "fainting (single)" { // Switch { var t = Test(if (showdown) (.{ NOP, NOP, HIT, HIT, ~CRIT, MAX_DMG }) else (.{ HIT, ~CRIT, MAX_DMG, HIT })).init( &.{.{ .species = .Venusaur, .moves = &.{.LeechSeed} }}, &.{ .{ .species = .Slowpoke, .hp = 1, .moves = &.{.WaterGun} }, .{ .species = .Dratini, .moves = &.{.DragonRage} }, }, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.LeechSeed, P2.ident(1), null); try t.log.expected.start(P2.ident(1), .LeechSeed); try t.log.expected.move(P2.ident(1), Move.WaterGun, P1.ident(1), null); try t.log.expected.resisted(P1.ident(1)); t.expected.p1.get(1).hp -= 15; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); t.expected.p2.get(1).hp = 0; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .LeechSeed); t.expected.p1.get(1).hp += 15; try t.log.expected.heal(P1.ident(1), t.expected.p1.get(1), .Silent); try t.log.expected.faint(P2.ident(1), true); try expectEqual(Result{ .p1 = .Pass, .p2 = .Switch }, try t.update(move(1), move(1))); var n = t.battle.actual.choices(.P1, .Pass, &choices); try expectEqualSlices(Choice, &[_]Choice{.{}}, choices[0..n]); n = t.battle.actual.choices(.P2, .Switch, &choices); try expectEqualSlices(Choice, &[_]Choice{swtch(2)}, choices[0..n]); try t.verify(); } // Win { var t = Test(if (showdown) .{ NOP, NOP, HIT } else .{HIT}).init( &.{.{ .species = .Dratini, .hp = 1, .status = BRN, .moves = &.{.DragonRage} }}, &.{.{ .species = .Slowpoke, .hp = 1, .moves = &.{.WaterGun} }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.DragonRage, P2.ident(1), null); t.expected.p2.get(1).hp = 0; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.faint(P2.ident(1), false); try t.log.expected.win(.P1); try expectEqual(Result.Win, try t.update(move(1), move(1))); try t.verify(); } // Lose { var t = Test(if (showdown) (.{ NOP, NOP, NOP, ~CRIT, MIN_DMG, HIT }) else (.{ ~CRIT, MIN_DMG, HIT })).init( &.{.{ .species = .Jolteon, .hp = 1, .moves = &.{.Swift} }}, &.{.{ .species = .Dratini, .status = BRN, .moves = &.{.DragonRage} }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Swift, P2.ident(1), null); t.expected.p2.get(1).hp -= 53; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.DragonRage, P1.ident(1), null); t.expected.p1.get(1).hp = 0; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.faint(P1.ident(1), false); try t.log.expected.win(.P2); try expectEqual(Result.Lose, try t.update(move(1), move(1))); try t.verify(); } } test "fainting (double)" { // Switch { var t = Test(if (showdown) (.{ NOP, NOP, HIT, CRIT, MAX_DMG }) else (.{ CRIT, MAX_DMG, HIT })).init( &.{ .{ .species = .Weezing, .hp = 1, .moves = &.{.Explosion} }, .{ .species = .Koffing, .moves = &.{.SelfDestruct} }, }, &.{ .{ .species = .Weedle, .hp = 1, .moves = &.{.PoisonSting} }, .{ .species = .Caterpie, .moves = &.{.StringShot} }, }, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Explosion, P2.ident(1), null); t.expected.p1.get(1).hp = 0; try t.log.expected.crit(P2.ident(1)); t.expected.p2.get(1).hp = 0; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.faint(P2.ident(1), false); try t.log.expected.faint(P1.ident(1), true); try expectEqual(Result{ .p1 = .Switch, .p2 = .Switch }, try t.update(move(1), move(1))); try t.verify(); } // Tie { var t = Test(if (showdown) (.{ NOP, NOP, HIT, CRIT, MAX_DMG }) else (.{ CRIT, MAX_DMG, HIT })).init( &.{.{ .species = .Weezing, .hp = 1, .moves = &.{.Explosion} }}, &.{.{ .species = .Weedle, .hp = 1, .moves = &.{.PoisonSting} }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Explosion, P2.ident(1), null); t.expected.p1.get(1).hp = 0; try t.log.expected.crit(P2.ident(1)); t.expected.p2.get(1).hp = 0; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.faint(P2.ident(1), false); try t.log.expected.faint(P1.ident(1), false); try t.log.expected.tie(); try expectEqual(Result.Tie, try t.update(move(1), move(1))); try t.verify(); } } test "end turn (turn limit)" { var t = Test(.{}).init( &.{ .{ .species = .Bulbasaur, .hp = 1, .moves = &.{.Tackle} }, .{ .species = .Charmander, .moves = &.{.Scratch} }, }, &.{ .{ .species = .Squirtle, .hp = 1, .moves = &.{.Tackle} }, .{ .species = .Pikachu, .moves = &.{.ThunderShock} }, }, ); defer t.deinit(); var max: u16 = if (showdown) 1000 else 65535; var i: usize = 0; while (i < max - 1) : (i += 1) { try expectEqual(Result.Default, try t.battle.actual.update(swtch(2), swtch(2), null)); } try expectEqual(max - 1, t.battle.actual.turn); const size = if (showdown) 20 else 18; var expected_buf: [size]u8 = undefined; var actual_buf: [size]u8 = undefined; var expected = FixedLog{ .writer = stream(&expected_buf).writer() }; var actual = FixedLog{ .writer = stream(&actual_buf).writer() }; const slot = if (showdown) 2 else 1; try expected.switched(P1.ident(slot), t.expected.p1.get(slot)); try expected.switched(P2.ident(slot), t.expected.p2.get(slot)); if (showdown) try expected.tie(); const result = if (showdown) Result.Tie else Result.Error; try expectEqual(result, try t.battle.actual.update(swtch(2), swtch(2), actual)); try expectEqual(max, t.battle.actual.turn); try expectLog(&expected_buf, &actual_buf); } test "Endless Battle Clause (initial)" { if (!showdown) return; var t = Test(.{}).init( &.{.{ .species = .Gengar, .moves = &.{.Tackle} }}, &.{.{ .species = .Gengar, .moves = &.{.Tackle} }}, ); defer t.deinit(); t.actual.p1.get(1).move(1).pp = 0; t.actual.p2.get(1).move(1).pp = 0; try t.log.expected.switched(P1.ident(1), t.expected.p1.get(1)); try t.log.expected.switched(P2.ident(1), t.expected.p2.get(1)); try t.log.expected.tie(); try expectEqual(Result.Tie, try t.battle.actual.update(.{}, .{}, t.log.actual)); try t.verify(); } test "Endless Battle Clause (basic)" { if (!showdown) return; { var t = Test(.{}).init( &.{.{ .species = .Mew, .moves = &.{.Transform} }}, &.{.{ .species = .Ditto, .moves = &.{.Transform} }}, ); defer t.deinit(); t.expected.p1.get(1).move(1).pp = 0; t.expected.p2.get(1).move(1).pp = 0; t.actual.p1.get(1).move(1).pp = 0; t.actual.p2.get(1).move(1).pp = 0; try t.log.expected.switched(P1.ident(1), t.expected.p1.get(1)); try t.log.expected.switched(P2.ident(1), t.expected.p2.get(1)); try t.log.expected.tie(); try expectEqual(Result.Tie, try t.battle.actual.update(.{}, .{}, t.log.actual)); try t.verify(); } { var t = Test(.{ NOP, NOP }).init( &.{ .{ .species = .Mew, .moves = &.{.Transform} }, .{ .species = .Muk, .moves = &.{.Pound} }, }, &.{.{ .species = .Ditto, .moves = &.{.Transform} }}, ); defer t.deinit(); try t.log.expected.switched(P1.ident(1), t.expected.p1.get(1)); try t.log.expected.switched(P2.ident(1), t.expected.p2.get(1)); try t.log.expected.turn(1); try expectEqual(Result.Default, try t.battle.actual.update(.{}, .{}, t.log.actual)); t.expected.p1.get(2).hp = 0; t.actual.p1.get(2).hp = 0; try t.log.expected.move(P1.ident(1), Move.Transform, P2.ident(1), null); try t.log.expected.transform(P1.ident(1), P2.ident(1)); try t.log.expected.move(P2.ident(1), Move.Transform, P1.ident(1), null); try t.log.expected.transform(P2.ident(1), P1.ident(1)); try t.log.expected.tie(); try expectEqual(Result.Tie, try t.update(move(1), move(1))); try t.verify(); } } test "choices" { var random = rng.PSRNG.init(0x27182818); var battle = Battle.random(&random, false); var n = battle.choices(.P1, .Move, &choices); try expectEqualSlices(Choice, &[_]Choice{ swtch(2), swtch(3), swtch(4), swtch(5), swtch(6), move(1), move(2), move(3), move(4), }, choices[0..n]); n = battle.choices(.P1, .Switch, &choices); try expectEqualSlices(Choice, &[_]Choice{ swtch(2), swtch(3), swtch(4), swtch(5), swtch(6), }, choices[0..n]); n = battle.choices(.P1, .Pass, &choices); try expectEqualSlices(Choice, &[_]Choice{.{}}, choices[0..n]); } // Moves // Move.{KarateChop,RazorLeaf,Crabhammer,Slash} test "HighCritical effect" { // Has a higher chance for a critical hit. const no_crit = if (showdown) comptime ranged(Species.chance(.Machop), 256) else 3; var t = Test(if (showdown) (.{ NOP, NOP, HIT, no_crit, MIN_DMG, HIT, no_crit, MIN_DMG }) else (.{ no_crit, MIN_DMG, HIT, no_crit, MIN_DMG, HIT })).init( &.{.{ .species = .Machop, .moves = &.{.KarateChop} }}, &.{.{ .species = .Machop, .level = 99, .moves = &.{.Strength} }}, ); defer t.deinit(); t.expected.p1.get(1).hp -= 73; t.expected.p2.get(1).hp -= 92; try t.log.expected.move(P1.ident(1), Move.KarateChop, P2.ident(1), null); try t.log.expected.crit(P2.ident(1)); try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.Strength, P1.ident(1), null); try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.verify(); } // Move.FocusEnergy test "FocusEnergy effect" { // While the user remains active, its chance for a critical hit is quartered. Fails if the user // already has the effect. If any Pokemon uses Haze, this effect ends. const crit = if (showdown) comptime ranged(Species.chance(.Machoke), 256) - 1 else 2; var t = Test(if (showdown) (.{ NOP, HIT, crit, MIN_DMG, NOP, HIT, crit, MIN_DMG }) else (.{ ~CRIT, crit, MIN_DMG, HIT, crit, MIN_DMG, HIT, ~CRIT })).init( &.{.{ .species = .Machoke, .moves = &.{ .FocusEnergy, .Strength } }}, &.{.{ .species = .Koffing, .moves = &.{ .DoubleTeam, .Haze } }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.FocusEnergy, P1.ident(1), null); try t.log.expected.start(P1.ident(1), .FocusEnergy); try t.log.expected.move(P2.ident(1), Move.DoubleTeam, P2.ident(1), null); try t.log.expected.boost(P2.ident(1), .Evasion, 1); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.move(P1.ident(1), Move.Strength, P2.ident(1), null); t.expected.p2.get(1).hp -= 60; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.Haze, P2.ident(1), null); try t.log.expected.activate(P2.ident(1), .Haze); try t.log.expected.clearallboost(); try t.log.expected.end(P1.ident(1), .FocusEnergy); try t.log.expected.turn(3); // No crit after Focus Energy (https://pkmn.cc/bulba-glitch-1#Critical_hit_ratio_error) try expectEqual(Result.Default, try t.update(move(2), move(2))); try t.log.expected.move(P1.ident(1), Move.Strength, P2.ident(1), null); try t.log.expected.crit(P2.ident(1)); t.expected.p2.get(1).hp -= 115; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.DoubleTeam, P2.ident(1), null); try t.log.expected.boost(P2.ident(1), .Evasion, 1); try t.log.expected.turn(4); // Crit once Haze removes Focus Energy try expectEqual(Result.Default, try t.update(move(2), move(1))); try t.verify(); } // Move.{DoubleSlap,CometPunch,FuryAttack,PinMissile,SpikeCannon,Barrage,FurySwipes} test "MultiHit effect" { // Hits two to five times. Has a 3/8 chance to hit two or three times, and a 1/8 chance to hit // four or five times. Damage is calculated once for the first hit and used for every hit. If // one of the hits breaks the target's substitute, the move ends. const hit3 = if (showdown) 0x60000000 else 1; const hit5 = MAX; var t = Test(if (showdown) (.{ NOP, HIT, hit3, ~CRIT, MAX_DMG, NOP, HIT, hit5, ~CRIT, MAX_DMG }) else (.{ ~CRIT, MAX_DMG, HIT, hit3, ~CRIT, MAX_DMG, HIT, hit5, hit5 })).init( &.{.{ .species = .Kangaskhan, .moves = &.{.CometPunch} }}, &.{.{ .species = .Slowpoke, .moves = &.{ .Substitute, .Teleport } }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.CometPunch, P2.ident(1), null); t.expected.p2.get(1).hp -= 31; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); t.expected.p2.get(1).hp -= 31; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); t.expected.p2.get(1).hp -= 31; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.hitcount(P2.ident(1), 3); try t.log.expected.move(P2.ident(1), Move.Substitute, P2.ident(1), null); try t.log.expected.start(P2.ident(1), .Substitute); t.expected.p2.get(1).hp -= 95; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.move(P1.ident(1), Move.CometPunch, P2.ident(1), null); try t.log.expected.activate(P2.ident(1), .Substitute); try t.log.expected.activate(P2.ident(1), .Substitute); try t.log.expected.activate(P2.ident(1), .Substitute); try t.log.expected.end(P2.ident(1), .Substitute); try t.log.expected.hitcount(P2.ident(1), 4); try t.log.expected.move(P2.ident(1), Move.Teleport, P2.ident(1), null); try t.log.expected.turn(3); // Breaking a target's Substitute ends the move try expectEqual(Result.Default, try t.update(move(1), move(2))); try t.verify(); } // Move.{DoubleKick,Bonemerang} test "DoubleHit effect" { // Hits twice. Damage is calculated once for the first hit and used for both hits. If the first // hit breaks the target's substitute, the move ends. var t = Test(if (showdown) (.{ NOP, HIT, ~CRIT, MAX_DMG, NOP, HIT, ~CRIT, MAX_DMG }) else (.{ ~CRIT, MAX_DMG, HIT, ~CRIT, MAX_DMG, HIT })).init( &.{.{ .species = .Marowak, .moves = &.{.Bonemerang} }}, &.{.{ .species = .Slowpoke, .level = 80, .moves = &.{ .Substitute, .Teleport } }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Bonemerang, P2.ident(1), null); t.expected.p2.get(1).hp -= 91; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); t.expected.p2.get(1).hp -= 91; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.hitcount(P2.ident(1), 2); try t.log.expected.move(P2.ident(1), Move.Substitute, P2.ident(1), null); try t.log.expected.start(P2.ident(1), .Substitute); t.expected.p2.get(1).hp -= 77; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.move(P1.ident(1), Move.Bonemerang, P2.ident(1), null); try t.log.expected.end(P2.ident(1), .Substitute); try t.log.expected.hitcount(P2.ident(1), 1); try t.log.expected.move(P2.ident(1), Move.Teleport, P2.ident(1), null); try t.log.expected.turn(3); // Breaking a target's Substitute ends the move try expectEqual(Result.Default, try t.update(move(1), move(2))); try t.verify(); } // Move.Twineedle // test "Twineedle effect" { // // Hits twice, with the second hit having a 20% chance to poison the target. If the first hit // // breaks the target's substitute, the move ends. // const proc = comptime ranged(52, 256) - 1; // const no_proc = proc + 1; // var t = Test( // // zig fmt: off // if (showdown) .{ // NOP, HIT, CRIT, MAX_DMG, proc, proc, // NOP, HIT, ~CRIT, MIN_DMG, proc, no_proc, no_proc, // NOP, HIT, ~CRIT, MIN_DMG, no_proc, proc, proc, // NOP, HIT, ~CRIT, MIN_DMG, proc, proc, // } else .{ // // TODO // } // // zig fmt: on // ).init( // &.{.{ .species = .Beedrill, .moves = &.{.Twineedle} }}, // &.{ // .{ .species = .Voltorb, .moves = &.{ .Substitute, .Teleport } }, // .{ .species = .Electrode, .moves = &.{.Explosion} }, // .{ .species = .Weezing, .moves = &.{.Explosion} }, // }, // ); // defer t.deinit(); // t.expected.p2.get(1).hp -= 70; // try t.log.expected.move(P2.ident(1), Move.Substitute, P2.ident(1), null); // try t.log.expected.start(P2.ident(1), .Substitute); // try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); // try t.log.expected.move(P1.ident(1), Move.Twineedle, P2.ident(1), null); // try t.log.expected.crit(P2.ident(1)); // try t.log.expected.end(P2.ident(1), .Substitute); // try t.log.expected.hitcount(P2.ident(1), 1); // try t.log.expected.turn(2); // // Breaking a target's Substitute ends the move // try expectEqual(Result.Default, try t.update(move(1), move(1))); // try t.log.expected.move(P2.ident(1), Move.Teleport, P2.ident(1), null); // try t.log.expected.move(P1.ident(1), Move.Twineedle, P2.ident(1), null); // t.expected.p2.get(1).hp -= 36; // try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); // if (showdown) { // t.expected.p2.get(1).status = Status.init(.PSN); // try t.log.expected.status(P2.ident(1), Status.init(.PSN), .None); // } // t.expected.p2.get(1).hp -= 36; // try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); // try t.log.expected.hitcount(P2.ident(1), 2); // try t.log.expected.turn(3); // // On Pokémon Showdown the first hit can poison the tatget // try expectEqual(Result.Default, try t.update(move(1), move(2))); // // if (showdown) try expectEqual(t.actual.p2.get(1).status, Status.init(.PSN)); // try t.log.expected.switched(P2.ident(2), t.expected.p2.get(2)); // try t.log.expected.move(P1.ident(1), Move.Twineedle, P2.ident(2), null); // t.expected.p2.get(2).hp -= 30; // try t.log.expected.damage(P2.ident(2), t.expected.p2.get(2), .None); // t.expected.p2.get(2).hp -= 30; // try t.log.expected.damage(P2.ident(2), t.expected.p2.get(2), .None); // t.expected.p2.get(2).status = Status.init(.PSN); // try t.log.expected.status(P2.ident(2), Status.init(.PSN), .None); // try t.log.expected.hitcount(P2.ident(2), 2); // try t.log.expected.turn(4); // // The second hit can always poison the target // try expectEqual(Result.Default, try t.update(move(1), swtch(2))); // // try expectEqual(t.actual.p2.get(2).status, Status.init(.PSN)); // try t.log.expected.switched(P2.ident(3), t.expected.p2.get(3)); // try t.log.expected.move(P1.ident(1), Move.Twineedle, P2.ident(3), null); // t.expected.p2.get(3).hp -= 45; // try t.log.expected.damage(P2.ident(3), t.expected.p2.get(3), .None); // t.expected.p2.get(3).hp -= 45; // try t.log.expected.damage(P2.ident(3), t.expected.p2.get(3), .None); // try t.log.expected.hitcount(P2.ident(3), 2); // try t.log.expected.turn(5); // // Poison types cannot be poisoned // try expectEqual(Result.Default, try t.update(move(1), swtch(3))); // try t.verify(); // } // Move.Toxic // Move.{PoisonPowder,PoisonGas} test "Poison effect" { // (Badly) Poisons the target. return error.SkipZigTest; } // Move.PoisonSting // Move.{Smog,Sludge} test "PoisonChance effect" { // Has a X% chance to poison the target. return error.SkipZigTest; } // Move.{FirePunch,Ember,Flamethrower}: BurnChance1 // Move.FireBlast: BurnChance2 test "BurnChance effect" { // Has a X% chance to burn the target. return error.SkipZigTest; } // Move.{IcePunch,IceBeam,Blizzard}: FreezeChance test "FreezeChance effect" { // Has a 10% chance to freeze the target. return error.SkipZigTest; } // Move.{ThunderWave,StunSpore,Glare} test "Paralyze effect" { // Paralyzes the target. const PROC = comptime ranged(63, 256) - 1; const NO_PROC = PROC + 1; var t = Test( // zig fmt: off if (showdown) .{ NOP, NOP, ~HIT, HIT, NOP, NOP, NOP, HIT, NO_PROC, HIT, NOP, NOP, PROC, NOP, NOP, HIT, NO_PROC, HIT, NOP, NOP, NO_PROC, NOP, NO_PROC, HIT, NOP, } else .{ ~HIT, HIT, NO_PROC, HIT, PROC, NO_PROC, HIT, NO_PROC, NO_PROC, HIT, } // zig fmt: on ).init( &.{ .{ .species = .Arbok, .moves = &.{.Glare} }, .{ .species = .Dugtrio, .moves = &.{ .Earthquake, .Substitute } }, }, &.{ .{ .species = .Magneton, .moves = &.{.ThunderWave} }, .{ .species = .Gengar, .moves = &.{ .Toxic, .ThunderWave, .Glare } }, }, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Glare, P2.ident(1), null); try t.log.expected.lastmiss(); try t.log.expected.miss(P1.ident(1)); try t.log.expected.move(P2.ident(1), Move.ThunderWave, P1.ident(1), null); try t.log.expected.status(P1.ident(1), Status.init(.PAR), .None); try t.log.expected.turn(2); // Glare can miss try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.move(P2.ident(1), Move.ThunderWave, P1.ident(1), null); try t.log.expected.fail(P1.ident(1), .Paralysis); try t.log.expected.move(P1.ident(1), Move.Glare, P2.ident(1), null); try t.log.expected.status(P2.ident(1), Status.init(.PAR), .None); try t.log.expected.turn(3); // Electric-type Pokémon can be paralyzed try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.switched(P2.ident(2), t.expected.p2.get(2)); try t.log.expected.cant(P1.ident(1), .Paralysis); try t.log.expected.turn(4); // Can be fully paralyzed try expectEqual(Result.Default, try t.update(move(1), swtch(2))); try t.log.expected.move(P2.ident(2), Move.Toxic, P1.ident(1), null); try t.log.expected.fail(P1.ident(1), .None); try t.log.expected.move(P1.ident(1), Move.Glare, P2.ident(2), null); try t.log.expected.status(P2.ident(2), Status.init(.PAR), .None); try t.log.expected.turn(5); // Glare ignores type immunity try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.switched(P1.ident(2), t.expected.p1.get(2)); try t.log.expected.move(P2.ident(2), Move.ThunderWave, P1.ident(2), null); try t.log.expected.immune(P1.ident(2), .None); try t.log.expected.turn(6); // Thunder Wave does not ignore type immunity try expectEqual(Result.Default, try t.update(swtch(2), move(2))); try t.log.expected.move(P1.ident(2), Move.Substitute, P1.ident(2), null); try t.log.expected.start(P1.ident(2), .Substitute); t.expected.p1.get(2).hp -= 68; try t.log.expected.damage(P1.ident(2), t.expected.p1.get(2), .None); try t.log.expected.move(P2.ident(2), Move.Glare, P1.ident(2), null); try t.log.expected.status(P1.ident(2), Status.init(.PAR), .None); try t.log.expected.turn(7); // Primary paralysis ignores Substitute try expectEqual(Result.Default, try t.update(move(2), move(3))); // // Paralysis lowers speed try expectEqual(Status.init(.PAR), t.actual.p2.stored().status); try expectEqual(@as(u16, 79), t.actual.p2.active.stats.spe); try expectEqual(@as(u16, 318), t.actual.p2.stored().stats.spe); try t.verify(); } // Move.{ThunderPunch,ThunderShock,Thunderbolt,Thunder}: ParalyzeChance1 // Move.{BodySlam,Lick}: ParalyzeChance2 test "ParalyzeChance effect" { // Has a X% chance to paralyze the target. return error.SkipZigTest; } // Move.{Sing,SleepPowder,Hypnosis,LovelyKiss,Spore} test "Sleep effect" { // Causes the target to fall asleep. return error.SkipZigTest; } // Move.{Supersonic,ConfuseRay} test "Confusion effect" { // Causes the target to become confused. return error.SkipZigTest; } // Move.{Psybeam,Confusion}: ConfusionChance test "ConfusionChance effect" { // Has a 10% chance to confuse the target. return error.SkipZigTest; } // Move.{Bite,BoneClub,HyperFang}: FlinchChance1 // Move.{Stomp,RollingKick,Headbutt,LowKick}: FlinchChance2 test "FlinchChance effect" { // Has a X% chance to flinch the target. return error.SkipZigTest; } // Move.Growl: AttackDown1 // Move.{TailWhip,Leer}: DefenseDown1 // Move.StringShot: SpeedDown1 // Move.{SandAttack,Smokescreen,Kinesis,Flash}: AccuracyDown1 // Move.Screech: DefenseDown2 test "StatDown effect" { // Lowers the target's X by Y stage(s). var t = Test( // zig fmt: off if (showdown) .{ NOP, NOP, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, NOP, NOP, HIT, NOP, HIT, NOP, NOP, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, } else .{ ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, HIT, ~CRIT, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, } // zig fmt: on ).init( &.{.{ .species = .Ekans, .moves = &.{ .Screech, .Strength } }}, &.{.{ .species = .Caterpie, .moves = &.{ .StringShot, .Tackle } }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Strength, P2.ident(1), null); t.expected.p2.get(1).hp -= 75; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.Tackle, P1.ident(1), null); t.expected.p1.get(1).hp -= 22; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(2), move(2))); try t.log.expected.move(P1.ident(1), Move.Screech, P2.ident(1), null); try t.log.expected.unboost(P2.ident(1), .Defense, 2); try t.log.expected.move(P2.ident(1), Move.StringShot, P1.ident(1), null); try t.log.expected.unboost(P1.ident(1), .Speed, 1); try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(@as(i4, -1), t.actual.p1.active.boosts.spe); try expectEqual(@as(i4, -2), t.actual.p2.active.boosts.def); try t.log.expected.move(P2.ident(1), Move.Tackle, P1.ident(1), null); t.expected.p1.get(1).hp -= 22; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.move(P1.ident(1), Move.Strength, P2.ident(1), null); t.expected.p2.get(1).hp -= 149; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.turn(4); try expectEqual(Result.Default, try t.update(move(2), move(2))); try t.verify(); } // Move.AuroraBeam: AttackDownChance // Move.Acid: DefenseDownChance // Move.{BubbleBeam,Constrict,Bubble}: SpeedDownChance // Move.Psychic: SpecialDownChance test "StatDownChance effect" { // Has a 33% chance to lower the target's X by 1 stage. const PROC = comptime ranged(85, 256) - 1; const NO_PROC = PROC + 1; var t = Test( // zig fmt: off if (showdown) .{ NOP, NOP, HIT, ~CRIT, MIN_DMG, NO_PROC, HIT, ~CRIT, MIN_DMG, PROC, NOP, NOP, HIT, ~CRIT, MIN_DMG, NO_PROC, HIT, ~CRIT, MIN_DMG, PROC, NOP, NOP, HIT, ~CRIT, MIN_DMG, NO_PROC, HIT, ~CRIT, MIN_DMG, NO_PROC, } else .{ ~CRIT, MIN_DMG, HIT, NO_PROC, ~CRIT, MIN_DMG, HIT, PROC, ~CRIT, MIN_DMG, HIT, NO_PROC, ~CRIT, MIN_DMG, HIT, PROC, ~CRIT, MIN_DMG, HIT, NO_PROC, ~CRIT, MIN_DMG, HIT, NO_PROC, } // zig fmt: on ).init( &.{.{ .species = .Alakazam, .moves = &.{.Psychic} }}, &.{.{ .species = .Starmie, .moves = &.{.BubbleBeam} }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Psychic, P2.ident(1), null); try t.log.expected.resisted(P2.ident(1)); t.expected.p2.get(1).hp -= 60; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.BubbleBeam, P1.ident(1), null); t.expected.p1.get(1).hp -= 57; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.unboost(P1.ident(1), .Speed, 1); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(@as(i4, -1), t.actual.p1.active.boosts.spe); try t.log.expected.move(P2.ident(1), Move.BubbleBeam, P1.ident(1), null); t.expected.p1.get(1).hp -= 57; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.move(P1.ident(1), Move.Psychic, P2.ident(1), null); try t.log.expected.resisted(P2.ident(1)); t.expected.p2.get(1).hp -= 60; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.unboost(P2.ident(1), .SpecialAttack, 1); try t.log.expected.unboost(P2.ident(1), .SpecialDefense, 1); try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(@as(i4, -1), t.actual.p2.active.boosts.spc); try t.log.expected.move(P2.ident(1), Move.BubbleBeam, P1.ident(1), null); t.expected.p1.get(1).hp -= 39; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.move(P1.ident(1), Move.Psychic, P2.ident(1), null); try t.log.expected.resisted(P2.ident(1)); t.expected.p2.get(1).hp -= 91; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.turn(4); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.verify(); } // Move.{Meditate,Sharpen}: AttackUp1 // Move.{Harden,Withdraw,DefenseCurl}: DefenseUp1 // Move.Growth: SpecialUp1 // Move.{DoubleTeam,Minimize}: EvasionUp1 // Move.SwordsDance: AttackUp2 // Move.{Barrier,AcidArmor}: DefenseUp2 // Move.Agility: SpeedUp2 // Move.Amnesia: SpecialUp2 test "StatUp effect" { // Raises the target's X by Y stage(s). var t = Test( // zig fmt: off if (showdown) .{ NOP, NOP, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, NOP, NOP, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, } else .{ ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, ~CRIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, } // zig fmt: on ).init( &.{.{ .species = .Scyther, .moves = &.{ .SwordsDance, .Cut } }}, &.{.{ .species = .Slowbro, .moves = &.{ .Withdraw, .WaterGun } }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Cut, P2.ident(1), null); t.expected.p2.get(1).hp -= 37; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.WaterGun, P1.ident(1), null); t.expected.p1.get(1).hp -= 54; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(2), move(2))); try t.log.expected.move(P1.ident(1), Move.SwordsDance, P1.ident(1), null); try t.log.expected.boost(P1.ident(1), .Attack, 2); try t.log.expected.move(P2.ident(1), Move.Withdraw, P2.ident(1), null); try t.log.expected.boost(P2.ident(1), .Defense, 1); try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(@as(i4, 2), t.actual.p1.active.boosts.atk); try expectEqual(@as(i4, 1), t.actual.p2.active.boosts.def); try t.log.expected.move(P1.ident(1), Move.Cut, P2.ident(1), null); t.expected.p2.get(1).hp -= 49; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.WaterGun, P1.ident(1), null); t.expected.p1.get(1).hp -= 54; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.turn(4); try expectEqual(Result.Default, try t.update(move(2), move(2))); try t.verify(); } // Move.{Guillotine,HornDrill,Fissure} test "OHKO effect" { // Deals 65535 damage to the target. Fails if the target's Speed is greater than the user's. var t = Test(if (showdown) (.{ NOP, NOP, ~HIT, NOP, NOP, HIT }) else (.{ ~CRIT, MIN_DMG, ~HIT, ~CRIT, MIN_DMG, ~CRIT, MIN_DMG, HIT })).init( &.{ .{ .species = .Kingler, .moves = &.{.Guillotine} }, .{ .species = .Tauros, .moves = &.{.HornDrill} }, }, &.{.{ .species = .Dugtrio, .moves = &.{.Fissure} }}, ); defer t.deinit(); try t.log.expected.move(P2.ident(1), Move.Fissure, P1.ident(1), null); try t.log.expected.lastmiss(); try t.log.expected.miss(P2.ident(1)); try t.log.expected.move(P1.ident(1), Move.Guillotine, P2.ident(1), null); try t.log.expected.immune(P2.ident(1), .OHKO); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.move(P2.ident(1), Move.Fissure, P1.ident(1), null); t.expected.p1.get(1).hp = 0; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.ohko(); try t.log.expected.faint(P1.ident(1), true); try expectEqual(Result{ .p1 = .Switch, .p2 = .Pass }, try t.update(move(1), move(1))); try t.verify(); } // Move.{RazorWind,SolarBeam,SkullBash,SkyAttack} test "Charge effect" { // This attack charges on the first turn and executes on the second. return error.SkipZigTest; } // Move.{Fly,Dig} test "Fly / Dig effect" { // This attack charges on the first turn and executes on the second. On the first turn, the user // avoids all attacks other than Bide, Swift, and Transform. If the user is fully paralyzed on // the second turn, it continues avoiding attacks until it switches out or successfully executes // the second turn of this move or {Fly,Dig}. return error.SkipZigTest; } // Move.{Whirlwind,Roar,Teleport} test "SwitchAndTeleport effect" { // No competitive use. var t = Test(if (showdown) .{ NOP, HIT, NOP, ~HIT } else .{}).init( &.{.{ .species = .Abra, .moves = &.{.Teleport} }}, &.{.{ .species = .Pidgey, .moves = &.{.Whirlwind} }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Teleport, P1.ident(1), null); try t.log.expected.move(P2.ident(1), Move.Whirlwind, P1.ident(1), null); try t.log.expected.turn(2); try t.log.expected.move(P1.ident(1), Move.Teleport, P1.ident(1), null); try t.log.expected.move(P2.ident(1), Move.Whirlwind, P1.ident(1), null); if (showdown) { try t.log.expected.lastmiss(); try t.log.expected.miss(P2.ident(1)); } try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.verify(); } // Move.Splash test "Splash effect" { // No competitive use. var t = Test(.{}).init( &.{.{ .species = .Gyarados, .moves = &.{.Splash} }}, &.{.{ .species = .Magikarp, .moves = &.{.Splash} }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Splash, P1.ident(1), null); try t.log.expected.activate(P1.ident(1), .Splash); try t.log.expected.move(P2.ident(1), Move.Splash, P2.ident(1), null); try t.log.expected.activate(P2.ident(1), .Splash); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.verify(); } // Move.{Bind,Wrap,FireSpin,Clamp} test "Trapping effect" { // The user spends two to five turns using this move. Has a 3/8 chance to last two or three // turns, and a 1/8 chance to last four or five turns. The damage calculated for the first turn // is used for every other turn. The user cannot select a move and the target cannot execute a // move during the effect, but both may switch out. If the user switches out, the target remains // unable to execute a move during that turn. If the target switches out, the user uses this // move again automatically, and if it had 0 PP at the time, it becomes 63. If the user or the // target switch out, or the user is prevented from moving, the effect ends. This move can // prevent the target from moving even if it has type immunity, but will not deal damage. return error.SkipZigTest; } // Move.{JumpKick,HighJumpKick} test "JumpKick effect" { // If this attack misses the target, the user takes 1 HP of crash damage. If the user has a // substitute, the crash damage is dealt to the target's substitute if it has one, otherwise no // crash damage is dealt. var t = Test( // zig fmt: off if (showdown) .{ NOP, NOP, ~HIT, HIT, CRIT, MAX_DMG, NOP, NOP, ~HIT, ~HIT, } else .{ ~CRIT, MIN_DMG, ~HIT, CRIT, MAX_DMG, HIT, ~CRIT, MIN_DMG, ~HIT, ~CRIT, MIN_DMG, ~HIT, } // zig fmt: on ).init( &.{.{ .species = .Hitmonlee, .moves = &.{ .JumpKick, .Substitute } }}, &.{.{ .species = .Hitmonlee, .level = 99, .moves = &.{ .HighJumpKick, .Substitute } }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Substitute, P1.ident(1), null); try t.log.expected.start(P1.ident(1), .Substitute); t.expected.p1.get(1).hp -= 75; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.move(P2.ident(1), Move.Substitute, P2.ident(1), null); try t.log.expected.start(P2.ident(1), .Substitute); t.expected.p2.get(1).hp -= 75; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(2), move(2))); try t.log.expected.move(P1.ident(1), Move.JumpKick, P2.ident(1), null); try t.log.expected.lastmiss(); try t.log.expected.miss(P1.ident(1)); try t.log.expected.activate(P2.ident(1), .Substitute); try t.log.expected.move(P2.ident(1), Move.HighJumpKick, P1.ident(1), null); try t.log.expected.crit(P1.ident(1)); try t.log.expected.end(P1.ident(1), .Substitute); try t.log.expected.turn(3); // Jump Kick causes crash damage to the opponent's sub if both Pokémon have one try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.move(P1.ident(1), Move.JumpKick, P2.ident(1), null); try t.log.expected.lastmiss(); try t.log.expected.miss(P1.ident(1)); t.expected.p1.get(1).hp -= 1; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.move(P2.ident(1), Move.HighJumpKick, P1.ident(1), null); try t.log.expected.lastmiss(); try t.log.expected.miss(P2.ident(1)); try t.log.expected.turn(4); // Jump Kick causes 1 HP crash damage unless only the user who crashed has a Substitute try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.verify(); } // Move.{TakeDown,DoubleEdge,Submission} test "Recoil effect" { // If the target lost HP, the user takes recoil damage equal to 1/4 the HP lost by the target, // rounded down, but not less than 1 HP. If this move breaks the target's substitute, the user // does not take any recoil damage. var t = Test(if (showdown) (.{ NOP, HIT, ~CRIT, MIN_DMG, NOP, HIT, ~CRIT, MAX_DMG, NOP, HIT, ~CRIT, MIN_DMG }) else (.{ ~CRIT, MIN_DMG, HIT, ~CRIT, MAX_DMG, HIT, ~CRIT, MIN_DMG, HIT })).init( &.{ .{ .species = .Slowpoke, .hp = 1, .moves = &.{.Teleport} }, .{ .species = .Rhydon, .moves = &.{ .TakeDown, .Teleport } }, }, &.{.{ .species = .Tauros, .moves = &.{ .DoubleEdge, .Substitute } }}, ); defer t.deinit(); try t.log.expected.move(P2.ident(1), Move.DoubleEdge, P1.ident(1), null); t.expected.p1.get(1).hp -= 1; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); t.expected.p2.get(1).hp -= 1; try t.log.expected.damageOf(P2.ident(1), t.expected.p2.get(1), .RecoilOf, P1.ident(1)); try t.log.expected.faint(P1.ident(1), true); // Recoil inflicts at least 1 HP try expectEqual(Result{ .p1 = .Switch, .p2 = .Pass }, try t.update(move(1), move(1))); try t.log.expected.switched(P1.ident(2), t.expected.p1.get(2)); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(swtch(2), .{})); try t.log.expected.move(P2.ident(1), Move.Substitute, P2.ident(1), null); try t.log.expected.start(P2.ident(1), .Substitute); t.expected.p2.get(1).hp -= 88; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P1.ident(2), Move.TakeDown, P2.ident(1), null); try t.log.expected.end(P2.ident(1), .Substitute); try t.log.expected.turn(3); // Deals no damage if the move breaks the target's Substitute try expectEqual(Result.Default, try t.update(move(1), move(2))); try t.log.expected.move(P2.ident(1), Move.DoubleEdge, P1.ident(2), null); try t.log.expected.resisted(P1.ident(2)); t.expected.p1.get(2).hp -= 48; try t.log.expected.damage(P1.ident(2), t.expected.p1.get(2), .None); t.expected.p2.get(1).hp -= 12; try t.log.expected.damageOf(P2.ident(1), t.expected.p2.get(1), .RecoilOf, P1.ident(2)); try t.log.expected.move(P1.ident(2), Move.Teleport, P1.ident(2), null); try t.log.expected.turn(4); // Inflicts 1/4 of damage dealt to user as recoil try expectEqual(Result.Default, try t.update(move(2), move(1))); try t.verify(); } // Move.Struggle test "Struggle effect" { // Deals Normal-type damage. If this move was successful, the user takes damage equal to 1/2 the // HP lost by the target, rounded down, but not less than 1 HP. This move is automatically used // if none of the user's known moves can be selected. var t = Test( // zig fmt: off if (showdown) .{ NOP, NOP, HIT, ~CRIT, MIN_DMG, NOP, NOP, HIT, ~CRIT, MIN_DMG, NOP, NOP, HIT, ~CRIT, MIN_DMG, } else .{ ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, } // zig fmt: on ).init( &.{ .{ .species = .Abra, .hp = 64, .moves = &.{ .Substitute, .Teleport } }, .{ .species = .Golem, .moves = &.{.Harden} }, }, &.{.{ .species = .Arcanine, .moves = &.{.Teleport} }}, ); defer t.deinit(); t.actual.p2.get(1).move(1).pp = 1; try t.log.expected.move(P2.ident(1), Move.Teleport, P2.ident(1), null); try t.log.expected.move(P1.ident(1), Move.Substitute, P1.ident(1), null); try t.log.expected.start(P1.ident(1), .Substitute); t.expected.p1.get(1).hp -= 63; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.turn(2); // Struggle only becomes an option if the user has no PP left try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(@as(u8, 0), t.actual.p2.get(1).move(1).pp); const n = t.battle.actual.choices(.P2, .Move, &choices); try expectEqualSlices(Choice, &[_]Choice{move(0)}, choices[0..n]); try t.log.expected.move(P2.ident(1), Move.Struggle, P1.ident(1), null); try t.log.expected.end(P1.ident(1), .Substitute); try t.log.expected.move(P1.ident(1), Move.Teleport, P1.ident(1), null); try t.log.expected.turn(3); // Deals no recoil damage if the move breaks the target's Substitute try expectEqual(Result.Default, try t.update(move(2), move(0))); try t.log.expected.move(P2.ident(1), Move.Struggle, P1.ident(1), null); t.expected.p1.get(1).hp -= 1; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); t.expected.p2.get(1).hp -= 1; try t.log.expected.damageOf(P2.ident(1), t.expected.p2.get(1), .RecoilOf, P1.ident(1)); try t.log.expected.faint(P1.ident(1), true); // Struggle recoil inflicts at least 1 HP try expectEqual(Result{ .p1 = .Switch, .p2 = .Pass }, try t.update(move(2), move(0))); try t.log.expected.switched(P1.ident(2), t.expected.p1.get(2)); try t.log.expected.turn(4); try expectEqual(Result.Default, try t.update(swtch(2), .{})); try t.log.expected.move(P2.ident(1), Move.Struggle, P1.ident(2), null); try t.log.expected.resisted(P1.ident(2)); t.expected.p1.get(2).hp -= 16; try t.log.expected.damage(P1.ident(2), t.expected.p1.get(2), .None); t.expected.p2.get(1).hp -= 8; try t.log.expected.damageOf(P2.ident(1), t.expected.p2.get(1), .RecoilOf, P1.ident(2)); try t.log.expected.move(P1.ident(2), Move.Harden, P1.ident(2), null); try t.log.expected.boost(P1.ident(2), .Defense, 1); try t.log.expected.turn(5); // Respects type effectiveness and inflicts 1/2 of damage dealt to user as recoil try expectEqual(Result.Default, try t.update(move(1), move(0))); try t.verify(); } // Move.{Thrash,PetalDance} test "Thrashing effect" { // Whether or not this move is successful, the user spends three or four turns locked into this // move and becomes confused immediately after its move on the last turn of the effect, even if // it is already confused. If the user is prevented from moving, the effect ends without causing // confusion. During the effect, this move's accuracy is overwritten every turn with the current // calculated accuracy including stat stage changes, but not to less than 1/256 or more than // 255/256. return error.SkipZigTest; } // Move.{SonicBoom,DragonRage} test "FixedDamage effect" { // Deals X HP of damage to the target. This move ignores type immunity. var t = Test(if (showdown) .{ NOP, NOP, HIT, HIT, NOP } else .{ HIT, HIT, HIT }).init( &.{.{ .species = .Voltorb, .moves = &.{.SonicBoom} }}, &.{ .{ .species = .Dratini, .moves = &.{.DragonRage} }, .{ .species = .Gastly, .moves = &.{.NightShade} }, }, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.SonicBoom, P2.ident(1), null); t.expected.p2.get(1).hp -= 20; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.DragonRage, P1.ident(1), null); t.expected.p1.get(1).hp -= 40; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.switched(P2.ident(2), t.expected.p2.get(2)); try t.log.expected.move(P1.ident(1), Move.SonicBoom, P2.ident(2), null); if (showdown) { try t.log.expected.immune(P2.ident(2), .None); } else { t.expected.p2.get(2).hp -= 20; try t.log.expected.damage(P2.ident(2), t.expected.p2.get(2), .None); } try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(1), swtch(2))); try t.verify(); } // Move.{SeismicToss,NightShade} test "LevelDamage effect" { // Deals damage to the target equal to the user's level. This move ignores type immunity. var t = Test((if (showdown) .{ NOP, NOP, HIT, HIT } else .{ HIT, HIT })).init( &.{.{ .species = .Gastly, .level = 22, .moves = &.{.NightShade} }}, &.{.{ .species = .Clefairy, .level = 16, .moves = &.{.SeismicToss} }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.NightShade, P2.ident(1), null); t.expected.p2.get(1).hp -= 22; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.SeismicToss, P1.ident(1), null); t.expected.p1.get(1).hp -= 16; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.verify(); } // Move.Psywave test "Psywave effect" { // Deals damage to the target equal to a random number from 1 to (user's level * 1.5 - 1), // rounded down, but not less than 1 HP. var t = Test((if (showdown) (.{ NOP, NOP, HIT, MAX_DMG, HIT, MIN_DMG }) else (.{ HIT, 88, 87, HIT, 255, 0 }))).init( &.{.{ .species = .Gengar, .level = 59, .moves = &.{.Psywave} }}, &.{.{ .species = .Clefable, .level = 42, .moves = &.{.Psywave} }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Psywave, P2.ident(1), null); t.expected.p2.get(1).hp -= 87; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.Psywave, P1.ident(1), null); // https://pkmn.cc/bulba-glitch-1#Psywave_desynchronization // https://glitchcity.wiki/Psywave_desync_glitch const result = if (showdown) Result.Default else Result.Error; if (showdown) try t.log.expected.turn(2); try expectEqual(result, try t.update(move(1), move(1))); try t.verify(); } // Move.SuperFang test "SuperFang effect" { // Deals damage to the target equal to half of its current HP, rounded down, but not less than 1 // HP. This move ignores type immunity. var t = Test((if (showdown) (.{ NOP, NOP, HIT, HIT, NOP, NOP, HIT }) else (.{ HIT, HIT, ~CRIT, MIN_DMG, HIT }))).init( &.{ .{ .species = .Raticate, .hp = 1, .moves = &.{.SuperFang} }, .{ .species = .Haunter, .moves = &.{.DreamEater} }, }, &.{.{ .species = .Rattata, .moves = &.{.SuperFang} }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.SuperFang, P2.ident(1), null); t.expected.p2.get(1).hp -= 131; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.SuperFang, P1.ident(1), null); t.expected.p1.get(1).hp -= 1; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.faint(P1.ident(1), true); try expectEqual(Result{ .p1 = .Switch, .p2 = .Pass }, try t.update(move(1), move(1))); try t.log.expected.switched(P1.ident(2), t.expected.p1.get(2)); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(swtch(2), .{})); try t.log.expected.move(P1.ident(2), Move.DreamEater, P2.ident(1), null); try t.log.expected.immune(P2.ident(1), .None); try t.log.expected.move(P2.ident(1), Move.SuperFang, P1.ident(2), null); t.expected.p1.get(2).hp -= 146; try t.log.expected.damage(P1.ident(2), t.expected.p1.get(2), .None); try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.verify(); } // Move.Disable test "Disable effect" { // For 0 to 7 turns, one of the target's known moves that has at least 1 PP remaining becomes // disabled, at random. Fails if one of the target's moves is already disabled, or if none of // the target's moves have PP remaining. If any Pokemon uses Haze, this effect ends. Whether or // not this move was successful, it counts as a hit for the purposes of the opponent's use of // Rage. return error.SkipZigTest; } // Move.Mist test "Mist effect" { // While the user remains active, it is protected from having its stat stages lowered by other // Pokemon, unless caused by the secondary effect of a move. Fails if the user already has the // effect. If any Pokemon uses Haze, this effect ends. const PROC = comptime ranged(85, 256) - 1; var t = Test( // zig fmt: off if (showdown) .{ NOP, HIT, ~CRIT, MIN_DMG, PROC, NOP, NOP, HIT, ~CRIT, MIN_DMG, NOP, HIT, NOP, HIT, ~CRIT, MIN_DMG, NOP, NOP, HIT, ~CRIT, MIN_DMG, NOP, HIT, } else .{ ~CRIT, MIN_DMG, HIT, PROC, ~CRIT, MIN_DMG, HIT, ~CRIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, HIT, } // zig fmt: on ).init( &.{.{ .species = .Articuno, .moves = &.{ .Mist, .Peck } }}, &.{.{ .species = .Vaporeon, .moves = &.{ .AuroraBeam, .Growl, .Haze } }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Mist, P1.ident(1), null); try t.log.expected.start(P1.ident(1), .Mist); try t.log.expected.move(P2.ident(1), Move.AuroraBeam, P1.ident(1), null); t.expected.p1.get(1).hp -= if (showdown) 43 else 42; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.unboost(P1.ident(1), .Attack, 1); try t.log.expected.turn(2); // Mist doesn't protect against secondary effects try expectEqual(Result.Default, try t.update(move(1), move(1))); try expect(t.actual.p1.active.volatiles.Mist); try expectEqual(@as(i4, -1), t.actual.p1.active.boosts.atk); try t.log.expected.move(P1.ident(1), Move.Peck, P2.ident(1), null); t.expected.p2.get(1).hp -= 31; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.Growl, P1.ident(1), null); try t.log.expected.activate(P1.ident(1), .Mist); try t.log.expected.fail(P1.ident(1), .None); try t.log.expected.turn(3); // Mist does protect against primary stat lowering effects try expectEqual(Result.Default, try t.update(move(2), move(2))); try expectEqual(@as(i4, -1), t.actual.p1.active.boosts.atk); try t.log.expected.move(P1.ident(1), Move.Peck, P2.ident(1), null); t.expected.p2.get(1).hp -= 31; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.Haze, P2.ident(1), null); try t.log.expected.activate(P2.ident(1), .Haze); try t.log.expected.clearallboost(); try t.log.expected.end(P1.ident(1), .Mist); try t.log.expected.turn(4); try expectEqual(Result.Default, try t.update(move(2), move(3))); try t.log.expected.move(P1.ident(1), Move.Peck, P2.ident(1), null); t.expected.p2.get(1).hp -= 48; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.Growl, P1.ident(1), null); try t.log.expected.unboost(P1.ident(1), .Attack, 1); try t.log.expected.turn(5); // Haze ends Mist's effect try expectEqual(Result.Default, try t.update(move(2), move(2))); try expect(!t.actual.p1.active.volatiles.Mist); try expectEqual(@as(i4, -1), t.actual.p1.active.boosts.atk); try t.verify(); } // Move.HyperBeam test "HyperBeam effect" { // If this move is successful, the user must recharge on the following turn and cannot select a // move, unless the target or its substitute was knocked out by this move. return error.SkipZigTest; } // Move.Counter test "Counter effect" { // Deals damage to the opposing Pokemon equal to twice the damage dealt by the last move used in // the battle. This move ignores type immunity. Fails if the user moves first, or if the // opposing side's last move was Counter, had 0 power, or was not Normal or Fighting type. Fails // if the last move used by either side did 0 damage and was not Confuse Ray, Conversion, Focus // Energy, Glare, Haze, Leech Seed, Light Screen, Mimic, Mist, Poison Gas, Poison Powder, // Recover, Reflect, Rest, Soft-Boiled, Splash, Stun Spore, Substitute, Supersonic, Teleport, // Thunder Wave, Toxic, or Transform. return error.SkipZigTest; } // Move.{Recover,SoftBoiled} test "Heal effect" { // The user restores 1/2 of its maximum HP, rounded down. Fails if (user's maximum HP - user's // current HP + 1) is divisible by 256. // https://pkmn.cc/bulba-glitch-1#HP_re covery_move_failure var t = Test((if (showdown) (.{ NOP, NOP, HIT, CRIT, MAX_DMG, HIT, ~CRIT, MIN_DMG }) else (.{ CRIT, MAX_DMG, HIT, ~CRIT, MIN_DMG, HIT }))).init( &.{.{ .species = .Alakazam, .moves = &.{ .Recover, .MegaKick } }}, &.{.{ .species = .Chansey, .hp = 448, .moves = &.{ .SoftBoiled, .MegaPunch } }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Recover, P1.ident(1), null); try t.log.expected.fail(P1.ident(1), .None); try t.log.expected.move(P2.ident(1), Move.SoftBoiled, P2.ident(1), null); try t.log.expected.fail(P2.ident(1), .None); try t.log.expected.turn(2); // Fails at full health or at specific fractions try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.move(P1.ident(1), Move.MegaKick, P2.ident(1), null); try t.log.expected.crit(P2.ident(1)); t.expected.p2.get(1).hp -= 362; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.MegaPunch, P1.ident(1), null); t.expected.p1.get(1).hp -= 51; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(2), move(2))); try t.log.expected.move(P1.ident(1), Move.Recover, P1.ident(1), null); t.expected.p1.get(1).hp += 51; try t.log.expected.heal(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.move(P2.ident(1), Move.SoftBoiled, P2.ident(1), null); t.expected.p2.get(1).hp += 351; try t.log.expected.heal(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.turn(4); // Heals 1/2 of maximum HP try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.verify(); } // Move.Rest test "Rest effect" { // The user falls asleep for the next two turns and restores all of its HP, curing itself of any // non-volatile status condition in the process. This does not remove the user's stat penalty // for burn or paralysis. Fails if the user has full HP. // https://pkmn.cc/bulba-glitch-1#HP_recovery_move_failure const PROC = comptime ranged(63, 256) - 1; const NO_PROC = PROC + 1; var t = Test( // zig fmt: off if (showdown) .{ NOP, HIT, NOP, NOP, HIT, ~CRIT, MIN_DMG, NO_PROC, NOP, MAX, NOP, HIT, ~CRIT, MIN_DMG, } else .{ HIT, ~CRIT, MIN_DMG, HIT, NO_PROC, ~CRIT, MIN_DMG, HIT } // zig fmt: on ).init( &.{ .{ .species = .Porygon, .moves = &.{ .ThunderWave, .Tackle, .Rest } }, .{ .species = .Dragonair, .moves = &.{.Slam} }, }, &.{ .{ .species = .Chansey, .hp = 192, .moves = &.{ .Rest, .Teleport } }, .{ .species = .Jynx, .moves = &.{.Hypnosis} }, }, ); defer t.deinit(); try t.log.expected.move(P2.ident(1), Move.Rest, P2.ident(1), null); try t.log.expected.fail(P2.ident(1), .None); try t.log.expected.move(P1.ident(1), Move.ThunderWave, P2.ident(1), null); t.expected.p2.get(1).status = Status.init(.PAR); try t.log.expected.status(P2.ident(1), Status.init(.PAR), .None); try t.log.expected.turn(2); // Fails at specific fractions try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(Status.init(.PAR), t.actual.p2.get(1).status); try expectEqual(@as(u16, 49), t.actual.p2.active.stats.spe); try expectEqual(@as(u16, 198), t.actual.p2.get(1).stats.spe); try t.log.expected.move(P1.ident(1), Move.Tackle, P2.ident(1), null); t.expected.p2.get(1).hp -= 77; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.Rest, P2.ident(1), null); t.expected.p2.get(1).hp += 588; t.expected.p2.get(1).status = Status.slf(2); try t.log.expected.statusFrom(P2.ident(1), Status.slf(2), Move.Rest); try t.log.expected.heal(P2.ident(1), t.expected.p2.get(1), .Silent); try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(2), move(1))); try expectEqual(Status.slf(2), t.actual.p2.get(1).status); var n = t.battle.actual.choices(.P1, .Move, &choices); try expectEqualSlices(Choice, &[_]Choice{ swtch(2), move(1), move(2), move(3) }, choices[0..n]); n = t.battle.actual.choices(.P2, .Move, &choices); if (showdown) { try expectEqualSlices(Choice, &[_]Choice{ swtch(2), move(1), move(2) }, choices[0..n]); } else { try expectEqualSlices(Choice, &[_]Choice{ swtch(2), move(0) }, choices[0..n]); } try t.log.expected.move(P1.ident(1), Move.Tackle, P2.ident(1), null); t.expected.p2.get(1).hp -= 77; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); t.expected.p2.get(1).status -= 1; try t.log.expected.cant(P2.ident(1), .Sleep); try t.log.expected.turn(4); try expectEqual(Result.Default, try t.update(move(2), move(1))); try t.log.expected.move(P1.ident(1), Move.Rest, P1.ident(1), null); try t.log.expected.fail(P1.ident(1), .None); t.expected.p2.get(1).status = 0; try t.log.expected.curestatus(P2.ident(1), Status.slf(1), .Message); try t.log.expected.turn(5); // Fails at full HP / Last two turns but stat penalty still remains after waking try expectEqual(Result.Default, try t.update(move(3), move(1))); try expectEqual(@as(u8, 0), t.actual.p2.get(1).status); try expectEqual(@as(u16, 49), t.actual.p2.active.stats.spe); try expectEqual(@as(u16, 198), t.actual.p2.get(1).stats.spe); try t.verify(); } // Move.{Absorb,MegaDrain,LeechLife} test "DrainHP effect" { // The user recovers 1/2 the HP lost by the target, rounded down. var t = Test((if (showdown) (.{ NOP, HIT, ~CRIT, MIN_DMG, NOP, NOP, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG }) else (.{ ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT }))).init( &.{ .{ .species = .Slowpoke, .hp = 1, .moves = &.{.Teleport} }, .{ .species = .Butterfree, .moves = &.{.MegaDrain} }, }, &.{.{ .species = .Parasect, .hp = 300, .moves = &.{.LeechLife} }}, ); defer t.deinit(); try t.log.expected.move(P2.ident(1), Move.LeechLife, P1.ident(1), null); try t.log.expected.supereffective(P1.ident(1)); t.expected.p1.get(1).hp -= 1; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); t.expected.p2.get(1).hp += 1; try t.log.expected.drain(P2.ident(1), t.expected.p2.get(1), P1.ident(1)); try t.log.expected.faint(P1.ident(1), true); // Heals at least 1 HP try expectEqual(Result{ .p1 = .Switch, .p2 = .Pass }, try t.update(move(1), move(1))); try t.log.expected.switched(P1.ident(2), t.expected.p1.get(2)); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(swtch(2), .{})); try t.log.expected.move(P1.ident(2), Move.MegaDrain, P2.ident(1), null); try t.log.expected.resisted(P2.ident(1)); t.expected.p2.get(1).hp -= 6; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P2.ident(1), Move.LeechLife, P1.ident(2), null); try t.log.expected.resisted(P1.ident(2)); t.expected.p1.get(2).hp -= 16; try t.log.expected.damage(P1.ident(2), t.expected.p1.get(2), .None); t.expected.p2.get(1).hp += 8; try t.log.expected.drain(P2.ident(1), t.expected.p2.get(1), P1.ident(2)); try t.log.expected.turn(3); // Heals 1/2 of the damage dealt unless the user is at full health try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.verify(); } // Move.DreamEater test "DreamEater effect" { // The target is unaffected by this move unless it is asleep. The user recovers 1/2 the HP lost // by the target, rounded down, but not less than 1 HP. If this move breaks the target's // substitute, the user does not recover any HP. var t = Test((if (showdown) (.{ NOP, NOP, HIT, NOP, MAX, NOP, HIT, ~CRIT, MIN_DMG, NOP, HIT, ~CRIT, MIN_DMG }) else (.{ ~CRIT, MIN_DMG, ~CRIT, HIT, MAX, ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT }))).init( &.{.{ .species = .Hypno, .hp = 100, .moves = &.{ .DreamEater, .Hypnosis } }}, &.{.{ .species = .Wigglytuff, .hp = 182, .moves = &.{.Teleport} }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.DreamEater, P2.ident(1), null); try t.log.expected.immune(P2.ident(1), .None); try t.log.expected.move(P2.ident(1), Move.Teleport, P2.ident(1), null); try t.log.expected.turn(2); // Fails unless the target is sleeping try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.move(P1.ident(1), Move.Hypnosis, P2.ident(1), null); t.expected.p2.get(1).status = Status.slp(7); try t.log.expected.statusFrom(P2.ident(1), t.expected.p2.get(1).status, Move.Hypnosis); try t.log.expected.cant(P2.ident(1), .Sleep); try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(2), move(1))); try t.log.expected.move(P1.ident(1), Move.DreamEater, P2.ident(1), null); t.expected.p2.get(1).hp -= 181; t.expected.p2.get(1).status -= 1; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); t.expected.p1.get(1).hp += 90; try t.log.expected.drain(P1.ident(1), t.expected.p1.get(1), P2.ident(1)); try t.log.expected.cant(P2.ident(1), .Sleep); try t.log.expected.turn(4); // Heals 1/2 of the damage dealt try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.move(P1.ident(1), Move.DreamEater, P2.ident(1), null); t.expected.p2.get(1).hp -= 1; t.expected.p2.get(1).status -= 1; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); t.expected.p1.get(1).hp += 1; try t.log.expected.drain(P1.ident(1), t.expected.p1.get(1), P2.ident(1)); try t.log.expected.faint(P2.ident(1), false); try t.log.expected.win(.P1); // Heals at least 1 HP try expectEqual(Result.Win, try t.update(move(1), move(1))); try t.verify(); } // Move.LeechSeed test "LeechSeed effect" { // At the end of each of the target's turns, The Pokemon at the user's position steals 1/16 of // the target's maximum HP, rounded down and multiplied by the target's current Toxic counter if // it has one, even if the target currently has less than that amount of HP remaining. If the // target switches out or any Pokemon uses Haze, this effect ends. Grass-type Pokemon are immune // to this move. var t = Test((if (showdown) (.{ NOP, NOP, ~HIT, NOP, HIT, NOP, NOP, HIT, HIT, NOP, HIT }) else (.{ HIT, ~HIT, HIT, HIT, HIT, HIT }))).init( &.{ .{ .species = .Venusaur, .moves = &.{.LeechSeed} }, .{ .species = .Exeggutor, .moves = &.{ .LeechSeed, .Teleport } }, }, &.{ .{ .species = .Gengar, .moves = &.{ .LeechSeed, .Substitute, .NightShade } }, .{ .species = .Slowbro, .hp = 1, .moves = &.{.Teleport} }, }, ); defer t.deinit(); try t.log.expected.move(P2.ident(1), Move.LeechSeed, P1.ident(1), null); if (showdown) { try t.log.expected.immune(P1.ident(1), .None); } else { try t.log.expected.lastmiss(); try t.log.expected.miss(P2.ident(1)); } try t.log.expected.move(P1.ident(1), Move.LeechSeed, P2.ident(1), null); try t.log.expected.lastmiss(); try t.log.expected.miss(P1.ident(1)); try t.log.expected.turn(2); // Leed Seed can miss / Grass-type Pokémon are immune try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.move(P2.ident(1), Move.Substitute, P2.ident(1), null); try t.log.expected.start(P2.ident(1), .Substitute); t.expected.p2.get(1).hp -= 80; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P1.ident(1), Move.LeechSeed, P2.ident(1), null); try t.log.expected.start(P2.ident(1), .LeechSeed); try t.log.expected.turn(3); // Leech Seed ignores Substitute try expectEqual(Result.Default, try t.update(move(1), move(2))); try t.log.expected.switched(P1.ident(2), t.expected.p1.get(2)); try t.log.expected.move(P2.ident(1), Move.Substitute, P2.ident(1), null); try t.log.expected.fail(P2.ident(1), .Substitute); t.expected.p2.get(1).hp -= 20; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .LeechSeed); try t.log.expected.turn(4); // Leech Seed does not |-heal| when at full health try expectEqual(Result.Default, try t.update(swtch(2), move(2))); try t.log.expected.move(P2.ident(1), Move.NightShade, P1.ident(2), null); t.expected.p1.get(2).hp -= 100; try t.log.expected.damage(P1.ident(2), t.expected.p1.get(2), .None); t.expected.p2.get(1).hp -= 20; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .LeechSeed); t.expected.p1.get(2).hp += 20; try t.log.expected.heal(P1.ident(2), t.expected.p1.get(2), .Silent); try t.log.expected.move(P1.ident(2), Move.LeechSeed, P2.ident(1), null); if (!showdown) { try t.log.expected.lastmiss(); try t.log.expected.miss(P1.ident(2)); } try t.log.expected.turn(5); // Leech Seed fails if already seeded / heals back damage try expectEqual(Result.Default, try t.update(move(1), move(3))); try t.log.expected.switched(P2.ident(2), t.expected.p2.get(2)); try t.log.expected.move(P1.ident(2), Move.LeechSeed, P2.ident(2), null); try t.log.expected.start(P2.ident(2), .LeechSeed); try t.log.expected.turn(6); // Switching breaks Leech Seed try expectEqual(Result.Default, try t.update(move(1), swtch(2))); try t.log.expected.move(P1.ident(2), Move.Teleport, P1.ident(2), null); try t.log.expected.move(P2.ident(2), Move.Teleport, P2.ident(2), null); t.expected.p2.get(2).hp = 0; try t.log.expected.damage(P2.ident(2), t.expected.p2.get(2), .LeechSeed); t.expected.p1.get(2).hp += 24; try t.log.expected.heal(P1.ident(2), t.expected.p1.get(2), .Silent); try t.log.expected.faint(P2.ident(2), true); // // Leech Seed's uncapped damage is added back try expectEqual(Result{ .p1 = .Pass, .p2 = .Switch }, try t.update(move(2), move(1))); try t.verify(); } // Move.PayDay test "PayDay effect" { // "Scatters coins" return error.SkipZigTest; } // Move.Rage test "Rage effect" { // Once this move is successfully used, the user automatically uses this move every turn and can // no longer switch out. During the effect, the user's Attack is raised by 1 stage every time it // is hit by the opposing Pokemon, and this move's accuracy is overwritten every turn with the // current calculated accuracy including stat stage changes, but not to less than 1/256 or more // than 255/256. return error.SkipZigTest; } // Move.Mimic test "Mimic effect" { // While the user remains active, this move is replaced by a random move known by the target, // even if the user already knows that move. The copied move keeps the remaining PP for this // move, regardless of the copied move's maximum PP. Whenever one PP is used for a copied move, // one PP is used for this move. return error.SkipZigTest; } // Move.LightScreen test "LightScreen effect" { // While the user remains active, its Special is doubled when taking damage. Critical hits // ignore this effect. If any Pokemon uses Haze, this effect ends. var t = Test((if (showdown) (.{ NOP, HIT, ~CRIT, MIN_DMG, NOP, HIT, ~CRIT, MIN_DMG, NOP, HIT, CRIT, MIN_DMG }) else (.{ ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, CRIT, MIN_DMG, HIT }))).init( &.{.{ .species = .Chansey, .moves = &.{ .LightScreen, .Teleport } }}, &.{.{ .species = .Vaporeon, .moves = &.{ .WaterGun, .Haze } }}, ); defer t.deinit(); try t.log.expected.move(P2.ident(1), Move.WaterGun, P1.ident(1), null); t.expected.p1.get(1).hp -= 45; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.move(P1.ident(1), Move.LightScreen, P1.ident(1), null); try t.log.expected.start(P1.ident(1), .LightScreen); try t.log.expected.turn(2); // Water Gun does normal damage before Light Screen try expectEqual(Result.Default, try t.update(move(1), move(1))); try expect(t.actual.p1.active.volatiles.LightScreen); try t.log.expected.move(P2.ident(1), Move.WaterGun, P1.ident(1), null); t.expected.p1.get(1).hp -= 23; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.move(P1.ident(1), Move.Teleport, P1.ident(1), null); try t.log.expected.turn(3); // Water Gun's damage is reduced after Light Screen try expectEqual(Result.Default, try t.update(move(2), move(1))); try t.log.expected.move(P2.ident(1), Move.WaterGun, P1.ident(1), null); try t.log.expected.crit(P1.ident(1)); t.expected.p1.get(1).hp -= 87; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.move(P1.ident(1), Move.Teleport, P1.ident(1), null); try t.log.expected.turn(4); // Critical hits ignore Light Screen try expectEqual(Result.Default, try t.update(move(2), move(1))); try t.log.expected.move(P2.ident(1), Move.Haze, P2.ident(1), null); try t.log.expected.activate(P2.ident(1), .Haze); try t.log.expected.clearallboost(); try t.log.expected.end(P1.ident(1), .LightScreen); try t.log.expected.move(P1.ident(1), Move.Teleport, P1.ident(1), null); try t.log.expected.turn(5); // Haze removes Light Screen try expectEqual(Result.Default, try t.update(move(2), move(2))); try expect(!t.actual.p1.active.volatiles.LightScreen); try t.verify(); } // Move.Reflect test "Reflect effect" { // While the user remains active, its Defense is doubled when taking damage. Critical hits // ignore this protection. This effect can be removed by Haze. var t = Test((if (showdown) (.{ NOP, HIT, ~CRIT, MIN_DMG, NOP, HIT, ~CRIT, MIN_DMG, NOP, HIT, CRIT, MIN_DMG }) else (.{ ~CRIT, MIN_DMG, HIT, ~CRIT, MIN_DMG, HIT, CRIT, MIN_DMG, HIT }))).init( &.{.{ .species = .Chansey, .moves = &.{ .Reflect, .Teleport } }}, &.{.{ .species = .Vaporeon, .moves = &.{ .Tackle, .Haze } }}, ); defer t.deinit(); try t.log.expected.move(P2.ident(1), Move.Tackle, P1.ident(1), null); t.expected.p1.get(1).hp -= 54; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.move(P1.ident(1), Move.Reflect, P1.ident(1), null); try t.log.expected.start(P1.ident(1), .Reflect); try t.log.expected.turn(2); // Tackle does normal damage before Reflect try expectEqual(Result.Default, try t.update(move(1), move(1))); try expect(t.actual.p1.active.volatiles.Reflect); try t.log.expected.move(P2.ident(1), Move.Tackle, P1.ident(1), null); t.expected.p1.get(1).hp -= 28; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.move(P1.ident(1), Move.Teleport, P1.ident(1), null); try t.log.expected.turn(3); // Tackle's damage is reduced after Reflect try expectEqual(Result.Default, try t.update(move(2), move(1))); try t.log.expected.move(P2.ident(1), Move.Tackle, P1.ident(1), null); try t.log.expected.crit(P1.ident(1)); t.expected.p1.get(1).hp -= 104; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); try t.log.expected.move(P1.ident(1), Move.Teleport, P1.ident(1), null); try t.log.expected.turn(4); // Critical hits ignore Reflect try expectEqual(Result.Default, try t.update(move(2), move(1))); try t.log.expected.move(P2.ident(1), Move.Haze, P2.ident(1), null); try t.log.expected.activate(P2.ident(1), .Haze); try t.log.expected.clearallboost(); try t.log.expected.end(P1.ident(1), .Reflect); try t.log.expected.move(P1.ident(1), Move.Teleport, P1.ident(1), null); try t.log.expected.turn(5); // Haze removes Reflect try expectEqual(Result.Default, try t.update(move(2), move(2))); try expect(!t.actual.p1.active.volatiles.Reflect); try t.verify(); } // Move.Haze test "Haze effect" { // Resets the stat stages of both Pokemon to 0 and removes stat reductions due to burn and // paralysis. Resets Toxic counters to 0 and removes the effect of confusion, Disable, Focus // Energy, Leech Seed, Light Screen, Mist, and Reflect from both Pokemon. Removes the opponent's // non-volatile status condition. return error.SkipZigTest; } // Move.Bide test "Bide effect" { // The user spends two or three turns locked into this move and then, on the second or third // turn after using this move, the user attacks the opponent, inflicting double the damage in HP // it lost during those turns. This move ignores type immunity and cannot be avoided even if the // target is using Dig or Fly. The user can choose to switch out during the effect. If the user // switches out or is prevented from moving during this move's use, the effect ends. During the // effect, if the opposing Pokemon switches out or uses Confuse Ray, Conversion, Focus Energy, // Glare, Haze, Leech Seed, Light Screen, Mimic, Mist, Poison Gas, Poison Powder, Recover, // Reflect, Rest, Soft-Boiled, Splash, Stun Spore, Substitute, Supersonic, Teleport, Thunder // Wave, Toxic, or Transform, the previous damage dealt to the user will be added to the total. // TODO subsequent turn don't decrement PP return error.SkipZigTest; } // Move.Metronome test "Metronome effect" { // A random move is selected for use, other than Metronome or Struggle. return error.SkipZigTest; } // Move.MirrorMove test "MirrorMove effect" { // The user uses the last move used by the target. Fails if the target has not made a move, or // if the last move used was Mirror Move. return error.SkipZigTest; } // Move.{SelfDestruct,Explosion} test "Explode effect" { // The user faints after using this move, unless the target's substitute was broken by the // damage. The target's Defense is halved during damage calculation. return error.SkipZigTest; } // Move.Swift test "Swift effect" { // This move does not check accuracy and hits even if the target is using Dig or Fly. var t = Test(if (showdown) (.{ NOP, NOP, NOP, ~CRIT, MIN_DMG, NOP, NOP }) // FIXME: SSR else (.{ ~CRIT, MIN_DMG })).init( &.{.{ .species = .Eevee, .moves = &.{.Swift} }}, &.{.{ .species = .Diglett, .moves = &.{.Dig} }}, ); defer t.deinit(); try t.log.expected.move(P2.ident(1), Move.Dig, .{}, null); try t.log.expected.prepare(P2.ident(1), Move.Dig); try t.log.expected.move(P1.ident(1), Move.Swift, P2.ident(1), null); t.expected.p2.get(1).hp -= 91; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.verify(); } // Move.Transform test "Transform effect" { // The user transforms into the target. The target's current stats, stat stages, types, moves, // DVs, species, and sprite are copied. The user's level and HP remain the same and each copied // move receives only 5 PP. This move can hit a target using Dig or Fly. return error.SkipZigTest; } // Move.Conversion test "Conversion effect" { // Causes the user's types to become the same as the current types of the target. var t = Test(if (showdown) .{NOP} else .{}).init( &.{.{ .species = .Porygon, .moves = &.{.Conversion} }}, &.{.{ .species = .Slowbro, .moves = &.{.Teleport} }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Conversion, P2.ident(1), null); try t.log.expected.typechange(P1.ident(1), Types{ .type1 = .Water, .type2 = .Psychic }); try t.log.expected.move(P2.ident(1), Move.Teleport, P2.ident(1), null); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.verify(); } // Move.Substitute test "Substitute effect" { // The user takes 1/4 of its maximum HP, rounded down, and puts it into a substitute to take its // place in battle. The substitute has 1 HP plus the HP used to create it, and is removed once // enough damage is inflicted on it or 255 damage is inflicted at once, or if the user switches // out or faints. Until the substitute is broken, it receives damage from all attacks made by // the opposing Pokemon and shields the user from status effects and stat stage changes caused // by the opponent, unless the effect is Disable, Leech Seed, sleep, primary paralysis, or // secondary confusion and the user's substitute did not break. The user still takes normal // damage from status effects while behind its substitute, unless the effect is confusion // damage, which is applied to the opposing Pokemon's substitute instead. If the substitute // breaks during a multi-hit attack, the attack ends. Fails if the user does not have enough HP // remaining to create a substitute, or if it already has a substitute. The user will create a // substitute and then faint if its current HP is exactly 1/4 of its maximum HP. return error.SkipZigTest; } // Pokémon Showdown Bugs test "Bide + Substitute bug" { return error.SkipZigTest; } test "Counter + Substitute bug" { // https://www.youtube.com/watch?v=_cEVqYFoBhE return error.SkipZigTest; } test "Counter + sleep = Desync Clause Mod bug" { // TODO return error.SkipZigTest; } test "Disable duration bug" { return error.SkipZigTest; } test "Hyper Beam + Substitute bug" { return error.SkipZigTest; } test "Mimic infinite PP bug" { // TODO return error.SkipZigTest; } test "Mirror Move + Wrap bug" { // TODO return error.SkipZigTest; } test "Mirror Move recharge bug" { // TODO return error.SkipZigTest; } test "Wrap locking + KOs bug" { // TODO return error.SkipZigTest; } // Glitches test "0 damage glitch" { // https://pkmn.cc/bulba-glitch-1#0_damage_glitch // https://www.youtube.com/watch?v=fxNzPeLlPTU var t = Test(if (showdown) (.{ NOP, NOP, NOP, HIT, HIT, ~CRIT, NOP, NOP, HIT, NOP, NOP, NOP, HIT, HIT, ~CRIT }) else (.{ ~CRIT, HIT, ~CRIT, HIT, ~CRIT, HIT, ~CRIT, HIT, ~CRIT, HIT })).init( &.{.{ .species = .Bulbasaur, .moves = &.{.Growl} }}, &.{ .{ .species = .Bellsprout, .level = 2, .stats = .{}, .moves = &.{.VineWhip} }, .{ .species = .Chansey, .level = 2, .stats = .{}, .moves = &.{.VineWhip} }, }, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Growl, P2.ident(1), null); try t.log.expected.unboost(P2.ident(1), .Attack, 1); try t.log.expected.move(P2.ident(1), Move.VineWhip, P1.ident(1), null); if (showdown) { try t.log.expected.resisted(P1.ident(1)); t.expected.p1.get(1).hp -= 1; try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); } else { try t.log.expected.lastmiss(); try t.log.expected.miss(P2.ident(1)); } try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.log.expected.switched(P2.ident(2), t.expected.p2.get(2)); try t.log.expected.move(P1.ident(1), Move.Growl, P2.ident(2), null); try t.log.expected.unboost(P2.ident(2), .Attack, 1); try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(1), swtch(2))); try t.log.expected.move(P1.ident(1), Move.Growl, P2.ident(2), null); try t.log.expected.unboost(P2.ident(2), .Attack, 1); try t.log.expected.move(P2.ident(2), Move.VineWhip, P1.ident(1), null); if (showdown) { try t.log.expected.resisted(P1.ident(1)); try t.log.expected.damage(P1.ident(1), t.expected.p1.get(1), .None); } else { try t.log.expected.lastmiss(); try t.log.expected.miss(P2.ident(2)); } try t.log.expected.turn(4); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.verify(); } test "1/256 miss glitch" { // https://pkmn.cc/bulba-glitch-1#1.2F256_miss_glitch var t = Test(if (showdown) (.{ NOP, NOP, ~HIT, ~HIT }) else (.{ CRIT, MAX_DMG, ~HIT, CRIT, MAX_DMG, ~HIT })).init( &.{.{ .species = .Jigglypuff, .moves = &.{.Pound} }}, &.{.{ .species = .NidoranF, .moves = &.{.Scratch} }}, ); defer t.deinit(); try t.log.expected.move(P2.ident(1), Move.Scratch, P1.ident(1), null); try t.log.expected.lastmiss(); try t.log.expected.miss(P2.ident(1)); try t.log.expected.move(P1.ident(1), Move.Pound, P2.ident(1), null); try t.log.expected.lastmiss(); try t.log.expected.miss(P1.ident(1)); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try t.verify(); } test "Bide damage accumulation glitches" { // https://glitchcity.wiki/Bide_fainted_Pokémon_damage_accumulation_glitch // https://glitchcity.wiki/Bide_non-damaging_move/action_damage_accumulation_glitch // https://www.youtube.com/watch?v=IVxHGyNDW4g return error.SkipZigTest; } test "Counter glitches" { // https://pkmn.cc/bulba-glitch-1#Counter_glitches // https://glitchcity.wiki/Counter_glitches_(Generation_I) // https://www.youtube.com/watch?v=ftTalHMjPRY return error.SkipZigTest; } test "Freeze top move selection glitch" { // https://glitchcity.wiki/Freeze_top_move_selection_glitch return error.SkipZigTest; } test "Toxic counter glitches" { // https://pkmn.cc/bulba-glitch-1#Toxic_counter_glitches // https://glitchcity.wiki/Leech_Seed_and_Toxic_stacking const brn = comptime ranged(77, 256) - 1; var t = Test(if (showdown) (.{ NOP, HIT, NOP, NOP, NOP, NOP, HIT, NOP, HIT, ~CRIT, MIN_DMG, brn, NOP }) else (.{ HIT, HIT, ~CRIT, MIN_DMG, HIT, brn })).init( &.{.{ .species = .Venusaur, .moves = &.{ .Toxic, .LeechSeed, .Teleport, .FireBlast } }}, &.{.{ .species = .Clefable, .hp = 392, .moves = &.{ .Teleport, .Rest } }}, ); defer t.deinit(); try t.log.expected.move(P1.ident(1), Move.Toxic, P2.ident(1), null); try t.log.expected.status(P2.ident(1), Status.init(.PSN), .None); try t.log.expected.move(P2.ident(1), Move.Rest, P2.ident(1), null); try t.log.expected.statusFrom(P2.ident(1), Status.slf(2), Move.Rest); t.expected.p2.get(1).hp += 1; t.expected.p2.get(1).status = Status.slf(2); try t.log.expected.heal(P2.ident(1), t.expected.p2.get(1), .Silent); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(2))); try expectEqual(@as(u4, 0), t.actual.p2.active.volatiles.toxic); try t.log.expected.move(P1.ident(1), Move.Teleport, P1.ident(1), null); try t.log.expected.cant(P2.ident(1), .Sleep); try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(3), move(1))); try expectEqual(@as(u4, 0), t.actual.p2.active.volatiles.toxic); try t.log.expected.move(P1.ident(1), Move.LeechSeed, P2.ident(1), null); try t.log.expected.start(P2.ident(1), .LeechSeed); // BUG: Showdown is missing onAfterMoveSelfPriority on sleep condition // if (showdown) { // t.expected.p2.get(1).hp -= 24; // try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .LeechSeed); // t.expected.p2.get(1).status = 0; // try t.log.expected.curestatus(P2.ident(1), Status.slp(1), .Message); // } else { t.expected.p2.get(1).status = 0; try t.log.expected.curestatus(P2.ident(1), Status.slf(1), .Message); t.expected.p2.get(1).hp -= 24; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .LeechSeed); // } try t.log.expected.turn(4); try expectEqual(Result.Default, try t.update(move(2), move(1))); try expectEqual(@as(u4, 1), t.actual.p2.active.volatiles.toxic); try t.log.expected.move(P1.ident(1), Move.FireBlast, P2.ident(1), null); t.expected.p2.get(1).hp -= 96; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); t.expected.p2.get(1).status = Status.init(.BRN); try t.log.expected.status(P2.ident(1), Status.init(.BRN), .None); try t.log.expected.move(P2.ident(1), Move.Teleport, P2.ident(1), null); t.expected.p2.get(1).hp -= 48; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .Burn); t.expected.p2.get(1).hp -= 72; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .LeechSeed); try t.log.expected.turn(5); try expectEqual(Result.Default, try t.update(move(4), move(1))); try expectEqual(@as(u4, 3), t.actual.p2.active.volatiles.toxic); try t.verify(); } test "Defrost move forcing" { // https://pkmn.cc/bulba-glitch-1#Defrost_move_forcing return error.SkipZigTest; } test "Division by 0" { // https://pkmn.cc/bulba-glitch-1#Division_by_0 return error.SkipZigTest; } test "Hyper Beam + Freeze permanent helplessness" { // https://pkmn.cc/bulba-glitch-1#Hyper_Beam_.2B_Freeze_permanent_helplessness // https://glitchcity.wiki/Haze_glitch // https://www.youtube.com/watch?v=gXQlct-DvVg return error.SkipZigTest; } test "Hyper Beam + Sleep move glitch" { // https://pkmn.cc/bulba-glitch-1#Hyper_Beam_.2B_Sleep_move_glitch // https://glitchcity.wiki/Hyper_Beam_sleep_move_glitch return error.SkipZigTest; } test "Hyper Beam automatic selection glitch" { // https://glitchcity.wiki/Hyper_Beam_automatic_selection_glitch return error.SkipZigTest; } test "Invulnerability glitch" { // https://pkmn.cc/bulba-glitch-1#Invulnerability_glitch // https://glitchcity.wiki/Invulnerability_glitch return error.SkipZigTest; } test "Stat modification errors" { // https://pkmn.cc/bulba-glitch-1#Stat_modification_errors // https://glitchcity.wiki/Stat_modification_glitches const PROC = comptime ranged(63, 256) - 1; const NO_PROC = PROC + 1; { var t = Test((if (showdown) (.{ NOP, NOP, HIT, HIT, NOP, NOP, NO_PROC, HIT, NOP, NO_PROC, HIT }) else (.{ ~CRIT, HIT, HIT, NO_PROC, ~CRIT, HIT, ~CRIT, ~CRIT, NO_PROC, ~CRIT, HIT }))).init( &.{.{ .species = .Bulbasaur, .level = 6, .stats = .{}, .moves = &.{ .StunSpore, .Growth }, }}, &.{.{ .species = .Pidgey, .level = 56, .stats = .{}, .moves = &.{.SandAttack} }}, ); defer t.deinit(); try t.start(); try expectEqual(@as(u16, 12), t.actual.p1.active.stats.spe); try expectEqual(@as(u16, 84), t.actual.p2.active.stats.spe); try t.log.expected.move(P2.ident(1), Move.SandAttack, P1.ident(1), null); try t.log.expected.unboost(P1.ident(1), .Accuracy, 1); try t.log.expected.move(P1.ident(1), Move.StunSpore, P2.ident(1), null); try t.log.expected.status(P2.ident(1), Status.init(.PAR), .None); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(@as(u16, 12), t.actual.p1.active.stats.spe); try expectEqual(@as(u16, 21), t.actual.p2.active.stats.spe); try t.log.expected.move(P2.ident(1), Move.SandAttack, P1.ident(1), null); try t.log.expected.unboost(P1.ident(1), .Accuracy, 1); try t.log.expected.move(P1.ident(1), Move.Growth, P1.ident(1), null); try t.log.expected.boost(P1.ident(1), .SpecialAttack, 1); try t.log.expected.boost(P1.ident(1), .SpecialDefense, 1); try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(2), move(1))); try expectEqual(@as(u16, 12), t.actual.p1.active.stats.spe); try expectEqual(@as(u16, 5), t.actual.p2.active.stats.spe); try t.log.expected.move(P1.ident(1), Move.Growth, P1.ident(1), null); try t.log.expected.boost(P1.ident(1), .SpecialAttack, 1); try t.log.expected.boost(P1.ident(1), .SpecialDefense, 1); try t.log.expected.move(P2.ident(1), Move.SandAttack, P1.ident(1), null); try t.log.expected.unboost(P1.ident(1), .Accuracy, 1); try t.log.expected.turn(4); try expectEqual(Result.Default, try t.update(move(2), move(1))); try expectEqual(@as(u16, 12), t.actual.p1.active.stats.spe); try expectEqual(@as(u16, 1), t.actual.p2.active.stats.spe); try t.verify(); } { var t = Test((if (showdown) (.{ NOP, HIT, NOP, NOP, NO_PROC, NOP, HIT, NOP, PROC, NOP, HIT, NOP, NOP, HIT, PROC }) else (.{ HIT, NO_PROC, ~CRIT, ~CRIT, HIT, PROC, ~CRIT, HIT, ~CRIT, HIT, PROC }))).init( &.{ .{ .species = .Bulbasaur, .level = 6, .stats = .{}, .moves = &.{ .StunSpore, .Growth }, }, .{ .species = .Cloyster, .level = 82, .stats = .{}, .moves = &.{.Withdraw} }, }, &.{.{ .species = .Rattata, .level = 2, .stats = .{}, .moves = &.{ .ThunderWave, .TailWhip, .StringShot }, }}, ); defer t.deinit(); try t.start(); try expectEqual(@as(u16, 144), t.actual.p1.pokemon[1].stats.spe); try expectEqual(@as(u16, 8), t.actual.p2.active.stats.spe); try t.log.expected.switched(P1.ident(2), t.expected.p1.get(2)); try t.log.expected.move(P2.ident(1), Move.ThunderWave, P1.ident(2), null); try t.log.expected.status(P1.ident(2), Status.init(.PAR), .None); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(swtch(2), move(1))); try expectEqual(@as(u16, 36), t.actual.p1.active.stats.spe); try expectEqual(@as(u16, 8), t.actual.p2.active.stats.spe); try t.log.expected.move(P1.ident(2), Move.Withdraw, P1.ident(2), null); try t.log.expected.boost(P1.ident(2), .Defense, 1); try t.log.expected.move(P2.ident(1), Move.TailWhip, P1.ident(2), null); try t.log.expected.unboost(P1.ident(2), .Defense, 1); try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(1), move(2))); try expectEqual(@as(u16, 9), t.actual.p1.active.stats.spe); try expectEqual(@as(u16, 8), t.actual.p2.active.stats.spe); try t.log.expected.cant(P1.ident(2), .Paralysis); try t.log.expected.move(P2.ident(1), Move.TailWhip, P1.ident(2), null); try t.log.expected.unboost(P1.ident(2), .Defense, 1); try t.log.expected.turn(4); try expectEqual(Result.Default, try t.update(move(1), move(2))); try expectEqual(@as(u16, 2), t.actual.p1.active.stats.spe); try expectEqual(@as(u16, 8), t.actual.p2.active.stats.spe); try t.log.expected.move(P2.ident(1), Move.StringShot, P1.ident(2), null); try t.log.expected.unboost(P1.ident(2), .Speed, 1); try t.log.expected.cant(P1.ident(2), .Paralysis); try t.log.expected.turn(5); try expectEqual(Result.Default, try t.update(move(1), move(3))); try expectEqual(@as(u16, 23), t.actual.p1.active.stats.spe); try expectEqual(@as(u16, 8), t.actual.p2.active.stats.spe); try t.verify(); } } test "Stat down modifier overflow glitch" { // https://www.youtube.com/watch?v=y2AOm7r39Jg const PROC = comptime ranged(85, 256) - 1; const NO_PROC = PROC + 1; // 342 -> 1026 { var t = Test((if (showdown) (.{ NOP, HIT, ~CRIT, MIN_DMG, PROC, NOP, HIT, ~CRIT, MIN_DMG, NO_PROC }) else (.{ ~CRIT, ~CRIT, ~CRIT, ~CRIT, MIN_DMG, HIT, PROC, ~CRIT }))).init( &.{.{ .species = .Porygon, .level = 58, .stats = .{}, .moves = &.{ .Recover, .Psychic }, }}, &.{.{ .species = .Mewtwo, .level = 99, .stats = .{ .hp = EXP, .atk = EXP, .def = EXP, .spe = EXP, .spc = 255 }, .moves = &.{ .Amnesia, .Recover }, }}, ); defer t.deinit(); try t.start(); try expectEqual(@as(u16, 342), t.actual.p2.active.stats.spc); try t.log.expected.move(P2.ident(1), Move.Amnesia, P2.ident(1), null); try t.log.expected.boost(P2.ident(1), .SpecialAttack, 2); try t.log.expected.boost(P2.ident(1), .SpecialDefense, 2); try t.log.expected.move(P1.ident(1), Move.Recover, P1.ident(1), null); try t.log.expected.fail(P1.ident(1), .None); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(@as(u16, 684), t.actual.p2.active.stats.spc); try expectEqual(@as(i4, 2), t.actual.p2.active.boosts.spc); try t.log.expected.move(P2.ident(1), Move.Amnesia, P2.ident(1), null); try t.log.expected.boost(P2.ident(1), .SpecialAttack, 2); try t.log.expected.boost(P2.ident(1), .SpecialDefense, 2); try t.log.expected.move(P1.ident(1), Move.Recover, P1.ident(1), null); try t.log.expected.fail(P1.ident(1), .None); try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(@as(u16, 999), t.actual.p2.active.stats.spc); try expectEqual(@as(i4, 4), t.actual.p2.active.boosts.spc); try t.log.expected.move(P2.ident(1), Move.Amnesia, P2.ident(1), null); if (showdown) { try t.log.expected.boost(P2.ident(1), .SpecialAttack, 2); try t.log.expected.boost(P2.ident(1), .SpecialDefense, 2); } else { try t.log.expected.fail(P2.ident(1), .None); } try t.log.expected.move(P1.ident(1), Move.Recover, P1.ident(1), null); try t.log.expected.fail(P1.ident(1), .None); try t.log.expected.turn(4); try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(@as(u16, 999), t.actual.p2.active.stats.spc); try expectEqual(@as(i4, if (showdown) 6 else 5), t.actual.p2.active.boosts.spc); try t.log.expected.move(P2.ident(1), Move.Recover, P2.ident(1), null); try t.log.expected.fail(P2.ident(1), .None); try t.log.expected.move(P1.ident(1), Move.Psychic, P2.ident(1), null); try t.log.expected.resisted(P2.ident(1)); t.expected.p2.get(1).hp -= 2; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.unboost(P2.ident(1), .SpecialAttack, 1); try t.log.expected.unboost(P2.ident(1), .SpecialDefense, 1); try t.log.expected.turn(5); try expectEqual(Result.Default, try t.update(move(2), move(2))); try expectEqual(@as(u16, if (showdown) 999 else 1026), t.actual.p2.active.stats.spc); try expectEqual(@as(i4, if (showdown) 5 else 4), t.actual.p2.active.boosts.spc); try t.log.expected.move(P2.ident(1), Move.Recover, P2.ident(1), null); t.expected.p2.get(1).hp += 2; try t.log.expected.heal(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P1.ident(1), Move.Psychic, P2.ident(1), null); if (showdown) { try t.log.expected.resisted(P2.ident(1)); t.expected.p2.get(1).hp -= 2; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.turn(6); } // Division by 0 const result = if (showdown) Result.Default else Result.Error; try expectEqual(result, try t.update(move(2), move(2))); try t.verify(); } // 343 -> 1029 { var t = Test((if (showdown) (.{ NOP, HIT, ~CRIT, MIN_DMG, PROC, NOP, HIT, ~CRIT, MIN_DMG, NO_PROC }) else (.{ ~CRIT, ~CRIT, ~CRIT, ~CRIT, MIN_DMG, HIT, PROC, ~CRIT, MIN_DMG, HIT }))).init( &.{.{ .species = .Porygon, .stats = .{}, .level = 58, .moves = &.{ .Recover, .Psychic }, }}, &.{.{ .species = .Mewtwo, .stats = .{}, .moves = &.{ .Amnesia, .Recover } }}, ); defer t.deinit(); try t.start(); try expectEqual(@as(u16, 343), t.actual.p2.active.stats.spc); try t.log.expected.move(P2.ident(1), Move.Amnesia, P2.ident(1), null); try t.log.expected.boost(P2.ident(1), .SpecialAttack, 2); try t.log.expected.boost(P2.ident(1), .SpecialDefense, 2); try t.log.expected.move(P1.ident(1), Move.Recover, P1.ident(1), null); try t.log.expected.fail(P1.ident(1), .None); try t.log.expected.turn(2); try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(@as(u16, 686), t.actual.p2.active.stats.spc); try expectEqual(@as(i4, 2), t.actual.p2.active.boosts.spc); try t.log.expected.move(P2.ident(1), Move.Amnesia, P2.ident(1), null); try t.log.expected.boost(P2.ident(1), .SpecialAttack, 2); try t.log.expected.boost(P2.ident(1), .SpecialDefense, 2); try t.log.expected.move(P1.ident(1), Move.Recover, P1.ident(1), null); try t.log.expected.fail(P1.ident(1), .None); try t.log.expected.turn(3); try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(@as(u16, 999), t.actual.p2.active.stats.spc); try expectEqual(@as(i4, 4), t.actual.p2.active.boosts.spc); try t.log.expected.move(P2.ident(1), Move.Amnesia, P2.ident(1), null); if (showdown) { try t.log.expected.boost(P2.ident(1), .SpecialAttack, 2); try t.log.expected.boost(P2.ident(1), .SpecialDefense, 2); } else { try t.log.expected.fail(P2.ident(1), .None); } try t.log.expected.move(P1.ident(1), Move.Recover, P1.ident(1), null); try t.log.expected.fail(P1.ident(1), .None); try t.log.expected.turn(4); try expectEqual(Result.Default, try t.update(move(1), move(1))); try expectEqual(@as(u16, 999), t.actual.p2.active.stats.spc); try expectEqual(@as(i4, if (showdown) 6 else 5), t.actual.p2.active.boosts.spc); try t.log.expected.move(P2.ident(1), Move.Recover, P2.ident(1), null); try t.log.expected.fail(P2.ident(1), .None); try t.log.expected.move(P1.ident(1), Move.Psychic, P2.ident(1), null); try t.log.expected.resisted(P2.ident(1)); t.expected.p2.get(1).hp -= 2; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.unboost(P2.ident(1), .SpecialAttack, 1); try t.log.expected.unboost(P2.ident(1), .SpecialDefense, 1); try t.log.expected.turn(5); try expectEqual(Result.Default, try t.update(move(2), move(2))); try expectEqual(@as(u16, if (showdown) 999 else 1029), t.actual.p2.active.stats.spc); try expectEqual(@as(i4, if (showdown) 5 else 4), t.actual.p2.active.boosts.spc); try t.log.expected.move(P2.ident(1), Move.Recover, P2.ident(1), null); t.expected.p2.get(1).hp += 2; try t.log.expected.heal(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.move(P1.ident(1), Move.Psychic, P2.ident(1), null); if (showdown) { try t.log.expected.resisted(P2.ident(1)); t.expected.p2.get(1).hp -= 2; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.turn(6); } else { try t.log.expected.resisted(P2.ident(1)); t.expected.p2.get(1).hp = 0; try t.log.expected.damage(P2.ident(1), t.expected.p2.get(1), .None); try t.log.expected.faint(P2.ident(1), false); try t.log.expected.win(.P1); } // Overflow means Mewtwo gets KOed const result = if (showdown) Result.Default else Result.Win; try expectEqual(result, try t.update(move(2), move(2))); try t.verify(); } } test "Struggle bypassing / Switch PP underflow" { // https://pkmn.cc/bulba-glitch-1#Struggle_bypassing // https://glitchcity.wiki/Switch_PP_underflow_glitch return error.SkipZigTest; } test "Trapping sleep glitch" { // https://pkmn.cc/bulba-glitch-1#Trapping_sleep_glitch return error.SkipZigTest; } test "Partial trapping move Mirror Move glitch" { // https://glitchcity.wiki/Partial_trapping_move_Mirror_Move_link_battle_glitch // https://pkmn.cc/bulba-glitch-1##Mirror_Move_glitch return error.SkipZigTest; } test "Rage and Thrash / Petal Dance accuracy bug" { // https://www.youtube.com/watch?v=NC5gbJeExbs return error.SkipZigTest; } test "Substitute HP drain bug" { // https://pkmn.cc/bulba-glitch-1#Substitute_HP_drain_bug // https://glitchcity.wiki/Substitute_drain_move_not_missing_glitch return error.SkipZigTest; } test "Substitute 1/4 HP glitch" { // https://glitchcity.wiki/Substitute_%C2%BC_HP_glitch return error.SkipZigTest; } test "Substitute + Confusion glitch" { // https://pkmn.cc/bulba-glitch-1#Substitute_.2B_Confusion_glitch // https://glitchcity.wiki/Confusion_and_Substitute_glitch return error.SkipZigTest; } test "Psywave infinite loop" { // https://pkmn.cc/bulba-glitch-1#Psywave_infinite_loop var t = Test((if (showdown) (.{ NOP, NOP, NOP, HIT, HIT, MAX_DMG }) else (.{ ~CRIT, HIT, HIT }))).init( &.{.{ .species = .Charmander, .level = 1, .moves = &.{.Psywave} }}, &.{.{ .species = .Rattata, .level = 3, .moves = &.{.TailWhip} }}, ); defer t.deinit(); try t.log.expected.move(P2.ident(1), Move.TailWhip, P1.ident(1), null); try t.log.expected.unboost(P1.ident(1), .Defense, 1); try t.log.expected.move(P1.ident(1), Move.Psywave, P2.ident(1), null); const result = if (showdown) Result.Default else Result.Error; if (showdown) try t.log.expected.turn(2); try expectEqual(result, try t.update(move(1), move(1))); try t.verify(); } // Miscellaneous // test "MAX_LOGS" { // if (showdown) return; // const MIRROR_MOVE = @enumToInt(Move.MirrorMove); // const CFZ = comptime ranged(128, 256); // const NO_CFZ = CFZ - 1; // // TODO: replace this with a handcrafted actual seed instead of using the fixed RNG // var battle = Battle.fixed( // // zig fmt: off // .{ // // Set up // HIT, // ~CRIT, @enumToInt(Move.LeechSeed), HIT, // HIT, 3, NO_CFZ, HIT, 3, // NO_CFZ, NO_CFZ, ~CRIT, @enumToInt(Move.SolarBeam), // // Scenario // NO_CFZ, // ~CRIT, MIRROR_MOVE, ~CRIT, // ~CRIT, MIRROR_MOVE, ~CRIT, // ~CRIT, MIRROR_MOVE, ~CRIT, // ~CRIT, MIRROR_MOVE, ~CRIT, // ~CRIT, MIRROR_MOVE, ~CRIT, // ~CRIT, MIRROR_MOVE, ~CRIT, // ~CRIT, MIRROR_MOVE, ~CRIT, // ~CRIT, MIRROR_MOVE, ~CRIT, // ~CRIT, MIRROR_MOVE, ~CRIT, // ~CRIT, MIRROR_MOVE, ~CRIT, // ~CRIT, @enumToInt(Move.PinMissile), CRIT, MIN_DMG, HIT, 3, 3, // NO_CFZ, CRIT, MIN_DMG, HIT, // }, // // zig fmt: on // &.{ // .{ // .species = .Bulbasaur, // .moves = &.{.LeechSeed}, // }, // .{ // .species = .Gengar, // .hp = 224, // .status = BRN, // .moves = &.{ .Metronome, .ConfuseRay, .Toxic }, // }, // }, // &.{ // .{ // .species = .Bulbasaur, // .moves = &.{.LeechSeed}, // }, // .{ // .species = .Gengar, // .status = BRN, // .moves = &.{ .Metronome, .ConfuseRay }, // }, // }, // ); // battle.side(.P2).get(2).stats.spe = 317; // make P2 slower to avoid speed ties // try expectEqual(Result.Default, try battle.update(.{}, .{}, null)); // // P1 switches into Leech Seed // try expectEqual(Result.Default, try battle.update(swtch(2), move(1), null)); // // P2 switches into to P1's Metronome -> Leech Seed // try expectEqual(Result.Default, try battle.update(move(1), swtch(2), null)); // // P1 and P2 confuse each other // try expectEqual(Result.Default, try battle.update(move(2), move(2), null)); // // P1 uses Toxic to noop while P2 uses Metronome -> Solar Beam // try expectEqual(Result.Default, try battle.update(move(3), move(1), null)); // try expectEqual(Move.SolarBeam, battle.side(.P2).last_selected_move); // try expectEqual(Move.Metronome, battle.side(.P2).last_used_move); // // BUG: data.MAX_LOGS not enough? // var buf: [data.MAX_LOGS * 100]u8 = undefined; // var log = FixedLog{ .writer = stream(&buf).writer() }; // // P1 uses Metronome -> Mirror Move -> ... -> Pin Missile, P2 -> Solar Beam // try expectEqual( // Result{ .p1 = .Switch, .p2 = .Pass }, try battle.update(move(1), move(0), log)); // try expect(battle.rng.exhausted()); // } fn Test(comptime rolls: anytype) type { return struct { const Self = @This(); battle: struct { expected: data.Battle(rng.FixedRNG(1, rolls.len)), actual: data.Battle(rng.FixedRNG(1, rolls.len)), }, buf: struct { expected: ArrayList(u8), actual: ArrayList(u8), }, log: struct { expected: Log(ArrayList(u8).Writer), actual: Log(ArrayList(u8).Writer), }, expected: struct { p1: *data.Side, p2: *data.Side, }, actual: struct { p1: *data.Side, p2: *data.Side, }, pub fn init( pokemon1: []const Pokemon, pokemon2: []const Pokemon, ) *Self { var t = std.testing.allocator.create(Self) catch unreachable; t.battle.expected = Battle.fixed(rolls, pokemon1, pokemon2); t.battle.actual = t.battle.expected; t.buf.expected = std.ArrayList(u8).init(std.testing.allocator); t.buf.actual = std.ArrayList(u8).init(std.testing.allocator); t.log.expected = Log(ArrayList(u8).Writer){ .writer = t.buf.expected.writer() }; t.log.actual = Log(ArrayList(u8).Writer){ .writer = t.buf.actual.writer() }; t.expected.p1 = t.battle.expected.side(.P1); t.expected.p2 = t.battle.expected.side(.P2); t.actual.p1 = t.battle.actual.side(.P1); t.actual.p2 = t.battle.actual.side(.P2); return t; } pub fn deinit(self: *Self) void { self.buf.expected.deinit(); self.buf.actual.deinit(); std.testing.allocator.destroy(self); } pub fn start(self: *Self) !void { var expected_buf: [22]u8 = undefined; var actual_buf: [22]u8 = undefined; var expected = FixedLog{ .writer = stream(&expected_buf).writer() }; var actual = FixedLog{ .writer = stream(&actual_buf).writer() }; try expected.switched(P1.ident(1), self.actual.p1.get(1)); try expected.switched(P2.ident(1), self.actual.p2.get(1)); try expected.turn(1); try expectEqual(Result.Default, try self.battle.actual.update(.{}, .{}, actual)); try expectLog(&expected_buf, &actual_buf); } pub fn update(self: *Self, c1: Choice, c2: Choice) !Result { if (self.battle.actual.turn == 0) try self.start(); return self.battle.actual.update(c1, c2, self.log.actual); } pub fn verify(t: *Self) !void { if (trace) try expectLog(t.buf.expected.items, t.buf.actual.items); for (t.expected.p1.pokemon) |p, i| try expectEqual(p.hp, t.actual.p1.pokemon[i].hp); for (t.expected.p2.pokemon) |p, i| try expectEqual(p.hp, t.actual.p2.pokemon[i].hp); try expect(t.battle.actual.rng.exhausted()); } }; } fn expectLog(expected: []const u8, actual: []const u8) !void { return protocol.expectLog(formatter, expected, actual); } fn formatter(kind: protocol.Kind, byte: u8) []const u8 { return switch (kind) { .Move => @tagName(@intToEnum(Move, byte)), .Species => @tagName(@intToEnum(Species, byte)), .Type => @tagName(@intToEnum(Type, byte)), .Status => Status.name(byte), }; } comptime { _ = @import("data.zig"); _ = @import("mechanics.zig"); }
src/lib/gen1/test.zig
const std = @import("std"); const info = std.log.info; const warn = std.log.warn; const bus = @import("bus.zig"); const rsp = @import("rsp.zig"); const mi = @import("mi.zig"); const InterruptSource = mi.InterruptSource; pub const RDPStatus = packed struct { x : bool = false, f : bool = false, fl: bool = false, g : bool = true, tb: bool = false, pb: bool = true, cb: bool = false, cr: bool = true, db: bool = false, ev: bool = false, sv: bool = false, }; pub const RDPRegs = struct { rdpStatus: RDPStatus = RDPStatus{}, rdpCMDStart: u24 = 0, rdpCMDEnd : u24 = 0, rdpCMDCurr : u24 = 0, }; const RDPCommand = enum(u64) { NoOperation = 0x00, SyncLoad = 0x26, SyncPipe = 0x27, SyncTile = 0x28, SyncFull = 0x29, SetScissor = 0x2D, SetOtherModes = 0x2F, SetTileSize = 0x32, LoadBlock = 0x33, SetTile = 0x35, FillRectangle = 0x36, SetFillColor = 0x37, SetEnvColor = 0x3B, SetCombine = 0x3C, SetTextureImage = 0x3D, SetMaskImage = 0x3E, SetColorImage = 0x3F, }; pub var rdpRegs: RDPRegs = RDPRegs{}; fn getCommandWord() u64 { var data: u64 = undefined; if (rdpRegs.rdpStatus.x) { @memcpy(@ptrCast([*]u8, &data), @ptrCast([*]u8, &rsp.spDMEM[@truncate(u12, rdpRegs.rdpCMDCurr)]), 8); } else { @memcpy(@ptrCast([*]u8, &data), @ptrCast([*]u8, &bus.ram[rdpRegs.rdpCMDCurr]), 8); } rdpRegs.rdpCMDCurr +%= 8; return @byteSwap(u64, data); } fn getCommand(cmdWord: u64) u64 { return (cmdWord >> 56) & 0x3F; } pub fn processDP() void { while (rdpRegs.rdpCMDCurr < rdpRegs.rdpCMDEnd) { const cmdWord = getCommandWord(); switch (getCommand(cmdWord)) { @enumToInt(RDPCommand.NoOperation) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.NoOperation), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, @enumToInt(RDPCommand.SyncLoad) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.SyncLoad), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, @enumToInt(RDPCommand.SyncPipe) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.SyncPipe), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, @enumToInt(RDPCommand.SyncTile) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.SyncTile), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, @enumToInt(RDPCommand.SyncFull) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.SyncFull), cmdWord, rdpRegs.rdpCMDCurr -% 8}); mi.setPending(InterruptSource.DP); }, @enumToInt(RDPCommand.SetScissor) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.SetScissor), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, @enumToInt(RDPCommand.SetOtherModes) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.SetOtherModes), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, @enumToInt(RDPCommand.SetTileSize) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.SetTileSize), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, @enumToInt(RDPCommand.LoadBlock) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.LoadBlock), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, @enumToInt(RDPCommand.SetTile) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.SetTile), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, @enumToInt(RDPCommand.FillRectangle) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.FillRectangle), cmdWord, rdpRegs.rdpCMDCurr -% 8}); const yh = (cmdWord >> 0) & 0xFFF; const xh = (cmdWord >> 12) & 0xFFF; const yl = (cmdWord >> 32) & 0xFFF; const xl = (cmdWord >> 48) & 0xFFF; info("[RDP] YH: {}, XH: {}, YL: {}, XL: {}", .{yh, xh, yl, xl}); }, @enumToInt(RDPCommand.SetFillColor) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.SetFillColor), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, @enumToInt(RDPCommand.SetEnvColor) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.SetEnvColor), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, @enumToInt(RDPCommand.SetCombine) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.SetCombine), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, @enumToInt(RDPCommand.SetTextureImage) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.SetTextureImage), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, @enumToInt(RDPCommand.SetMaskImage) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.SetMaskImage), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, @enumToInt(RDPCommand.SetColorImage) => { info("[RDP] {s} ({X}h) @ {X}h", .{@tagName(RDPCommand.SetColorImage), cmdWord, rdpRegs.rdpCMDCurr -% 8}); }, else => { warn("[RDP] Unhandled command {X}h ({X}h) @ {X}h.", .{getCommand(cmdWord), cmdWord, rdpRegs.rdpCMDCurr -% 8}); @panic("unhandled RDP command"); } } } rdpRegs.rdpStatus.ev = false; rdpRegs.rdpStatus.sv = false; }
src/core/rdp.zig
const utils = @import("main.zig").utils; const std = @import("std"); pub const print = struct { /// Returns the ANSI sequence as a []const u8 pub const reset = utils.comptimeCsi("0m", .{}); /// Returns the ANSI sequence to set bold mode pub const bold = utils.comptimeCsi("1m", .{}); pub const no_bold = utils.comptimeCsi("22m", .{}); /// Returns the ANSI sequence to set dim mode pub const dim = utils.comptimeCsi("2m", .{}); pub const no_dim = utils.comptimeCsi("22m", .{}); /// Returns the ANSI sequence to set italic mode pub const italic = utils.comptimeCsi("3m", .{}); pub const no_italic = utils.comptimeCsi("23m", .{}); /// Returns the ANSI sequence to set underline mode pub const underline = utils.comptimeCsi("4m", .{}); pub const no_underline = utils.comptimeCsi("24m", .{}); /// Returns the ANSI sequence to set blinking mode pub const blinking = utils.comptimeCsi("5m", .{}); pub const no_blinking = utils.comptimeCsi("25m", .{}); /// Returns the ANSI sequence to set reverse mode pub const reverse = utils.comptimeCsi("7m", .{}); pub const no_reverse = utils.comptimeCsi("27m", .{}); /// Returns the ANSI sequence to set hidden/invisible mode pub const invisible = utils.comptimeCsi("8m", .{}); pub const no_invisible = utils.comptimeCsi("28m", .{}); /// Returns the ANSI sequence to set strikethrough mode pub const strikethrough = utils.comptimeCsi("9m", .{}); pub const no_strikethrough = utils.comptimeCsi("29m", .{}); }; /// Returns the ANSI sequence as a []const u8 pub fn reset(writer: anytype) !void { return std.fmt.format(writer, utils.reset_all, .{}); } /// Returns the ANSI sequence to set bold mode pub fn bold(writer: anytype) !void { return std.fmt.format(writer, utils.style_bold, .{}); } /// Returns the ANSI sequence to unset bold mode pub fn noBold(writer: anytype) !void { return std.fmt.format(writer, utils.style_no_bold, .{}); } /// Returns the ANSI sequence to set dim mode pub fn dim(writer: anytype) !void { return std.fmt.format(writer, utils.style_dim, .{}); } /// Returns the ANSI sequence to unset dim mode pub fn noDim(writer: anytype) !void { return std.fmt.format(writer, utils.style_no_dim, .{}); } /// Returns the ANSI sequence to set italic mode pub fn italic(writer: anytype) !void { return std.fmt.format(writer, utils.style_italic, .{}); } /// Returns the ANSI sequence to unset italic mode pub fn noItalic(writer: anytype) !void { return std.fmt.format(writer, utils.style_no_italic, .{}); } /// Returns the ANSI sequence to set underline mode pub fn underline(writer: anytype) !void { return std.fmt.format(writer, utils.style_underline, .{}); } /// Returns the ANSI sequence to unset underline mode pub fn noUnderline(writer: anytype) !void { return std.fmt.format(writer, utils.style_no_underline, .{}); } /// Returns the ANSI sequence to set blinking mode pub fn blinking(writer: anytype) !void { return std.fmt.format(writer, utils.style_blinking, .{}); } /// Returns the ANSI sequence to unset blinking mode pub fn noBlinking(writer: anytype) !void { return std.fmt.format(writer, utils.style_no_blinking, .{}); } /// Returns the ANSI sequence to set reverse mode pub fn reverse(writer: anytype) !void { return std.fmt.format(writer, utils.style_reverse, .{}); } /// Returns the ANSI sequence to unset reverse mode pub fn noReverse(writer: anytype) !void { return std.fmt.format(writer, utils.style_no_reverse, .{}); } /// Returns the ANSI sequence to set hidden/invisible mode pub fn hidden(writer: anytype) !void { return std.fmt.format(writer, utils.style_invisible, .{}); } /// Returns the ANSI sequence to unset hidden/invisible mode pub fn noHidden(writer: anytype) !void { return std.fmt.format(writer, utils.style_no_invisible, .{}); } /// Returns the ansi sequence to set strikethrough mode pub fn strikethrough(writer: anytype) !void { return std.fmt.format(writer, utils.style_strikethrough, .{}); } /// Returns the ansi sequence to unset strikethrough mode pub fn noStrikethrough(writer: anytype) !void { return std.fmt.format(writer, utils.style_no_strikethrough, .{}); }
src/style.zig
pub const QOS_MAX_OBJECT_STRING_LENGTH = @as(u32, 256); pub const QOS_TRAFFIC_GENERAL_ID_BASE = @as(u32, 4000); pub const SERVICETYPE_NOTRAFFIC = @as(u32, 0); pub const SERVICETYPE_BESTEFFORT = @as(u32, 1); pub const SERVICETYPE_CONTROLLEDLOAD = @as(u32, 2); pub const SERVICETYPE_GUARANTEED = @as(u32, 3); pub const SERVICETYPE_NETWORK_UNAVAILABLE = @as(u32, 4); pub const SERVICETYPE_GENERAL_INFORMATION = @as(u32, 5); pub const SERVICETYPE_NOCHANGE = @as(u32, 6); pub const SERVICETYPE_NONCONFORMING = @as(u32, 9); pub const SERVICETYPE_NETWORK_CONTROL = @as(u32, 10); pub const SERVICETYPE_QUALITATIVE = @as(u32, 13); pub const SERVICE_BESTEFFORT = @as(u32, 2147549184); pub const SERVICE_CONTROLLEDLOAD = @as(u32, 2147614720); pub const SERVICE_GUARANTEED = @as(u32, 2147745792); pub const SERVICE_QUALITATIVE = @as(u32, 2149580800); pub const SERVICE_NO_TRAFFIC_CONTROL = @as(u32, 2164260864); pub const SERVICE_NO_QOS_SIGNALING = @as(u32, 1073741824); pub const QOS_NOT_SPECIFIED = @as(u32, 4294967295); pub const POSITIVE_INFINITY_RATE = @as(u32, 4294967294); pub const QOS_GENERAL_ID_BASE = @as(u32, 2000); pub const TC_NONCONF_BORROW = @as(u32, 0); pub const TC_NONCONF_SHAPE = @as(u32, 1); pub const TC_NONCONF_DISCARD = @as(u32, 2); pub const TC_NONCONF_BORROW_PLUS = @as(u32, 3); pub const SESSFLG_E_Police = @as(u32, 1); pub const Opt_Share_mask = @as(u32, 24); pub const Opt_Distinct = @as(u32, 8); pub const Opt_Shared = @as(u32, 16); pub const Opt_SndSel_mask = @as(u32, 7); pub const Opt_Wildcard = @as(u32, 1); pub const Opt_Explicit = @as(u32, 2); pub const ERROR_SPECF_InPlace = @as(u32, 1); pub const ERROR_SPECF_NotGuilty = @as(u32, 2); pub const ERR_FORWARD_OK = @as(u32, 32768); pub const ERR_Usage_globl = @as(u32, 0); pub const ERR_Usage_local = @as(u32, 16); pub const ERR_Usage_serv = @as(u32, 17); pub const ERR_global_mask = @as(u32, 4095); pub const GENERAL_INFO = @as(u32, 1); pub const GUARANTEED_SERV = @as(u32, 2); pub const PREDICTIVE_SERV = @as(u32, 3); pub const CONTROLLED_DELAY_SERV = @as(u32, 4); pub const CONTROLLED_LOAD_SERV = @as(u32, 5); pub const QUALITATIVE_SERV = @as(u32, 6); pub const INTSERV_VERS_MASK = @as(u32, 240); pub const INTSERV_VERSION0 = @as(u32, 0); pub const ISSH_BREAK_BIT = @as(u32, 128); pub const ISPH_FLG_INV = @as(u32, 128); pub const RSVP_PATH = @as(u32, 1); pub const RSVP_RESV = @as(u32, 2); pub const RSVP_PATH_ERR = @as(u32, 3); pub const RSVP_RESV_ERR = @as(u32, 4); pub const RSVP_PATH_TEAR = @as(u32, 5); pub const RSVP_RESV_TEAR = @as(u32, 6); pub const RSVP_Err_NONE = @as(u32, 0); pub const RSVP_Erv_Nonev = @as(u32, 0); pub const RSVP_Err_ADMISSION = @as(u32, 1); pub const RSVP_Erv_Other = @as(u32, 0); pub const RSVP_Erv_DelayBnd = @as(u32, 1); pub const RSVP_Erv_Bandwidth = @as(u32, 2); pub const RSVP_Erv_MTU = @as(u32, 3); pub const RSVP_Erv_Flow_Rate = @as(u32, 32769); pub const RSVP_Erv_Bucket_szie = @as(u32, 32770); pub const RSVP_Erv_Peak_Rate = @as(u32, 32771); pub const RSVP_Erv_Min_Policied_size = @as(u32, 32772); pub const RSVP_Err_POLICY = @as(u32, 2); pub const POLICY_ERRV_NO_MORE_INFO = @as(u32, 1); pub const POLICY_ERRV_UNSUPPORTED_CREDENTIAL_TYPE = @as(u32, 2); pub const POLICY_ERRV_INSUFFICIENT_PRIVILEGES = @as(u32, 3); pub const POLICY_ERRV_EXPIRED_CREDENTIALS = @as(u32, 4); pub const POLICY_ERRV_IDENTITY_CHANGED = @as(u32, 5); pub const POLICY_ERRV_UNKNOWN = @as(u32, 0); pub const POLICY_ERRV_GLOBAL_DEF_FLOW_COUNT = @as(u32, 1); pub const POLICY_ERRV_GLOBAL_GRP_FLOW_COUNT = @as(u32, 2); pub const POLICY_ERRV_GLOBAL_USER_FLOW_COUNT = @as(u32, 3); pub const POLICY_ERRV_GLOBAL_UNAUTH_USER_FLOW_COUNT = @as(u32, 4); pub const POLICY_ERRV_SUBNET_DEF_FLOW_COUNT = @as(u32, 5); pub const POLICY_ERRV_SUBNET_GRP_FLOW_COUNT = @as(u32, 6); pub const POLICY_ERRV_SUBNET_USER_FLOW_COUNT = @as(u32, 7); pub const POLICY_ERRV_SUBNET_UNAUTH_USER_FLOW_COUNT = @as(u32, 8); pub const POLICY_ERRV_GLOBAL_DEF_FLOW_DURATION = @as(u32, 9); pub const POLICY_ERRV_GLOBAL_GRP_FLOW_DURATION = @as(u32, 10); pub const POLICY_ERRV_GLOBAL_USER_FLOW_DURATION = @as(u32, 11); pub const POLICY_ERRV_GLOBAL_UNAUTH_USER_FLOW_DURATION = @as(u32, 12); pub const POLICY_ERRV_SUBNET_DEF_FLOW_DURATION = @as(u32, 13); pub const POLICY_ERRV_SUBNET_GRP_FLOW_DURATION = @as(u32, 14); pub const POLICY_ERRV_SUBNET_USER_FLOW_DURATION = @as(u32, 15); pub const POLICY_ERRV_SUBNET_UNAUTH_USER_FLOW_DURATION = @as(u32, 16); pub const POLICY_ERRV_GLOBAL_DEF_FLOW_RATE = @as(u32, 17); pub const POLICY_ERRV_GLOBAL_GRP_FLOW_RATE = @as(u32, 18); pub const POLICY_ERRV_GLOBAL_USER_FLOW_RATE = @as(u32, 19); pub const POLICY_ERRV_GLOBAL_UNAUTH_USER_FLOW_RATE = @as(u32, 20); pub const POLICY_ERRV_SUBNET_DEF_FLOW_RATE = @as(u32, 21); pub const POLICY_ERRV_SUBNET_GRP_FLOW_RATE = @as(u32, 22); pub const POLICY_ERRV_SUBNET_USER_FLOW_RATE = @as(u32, 23); pub const POLICY_ERRV_SUBNET_UNAUTH_USER_FLOW_RATE = @as(u32, 24); pub const POLICY_ERRV_GLOBAL_DEF_PEAK_RATE = @as(u32, 25); pub const POLICY_ERRV_GLOBAL_GRP_PEAK_RATE = @as(u32, 26); pub const POLICY_ERRV_GLOBAL_USER_PEAK_RATE = @as(u32, 27); pub const POLICY_ERRV_GLOBAL_UNAUTH_USER_PEAK_RATE = @as(u32, 28); pub const POLICY_ERRV_SUBNET_DEF_PEAK_RATE = @as(u32, 29); pub const POLICY_ERRV_SUBNET_GRP_PEAK_RATE = @as(u32, 30); pub const POLICY_ERRV_SUBNET_USER_PEAK_RATE = @as(u32, 31); pub const POLICY_ERRV_SUBNET_UNAUTH_USER_PEAK_RATE = @as(u32, 32); pub const POLICY_ERRV_GLOBAL_DEF_SUM_FLOW_RATE = @as(u32, 33); pub const POLICY_ERRV_GLOBAL_GRP_SUM_FLOW_RATE = @as(u32, 34); pub const POLICY_ERRV_GLOBAL_USER_SUM_FLOW_RATE = @as(u32, 35); pub const POLICY_ERRV_GLOBAL_UNAUTH_USER_SUM_FLOW_RATE = @as(u32, 36); pub const POLICY_ERRV_SUBNET_DEF_SUM_FLOW_RATE = @as(u32, 37); pub const POLICY_ERRV_SUBNET_GRP_SUM_FLOW_RATE = @as(u32, 38); pub const POLICY_ERRV_SUBNET_USER_SUM_FLOW_RATE = @as(u32, 39); pub const POLICY_ERRV_SUBNET_UNAUTH_USER_SUM_FLOW_RATE = @as(u32, 40); pub const POLICY_ERRV_GLOBAL_DEF_SUM_PEAK_RATE = @as(u32, 41); pub const POLICY_ERRV_GLOBAL_GRP_SUM_PEAK_RATE = @as(u32, 42); pub const POLICY_ERRV_GLOBAL_USER_SUM_PEAK_RATE = @as(u32, 43); pub const POLICY_ERRV_GLOBAL_UNAUTH_USER_SUM_PEAK_RATE = @as(u32, 44); pub const POLICY_ERRV_SUBNET_DEF_SUM_PEAK_RATE = @as(u32, 45); pub const POLICY_ERRV_SUBNET_GRP_SUM_PEAK_RATE = @as(u32, 46); pub const POLICY_ERRV_SUBNET_USER_SUM_PEAK_RATE = @as(u32, 47); pub const POLICY_ERRV_SUBNET_UNAUTH_USER_SUM_PEAK_RATE = @as(u32, 48); pub const POLICY_ERRV_UNKNOWN_USER = @as(u32, 49); pub const POLICY_ERRV_NO_PRIVILEGES = @as(u32, 50); pub const POLICY_ERRV_EXPIRED_USER_TOKEN = @as(u32, 51); pub const POLICY_ERRV_NO_RESOURCES = @as(u32, 52); pub const POLICY_ERRV_PRE_EMPTED = @as(u32, 53); pub const POLICY_ERRV_USER_CHANGED = @as(u32, 54); pub const POLICY_ERRV_NO_ACCEPTS = @as(u32, 55); pub const POLICY_ERRV_NO_MEMORY = @as(u32, 56); pub const POLICY_ERRV_CRAZY_FLOWSPEC = @as(u32, 57); pub const RSVP_Err_NO_PATH = @as(u32, 3); pub const RSVP_Err_NO_SENDER = @as(u32, 4); pub const RSVP_Err_BAD_STYLE = @as(u32, 5); pub const RSVP_Err_UNKNOWN_STYLE = @as(u32, 6); pub const RSVP_Err_BAD_DSTPORT = @as(u32, 7); pub const RSVP_Err_BAD_SNDPORT = @as(u32, 8); pub const RSVP_Err_AMBIG_FILTER = @as(u32, 9); pub const RSVP_Err_PREEMPTED = @as(u32, 12); pub const RSVP_Err_UNKN_OBJ_CLASS = @as(u32, 13); pub const RSVP_Err_UNKNOWN_CTYPE = @as(u32, 14); pub const RSVP_Err_API_ERROR = @as(u32, 20); pub const RSVP_Err_TC_ERROR = @as(u32, 21); pub const RSVP_Erv_Conflict_Serv = @as(u32, 1); pub const RSVP_Erv_No_Serv = @as(u32, 2); pub const RSVP_Erv_Crazy_Flowspec = @as(u32, 3); pub const RSVP_Erv_Crazy_Tspec = @as(u32, 4); pub const RSVP_Err_TC_SYS_ERROR = @as(u32, 22); pub const RSVP_Err_RSVP_SYS_ERROR = @as(u32, 23); pub const RSVP_Erv_MEMORY = @as(u32, 1); pub const RSVP_Erv_API = @as(u32, 2); pub const LPM_PE_USER_IDENTITY = @as(u32, 2); pub const LPM_PE_APP_IDENTITY = @as(u32, 3); pub const ERROR_NO_MORE_INFO = @as(u32, 1); pub const UNSUPPORTED_CREDENTIAL_TYPE = @as(u32, 2); pub const INSUFFICIENT_PRIVILEGES = @as(u32, 3); pub const EXPIRED_CREDENTIAL = @as(u32, 4); pub const IDENTITY_CHANGED = @as(u32, 5); pub const LPM_OK = @as(u32, 0); pub const INV_LPM_HANDLE = @as(u32, 1); pub const LPM_TIME_OUT = @as(u32, 2); pub const INV_REQ_HANDLE = @as(u32, 3); pub const DUP_RESULTS = @as(u32, 4); pub const INV_RESULTS = @as(u32, 5); pub const LPM_PE_ALL_TYPES = @as(u32, 0); pub const LPM_API_VERSION_1 = @as(u32, 1); pub const PCM_VERSION_1 = @as(u32, 1); pub const LPV_RESERVED = @as(u32, 0); pub const LPV_MIN_PRIORITY = @as(u32, 1); pub const LPV_MAX_PRIORITY = @as(u32, 65280); pub const LPV_DROP_MSG = @as(u32, 65533); pub const LPV_DONT_CARE = @as(u32, 65534); pub const LPV_REJECT = @as(u32, 65535); pub const FORCE_IMMEDIATE_REFRESH = @as(u32, 1); pub const LPM_RESULT_READY = @as(u32, 0); pub const LPM_RESULT_DEFER = @as(u32, 1); pub const RCVD_PATH_TEAR = @as(u32, 1); pub const RCVD_RESV_TEAR = @as(u32, 2); pub const ADM_CTRL_FAILED = @as(u32, 3); pub const STATE_TIMEOUT = @as(u32, 4); pub const FLOW_DURATION = @as(u32, 5); pub const RESOURCES_ALLOCATED = @as(u32, 1); pub const RESOURCES_MODIFIED = @as(u32, 2); pub const CURRENT_TCI_VERSION = @as(u32, 2); pub const TC_NOTIFY_IFC_UP = @as(u32, 1); pub const TC_NOTIFY_IFC_CLOSE = @as(u32, 2); pub const TC_NOTIFY_IFC_CHANGE = @as(u32, 3); pub const TC_NOTIFY_PARAM_CHANGED = @as(u32, 4); pub const TC_NOTIFY_FLOW_CLOSE = @as(u32, 5); pub const MAX_STRING_LENGTH = @as(u32, 256); pub const QOS_OUTGOING_DEFAULT_MINIMUM_BANDWIDTH = @as(u32, 4294967295); pub const QOS_QUERYFLOW_FRESH = @as(u32, 1); pub const QOS_NON_ADAPTIVE_FLOW = @as(u32, 2); pub const IS_GUAR_RSPEC = @as(i32, 130); pub const GUAR_ADSPARM_C = @as(i32, 131); pub const GUAR_ADSPARM_D = @as(i32, 132); pub const GUAR_ADSPARM_Ctot = @as(i32, 133); pub const GUAR_ADSPARM_Dtot = @as(i32, 134); pub const GUAR_ADSPARM_Csum = @as(i32, 135); pub const GUAR_ADSPARM_Dsum = @as(i32, 136); //-------------------------------------------------------------------------------- // Section: Types (81) //-------------------------------------------------------------------------------- pub const LPM_HANDLE = isize; pub const RHANDLE = isize; pub const FLOWSPEC = extern struct { TokenRate: u32, TokenBucketSize: u32, PeakBandwidth: u32, Latency: u32, DelayVariation: u32, ServiceType: u32, MaxSduSize: u32, MinimumPolicedSize: u32, }; pub const QOS_OBJECT_HDR = extern struct { ObjectType: u32, ObjectLength: u32, }; pub const QOS_SD_MODE = extern struct { ObjectHdr: QOS_OBJECT_HDR, ShapeDiscardMode: u32, }; pub const QOS_SHAPING_RATE = extern struct { ObjectHdr: QOS_OBJECT_HDR, ShapingRate: u32, }; pub const RsvpObjHdr = extern struct { obj_length: u16, obj_class: u8, obj_ctype: u8, }; pub const Session_IPv4 = extern struct { sess_destaddr: IN_ADDR, sess_protid: u8, sess_flags: u8, sess_destport: u16, }; pub const RSVP_SESSION = extern struct { sess_header: RsvpObjHdr, sess_u: extern union { sess_ipv4: Session_IPv4, }, }; pub const Rsvp_Hop_IPv4 = extern struct { hop_ipaddr: IN_ADDR, hop_LIH: u32, }; pub const RSVP_HOP = extern struct { hop_header: RsvpObjHdr, hop_u: extern union { hop_ipv4: Rsvp_Hop_IPv4, }, }; pub const RESV_STYLE = extern struct { style_header: RsvpObjHdr, style_word: u32, }; pub const Filter_Spec_IPv4 = extern struct { filt_ipaddr: IN_ADDR, filt_unused: u16, filt_port: u16, }; pub const Filter_Spec_IPv4GPI = extern struct { filt_ipaddr: IN_ADDR, filt_gpi: u32, }; pub const FILTER_SPEC = extern struct { filt_header: RsvpObjHdr, filt_u: extern union { filt_ipv4: Filter_Spec_IPv4, filt_ipv4gpi: Filter_Spec_IPv4GPI, }, }; pub const Scope_list_ipv4 = extern struct { scopl_ipaddr: [1]IN_ADDR, }; pub const RSVP_SCOPE = extern struct { scopl_header: RsvpObjHdr, scope_u: extern union { scopl_ipv4: Scope_list_ipv4, }, }; pub const Error_Spec_IPv4 = extern struct { errs_errnode: IN_ADDR, errs_flags: u8, errs_code: u8, errs_value: u16, }; pub const ERROR_SPEC = extern struct { errs_header: RsvpObjHdr, errs_u: extern union { errs_ipv4: Error_Spec_IPv4, }, }; pub const POLICY_DATA = extern struct { PolicyObjHdr: RsvpObjHdr, usPeOffset: u16, usReserved: u16, }; pub const POLICY_ELEMENT = extern struct { usPeLength: u16, usPeType: u16, ucPeData: [4]u8, }; pub const int_serv_wkp = enum(i32) { HOP_CNT = 4, PATH_BW = 6, MIN_LATENCY = 8, COMPOSED_MTU = 10, TB_TSPEC = 127, Q_TSPEC = 128, }; pub const IS_WKP_HOP_CNT = int_serv_wkp.HOP_CNT; pub const IS_WKP_PATH_BW = int_serv_wkp.PATH_BW; pub const IS_WKP_MIN_LATENCY = int_serv_wkp.MIN_LATENCY; pub const IS_WKP_COMPOSED_MTU = int_serv_wkp.COMPOSED_MTU; pub const IS_WKP_TB_TSPEC = int_serv_wkp.TB_TSPEC; pub const IS_WKP_Q_TSPEC = int_serv_wkp.Q_TSPEC; pub const IntServMainHdr = extern struct { ismh_version: u8, ismh_unused: u8, ismh_len32b: u16, }; pub const IntServServiceHdr = extern struct { issh_service: u8, issh_flags: u8, issh_len32b: u16, }; pub const IntServParmHdr = extern struct { isph_parm_num: u8, isph_flags: u8, isph_len32b: u16, }; pub const GenTspecParms = extern struct { TB_Tspec_r: f32, TB_Tspec_b: f32, TB_Tspec_p: f32, TB_Tspec_m: u32, TB_Tspec_M: u32, }; pub const GenTspec = extern struct { gen_Tspec_serv_hdr: IntServServiceHdr, gen_Tspec_parm_hdr: IntServParmHdr, gen_Tspec_parms: GenTspecParms, }; pub const QualTspecParms = extern struct { TB_Tspec_M: u32, }; pub const QualTspec = extern struct { qual_Tspec_serv_hdr: IntServServiceHdr, qual_Tspec_parm_hdr: IntServParmHdr, qual_Tspec_parms: QualTspecParms, }; pub const QualAppFlowSpec = extern struct { Q_spec_serv_hdr: IntServServiceHdr, Q_spec_parm_hdr: IntServParmHdr, Q_spec_parms: QualTspecParms, }; pub const IntServTspecBody = extern struct { st_mh: IntServMainHdr, tspec_u: extern union { gen_stspec: GenTspec, qual_stspec: QualTspec, }, }; pub const SENDER_TSPEC = extern struct { stspec_header: RsvpObjHdr, stspec_body: IntServTspecBody, }; pub const CtrlLoadFlowspec = extern struct { CL_spec_serv_hdr: IntServServiceHdr, CL_spec_parm_hdr: IntServParmHdr, CL_spec_parms: GenTspecParms, }; pub const GuarRspec = extern struct { Guar_R: f32, Guar_S: u32, }; pub const GuarFlowSpec = extern struct { Guar_serv_hdr: IntServServiceHdr, Guar_Tspec_hdr: IntServParmHdr, Guar_Tspec_parms: GenTspecParms, Guar_Rspec_hdr: IntServParmHdr, Guar_Rspec: GuarRspec, }; pub const IntServFlowSpec = extern struct { spec_mh: IntServMainHdr, spec_u: extern union { CL_spec: CtrlLoadFlowspec, G_spec: GuarFlowSpec, Q_spec: QualAppFlowSpec, }, }; pub const IS_FLOWSPEC = extern struct { flow_header: RsvpObjHdr, flow_body: IntServFlowSpec, }; pub const flow_desc = extern struct { u1: extern union { stspec: ?*SENDER_TSPEC, isflow: ?*IS_FLOWSPEC, }, u2: extern union { stemp: ?*FILTER_SPEC, fspec: ?*FILTER_SPEC, }, }; pub const Gads_parms_t = extern struct { Gads_serv_hdr: IntServServiceHdr, Gads_Ctot_hdr: IntServParmHdr, Gads_Ctot: u32, Gads_Dtot_hdr: IntServParmHdr, Gads_Dtot: u32, Gads_Csum_hdr: IntServParmHdr, Gads_Csum: u32, Gads_Dsum_hdr: IntServParmHdr, Gads_Dsum: u32, }; pub const GenAdspecParams = extern struct { gen_parm_hdr: IntServServiceHdr, gen_parm_hopcnt_hdr: IntServParmHdr, gen_parm_hopcnt: u32, gen_parm_pathbw_hdr: IntServParmHdr, gen_parm_path_bw: f32, gen_parm_minlat_hdr: IntServParmHdr, gen_parm_min_latency: u32, gen_parm_compmtu_hdr: IntServParmHdr, gen_parm_composed_MTU: u32, }; pub const IS_ADSPEC_BODY = extern struct { adspec_mh: IntServMainHdr, adspec_genparms: GenAdspecParams, }; pub const ADSPEC = extern struct { adspec_header: RsvpObjHdr, adspec_body: IS_ADSPEC_BODY, }; pub const ID_ERROR_OBJECT = extern struct { usIdErrLength: u16, ucAType: u8, ucSubType: u8, usReserved: u16, usIdErrorValue: u16, ucIdErrData: [4]u8, }; pub const RSVP_MSG_OBJS = extern struct { RsvpMsgType: i32, pRsvpSession: ?*RSVP_SESSION, pRsvpFromHop: ?*RSVP_HOP, pRsvpToHop: ?*RSVP_HOP, pResvStyle: ?*RESV_STYLE, pRsvpScope: ?*RSVP_SCOPE, FlowDescCount: i32, pFlowDescs: ?*flow_desc, PdObjectCount: i32, ppPdObjects: ?*?*POLICY_DATA, pErrorSpec: ?*ERROR_SPEC, pAdspec: ?*ADSPEC, }; pub const PALLOCMEM = fn( Size: u32, ) callconv(@import("std").os.windows.WINAPI) ?*c_void; pub const PFREEMEM = fn( pv: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) void; pub const policy_decision = extern struct { lpvResult: u32, wPolicyErrCode: u16, wPolicyErrValue: u16, }; pub const CBADMITRESULT = fn( LpmHandle: LPM_HANDLE, RequestHandle: RHANDLE, ulPcmActionFlags: u32, LpmError: i32, PolicyDecisionsCount: i32, pPolicyDecisions: ?*policy_decision, ) callconv(@import("std").os.windows.WINAPI) ?*u32; pub const CBGETRSVPOBJECTS = fn( LpmHandle: LPM_HANDLE, RequestHandle: RHANDLE, LpmError: i32, RsvpObjectsCount: i32, ppRsvpObjects: ?*?*RsvpObjHdr, ) callconv(@import("std").os.windows.WINAPI) ?*u32; pub const LPM_INIT_INFO = extern struct { PcmVersionNumber: u32, ResultTimeLimit: u32, ConfiguredLpmCount: i32, AllocMemory: ?PALLOCMEM, FreeMemory: ?PFREEMEM, PcmAdmitResultCallback: ?CBADMITRESULT, GetRsvpObjectsCallback: ?CBGETRSVPOBJECTS, }; pub const lpmiptable = extern struct { ulIfIndex: u32, MediaType: u32, IfIpAddr: IN_ADDR, IfNetMask: IN_ADDR, }; pub const QOS_TRAFFIC_TYPE = enum(i32) { BestEffort = 0, Background = 1, ExcellentEffort = 2, AudioVideo = 3, Voice = 4, Control = 5, }; pub const QOSTrafficTypeBestEffort = QOS_TRAFFIC_TYPE.BestEffort; pub const QOSTrafficTypeBackground = QOS_TRAFFIC_TYPE.Background; pub const QOSTrafficTypeExcellentEffort = QOS_TRAFFIC_TYPE.ExcellentEffort; pub const QOSTrafficTypeAudioVideo = QOS_TRAFFIC_TYPE.AudioVideo; pub const QOSTrafficTypeVoice = QOS_TRAFFIC_TYPE.Voice; pub const QOSTrafficTypeControl = QOS_TRAFFIC_TYPE.Control; pub const QOS_SET_FLOW = enum(i32) { TrafficType = 0, OutgoingRate = 1, OutgoingDSCPValue = 2, }; pub const QOSSetTrafficType = QOS_SET_FLOW.TrafficType; pub const QOSSetOutgoingRate = QOS_SET_FLOW.OutgoingRate; pub const QOSSetOutgoingDSCPValue = QOS_SET_FLOW.OutgoingDSCPValue; pub const QOS_PACKET_PRIORITY = extern struct { ConformantDSCPValue: u32, NonConformantDSCPValue: u32, ConformantL2Value: u32, NonConformantL2Value: u32, }; pub const QOS_FLOW_FUNDAMENTALS = extern struct { BottleneckBandwidthSet: BOOL, BottleneckBandwidth: u64, AvailableBandwidthSet: BOOL, AvailableBandwidth: u64, RTTSet: BOOL, RTT: u32, }; pub const QOS_FLOWRATE_REASON = enum(i32) { NotApplicable = 0, ContentChange = 1, Congestion = 2, HigherContentEncoding = 3, UserCaused = 4, }; pub const QOSFlowRateNotApplicable = QOS_FLOWRATE_REASON.NotApplicable; pub const QOSFlowRateContentChange = QOS_FLOWRATE_REASON.ContentChange; pub const QOSFlowRateCongestion = QOS_FLOWRATE_REASON.Congestion; pub const QOSFlowRateHigherContentEncoding = QOS_FLOWRATE_REASON.HigherContentEncoding; pub const QOSFlowRateUserCaused = QOS_FLOWRATE_REASON.UserCaused; pub const QOS_SHAPING = enum(i32) { ShapeOnly = 0, ShapeAndMark = 1, UseNonConformantMarkings = 2, }; pub const QOSShapeOnly = QOS_SHAPING.ShapeOnly; pub const QOSShapeAndMark = QOS_SHAPING.ShapeAndMark; pub const QOSUseNonConformantMarkings = QOS_SHAPING.UseNonConformantMarkings; pub const QOS_FLOWRATE_OUTGOING = extern struct { Bandwidth: u64, ShapingBehavior: QOS_SHAPING, Reason: QOS_FLOWRATE_REASON, }; pub const QOS_QUERY_FLOW = enum(i32) { FlowFundamentals = 0, PacketPriority = 1, OutgoingRate = 2, }; pub const QOSQueryFlowFundamentals = QOS_QUERY_FLOW.FlowFundamentals; pub const QOSQueryPacketPriority = QOS_QUERY_FLOW.PacketPriority; pub const QOSQueryOutgoingRate = QOS_QUERY_FLOW.OutgoingRate; pub const QOS_NOTIFY_FLOW = enum(i32) { Congested = 0, Uncongested = 1, Available = 2, }; pub const QOSNotifyCongested = QOS_NOTIFY_FLOW.Congested; pub const QOSNotifyUncongested = QOS_NOTIFY_FLOW.Uncongested; pub const QOSNotifyAvailable = QOS_NOTIFY_FLOW.Available; pub const QOS_VERSION = extern struct { MajorVersion: u16, MinorVersion: u16, }; pub const QOS_FRIENDLY_NAME = extern struct { ObjectHdr: QOS_OBJECT_HDR, FriendlyName: [256]u16, }; pub const QOS_TRAFFIC_CLASS = extern struct { ObjectHdr: QOS_OBJECT_HDR, TrafficClass: u32, }; pub const QOS_DS_CLASS = extern struct { ObjectHdr: QOS_OBJECT_HDR, DSField: u32, }; pub const QOS_DIFFSERV = extern struct { ObjectHdr: QOS_OBJECT_HDR, DSFieldCount: u32, DiffservRule: [1]u8, }; pub const QOS_DIFFSERV_RULE = extern struct { InboundDSField: u8, ConformingOutboundDSField: u8, NonConformingOutboundDSField: u8, ConformingUserPriority: u8, NonConformingUserPriority: u8, }; pub const QOS_TCP_TRAFFIC = extern struct { ObjectHdr: QOS_OBJECT_HDR, }; pub const TCI_NOTIFY_HANDLER = fn( ClRegCtx: ?HANDLE, ClIfcCtx: ?HANDLE, Event: u32, SubCode: ?HANDLE, BufSize: u32, // TODO: what to do with BytesParamIndex 4? Buffer: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) void; pub const TCI_ADD_FLOW_COMPLETE_HANDLER = fn( ClFlowCtx: ?HANDLE, Status: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const TCI_MOD_FLOW_COMPLETE_HANDLER = fn( ClFlowCtx: ?HANDLE, Status: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const TCI_DEL_FLOW_COMPLETE_HANDLER = fn( ClFlowCtx: ?HANDLE, Status: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const TCI_CLIENT_FUNC_LIST = extern struct { ClNotifyHandler: ?TCI_NOTIFY_HANDLER, ClAddFlowCompleteHandler: ?TCI_ADD_FLOW_COMPLETE_HANDLER, ClModifyFlowCompleteHandler: ?TCI_MOD_FLOW_COMPLETE_HANDLER, ClDeleteFlowCompleteHandler: ?TCI_DEL_FLOW_COMPLETE_HANDLER, }; pub const ADDRESS_LIST_DESCRIPTOR = extern struct { MediaType: u32, AddressList: NETWORK_ADDRESS_LIST, }; pub const TC_IFC_DESCRIPTOR = extern struct { Length: u32, pInterfaceName: ?PWSTR, pInterfaceID: ?PWSTR, AddressListDesc: ADDRESS_LIST_DESCRIPTOR, }; pub const TC_SUPPORTED_INFO_BUFFER = extern struct { InstanceIDLength: u16, InstanceID: [256]u16, InterfaceLuid: u64, AddrListDesc: ADDRESS_LIST_DESCRIPTOR, }; pub const TC_GEN_FILTER = extern struct { AddressType: u16, PatternSize: u32, Pattern: ?*c_void, Mask: ?*c_void, }; pub const TC_GEN_FLOW = extern struct { SendingFlowspec: FLOWSPEC, ReceivingFlowspec: FLOWSPEC, TcObjectsLength: u32, TcObjects: [1]QOS_OBJECT_HDR, }; pub const IP_PATTERN = extern struct { Reserved1: u32, Reserved2: u32, SrcAddr: u32, DstAddr: u32, S_un: extern union { S_un_ports: extern struct { s_srcport: u16, s_dstport: u16, }, S_un_icmp: extern struct { s_type: u8, s_code: u8, filler: u16, }, S_Spi: u32, }, ProtocolId: u8, Reserved3: [3]u8, }; pub const IPX_PATTERN = extern struct { Src: extern struct { NetworkAddress: u32, NodeAddress: [6]u8, Socket: u16, }, Dest: extern struct { NetworkAddress: u32, NodeAddress: [6]u8, Socket: u16, }, }; pub const ENUMERATION_BUFFER = extern struct { Length: u32, OwnerProcessId: u32, FlowNameLength: u16, FlowName: [256]u16, pFlow: ?*TC_GEN_FLOW, NumberOfFilters: u32, GenericFilter: [1]TC_GEN_FILTER, }; pub const QOS = extern struct { SendingFlowspec: FLOWSPEC, ReceivingFlowspec: FLOWSPEC, ProviderSpecific: WSABUF, }; //-------------------------------------------------------------------------------- // Section: Functions (31) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSCreateHandle( Version: ?*QOS_VERSION, QOSHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSCloseHandle( QOSHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSStartTrackingClient( QOSHandle: ?HANDLE, DestAddr: ?*SOCKADDR, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSStopTrackingClient( QOSHandle: ?HANDLE, DestAddr: ?*SOCKADDR, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSEnumerateFlows( QOSHandle: ?HANDLE, Size: ?*u32, // TODO: what to do with BytesParamIndex 1? Buffer: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSAddSocketToFlow( QOSHandle: ?HANDLE, Socket: ?SOCKET, DestAddr: ?*SOCKADDR, TrafficType: QOS_TRAFFIC_TYPE, Flags: u32, FlowId: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' // This function from dll 'qwave' is being skipped because it has some sort of issue pub fn QOSRemoveSocketFromFlow() void { @panic("this function is not working"); } // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSSetFlow( QOSHandle: ?HANDLE, FlowId: u32, Operation: QOS_SET_FLOW, Size: u32, // TODO: what to do with BytesParamIndex 3? Buffer: ?*c_void, Flags: u32, Overlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSQueryFlow( QOSHandle: ?HANDLE, FlowId: u32, Operation: QOS_QUERY_FLOW, Size: ?*u32, // TODO: what to do with BytesParamIndex 3? Buffer: ?*c_void, Flags: u32, Overlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSNotifyFlow( QOSHandle: ?HANDLE, FlowId: u32, Operation: QOS_NOTIFY_FLOW, Size: ?*u32, // TODO: what to do with BytesParamIndex 3? Buffer: ?*c_void, Flags: u32, Overlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSCancel( QOSHandle: ?HANDLE, Overlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcRegisterClient( TciVersion: u32, ClRegCtx: ?HANDLE, ClientHandlerList: ?*TCI_CLIENT_FUNC_LIST, pClientHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcEnumerateInterfaces( ClientHandle: ?HANDLE, pBufferSize: ?*u32, InterfaceBuffer: ?*TC_IFC_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcOpenInterfaceA( pInterfaceName: ?PSTR, ClientHandle: ?HANDLE, ClIfcCtx: ?HANDLE, pIfcHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcOpenInterfaceW( pInterfaceName: ?PWSTR, ClientHandle: ?HANDLE, ClIfcCtx: ?HANDLE, pIfcHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcCloseInterface( IfcHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcQueryInterface( IfcHandle: ?HANDLE, pGuidParam: ?*Guid, NotifyChange: BOOLEAN, pBufferSize: ?*u32, // TODO: what to do with BytesParamIndex 3? Buffer: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcSetInterface( IfcHandle: ?HANDLE, pGuidParam: ?*Guid, BufferSize: u32, // TODO: what to do with BytesParamIndex 2? Buffer: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcQueryFlowA( pFlowName: ?PSTR, pGuidParam: ?*Guid, pBufferSize: ?*u32, // TODO: what to do with BytesParamIndex 2? Buffer: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcQueryFlowW( pFlowName: ?PWSTR, pGuidParam: ?*Guid, pBufferSize: ?*u32, // TODO: what to do with BytesParamIndex 2? Buffer: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcSetFlowA( pFlowName: ?PSTR, pGuidParam: ?*Guid, BufferSize: u32, // TODO: what to do with BytesParamIndex 2? Buffer: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcSetFlowW( pFlowName: ?PWSTR, pGuidParam: ?*Guid, BufferSize: u32, // TODO: what to do with BytesParamIndex 2? Buffer: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcAddFlow( IfcHandle: ?HANDLE, ClFlowCtx: ?HANDLE, Flags: u32, pGenericFlow: ?*TC_GEN_FLOW, pFlowHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcGetFlowNameA( FlowHandle: ?HANDLE, StrSize: u32, pFlowName: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcGetFlowNameW( FlowHandle: ?HANDLE, StrSize: u32, pFlowName: [*:0]u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcModifyFlow( FlowHandle: ?HANDLE, pGenericFlow: ?*TC_GEN_FLOW, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcAddFilter( FlowHandle: ?HANDLE, pGenericFilter: ?*TC_GEN_FILTER, pFilterHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcDeregisterClient( ClientHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcDeleteFlow( FlowHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcDeleteFilter( FilterHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcEnumerateFlows( IfcHandle: ?HANDLE, pEnumHandle: ?*?HANDLE, pFlowCount: ?*u32, pBufSize: ?*u32, Buffer: ?*ENUMERATION_BUFFER, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (4) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const TcOpenInterface = thismodule.TcOpenInterfaceA; pub const TcQueryFlow = thismodule.TcQueryFlowA; pub const TcSetFlow = thismodule.TcSetFlowA; pub const TcGetFlowName = thismodule.TcGetFlowNameA; }, .wide => struct { pub const TcOpenInterface = thismodule.TcOpenInterfaceW; pub const TcQueryFlow = thismodule.TcQueryFlowW; pub const TcSetFlow = thismodule.TcSetFlowW; pub const TcGetFlowName = thismodule.TcGetFlowNameW; }, .unspecified => if (@import("builtin").is_test) struct { pub const TcOpenInterface = *opaque{}; pub const TcQueryFlow = *opaque{}; pub const TcSetFlow = *opaque{}; pub const TcGetFlowName = *opaque{}; } else struct { pub const TcOpenInterface = @compileError("'TcOpenInterface' requires that UNICODE be set to true or false in the root module"); pub const TcQueryFlow = @compileError("'TcQueryFlow' requires that UNICODE be set to true or false in the root module"); pub const TcSetFlow = @compileError("'TcSetFlow' requires that UNICODE be set to true or false in the root module"); pub const TcGetFlowName = @compileError("'TcGetFlowName' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (12) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BOOLEAN = @import("../foundation.zig").BOOLEAN; const HANDLE = @import("../foundation.zig").HANDLE; const IN_ADDR = @import("../networking/win_sock.zig").IN_ADDR; const NETWORK_ADDRESS_LIST = @import("../network_management/ndis.zig").NETWORK_ADDRESS_LIST; const OVERLAPPED = @import("../system/system_services.zig").OVERLAPPED; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const SOCKADDR = @import("../networking/win_sock.zig").SOCKADDR; const SOCKET = @import("../networking/win_sock.zig").SOCKET; const WSABUF = @import("../networking/win_sock.zig").WSABUF; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PALLOCMEM")) { _ = PALLOCMEM; } if (@hasDecl(@This(), "PFREEMEM")) { _ = PFREEMEM; } if (@hasDecl(@This(), "CBADMITRESULT")) { _ = CBADMITRESULT; } if (@hasDecl(@This(), "CBGETRSVPOBJECTS")) { _ = CBGETRSVPOBJECTS; } if (@hasDecl(@This(), "TCI_NOTIFY_HANDLER")) { _ = TCI_NOTIFY_HANDLER; } if (@hasDecl(@This(), "TCI_ADD_FLOW_COMPLETE_HANDLER")) { _ = TCI_ADD_FLOW_COMPLETE_HANDLER; } if (@hasDecl(@This(), "TCI_MOD_FLOW_COMPLETE_HANDLER")) { _ = TCI_MOD_FLOW_COMPLETE_HANDLER; } if (@hasDecl(@This(), "TCI_DEL_FLOW_COMPLETE_HANDLER")) { _ = TCI_DEL_FLOW_COMPLETE_HANDLER; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
deps/zigwin32/win32/network_management/qo_s.zig
const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; const assert = std.debug.assert; const Compilation = @import("Compilation.zig"); const Source = @import("Source.zig"); const Tokenizer = @import("Tokenizer.zig"); const Preprocessor = @import("Preprocessor.zig"); const Tree = @import("Tree.zig"); const Token = Tree.Token; const TokenIndex = Tree.TokenIndex; const NodeIndex = Tree.NodeIndex; const Type = @import("Type.zig"); const Diagnostics = @import("Diagnostics.zig"); const NodeList = std.ArrayList(NodeIndex); const Parser = @This(); pub const Result = struct { ty: Type = .{ .specifier = .int }, data: union(enum) { unsigned: u64, signed: i64, lval: NodeIndex, node: NodeIndex, none, } = .none, pub fn getBool(res: Result) bool { return switch (res.data) { .signed => |v| v != 0, .unsigned => |v| v != 0, .none, .node, .lval => unreachable, }; } fn expect(res: Result, p: *Parser) Error!void { if (res.data == .none) { try p.errTok(.expected_expr, p.tok_i); return error.ParsingFailed; } } fn node(p: *Parser, n: Tree.Node) !Result { const index = try p.addNode(n); return Result{ .ty = n.ty, .data = .{ .lval = index } }; } fn lval(p: *Parser, n: Tree.Node) !Result { const index = try p.addNode(n); return Result{ .ty = n.ty, .data = .{ .lval = index } }; } fn toNode(res: Result, p: *Parser) !NodeIndex { var parts: [2]TokenIndex = undefined; switch (res.data) { .none => return 0, .node, .lval => |n| return n, .signed => |v| parts = @bitCast([2]TokenIndex, v), .unsigned => |v| parts = @bitCast([2]TokenIndex, v), } return p.addNode(.{ .tag = .int_literal, .ty = res.ty, .data = .{ .first = parts[0], .second = parts[1] }, }); } fn coerce(res: Result, p: *Parser, dest_ty: Type) !Result { var casted = res; var cur_ty = res.ty; if (casted.data == .lval) { cur_ty.qual.@"const" = false; casted = try node(p, .{ .tag = .lval_to_rval, .ty = cur_ty, .data = .{ .first = try casted.toNode(p) }, }); } if (dest_ty.specifier == .pointer and cur_ty.isArray()) { const elem_ty = &cur_ty.data.array.elem; cur_ty.specifier = .pointer; cur_ty.data = .{ .sub_type = elem_ty }; casted = try node(p, .{ .tag = .array_to_pointer, .ty = cur_ty, .data = .{ .first = try casted.toNode(p) }, }); } return casted; } /// Return true if both are constants. fn adjustTypes(a: *Result, b: *Result, p: *Parser) !bool { const a_is_unsigned = a.ty.isUnsignedInt(p.pp.comp); const b_is_unsigned = b.ty.isUnsignedInt(p.pp.comp); if (a_is_unsigned != b_is_unsigned) {} return (a.data == .unsigned or a.data == .signed) and (b.data == .unsigned or b.data == .signed); } fn hash(res: Result) u64 { var val: i64 = undefined; switch (res.data) { .unsigned => |v| val = @bitCast(i64, v), // doesn't matter we only want a hash .signed => |v| val = v, .none, .node, .lval => unreachable, } return std.hash.Wyhash.hash(0, mem.asBytes(&val)); } fn eql(a: Result, b: Result) bool { return a.compare(.eq, b); } fn compare(a: Result, op: std.math.CompareOperator, b: Result) bool { switch (a.data) { .unsigned => |val| return std.math.compare(val, op, b.data.unsigned), .signed => |val| return std.math.compare(val, op, b.data.signed), .none, .node, .lval => unreachable, } } fn mul(a: *Result, tok: TokenIndex, b: Result, p: *Parser) !void { const size = a.ty.sizeof(p.pp.comp); var overflow = false; switch (a.data) { .unsigned => |*v| { switch (size) { 1 => unreachable, // upcasted to int 2 => unreachable, // upcasted to int 4 => { var res: u32 = undefined; overflow = @mulWithOverflow(u32, @truncate(u32, v.*), @truncate(u32, b.data.unsigned), &res); v.* = res; }, 8 => overflow = @mulWithOverflow(u64, v.*, b.data.unsigned, v), else => unreachable, } if (overflow) try p.errExtra(.overflow_unsigned, tok, .{ .unsigned = v.* }); }, .signed => |*v| { switch (size) { 1 => unreachable, // upcasted to int 2 => unreachable, // upcasted to int 4 => { var res: i32 = undefined; overflow = @mulWithOverflow(i32, @truncate(i32, v.*), @truncate(i32, b.data.signed), &res); v.* = res; }, 8 => overflow = @mulWithOverflow(i64, v.*, b.data.signed, v), else => unreachable, } if (overflow) try p.errExtra(.overflow_signed, tok, .{ .signed = v.* }); }, .none, .node, .lval => unreachable, } } fn add(a: *Result, tok: TokenIndex, b: Result, p: *Parser) !void { const size = a.ty.sizeof(p.pp.comp); var overflow = false; switch (a.data) { .unsigned => |*v| { switch (size) { 1 => unreachable, // upcasted to int 2 => unreachable, // upcasted to int 4 => { var res: u32 = undefined; overflow = @addWithOverflow(u32, @truncate(u32, v.*), @truncate(u32, b.data.unsigned), &res); v.* = res; }, 8 => overflow = @addWithOverflow(u64, v.*, b.data.unsigned, v), else => unreachable, } if (overflow) try p.errExtra(.overflow_unsigned, tok, .{ .unsigned = v.* }); }, .signed => |*v| { switch (size) { 1 => unreachable, // upcasted to int 2 => unreachable, // upcasted to int 4 => { var res: i32 = undefined; overflow = @addWithOverflow(i32, @truncate(i32, v.*), @truncate(i32, b.data.signed), &res); v.* = res; }, 8 => overflow = @addWithOverflow(i64, v.*, b.data.signed, v), else => unreachable, } if (overflow) try p.errExtra(.overflow_signed, tok, .{ .signed = v.* }); }, .none, .node, .lval => unreachable, } } fn sub(a: *Result, tok: TokenIndex, b: Result, p: *Parser) !void { const size = a.ty.sizeof(p.pp.comp); var overflow = false; switch (a.data) { .unsigned => |*v| { switch (size) { 1 => unreachable, // upcasted to int 2 => unreachable, // upcasted to int 4 => { var res: u32 = undefined; overflow = @subWithOverflow(u32, @truncate(u32, v.*), @truncate(u32, b.data.unsigned), &res); v.* = res; }, 8 => overflow = @subWithOverflow(u64, v.*, b.data.unsigned, v), else => unreachable, } if (overflow) try p.errExtra(.overflow_unsigned, tok, .{ .unsigned = v.* }); }, .signed => |*v| { switch (size) { 1 => unreachable, // upcasted to int 2 => unreachable, // upcasted to int 4 => { var res: i32 = undefined; overflow = @subWithOverflow(i32, @truncate(i32, v.*), @truncate(i32, b.data.signed), &res); v.* = res; }, 8 => overflow = @subWithOverflow(i64, v.*, b.data.signed, v), else => unreachable, } if (overflow) try p.errExtra(.overflow_signed, tok, .{ .signed = v.* }); }, .none, .node, .lval => unreachable, } } }; const Scope = union(enum) { typedef: Symbol, @"struct": Symbol, @"union": Symbol, @"enum": Symbol, symbol: Symbol, enumeration: Enumeration, loop, @"switch": *Switch, const Symbol = struct { name: []const u8, node: NodeIndex, name_tok: TokenIndex, }; const Enumeration = struct { name: []const u8, value: Result, }; const Switch = struct { cases: CaseMap, default: ?Case = null, const ResultContext = struct { pub fn eql(_: ResultContext, a: Result, b: Result) bool { return a.eql(b); } pub fn hash(_: ResultContext, a: Result) u64 { return a.hash(); } }; const CaseMap = std.HashMap(Result, Case, ResultContext, std.hash_map.default_max_load_percentage); const Case = struct { node: NodeIndex, tok: TokenIndex, }; }; }; const Label = union(enum) { unresolved_goto: TokenIndex, label: TokenIndex, }; pub const Error = Compilation.Error || error{ParsingFailed}; pp: *Preprocessor, arena: *Allocator, nodes: Tree.Node.List = .{}, data: NodeList, scopes: std.ArrayList(Scope), tok_ids: []const Token.Id, tok_i: TokenIndex = 0, want_const: bool = false, in_function: bool = false, cur_decl_list: *NodeList, labels: std.ArrayList(Label), label_count: u32 = 0, fn eatToken(p: *Parser, id: Token.Id) ?TokenIndex { if (p.tok_ids[p.tok_i] == id) { defer p.tok_i += 1; return p.tok_i; } else return null; } fn expectToken(p: *Parser, expected: Token.Id) Error!TokenIndex { const actual = p.tok_ids[p.tok_i]; if (actual != expected) { try p.errExtra( switch (actual) { .invalid => .expected_invalid, else => .expected_token, }, p.tok_i, .{ .tok_id = .{ .expected = expected, .actual = actual, } }, ); return error.ParsingFailed; } defer p.tok_i += 1; return p.tok_i; } fn tokSlice(p: *Parser, tok: TokenIndex) []const u8 { if (p.tok_ids[tok].lexeme()) |some| return some; const loc = p.pp.tokens.items(.loc)[tok]; var tmp_tokenizer = Tokenizer{ .buf = if (loc.id == .generated) p.pp.generated.items else p.pp.comp.getSource(loc.id).buf, .index = loc.byte_offset, .source = .generated, }; const res = tmp_tokenizer.next(); return tmp_tokenizer.buf[res.start..res.end]; } fn expectClosing(p: *Parser, opening: TokenIndex, id: Token.Id) Error!void { _ = p.expectToken(id) catch |e| { if (e == error.ParsingFailed) { try p.pp.comp.diag.add(.{ .tag = switch (id) { .r_paren => .to_match_paren, .r_brace => .to_match_brace, .r_bracket => .to_match_brace, else => unreachable, }, .loc = p.pp.tokens.items(.loc)[opening], }); } return e; }; } pub fn errStr(p: *Parser, tag: Diagnostics.Tag, tok_i: TokenIndex, str: []const u8) Compilation.Error!void { @setCold(true); return p.errExtra(tag, tok_i, .{ .str = str }); } pub fn errExtra(p: *Parser, tag: Diagnostics.Tag, tok_i: TokenIndex, extra: Diagnostics.Message.Extra) Compilation.Error!void { @setCold(true); try p.pp.comp.diag.add(.{ .tag = tag, .loc = p.pp.tokens.items(.loc)[tok_i], .extra = extra, }); } pub fn errTok(p: *Parser, tag: Diagnostics.Tag, tok_i: TokenIndex) Compilation.Error!void { @setCold(true); try p.pp.comp.diag.add(.{ .tag = tag, .loc = p.pp.tokens.items(.loc)[tok_i], }); } pub fn err(p: *Parser, tag: Diagnostics.Tag) Compilation.Error!void { @setCold(true); return p.errTok(tag, p.tok_i); } pub fn todo(p: *Parser, msg: []const u8) Error { try p.errStr(.todo, p.tok_i, msg); return error.ParsingFailed; } fn addNode(p: *Parser, node: Tree.Node) Allocator.Error!NodeIndex { const res = p.nodes.len; try p.nodes.append(p.pp.comp.gpa, node); return @intCast(u32, res); } const Range = struct { start: u32, end: u32 }; fn addList(p: *Parser, nodes: []const NodeIndex) Allocator.Error!Range { const start = @intCast(u32, p.data.items.len); try p.data.appendSlice(nodes); const end = @intCast(u32, p.data.items.len); return Range{ .start = start, .end = end }; } fn findTypedef(p: *Parser, name: []const u8) ?Scope.Symbol { var i = p.scopes.items.len; while (i > 0) { i -= 1; switch (p.scopes.items[i]) { .typedef => |t| if (mem.eql(u8, t.name, name)) return t, else => {}, } } return null; } fn findSymbol(p: *Parser, name_tok: TokenIndex) ?Scope { const name = p.tokSlice(name_tok); var i = p.scopes.items.len; while (i > 0) { i -= 1; const sym = p.scopes.items[i]; switch (sym) { .symbol => |s| if (mem.eql(u8, s.name, name)) return sym, .enumeration => |e| if (mem.eql(u8, e.name, name)) return sym, else => {}, } } return null; } fn inLoop(p: *Parser) bool { var i = p.scopes.items.len; while (i > 0) { i -= 1; switch (p.scopes.items[i]) { .loop => return true, else => {}, } } return false; } fn inLoopOrSwitch(p: *Parser) bool { var i = p.scopes.items.len; while (i > 0) { i -= 1; switch (p.scopes.items[i]) { .loop, .@"switch" => return true, else => {}, } } return false; } fn findLabel(p: *Parser, name: []const u8) ?NodeIndex { for (p.labels.items) |item| { switch (item) { .label => |l| if (mem.eql(u8, p.tokSlice(l), name)) return l, .unresolved_goto => {}, } } return null; } fn findSwitch(p: *Parser) ?*Scope.Switch { var i = p.scopes.items.len; while (i > 0) { i -= 1; switch (p.scopes.items[i]) { .@"switch" => |s| return s, else => {}, } } return null; } /// root : (decl | staticAssert)* pub fn parse(pp: *Preprocessor) Compilation.Error!Tree { var root_decls = NodeList.init(pp.comp.gpa); defer root_decls.deinit(); var arena = std.heap.ArenaAllocator.init(pp.comp.gpa); errdefer arena.deinit(); var p = Parser{ .pp = pp, .arena = &arena.allocator, .tok_ids = pp.tokens.items(.id), .cur_decl_list = &root_decls, .scopes = std.ArrayList(Scope).init(pp.comp.gpa), .data = NodeList.init(pp.comp.gpa), .labels = std.ArrayList(Label).init(pp.comp.gpa), }; defer p.scopes.deinit(); defer p.data.deinit(); defer p.labels.deinit(); errdefer p.nodes.deinit(pp.comp.gpa); // NodeIndex 0 must be invalid _ = try p.addNode(.{ .tag = .invalid, .ty = undefined }); while (p.eatToken(.eof) == null) { if (p.staticAssert() catch |er| switch (er) { error.ParsingFailed => { p.nextExternDecl(); continue; }, else => |e| return e, }) continue; if (p.decl() catch |er| switch (er) { error.ParsingFailed => { p.nextExternDecl(); continue; }, else => |e| return e, }) continue; try p.err(.expected_external_decl); p.tok_i += 1; } return Tree{ .comp = pp.comp, .tokens = pp.tokens.slice(), .arena = arena, .generated = pp.generated.items, .nodes = p.nodes.toOwnedSlice(), .data = p.data.toOwnedSlice(), .root_decls = root_decls.toOwnedSlice(), }; } fn nextExternDecl(p: *Parser) void { var parens: u32 = 0; while (p.tok_i < p.tok_ids.len) : (p.tok_i += 1) { switch (p.tok_ids[p.tok_i]) { .l_paren, .l_brace, .l_bracket => parens += 1, .r_paren, .r_brace, .r_bracket => if (parens != 0) { parens -= 1; }, .keyword_typedef, .keyword_extern, .keyword_static, .keyword_auto, .keyword_register, .keyword_thread_local, .keyword_inline, .keyword_noreturn, .keyword_void, .keyword_bool, .keyword_char, .keyword_short, .keyword_int, .keyword_long, .keyword_signed, .keyword_unsigned, .keyword_float, .keyword_double, .keyword_complex, .keyword_atomic, .keyword_enum, .keyword_struct, .keyword_union, .keyword_alignas, .identifier, => if (parens == 0) return, else => {}, } } p.tok_i -= 1; // so that we can consume the eof token elsewhere } // ====== declarations ====== /// decl /// : declSpec (initDeclarator ( ',' initDeclarator)*)? ';' /// | declSpec declarator decl* compoundStmt fn decl(p: *Parser) Error!bool { const first_tok = p.tok_i; var decl_spec = if (try p.declSpec()) |some| some else blk: { if (p.in_function) return false; switch (p.tok_ids[first_tok]) { .asterisk, .l_paren, .identifier => {}, else => return false, } var d: DeclSpec = .{}; var spec: Type.Builder = .{}; try spec.finish(p, &d.ty); break :blk d; }; var init_d = (try p.initDeclarator(&decl_spec)) orelse { // TODO return if enum struct or union try p.errTok(.missing_declaration, first_tok); _ = try p.expectToken(.semicolon); return true; }; // Check for function definition. if (init_d.d.func_declarator != null and init_d.initializer == 0 and init_d.d.ty.isFunc()) fn_def: { switch (p.tok_ids[p.tok_i]) { .comma, .semicolon => break :fn_def, .l_brace => {}, else => { if (!p.in_function) try p.err(.expected_fn_body); break :fn_def; }, } // TODO declare all parameters // for (init_d.d.ty.data.func.param_types) |param| {} // Collect old style parameter declarations. if (init_d.d.old_style_func != null and !p.in_function) { param_loop: while (true) { const param_decl_spec = (try p.declSpec()) orelse break; if (p.eatToken(.semicolon)) |semi| { try p.errTok(.missing_declaration, semi); continue :param_loop; } while (true) { var d = (try p.declarator(param_decl_spec.ty, .normal)) orelse { try p.errTok(.missing_declaration, first_tok); _ = try p.expectToken(.semicolon); continue :param_loop; }; if (d.ty.isFunc()) { // Params declared as functions are converted to function pointers. const elem_ty = try p.arena.create(Type); elem_ty.* = d.ty; d.ty = Type{ .specifier = .pointer, .data = .{ .sub_type = elem_ty }, }; } else if (d.ty.specifier == .void) { try p.errTok(.invalid_void_param, d.name); } // TODO declare and check that d.name is in init_d.d.ty.data.func.param_types if (p.eatToken(.comma) == null) break; } _ = try p.expectToken(.semicolon); } } if (p.in_function) try p.err(.func_not_in_root); const in_function = p.in_function; p.in_function = true; defer p.in_function = in_function; const node = try p.addNode(.{ .ty = init_d.d.ty, .tag = try decl_spec.validateFnDef(p), .data = .{ .first = init_d.d.name }, }); try p.scopes.append(.{ .symbol = .{ .name = p.tokSlice(init_d.d.name), .node = node, .name_tok = init_d.d.name, } }); const body = try p.compoundStmt(); p.nodes.items(.data)[node].second = body.?; // check gotos if (!in_function) { for (p.labels.items) |item| { if (item == .unresolved_goto) try p.errStr(.undeclared_label, item.unresolved_goto, p.tokSlice(item.unresolved_goto)); } p.labels.items.len = 0; p.label_count = 0; } try p.cur_decl_list.append(node); return true; } // Declare all variable/typedef declarators. while (true) { if (init_d.d.old_style_func) |tok_i| try p.errTok(.invalid_old_style_params, tok_i); const node = try p.addNode(.{ .ty = init_d.d.ty, .tag = try decl_spec.validate(p, init_d.d.ty, init_d.initializer != 0), .data = .{ .first = init_d.d.name, .second = init_d.initializer }, }); try p.cur_decl_list.append(node); if (decl_spec.storage_class == .typedef) { try p.scopes.append(.{ .typedef = .{ .name = p.tokSlice(init_d.d.name), .node = node, .name_tok = init_d.d.name, } }); } else { try p.scopes.append(.{ .symbol = .{ .name = p.tokSlice(init_d.d.name), .node = node, .name_tok = init_d.d.name, } }); } if (p.eatToken(.comma) == null) break; init_d = (try p.initDeclarator(&decl_spec)) orelse { try p.err(.expected_ident_or_l_paren); continue; }; } _ = try p.expectToken(.semicolon); return true; } /// staticAssert : keyword_static_assert '(' constExpr ',' STRING_LITERAL ')' ';' fn staticAssert(p: *Parser) Error!bool { const static_assert = p.eatToken(.keyword_static_assert) orelse return false; const l_paren = try p.expectToken(.l_paren); var start = p.tok_i; const res = try p.constExpr(); const end = p.tok_i; _ = try p.expectToken(.comma); const str = try p.expectToken(.string_literal); // TODO resolve string literal try p.expectClosing(l_paren, .r_paren); if (!res.getBool()) { var msg = std.ArrayList(u8).init(p.pp.comp.gpa); defer msg.deinit(); try msg.append('\''); while (start < end) { try msg.appendSlice(p.tokSlice(start)); start += 1; if (start != end) try msg.append(' '); } try msg.appendSlice("' "); try msg.appendSlice(p.tokSlice(str)); try p.errStr(.static_assert_failure, static_assert, try p.arena.dupe(u8, msg.items)); } return true; } pub const DeclSpec = struct { storage_class: union(enum) { auto: TokenIndex, @"extern": TokenIndex, register: TokenIndex, static: TokenIndex, typedef: TokenIndex, none, } = .none, thread_local: ?TokenIndex = null, @"inline": ?TokenIndex = null, @"noreturn": ?TokenIndex = null, ty: Type = .{ .specifier = undefined }, fn validateParam(d: DeclSpec, p: *Parser, ty: Type) Error!Tree.Tag { _ = ty; switch (d.storage_class) { .none, .register => {}, .auto, .@"extern", .static, .typedef => |tok_i| try p.errTok(.invalid_storage_on_param, tok_i), } if (d.thread_local) |tok_i| try p.errTok(.threadlocal_non_var, tok_i); if (d.@"inline") |tok_i| try p.errStr(.func_spec_non_func, tok_i, "inline"); if (d.@"noreturn") |tok_i| try p.errStr(.func_spec_non_func, tok_i, "_Noreturn"); return if (d.storage_class == .register) .register_param_decl else .param_decl; } fn validateFnDef(d: DeclSpec, p: *Parser) Error!Tree.Tag { switch (d.storage_class) { .none, .@"extern", .static => {}, .auto, .register, .typedef => |tok_i| try p.errTok(.illegal_storage_on_func, tok_i), } if (d.thread_local) |tok_i| try p.errTok(.threadlocal_non_var, tok_i); const is_static = d.storage_class == .static; const is_inline = d.@"inline" != null; const is_noreturn = d.@"noreturn" != null; if (is_static) { if (is_inline and is_noreturn) return .noreturn_inline_static_fn_def; if (is_inline) return .inline_static_fn_def; if (is_noreturn) return .noreturn_static_fn_def; return .static_fn_def; } else { if (is_inline and is_noreturn) return .noreturn_inline_fn_def; if (is_inline) return .inline_fn_def; if (is_noreturn) return .noreturn_fn_def; return .fn_def; } } fn validate(d: DeclSpec, p: *Parser, ty: Type, has_init: bool) Error!Tree.Tag { const is_static = d.storage_class == .static; if (ty.isFunc() and d.storage_class != .typedef) { switch (d.storage_class) { .none, .@"extern" => {}, .static => |tok_i| if (p.in_function) try p.errTok(.static_func_not_global, tok_i), .typedef => unreachable, .auto, .register => |tok_i| try p.errTok(.illegal_storage_on_func, tok_i), } if (d.thread_local) |tok_i| try p.errTok(.threadlocal_non_var, tok_i); const is_inline = d.@"inline" != null; const is_noreturn = d.@"noreturn" != null; if (is_static) { if (is_inline and is_noreturn) return .noreturn_inline_static_fn_proto; if (is_inline) return .inline_static_fn_proto; if (is_noreturn) return .noreturn_static_fn_proto; return .static_fn_proto; } else { if (is_inline and is_noreturn) return .noreturn_inline_fn_proto; if (is_inline) return .inline_fn_proto; if (is_noreturn) return .noreturn_fn_proto; return .fn_proto; } } else { if (d.@"inline") |tok_i| try p.errStr(.func_spec_non_func, tok_i, "inline"); if (d.@"noreturn") |tok_i| try p.errStr(.func_spec_non_func, tok_i, "_Noreturn"); switch (d.storage_class) { .auto, .register => if (!p.in_function) try p.err(.illegal_storage_on_global), .typedef => return .typedef, else => {}, } const is_extern = d.storage_class == .@"extern" and !has_init; if (d.thread_local != null) { if (is_static) return .threadlocal_static_var; if (is_extern) return .threadlocal_extern_var; return .threadlocal_var; } else { if (is_static) return .static_var; if (is_extern) return .extern_var; return .@"var"; } } } }; /// declSpec: (storageClassSpec | typeSpec | typeQual | funcSpec | alignSpec)+ /// storageClassSpec: /// : keyword_typedef /// | keyword_extern /// | keyword_static /// | keyword_threadlocal /// | keyword_auto /// | keyword_register /// funcSpec : keyword_inline | keyword_noreturn fn declSpec(p: *Parser) Error!?DeclSpec { var d: DeclSpec = .{}; var spec: Type.Builder = .{}; const start = p.tok_i; while (true) { if (try p.typeSpec(&spec, &d.ty)) continue; const id = p.tok_ids[p.tok_i]; switch (id) { .keyword_typedef, .keyword_extern, .keyword_static, .keyword_auto, .keyword_register, => { if (d.storage_class != .none) { try p.errStr(.multiple_storage_class, p.tok_i, @tagName(d.storage_class)); return error.ParsingFailed; } if (d.thread_local != null) { switch (id) { .keyword_typedef, .keyword_auto, .keyword_register, => try p.errStr(.cannot_combine_spec, p.tok_i, id.lexeme().?), else => {}, } } switch (id) { .keyword_typedef => d.storage_class = .{ .typedef = p.tok_i }, .keyword_extern => d.storage_class = .{ .@"extern" = p.tok_i }, .keyword_static => d.storage_class = .{ .static = p.tok_i }, .keyword_auto => d.storage_class = .{ .auto = p.tok_i }, .keyword_register => d.storage_class = .{ .register = p.tok_i }, else => unreachable, } }, .keyword_thread_local => { if (d.thread_local != null) { try p.errStr(.duplicate_decl_spec, p.tok_i, "_Thread_local"); } switch (d.storage_class) { .@"extern", .none, .static => {}, else => try p.errStr(.cannot_combine_spec, p.tok_i, @tagName(d.storage_class)), } d.thread_local = p.tok_i; }, .keyword_inline => { if (d.@"inline" != null) { try p.errStr(.duplicate_decl_spec, p.tok_i, "inline"); } d.@"inline" = p.tok_i; }, .keyword_noreturn => { if (d.@"noreturn" != p.tok_i) { try p.errStr(.duplicate_decl_spec, p.tok_i, "_Noreturn"); } d.@"noreturn" = null; }, else => break, } p.tok_i += 1; } if (p.tok_i == start) return null; try spec.finish(p, &d.ty); return d; } const InitDeclarator = struct { d: Declarator, initializer: NodeIndex = 0 }; /// initDeclarator : declarator ('=' initializer)? fn initDeclarator(p: *Parser, decl_spec: *DeclSpec) Error!?InitDeclarator { var init_d = InitDeclarator{ .d = (try p.declarator(decl_spec.ty, .normal)) orelse return null, }; if (p.eatToken(.equal)) |_| { if (decl_spec.storage_class == .typedef or decl_spec.ty.isFunc()) try p.err(.illegal_initializer); if (decl_spec.storage_class == .@"extern") { try p.err(.extern_initializer); decl_spec.storage_class = .none; } const init = try p.initializer(); const casted = try init.coerce(p, init_d.d.ty); init_d.initializer = try casted.toNode(p); } return init_d; } /// typeSpec /// : keyword_void /// | keyword_char /// | keyword_short /// | keyword_int /// | keyword_long /// | keyword_float /// | keyword_double /// | keyword_signed /// | keyword_unsigned /// | keyword_bool /// | keyword_complex /// | atomicTypeSpec /// | recordSpec /// | enumSpec /// | typedef // IDENTIFIER /// atomicTypeSpec : keyword_atomic '(' typeName ')' /// alignSpec : keyword_alignas '(' typeName ')' fn typeSpec(p: *Parser, ty: *Type.Builder, complete_type: *Type) Error!bool { const start = p.tok_i; while (true) { if (try p.typeQual(complete_type)) continue; switch (p.tok_ids[p.tok_i]) { .keyword_void => try ty.combine(p, .void), .keyword_bool => try ty.combine(p, .bool), .keyword_char => try ty.combine(p, .char), .keyword_short => try ty.combine(p, .short), .keyword_int => try ty.combine(p, .int), .keyword_long => try ty.combine(p, .long), .keyword_signed => try ty.combine(p, .signed), .keyword_unsigned => try ty.combine(p, .unsigned), .keyword_float => try ty.combine(p, .float), .keyword_double => try ty.combine(p, .double), .keyword_complex => try ty.combine(p, .complex), .keyword_atomic => return p.todo("atomic types"), .keyword_enum => { try ty.combine(p, .{ .@"enum" = 0 }); ty.kind.@"enum" = try p.enumSpec(); continue; }, .keyword_struct => { try ty.combine(p, .{ .@"struct" = 0 }); ty.kind.@"struct" = try p.recordSpec(); continue; }, .keyword_union => { try ty.combine(p, .{ .@"union" = 0 }); ty.kind.@"union" = try p.recordSpec(); continue; }, .keyword_alignas => { if (complete_type.alignment != 0) try p.errStr(.duplicate_decl_spec, p.tok_i, "alignment"); const l_paren = try p.expectToken(.l_paren); const other_type = (try p.typeName()) orelse { try p.err(.expected_type); return error.ParsingFailed; }; try p.expectClosing(l_paren, .r_paren); complete_type.alignment = other_type.alignment; }, .identifier => { const typedef = p.findTypedef(p.tokSlice(p.tok_i)) orelse break; const new_spec = Type.Builder.fromType(p.nodes.items(.ty)[typedef.node]); const err_start = p.pp.comp.diag.list.items.len; ty.combine(p, new_spec) catch { // Remove new error messages // TODO improve/make threadsafe? p.pp.comp.diag.list.items.len = err_start; break; }; ty.typedef = .{ .tok = typedef.name_tok, .spec = new_spec.str(), }; }, else => break, } p.tok_i += 1; } return p.tok_i != start; } /// recordSpec /// : (keyword_struct | keyword_union) IDENTIFIER? { recordDecl* } /// | (keyword_struct | keyword_union) IDENTIFIER fn recordSpec(p: *Parser) Error!NodeIndex { // const kind_tok = p.tok_ids[p.tok_i]; p.tok_i += 1; return p.todo("recordSpec"); } /// recordDecl /// : specQual (recordDeclarator (',' recordDeclarator)*)? ; /// | staticAssert fn recordDecl(p: *Parser) Error!NodeIndex { return p.todo("recordDecl"); } /// recordDeclarator : declarator (':' constExpr)? fn recordDeclarator(p: *Parser) Error!NodeIndex { return p.todo("recordDeclarator"); } /// specQual : (typeSpec | typeQual | alignSpec)+ fn specQual(p: *Parser) Error!?Type { var spec: Type.Builder = .{}; var ty: Type = .{ .specifier = undefined }; if (try p.typeSpec(&spec, &ty)) { try spec.finish(p, &ty); return ty; } return null; } /// enumSpec /// : keyword_enum IDENTIFIER? { enumerator (',' enumerator)? ',') } /// | keyword_enum IDENTIFIER fn enumSpec(p: *Parser) Error!NodeIndex { // const enum_tok = p.tok_ids[p.tok_i]; p.tok_i += 1; return p.todo("enumSpec"); } /// enumerator : IDENTIFIER ('=' constExpr) fn enumerator(p: *Parser) Error!NodeIndex { return p.todo("enumerator"); } /// typeQual : keyword_const | keyword_restrict | keyword_volatile | keyword_atomic fn typeQual(p: *Parser, ty: *Type) Error!bool { var any = false; while (true) { switch (p.tok_ids[p.tok_i]) { .keyword_restrict => { if (ty.specifier != .pointer) try p.errExtra(.restrict_non_pointer, p.tok_i, .{ .str = Type.Builder.fromType(ty.*).str() }) else if (ty.qual.restrict) try p.errStr(.duplicate_decl_spec, p.tok_i, "restrict") else ty.qual.restrict = true; }, .keyword_const => { if (ty.qual.@"const") try p.errStr(.duplicate_decl_spec, p.tok_i, "const") else ty.qual.@"const" = true; }, .keyword_volatile => { if (ty.qual.@"volatile") try p.errStr(.duplicate_decl_spec, p.tok_i, "volatile") else ty.qual.@"volatile" = true; }, .keyword_atomic => { if (ty.qual.atomic) try p.errStr(.duplicate_decl_spec, p.tok_i, "atomic") else ty.qual.atomic = true; }, else => break, } p.tok_i += 1; any = true; } return any; } const Declarator = struct { name: TokenIndex, ty: Type, func_declarator: ?TokenIndex = null, old_style_func: ?TokenIndex = null, }; const DeclaratorKind = enum { normal, abstract, param }; /// declarator : pointer? (IDENTIFIER | '(' declarator ')') directDeclarator* /// abstractDeclarator /// : pointer? ('(' abstractDeclarator ')')? directAbstractDeclarator* fn declarator( p: *Parser, base_type: Type, kind: DeclaratorKind, ) Error!?Declarator { const start = p.tok_i; var d = Declarator{ .name = 0, .ty = try p.pointer(base_type) }; if (kind != .abstract and p.tok_ids[p.tok_i] == .identifier) { d.name = p.tok_i; p.tok_i += 1; d.ty = try p.directDeclarator(d.ty, &d, kind); return d; } else if (p.eatToken(.l_paren)) |l_paren| blk: { var res = (try p.declarator(.{ .specifier = .void }, kind)) orelse { p.tok_i = l_paren; break :blk; }; try p.expectClosing(l_paren, .r_paren); const suffix_start = p.tok_i; const outer = try p.directDeclarator(d.ty, &d, kind); try res.ty.combine(outer, p, res.func_declarator orelse suffix_start); res.old_style_func = d.old_style_func; return res; } if (kind == .normal) { try p.err(.expected_ident_or_l_paren); } d.ty = try p.directDeclarator(d.ty, &d, kind); if (start == p.tok_i) return null; return d; } /// directDeclarator /// : '[' typeQual* assignExpr? ']' directDeclarator? /// | '[' keyword_static typeQual* assignExpr ']' directDeclarator? /// | '[' typeQual+ keyword_static assignExpr ']' directDeclarator? /// | '[' typeQual* '*' ']' directDeclarator? /// | '(' paramDecls ')' directDeclarator? /// | '(' (IDENTIFIER (',' IDENTIFIER))? ')' directDeclarator? /// directAbstractDeclarator /// : '[' typeQual* assignExpr? ']' /// | '[' keyword_static typeQual* assignExpr ']' /// | '[' typeQual+ keyword_static assignExpr ']' /// | '[' '*' ']' /// | '(' paramDecls? ')' fn directDeclarator(p: *Parser, base_type: Type, d: *Declarator, kind: DeclaratorKind) Error!Type { if (p.eatToken(.l_bracket)) |l_bracket| { var res_ty = Type{ // so that we can get any restrict type that might be present .specifier = .pointer, }; var got_quals = try p.typeQual(&res_ty); var static = p.eatToken(.keyword_static); if (static != null and !got_quals) got_quals = try p.typeQual(&res_ty); var star = p.eatToken(.asterisk); const size = if (star) |_| Result{} else try p.assignExpr(); try p.expectClosing(l_bracket, .r_bracket); if (star != null and static != null) { try p.errTok(.invalid_static_star, static.?); static = null; } if (kind != .param) { if (static != null) try p.errTok(.static_non_param, l_bracket) else if (got_quals) try p.errTok(.array_qualifiers, l_bracket); if (star) |some| try p.errTok(.star_non_param, some); static = null; res_ty.qual = .{}; star = null; } if (static) |_| try size.expect(p); switch (size.data) { .none => if (star) |_| { const elem_ty = try p.arena.create(Type); res_ty.data = .{ .sub_type = elem_ty }; res_ty.specifier = .unspecified_variable_len_array; } else { const arr_ty = try p.arena.create(Type.Array); arr_ty.len = 0; res_ty.data = .{ .array = arr_ty }; res_ty.specifier = .incomplete_array; }, .lval, .node => |n| { if (!p.in_function and kind != .param) try p.errTok(.variable_len_array_file_scope, l_bracket); const vla_ty = try p.arena.create(Type.VLA); vla_ty.expr = n; res_ty.data = .{ .vla = vla_ty }; res_ty.specifier = .variable_len_array; if (static) |some| try p.errTok(.useless_static, some); }, .unsigned => |v| { const arr_ty = try p.arena.create(Type.Array); arr_ty.len = v; res_ty.data = .{ .array = arr_ty }; res_ty.specifier = .array; }, .signed => |v| { if (v < 0) try p.errTok(.negative_array_size, l_bracket); const arr_ty = try p.arena.create(Type.Array); arr_ty.len = @bitCast(u64, v); res_ty.data = .{ .array = arr_ty }; res_ty.specifier = .array; }, } const outer = try p.directDeclarator(base_type, d, kind); try res_ty.combine(outer, p, l_bracket); return res_ty; } else if (p.eatToken(.l_paren)) |l_paren| { d.func_declarator = l_paren; if (p.tok_ids[p.tok_i] == .ellipsis) { try p.err(.param_before_var_args); p.tok_i += 1; } const func_ty = try p.arena.create(Type.Func); func_ty.param_types = &.{}; var specifier: Type.Specifier = .func; if (try p.paramDecls()) |params| { func_ty.param_types = params; if (p.eatToken(.ellipsis)) |_| specifier = .var_args_func; } else if (p.tok_ids[p.tok_i] == .r_paren) { specifier = .old_style_func; } else if (p.tok_ids[p.tok_i] == .identifier) { d.old_style_func = p.tok_i; var params = NodeList.init(p.pp.comp.gpa); defer params.deinit(); specifier = .old_style_func; while (true) { const param = try p.addNode(.{ .tag = .param_decl, .ty = .{ .specifier = .int }, .data = .{ .first = try p.expectToken(.identifier) }, }); try params.append(param); if (p.eatToken(.comma) == null) break; } func_ty.param_types = try p.arena.dupe(NodeIndex, params.items); } else { try p.err(.expected_param_decl); } try p.expectClosing(l_paren, .r_paren); var res_ty = Type{ .specifier = specifier, .data = .{ .func = func_ty }, }; const outer = try p.directDeclarator(base_type, d, kind); try res_ty.combine(outer, p, l_paren); return res_ty; } else return base_type; } /// pointer : '*' typeQual* pointer? fn pointer(p: *Parser, base_ty: Type) Error!Type { var ty = base_ty; while (p.eatToken(.asterisk)) |_| { const elem_ty = try p.arena.create(Type); elem_ty.* = ty; ty = Type{ .specifier = .pointer, .data = .{ .sub_type = elem_ty }, }; _ = try p.typeQual(&ty); } return ty; } /// paramDecls : paramDecl (',' paramDecl)* (',' '...') /// paramDecl : declSpec (declarator | abstractDeclarator) fn paramDecls(p: *Parser) Error!?[]NodeIndex { var params = NodeList.init(p.pp.comp.gpa); defer params.deinit(); while (true) { const param_decl_spec = if (try p.declSpec()) |some| some else if (params.items.len == 0) return null else blk: { var d: DeclSpec = .{}; var spec: Type.Builder = .{}; try spec.finish(p, &d.ty); break :blk d; }; var name_tok = p.tok_i; var param_ty = param_decl_spec.ty; if (try p.declarator(param_decl_spec.ty, .param)) |some| { if (some.old_style_func) |tok_i| try p.errTok(.invalid_old_style_params, tok_i); // TODO declare(); name_tok = some.name; param_ty = some.ty; } if (param_ty.isFunc()) { // params declared as functions are converted to function pointers const elem_ty = try p.arena.create(Type); elem_ty.* = param_ty; param_ty = Type{ .specifier = .pointer, .data = .{ .sub_type = elem_ty }, }; } else if (param_ty.specifier == .void) { // validate void parameters if (params.items.len == 0) { if (p.tok_ids[p.tok_i] != .r_paren) { try p.err(.void_only_param); if (param_ty.qual.any()) try p.err(.void_param_qualified); return error.ParsingFailed; } return &[0]NodeIndex{}; } try p.err(.void_must_be_first_param); return error.ParsingFailed; } else if (param_ty.isArray()) { // TODO convert to pointer } const param = try p.addNode(.{ .tag = try param_decl_spec.validateParam(p, param_ty), .ty = param_ty, .data = .{ .first = name_tok }, }); try params.append(param); if (p.eatToken(.comma) == null) break; if (p.tok_ids[p.tok_i] == .ellipsis) break; } return try p.arena.dupe(NodeIndex, params.items); } /// typeName : specQual abstractDeclarator fn typeName(p: *Parser) Error!?Type { var ty = (try p.specQual()) orelse return null; if (try p.declarator(ty, .abstract)) |some| { if (some.old_style_func) |tok_i| try p.errTok(.invalid_old_style_params, tok_i); return some.ty; } else return ty; } /// initializer /// : assignExpr /// | '{' initializerItems '}' fn initializer(p: *Parser) Error!Result { if (p.eatToken(.l_brace)) |_| { return p.todo("compound initializer"); } const res = try p.assignExpr(); try res.expect(p); return res; } /// initializerItems : designation? initializer (',' designation? initializer)? ','? fn initializerItems(p: *Parser) Error!NodeIndex { return p.todo("initializerItems"); } /// designation : designator+ '=' fn designation(p: *Parser) Error!NodeIndex { return p.todo("designation"); } /// designator /// : '[' constExpr ']' /// | '.' identifier fn designator(p: *Parser) Error!NodeIndex { return p.todo("designator"); } // ====== statements ====== /// stmt /// : labeledStmt /// | compoundStmt /// | keyword_if '(' expr ')' stmt (keyword_else stmt)? /// | keyword_switch '(' expr ')' stmt /// | keyword_while '(' expr ')' stmt /// | keyword_do stmt while '(' expr ')' ';' /// | keyword_for '(' (decl | expr? ';') expr? ';' expr? ')' stmt /// | keyword_goto IDENTIFIER ';' /// | keyword_continue ';' /// | keyword_break ';' /// | keyword_return expr? ';' /// | expr? ';' fn stmt(p: *Parser) Error!NodeIndex { if (try p.labeledStmt()) |some| return some; if (try p.compoundStmt()) |some| return some; if (p.eatToken(.keyword_if)) |_| { const start_scopes_len = p.scopes.items.len; defer p.scopes.items.len = start_scopes_len; const l_paren = try p.expectToken(.l_paren); const cond = try p.expr(); // TODO validate type try cond.expect(p); const cond_node = try cond.toNode(p); try p.expectClosing(l_paren, .r_paren); const then = try p.stmt(); const @"else" = if (p.eatToken(.keyword_else)) |_| try p.stmt() else 0; if (then != 0 and @"else" != 0) return try p.addNode(.{ .tag = .if_then_else_stmt, .data = .{ .first = cond_node, .second = (try p.addList(&.{ then, @"else" })).start }, }) else if (then == 0 and @"else" != 0) return try p.addNode(.{ .tag = .if_else_stmt, .data = .{ .first = cond_node, .second = @"else" }, }) else return try p.addNode(.{ .tag = .if_then_stmt, .data = .{ .first = cond_node, .second = then }, }); } if (p.eatToken(.keyword_switch)) |_| { const start_scopes_len = p.scopes.items.len; defer p.scopes.items.len = start_scopes_len; const l_paren = try p.expectToken(.l_paren); const cond = try p.expr(); // TODO validate type try cond.expect(p); const cond_node = try cond.toNode(p); try p.expectClosing(l_paren, .r_paren); var switch_scope = Scope.Switch{ .cases = Scope.Switch.CaseMap.init(p.pp.comp.gpa), }; defer switch_scope.cases.deinit(); try p.scopes.append(.{ .@"switch" = &switch_scope }); const body = try p.stmt(); return try p.addNode(.{ .tag = .switch_stmt, .data = .{ .first = cond_node, .second = body }, }); } if (p.eatToken(.keyword_while)) |_| { const start_scopes_len = p.scopes.items.len; defer p.scopes.items.len = start_scopes_len; const l_paren = try p.expectToken(.l_paren); const cond = try p.expr(); // TODO validate type try cond.expect(p); const cond_node = try cond.toNode(p); try p.expectClosing(l_paren, .r_paren); try p.scopes.append(.loop); const body = try p.stmt(); return try p.addNode(.{ .tag = .while_stmt, .data = .{ .first = cond_node, .second = body }, }); } if (p.eatToken(.keyword_do)) |_| { const start_scopes_len = p.scopes.items.len; defer p.scopes.items.len = start_scopes_len; try p.scopes.append(.loop); const body = try p.stmt(); p.scopes.items.len = start_scopes_len; _ = try p.expectToken(.keyword_while); const l_paren = try p.expectToken(.l_paren); const cond = try p.expr(); // TODO validate type try cond.expect(p); const cond_node = try cond.toNode(p); try p.expectClosing(l_paren, .r_paren); _ = try p.expectToken(.semicolon); return try p.addNode(.{ .tag = .do_while_stmt, .data = .{ .first = cond_node, .second = body }, }); } if (p.eatToken(.keyword_for)) |_| { const start_scopes_len = p.scopes.items.len; defer p.scopes.items.len = start_scopes_len; var decls = NodeList.init(p.pp.comp.gpa); defer decls.deinit(); const saved_decls = p.cur_decl_list; defer p.cur_decl_list = saved_decls; p.cur_decl_list = &decls; const l_paren = try p.expectToken(.l_paren); const got_decl = try p.decl(); // for (init const init_start = p.tok_i; const init = if (!got_decl) try p.expr() else Result{}; const init_node = try init.toNode(p); try p.maybeWarnUnused(init_node, init_start); if (!got_decl) _ = try p.expectToken(.semicolon); // for (init; cond const cond = try p.expr(); const cond_node = try cond.toNode(p); _ = try p.expectToken(.semicolon); // for (init; cond; incr const incr_start = p.tok_i; const incr = try p.expr(); const incr_node = try incr.toNode(p); try p.maybeWarnUnused(incr_node, incr_start); try p.expectClosing(l_paren, .r_paren); try p.scopes.append(.loop); const body = try p.stmt(); if (got_decl) { const start = (try p.addList(decls.items)).start; const end = (try p.addList(&.{ cond_node, incr_node, body })).end; return try p.addNode(.{ .tag = .for_decl_stmt, .data = .{ .first = start, .second = end }, }); } else if (init.data == .none and cond.data == .none and incr.data == .none) { return try p.addNode(.{ .tag = .forever_stmt, .data = .{ .first = body }, }); } else { const range = try p.addList(&.{ init_node, cond_node, incr_node }); return try p.addNode(.{ .tag = .for_stmt, .data = .{ .first = range.start, .second = body }, }); } } if (p.eatToken(.keyword_goto)) |_| { const name_tok = try p.expectToken(.identifier); const str = p.tokSlice(name_tok); if (p.findLabel(str) == null) { try p.labels.append(.{ .unresolved_goto = name_tok }); } _ = try p.expectToken(.semicolon); return try p.addNode(.{ .tag = .goto_stmt, .data = .{ .first = name_tok }, }); } if (p.eatToken(.keyword_continue)) |cont| { if (!p.inLoop()) try p.errTok(.continue_not_in_loop, cont); _ = try p.expectToken(.semicolon); return try p.addNode(.{ .tag = .continue_stmt }); } if (p.eatToken(.keyword_break)) |br| { if (!p.inLoopOrSwitch()) try p.errTok(.break_not_in_loop_or_switch, br); _ = try p.expectToken(.semicolon); return try p.addNode(.{ .tag = .break_stmt }); } if (p.eatToken(.keyword_return)) |_| { const e = try p.expr(); _ = try p.expectToken(.semicolon); // TODO cast to return type const result = try e.toNode(p); return try p.addNode(.{ .tag = .return_stmt, .data = .{ .first = result }, }); } const expr_start = p.tok_i; const e = try p.expr(); if (e.data != .none) { _ = try p.expectToken(.semicolon); const expr_node = try e.toNode(p); try p.maybeWarnUnused(expr_node, expr_start); return expr_node; } if (p.eatToken(.semicolon)) |_| return @as(NodeIndex, 0); try p.err(.expected_stmt); return error.ParsingFailed; } fn maybeWarnUnused(p: *Parser, node: NodeIndex, expr_start: TokenIndex) Error!void { switch (p.nodes.items(.tag)[node]) { .invalid, // So that we don't need to check for node == 0 .assign_expr, .mul_assign_expr, .div_assign_expr, .mod_assign_expr, .add_assign_expr, .sub_assign_expr, .shl_assign_expr, .shr_assign_expr, .and_assign_expr, .xor_assign_expr, .or_assign_expr, .call_expr, .call_expr_one, => {}, else => try p.errTok(.unused_value, expr_start), } } /// labeledStmt /// : IDENTIFIER ':' stmt /// | keyword_case constExpr ':' stmt /// | keyword_default ':' stmt fn labeledStmt(p: *Parser) Error!?NodeIndex { if (p.tok_ids[p.tok_i] == .identifier and p.tok_ids[p.tok_i + 1] == .colon) { const name_tok = p.tok_i; const str = p.tokSlice(name_tok); if (p.findLabel(str)) |some| { try p.errStr(.duplicate_label, name_tok, str); try p.errStr(.previous_label, some, str); } else { p.label_count += 1; try p.labels.append(.{ .label = name_tok }); var i: usize = 0; while (i < p.labels.items.len) : (i += 1) { if (p.labels.items[i] == .unresolved_goto and mem.eql(u8, p.tokSlice(p.labels.items[i].unresolved_goto), str)) { _ = p.labels.swapRemove(i); } } } p.tok_i += 2; return try p.addNode(.{ .tag = .labeled_stmt, .data = .{ .first = name_tok, .second = try p.stmt() }, }); } else if (p.eatToken(.keyword_case)) |case| { const val = try p.constExpr(); _ = try p.expectToken(.colon); const s = try p.stmt(); const node = try p.addNode(.{ .tag = .case_stmt, .data = .{ .first = try val.toNode(p), .second = s }, }); if (p.findSwitch()) |some| { const gop = try some.cases.getOrPut(val); if (gop.found_existing) { switch (val.data) { .unsigned => |v| try p.errExtra(.duplicate_switch_case_unsigned, case, .{ .unsigned = v }), .signed => |v| try p.errExtra(.duplicate_switch_case_signed, case, .{ .signed = v }), else => unreachable, } try p.errTok(.previous_case, gop.value_ptr.tok); } else { gop.value_ptr.* = .{ .tok = case, .node = node, }; } } else { try p.errStr(.case_not_in_switch, case, "case"); } return node; } else if (p.eatToken(.keyword_default)) |default| { _ = try p.expectToken(.colon); const s = try p.stmt(); const node = try p.addNode(.{ .tag = .default_stmt, .data = .{ .first = s }, }); if (p.findSwitch()) |some| { if (some.default) |previous| { try p.errTok(.multiple_default, default); try p.errTok(.previous_case, previous.tok); } else { some.default = .{ .tok = default, .node = node, }; } } else { try p.errStr(.case_not_in_switch, default, "default"); } return node; } else return null; } /// compoundStmt : '{' ( decl| staticAssert | stmt)* '}' fn compoundStmt(p: *Parser) Error!?NodeIndex { const l_brace = p.eatToken(.l_brace) orelse return null; var statements = NodeList.init(p.pp.comp.gpa); defer statements.deinit(); const saved_decls = p.cur_decl_list; defer p.cur_decl_list = saved_decls; p.cur_decl_list = &statements; var noreturn_index: ?TokenIndex = null; var noreturn_label_count: u32 = 0; while (p.eatToken(.r_brace) == null) { if (p.staticAssert() catch |er| switch (er) { error.ParsingFailed => { try p.nextStmt(l_brace); continue; }, else => |e| return e, }) continue; if (p.decl() catch |er| switch (er) { error.ParsingFailed => { try p.nextStmt(l_brace); continue; }, else => |e| return e, }) continue; const s = p.stmt() catch |er| switch (er) { error.ParsingFailed => { try p.nextStmt(l_brace); continue; }, else => |e| return e, }; if (s == 0) continue; try statements.append(s); if (noreturn_index == null and p.nodeIsNoreturn(s)) { noreturn_index = p.tok_i; noreturn_label_count = p.label_count; } } if (noreturn_index) |some| { // if new labels were defined we cannot be certain that the code is unreachable if (some != p.tok_i - 1 and noreturn_label_count == p.label_count) try p.errTok(.unreachable_code, some); } switch (statements.items.len) { 0 => return try p.addNode(.{ .tag = .compound_stmt_two }), 1 => return try p.addNode(.{ .tag = .compound_stmt_two, .data = .{ .first = statements.items[0] }, }), 2 => return try p.addNode(.{ .tag = .compound_stmt_two, .data = .{ .first = statements.items[0], .second = statements.items[1] }, }), else => { const range = try p.addList(statements.items); return try p.addNode(.{ .tag = .compound_stmt, .data = .{ .first = range.start, .second = range.end }, }); }, } } fn nodeIsNoreturn(p: *Parser, node: NodeIndex) bool { switch (p.nodes.items(.tag)[node]) { .break_stmt, .continue_stmt, .return_stmt => return true, .if_then_else_stmt => { const data = p.data.items[p.nodes.items(.data)[node].second..]; return p.nodeIsNoreturn(data[0]) and p.nodeIsNoreturn(data[1]); }, else => return false, } } fn nextStmt(p: *Parser, l_brace: TokenIndex) !void { var parens: u32 = 0; while (p.tok_i < p.tok_ids.len) : (p.tok_i += 1) { switch (p.tok_ids[p.tok_i]) { .l_paren, .l_brace, .l_bracket => parens += 1, .r_paren, .r_bracket => if (parens != 0) { parens -= 1; }, .r_brace => if (parens == 0) return else { parens -= 1; }, .keyword_for, .keyword_while, .keyword_do, .keyword_if, .keyword_goto, .keyword_switch, .keyword_case, .keyword_default, .keyword_continue, .keyword_break, .keyword_return, .keyword_typedef, .keyword_extern, .keyword_static, .keyword_auto, .keyword_register, .keyword_thread_local, .keyword_inline, .keyword_noreturn, .keyword_void, .keyword_bool, .keyword_char, .keyword_short, .keyword_int, .keyword_long, .keyword_signed, .keyword_unsigned, .keyword_float, .keyword_double, .keyword_complex, .keyword_atomic, .keyword_enum, .keyword_struct, .keyword_union, .keyword_alignas, => if (parens == 0) return, else => {}, } } p.tok_i -= 1; // So we can consume EOF try p.expectClosing(l_brace, .r_brace); unreachable; } // ====== expressions ====== /// expr : assignExpr (',' assignExpr)* fn expr(p: *Parser) Error!Result { var lhs = try p.assignExpr(); while (p.eatToken(.comma)) |_| { return p.todo("comma operator"); } return lhs; } /// assignExpr /// : condExpr /// | unExpr ('=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|=') assignExpr fn assignExpr(p: *Parser) Error!Result { return p.condExpr(); // TODO } /// constExpr : condExpr pub fn constExpr(p: *Parser) Error!Result { const saved_const = p.want_const; defer p.want_const = saved_const; p.want_const = true; const res = try p.condExpr(); try res.expect(p); return res; } /// condExpr : lorExpr ('?' expression? ':' condExpr)? fn condExpr(p: *Parser) Error!Result { const cond = try p.lorExpr(); if (p.eatToken(.question_mark) == null) return cond; const then_expr = try p.expr(); _ = try p.expectToken(.colon); const else_expr = try p.condExpr(); if (cond.data == .signed or cond.data == .unsigned) { return if (cond.getBool()) then_expr else else_expr; } return p.todo("ast"); } /// lorExpr : landExpr ('||' landExpr)* fn lorExpr(p: *Parser) Error!Result { var lhs = try p.landExpr(); while (p.eatToken(.pipe_pipe)) |_| { const rhs = try p.landExpr(); if ((lhs.data == .unsigned or lhs.data == .signed) and (rhs.data == .unsigned or rhs.data == .signed)) { // TODO short circuit evaluation lhs = Result{ .data = .{ .signed = @boolToInt(lhs.getBool() or rhs.getBool()) } }; } else return p.todo("ast"); } return lhs; } /// landExpr : orExpr ('&&' orExpr)* fn landExpr(p: *Parser) Error!Result { var lhs = try p.orExpr(); while (p.eatToken(.ampersand_ampersand)) |_| { const rhs = try p.orExpr(); if ((lhs.data == .unsigned or lhs.data == .signed) and (rhs.data == .unsigned or rhs.data == .signed)) { // TODO short circuit evaluation lhs = Result{ .data = .{ .signed = @boolToInt(lhs.getBool() and rhs.getBool()) } }; } else return p.todo("ast"); } return lhs; } /// orExpr : xorExpr ('|' xorExpr)* fn orExpr(p: *Parser) Error!Result { var lhs = try p.xorExpr(); while (p.eatToken(.pipe)) |_| { var rhs = try p.xorExpr(); if (try lhs.adjustTypes(&rhs, p)) { lhs.data = switch (lhs.data) { .unsigned => |v| .{ .unsigned = v | rhs.data.unsigned }, .signed => |v| .{ .signed = v | rhs.data.signed }, else => unreachable, }; } else return p.todo("ast"); } return lhs; } /// xorExpr : andExpr ('^' andExpr)* fn xorExpr(p: *Parser) Error!Result { var lhs = try p.andExpr(); while (p.eatToken(.caret)) |_| { var rhs = try p.andExpr(); if (try lhs.adjustTypes(&rhs, p)) { lhs.data = switch (lhs.data) { .unsigned => |v| .{ .unsigned = v ^ rhs.data.unsigned }, .signed => |v| .{ .signed = v ^ rhs.data.signed }, else => unreachable, }; } else return p.todo("ast"); } return lhs; } /// andExpr : eqExpr ('&' eqExpr)* fn andExpr(p: *Parser) Error!Result { var lhs = try p.eqExpr(); while (p.eatToken(.ampersand)) |_| { var rhs = try p.eqExpr(); if (try lhs.adjustTypes(&rhs, p)) { lhs.data = switch (lhs.data) { .unsigned => |v| .{ .unsigned = v & rhs.data.unsigned }, .signed => |v| .{ .signed = v & rhs.data.signed }, else => unreachable, }; } else return p.todo("ast"); } return lhs; } /// eqExpr : compExpr (('==' | '!=') compExpr)* fn eqExpr(p: *Parser) Error!Result { var lhs = try p.compExpr(); while (true) { const eq = p.eatToken(.equal_equal); const ne = eq orelse p.eatToken(.bang_equal); if (ne == null) break; var rhs = try p.compExpr(); if (try lhs.adjustTypes(&rhs, p)) { const res = if (eq != null) lhs.compare(.eq, rhs) else lhs.compare(.neq, rhs); lhs = Result{ .data = .{ .signed = @boolToInt(res) } }; } else return p.todo("ast"); } return lhs; } /// compExpr : shiftExpr (('<' | '<=' | '>' | '>=') shiftExpr)* fn compExpr(p: *Parser) Error!Result { var lhs = try p.shiftExpr(); while (true) { const lt = p.eatToken(.angle_bracket_left); const le = lt orelse p.eatToken(.angle_bracket_left_equal); const gt = le orelse p.eatToken(.angle_bracket_right); const ge = gt orelse p.eatToken(.angle_bracket_right_equal); if (ge == null) break; var rhs = try p.shiftExpr(); if (try lhs.adjustTypes(&rhs, p)) { const res = if (lt != null) lhs.compare(.lt, rhs) else if (le != null) lhs.compare(.lte, rhs) else if (gt != null) lhs.compare(.gt, rhs) else lhs.compare(.gte, rhs); lhs = Result{ .data = .{ .signed = @boolToInt(res) } }; } else return p.todo("ast"); } return lhs; } /// shiftExpr : addExpr (('<<' | '>>') addExpr)* fn shiftExpr(p: *Parser) Error!Result { var lhs = try p.addExpr(); while (true) { const shl = p.eatToken(.angle_bracket_angle_bracket_left); const shr = shl orelse p.eatToken(.angle_bracket_angle_bracket_right); if (shr == null) break; var rhs = try p.addExpr(); if (try lhs.adjustTypes(&rhs, p)) { // TODO overflow if (shl != null) { lhs.data = switch (lhs.data) { .unsigned => |v| .{ .unsigned = v << @intCast(u6, rhs.data.unsigned) }, .signed => |v| .{ .signed = v << @intCast(u6, rhs.data.signed) }, else => unreachable, }; } else { lhs.data = switch (lhs.data) { .unsigned => |v| .{ .unsigned = v >> @intCast(u6, rhs.data.unsigned) }, .signed => |v| .{ .signed = v >> @intCast(u6, rhs.data.signed) }, else => unreachable, }; } } else return p.todo("ast"); } return lhs; } /// addExpr : mulExpr (('+' | '-') mulExpr)* fn addExpr(p: *Parser) Error!Result { var lhs = try p.mulExpr(); while (true) { const plus = p.eatToken(.plus); const minus = plus orelse p.eatToken(.minus); if (minus == null) break; var rhs = try p.mulExpr(); if (try lhs.adjustTypes(&rhs, p)) { if (plus != null) { try lhs.add(plus.?, rhs, p); } else { try lhs.sub(minus.?, rhs, p); } } else return p.todo("ast"); } return lhs; } /// mulExpr : castExpr (('*' | '/' | '%') castExpr)*´ fn mulExpr(p: *Parser) Error!Result { var lhs = try p.castExpr(); while (true) { const mul = p.eatToken(.asterisk); const div = mul orelse p.eatToken(.slash); const percent = div orelse p.eatToken(.percent); if (percent == null) break; var rhs = try p.castExpr(); if (try lhs.adjustTypes(&rhs, p)) { // TODO divide by zero if (mul != null) { try lhs.mul(mul.?, rhs, p); } else if (div != null) { lhs.data = switch (lhs.data) { .unsigned => |v| .{ .unsigned = v / rhs.data.unsigned }, .signed => |v| .{ .signed = @divFloor(v, rhs.data.signed) }, else => unreachable, }; } else { lhs.data = switch (lhs.data) { .unsigned => |v| .{ .unsigned = v % rhs.data.unsigned }, .signed => |v| .{ .signed = @rem(v, rhs.data.signed) }, else => unreachable, }; } } else return p.todo("ast"); } return lhs; } /// castExpr : ( '(' typeName ')' )* unExpr fn castExpr(p: *Parser) Error!Result { while (p.eatToken(.l_paren)) |l_paren| { const ty = (try p.typeName()) orelse { p.tok_i -= 1; break; }; try p.expectClosing(l_paren, .r_paren); _ = ty; return p.todo("cast"); } return p.unExpr(); } /// unExpr /// : primaryExpr suffixExpr* /// | ('&' | '*' | '+' | '-' | '~' | '!' | '++' | '--') castExpr /// | keyword_sizeof unExpr /// | keyword_sizeof '(' typeName ')' /// | keyword_alignof '(' typeName ')' fn unExpr(p: *Parser) Error!Result { switch (p.tok_ids[p.tok_i]) { .ampersand => return p.todo("unExpr ampersand"), .asterisk => return p.todo("unExpr asterisk"), .plus => { p.tok_i += 1; // TODO upcast to int / validate arithmetic type return p.castExpr(); }, .minus => { p.tok_i += 1; var operand = try p.castExpr(); // TODO upcast to int / validate arithmetic type const size = operand.ty.sizeof(p.pp.comp); switch (operand.data) { .unsigned => |*v| switch (size) { 1, 2, 4 => v.* = @truncate(u32, 0 -% v.*), 8 => v.* = 0 -% v.*, else => unreachable, }, .signed => |*v| switch (size) { 1, 2, 4 => v.* = @truncate(i32, 0 -% v.*), 8 => v.* = 0 -% v.*, else => unreachable, }, else => return p.todo("ast"), } return operand; }, .plus_plus => return p.todo("unary inc"), .minus_minus => return p.todo("unary dec"), .tilde => return p.todo("unExpr tilde"), .bang => { p.tok_i += 1; const lhs = try p.unExpr(); if (lhs.data == .unsigned or lhs.data == .signed) { return Result{ .data = .{ .signed = @boolToInt(!lhs.getBool()) } }; } return p.todo("ast"); }, .keyword_sizeof => return p.todo("unExpr sizeof"), else => { var lhs = try p.primaryExpr(); while (true) { const suffix = try p.suffixExpr(lhs); if (suffix.data == .none) break; lhs = suffix; } return lhs; }, } } /// suffixExpr /// : '[' expr ']' /// | '(' argumentExprList? ')' /// | '.' IDENTIFIER /// | '->' IDENTIFIER /// | '++' /// | '--' /// argumentExprList : assignExpr (',' assignExpr)* fn suffixExpr(p: *Parser, lhs: Result) Error!Result { switch (p.tok_ids[p.tok_i]) { .l_paren => { const l_paren = p.tok_i; p.tok_i += 1; const ty = lhs.ty.isCallable() orelse { try p.errStr(.not_callable, l_paren, Type.Builder.fromType(lhs.ty).str()); return error.ParsingFailed; }; const param_types = ty.data.func.param_types; var args = NodeList.init(p.pp.comp.gpa); defer args.deinit(); var first_after = l_paren; if (p.eatToken(.r_paren) == null) { while (true) { if (args.items.len == param_types.len) first_after = p.tok_i; const arg = try p.assignExpr(); try arg.expect(p); if (args.items.len < param_types.len) { const param_ty = p.nodes.items(.ty)[param_types[args.items.len]]; const casted = try arg.coerce(p, param_ty); try args.append(try casted.toNode(p)); } else { // TODO coerce to var args passable type try args.append(try arg.toNode(p)); } _ = p.eatToken(.comma) orelse break; } try p.expectClosing(l_paren, .r_paren); } const extra = Diagnostics.Message.Extra{ .arguments = .{ .expected = @intCast(u32, param_types.len), .actual = @intCast(u32, args.items.len) } }; if (ty.specifier == .func and param_types.len != args.items.len) { try p.errExtra(.expected_arguments, first_after, extra); } if (ty.specifier == .old_style_func and param_types.len != args.items.len) { try p.errExtra(.expected_arguments_old, first_after, extra); } if (ty.specifier == .var_args_func and args.items.len < param_types.len) { try p.errExtra(.expected_at_least_arguments, first_after, extra); } switch (args.items.len) { 0 => return try Result.node(p, .{ .tag = .call_expr_one, .ty = ty.data.func.return_type, .data = .{ .first = try lhs.toNode(p) }, }), 1 => return try Result.node(p, .{ .tag = .call_expr_one, .ty = ty.data.func.return_type, .data = .{ .first = try lhs.toNode(p), .second = args.items[0] }, }), else => { try p.data.append(try lhs.toNode(p)); const range = try p.addList(args.items); return try Result.node(p, .{ .tag = .call_expr, .ty = ty.data.func.return_type, .data = .{ .first = range.start - 1, .second = range.end }, }); }, } }, .l_bracket => return p.todo("array access"), .period => return p.todo("member access"), .arrow => return p.todo("member access pointer"), .plus_plus => return p.todo("post inc"), .minus_minus => return p.todo("post dec"), else => return Result{}, } } /// primaryExpr /// : IDENTIFIER /// | INTEGER_LITERAL /// | FLOAT_LITERAL /// | CHAR_LITERAL /// | STRING_LITERAL /// | '(' expr ')' /// | '(' typeName ')' '{' initializerItems '}' /// | keyword_generic '(' assignExpr ',' genericAssoc (',' genericAssoc)* ')' /// /// genericAssoc /// : typeName ':' assignExpr /// | keyword_default ':' assignExpr fn primaryExpr(p: *Parser) Error!Result { if (p.eatToken(.l_paren)) |l_paren| { const e = try p.expr(); try p.expectClosing(l_paren, .r_paren); return e; } switch (p.tok_ids[p.tok_i]) { .identifier => { const name_tok = p.tok_i; p.tok_i += 1; const sym = p.findSymbol(name_tok) orelse { if (p.tok_ids[p.tok_i] == .l_paren) { // implicitly declare simple functions as like `puts("foo")`; const name = p.tokSlice(name_tok); try p.errStr(.implicit_func_decl, name_tok, name); const func_ty = try p.arena.create(Type.Func); func_ty.* = .{ .return_type = .{ .specifier = .int }, .param_types = &.{} }; const ty: Type = .{ .specifier = .old_style_func, .data = .{ .func = func_ty } }; const node = try p.addNode(.{ .ty = ty, .tag = .fn_proto, .data = .{ .first = name_tok }, }); try p.cur_decl_list.append(node); try p.scopes.append(.{ .symbol = .{ .name = name, .node = node, .name_tok = name_tok, } }); return try Result.lval(p, .{ .tag = .decl_ref_expr, .ty = ty, .data = .{ .first = name_tok, .second = node }, }); } try p.errStr(.undeclared_identifier, name_tok, p.tokSlice(name_tok)); return error.ParsingFailed; }; switch (sym) { .enumeration => |e| return e.value, .symbol => |s| { // TODO actually check type if (p.want_const) { try p.err(.expected_integer_constant_expr); return error.ParsingFailed; } return try Result.lval(p, .{ .tag = .decl_ref_expr, .ty = p.nodes.items(.ty)[s.node], .data = .{ .first = name_tok, .second = s.node }, }); }, else => unreachable, } }, .string_literal, .string_literal_utf_16, .string_literal_utf_8, .string_literal_utf_32, .string_literal_wide, => { if (p.want_const) { try p.err(.expected_integer_constant_expr); return error.ParsingFailed; } var start = p.tok_i; // use 1 for wchar_t var width: ?u8 = null; while (true) { switch (p.tok_ids[p.tok_i]) { .string_literal => {}, .string_literal_utf_16 => if (width) |some| { if (some != 16) try p.err(.unsupported_str_cat); } else { width = 16; }, .string_literal_utf_8 => if (width) |some| { if (some != 8) try p.err(.unsupported_str_cat); } else { width = 8; }, .string_literal_utf_32 => if (width) |some| { if (some != 32) try p.err(.unsupported_str_cat); } else { width = 32; }, .string_literal_wide => if (width) |some| { if (some != 1) try p.err(.unsupported_str_cat); } else { width = 1; }, else => break, } p.tok_i += 1; } if (width == null) width = 8; if (width.? != 8) return p.todo("non-utf8 strings"); var builder = std.ArrayList(u8).init(p.pp.comp.gpa); defer builder.deinit(); while (start < p.tok_i) : (start += 1) { var slice = p.tokSlice(start); slice = slice[mem.indexOf(u8, slice, "\"").? + 1 .. slice.len - 1]; var i: u32 = 0; try builder.ensureCapacity(slice.len); while (i < slice.len) : (i += 1) { switch (slice[i]) { '\\' => { i += 1; switch (slice[i]) { '\n' => i += 1, '\r' => i += 2, '\'', '\"', '\\', '?' => |c| builder.appendAssumeCapacity(c), 'n' => builder.appendAssumeCapacity('\n'), 'r' => builder.appendAssumeCapacity('\r'), 't' => builder.appendAssumeCapacity('\t'), 'a' => builder.appendAssumeCapacity(0x07), 'b' => builder.appendAssumeCapacity(0x08), 'e' => builder.appendAssumeCapacity(0x1B), 'f' => builder.appendAssumeCapacity(0x0C), 'v' => builder.appendAssumeCapacity(0x0B), 'x' => return p.todo("hex escape"), 'u' => return p.todo("u escape"), 'U' => return p.todo("U escape"), '0'...'7' => return p.todo("octal escape"), else => unreachable, } }, else => |c| builder.appendAssumeCapacity(c), } } } try builder.append(0); const str = try p.arena.dupe(u8, builder.items); const ptr_loc = @intCast(u32, p.data.items.len); const ptr_val = @bitCast([2]u32, @ptrToInt(str.ptr)); try p.data.appendSlice(&ptr_val); const arr_ty = try p.arena.create(Type.Array); arr_ty.* = .{ .elem = .{ .specifier = .char }, .len = str.len }; return try Result.node(p, .{ .tag = .string_literal_expr, .ty = .{ .specifier = .array, .data = .{ .array = arr_ty }, }, .data = .{ .first = ptr_loc, .second = @intCast(u32, str.len) }, }); }, .char_literal, .char_literal_utf_16, .char_literal_utf_32, .char_literal_wide, => { if (p.want_const) { return p.todo("char literals"); } return p.todo("ast"); }, .float_literal, .float_literal_f, .float_literal_l, => { if (p.want_const) { try p.err(.expected_integer_constant_expr); return error.ParsingFailed; } return p.todo("ast"); }, .zero => { p.tok_i += 1; return Result{ .data = .{ .signed = 0 } }; }, .one => { p.tok_i += 1; return Result{ .data = .{ .signed = 1 } }; }, .integer_literal, .integer_literal_u, .integer_literal_l, .integer_literal_lu, .integer_literal_ll, .integer_literal_llu, => { const id = p.tok_ids[p.tok_i]; var slice = p.tokSlice(p.tok_i); var base: u8 = 10; if (mem.startsWith(u8, slice, "0x") or mem.startsWith(u8, slice, "0X")) { slice = slice[2..]; base = 10; } else if (mem.startsWith(u8, slice, "0b") or mem.startsWith(u8, slice, "0B")) { slice = slice[2..]; base = 2; } else if (slice[0] == '0') { base = 8; } switch (id) { .integer_literal_u, .integer_literal_l => slice = slice[0 .. slice.len - 1], .integer_literal_lu, .integer_literal_ll => slice = slice[0 .. slice.len - 2], .integer_literal_llu => slice = slice[0 .. slice.len - 3], else => {}, } var val: u64 = 0; var overflow = false; for (slice) |c| { const digit: u64 = switch (c) { '0'...'9' => c - '0', 'A'...'Z' => c - 'A' + 10, 'a'...'z' => c - 'a' + 10, else => unreachable, }; if (val != 0 and @mulWithOverflow(u64, val, base, &val)) overflow = true; if (@addWithOverflow(u64, val, digit, &val)) overflow = true; } if (overflow) { try p.err(.int_literal_too_big); return Result{ .ty = .{ .specifier = .ulong_long }, .data = .{ .unsigned = val } }; } p.tok_i += 1; if (base == 10) { switch (id) { .integer_literal => return p.castInt(val, &.{ .int, .long, .long_long }), .integer_literal_u => return p.castInt(val, &.{ .uint, .ulong, .ulong_long }), .integer_literal_l => return p.castInt(val, &.{ .long, .long_long }), .integer_literal_lu => return p.castInt(val, &.{ .ulong, .ulong_long }), .integer_literal_ll => return p.castInt(val, &.{.long_long}), .integer_literal_llu => return p.castInt(val, &.{.ulong_long}), else => unreachable, } } else { switch (id) { .integer_literal => return p.castInt(val, &.{ .int, .uint, .long, .ulong, .long_long, .ulong_long }), .integer_literal_u => return p.castInt(val, &.{ .uint, .ulong, .ulong_long }), .integer_literal_l => return p.castInt(val, &.{ .long, .ulong, .long_long, .ulong_long }), .integer_literal_lu => return p.castInt(val, &.{ .ulong, .ulong_long }), .integer_literal_ll => return p.castInt(val, &.{ .long_long, .ulong_long }), .integer_literal_llu => return p.castInt(val, &.{.ulong_long}), else => unreachable, } } }, .keyword_generic => { return p.todo("generic"); }, else => return Result{}, } } fn castInt(p: *Parser, val: u64, specs: []const Type.Specifier) Error!Result { for (specs) |spec| { const ty = Type{ .specifier = spec }; const unsigned = ty.isUnsignedInt(p.pp.comp); const size = ty.sizeof(p.pp.comp); if (unsigned) { switch (size) { 2 => if (val < std.math.maxInt(u16)) return Result{ .ty = ty, .data = .{ .unsigned = val } }, 4 => if (val < std.math.maxInt(u32)) return Result{ .ty = ty, .data = .{ .unsigned = val } }, 8 => if (val < std.math.maxInt(u64)) return Result{ .ty = ty, .data = .{ .unsigned = val } }, else => unreachable, } } else { switch (size) { 2 => if (val < std.math.maxInt(i16)) return Result{ .ty = ty, .data = .{ .signed = @intCast(i16, val) } }, 4 => if (val < std.math.maxInt(i32)) return Result{ .ty = ty, .data = .{ .signed = @intCast(i32, val) } }, 8 => if (val < std.math.maxInt(i64)) return Result{ .ty = ty, .data = .{ .signed = @intCast(i64, val) } }, else => unreachable, } } } return Result{ .ty = .{ .specifier = .ulong_long }, .data = .{ .unsigned = val } }; }
src/Parser.zig
const std = @import("std"); pub fn unwrapPtr(comptime SomeType: type) type { const ti = @typeInfo(SomeType); const T = if (ti == .Pointer and ti.Pointer.size == .One) SomeType.Child else SomeType; return T; } pub fn isString(comptime SomeT: type) bool { const ti = @typeInfo(SomeT); if (ti == .Pointer and ti.Pointer.child == u8 and ti.Pointer.size == .Slice) return true; if (ti == .Array and ti.Array.child == u8) return true; return false; } pub fn internalFmt( out: var, args: var, comptime depth: usize, ) @TypeOf(out).Child.Error!void { if (depth > 5) { try out.writeAll("..."); return; } const Args = unwrapPtr(@TypeOf(args)); if (comptime isString(Args)) return internalFmt(out, .{args}, depth); if (@typeInfo(Args) != .Struct) { @compileError("Expected tuple, got " ++ @typeName(Args)); } inline for (@typeInfo(Args).Struct.fields) |field| { const arg = @field(args, field.name); // runtime const Arg = unwrapPtr(@TypeOf(arg)); if (comptime isString(unwrapPtr(Arg))) { try out.writeAll(@as([]const u8, arg)); continue; } const ti = @typeInfo(Arg); if ((ti != .Struct and ti != .Enum and ti != .Union) or !@hasDecl(Arg, "formatOverride")) { @compileError("For non-strings, use a helper function eg fmt.num or fmt.structt. Expected []const u8/struct/enum/union, got " ++ @typeName(Arg)); } try arg.formatOverride(struct { out: @TypeOf(out), pub fn fmt(me: @This(), fmtargs: var) !void { try internalFmt(me.out, fmtargs, depth + 1); } }{ .out = out }); } } pub fn fmt(out: var, args: var) !void { try internalFmt(out, args, 0); } fn getNumReturnType(comptime NumType: type) type { const ti = @typeInfo(NumType); const F = std.fmt.FormatOptions; return struct { v: NumType, pub fn formatOverride(me: @This(), print: var) !void { switch (ti) { .Float => try std.fmt.formatFloatDecimal(me.v, F{}, print.out), .Int, .ComptimeInt => try std.fmt.formatInt(me.v, 10, false, F{}, print.out), else => @compileError("not supported number: " ++ @typeName(NumType)), } } }; } // we can also include options for precision, width, alignment, and fill in a more complicated version of this function // also for ints: radix, uppercase pub fn num(number: var) getNumReturnType(@TypeOf(number)) { return getNumReturnType(@TypeOf(number)){ .v = number }; } pub fn typePrint(comptime Type: type) []const u8 { const indent = [_]u8{0}; const ti = @typeInfo(Type); return switch (ti) { .Struct => |stru| blk: { var res: []const u8 = "struct {"; const newline = "\n" ++ (indent ** indentationLevel); for (stru.fields) |field| { res = res ++ newline ++ indent ++ field.name ++ ": " ++ typePrint(field.field_type, indentationLevel + 1) ++ ","; } for (stru.decls) |decl| { res = res ++ newline ++ indent ++ "const " ++ decl.name ++ ";"; } res = res ++ newline ++ "}"; break :blk res; }, else => @typeName(Type), }; } fn getTypReturnType(comptime Type: type) type { const ti = @typeInfo(Type); return struct { // should formatOverride be given an indentation level/var printIndent arg? pub fn formatOverride(me: @This(), print: var) !void { try print.fmt(typePrint(Type)); } }; } pub fn typ(comptime Type: var) getTypReturnType(Type) { return getTypReturnType(Type){}; } pub fn warn(args: var) void { const held = std.debug.getStderrMutex().acquire(); defer held.release(); const stderr = std.debug.getStderrStream(); noasync fmt(stderr, args) catch return; } pub const BufPrintError = error{NoSpaceLeft}; pub fn bufPrint(buf: []u8, args: var) BufPrintError![]u8 { var fbs = std.io.fixedBufferStream(buf); try fmt(&fbs.outStream(), args); return fbs.getWritten(); } /// note that counting before printing generates double the /// binary size because all printing has to be done twice. pub fn count(args: var) u64 { var counting_stream = std.io.countingOutStream(std.io.null_out_stream); fmt(&counting_stream.outStream(), args) catch |err| switch (err) {}; return counting_stream.bytes_written; } pub const AllocPrintError = error{OutOfMemory}; pub fn allocPrint(allocator: *mem.Allocator, args: var) AllocPrintError![]u8 { const size = math.cast(usize, count(args)) catch |err| switch (err) { error.Overflow => return error.OutOfMemory, }; const buf = try allocator.alloc(u8, size); return bufPrint(buf, args) catch |err| switch (err) { error.NoSpaceLeft => unreachable, // we just counted the size above }; } pub fn allocPrint0(allocator: *mem.Allocator, args: var) AllocPrintError![:0]u8 { const result = try allocPrint(allocator, args ++ .{"\x00"}); return result[0 .. result.len - 1 :0]; } pub fn comptimeFmt(comptime args: var) []const u8 { comptime { const width = count(args); var buf: [width]u8 = undefined; return bufPrint(&buf, args) catch unreachable; } } pub fn main() !void { warn("Warn testing!\n"); warn(.{ "My number is: ", num(@as(u64, 25)), "\n" }); warn(.{ "My float is: ", num(@as(f64, 554.32)), "\n" }); warn(.{ "My type is: ", typ(u32), "\n" }); warn(.{ comptime comptimeFmt(.{num(@as(u64, 25))}), "\n" }); // const max = 25; // var load = 0; // while (load <= max) : (load += 1) { // warn(.{ // "\r[", // repeatString("#", load), // repeatString(" ", max - load), // "] (", // num(load), // " / ", // num(max), // ")", // }); // } // warn("\n"); // // const SomeStruct = struct { // a: []const u8, // b: i64, // }; // somewhere we need to demo printing a hashmap or array // also adding custom overrides (comptime)? // warn(.{fmt.addOverride(SomeStruct, overridefn)}) }
src/main.zig
const std = @import("std"); const sys = @import("sys.zig"); const CLONE = std.os.linux.CLONE; const MS = std.os.linux.MS; const MNT = std.os.linux.MNT; const EPOLL = std.os.linux.EPOLL; pub fn IOStreams(comptime Stdin: type, comptime Stdout: type, comptime Stderr: type) type { return struct { stdin: Stdin, stdout: Stdout, stderr: Stderr, pipes: [3]Pipe = undefined, const Self = @This(); pub fn initPipes(self: *Self) !void { for (self.pipes) |*pipe, i| { pipe.* = try Pipe.init(if (i == 0) .read else .write); } } pub fn setPipesAsStdio(self: *Self) !void { for (self.pipes) |*p, i| { p.close(.parent); try std.os.dup2(p.get(.child), @intCast(i32, i)); p.close(.child); } } pub fn readPipes(self: *Self, timeout: u32) !void { for (self.pipes) |*p| { p.close(.child); } const epollfd = try std.os.epoll_create1(0); defer std.os.close(epollfd); const epoll_event = std.os.linux.epoll_event; for (self.pipes) |p, i| { try std.os.epoll_ctl(epollfd, EPOLL.CTL_ADD, p.get(.parent), &epoll_event{ .events = if (i == 0) EPOLL.OUT else EPOLL.IN, .data = .{ .fd = p.get(.parent), }, }); } const timerfd = try sys.timerfd_create(std.os.linux.CLOCK.REALTIME, 0); defer std.os.close(timerfd); try sys.timerfd_settime(timerfd, 0, &std.os.linux.itimerspec{ .it_interval = .{ .tv_sec = 0, .tv_nsec = 0, }, .it_value = .{ .tv_sec = timeout, .tv_nsec = 0, }, }, null); try std.os.epoll_ctl(epollfd, EPOLL.CTL_ADD, timerfd, &epoll_event{ .events = EPOLL.IN, .data = .{ .fd = timerfd, }, }); var open_fds: u32 = 3; while (open_fds > 0) { var events: [3]std.os.linux.epoll_event = undefined; const nfds = std.os.epoll_wait(epollfd, &events, -1); std.log.debug("got {} events", .{nfds}); for (events[0..nfds]) |event| { if (event.data.fd == timerfd) { return error.Timeout; } const p: *Pipe = brk: { for (self.pipes) |*p| { if (p.get(.parent) == event.data.fd) break :brk p; } unreachable; }; if (event.events & (EPOLL.IN | EPOLL.OUT) != 0) { var buf: [1024]u8 = undefined; switch (p.mode) { .read => { const r = try self.stdin.read(&buf); if (r == 0) { std.log.debug("closing stdin", .{}); try std.os.epoll_ctl(epollfd, EPOLL.CTL_DEL, event.data.fd, null); p.close(.parent); open_fds -= 1; } else { std.log.debug("writing {} bytes to stdin", .{r}); const w = try std.os.write(event.data.fd, buf[0..r]); std.debug.assert(w == r); } }, .write => { const r = try std.os.read(event.data.fd, &buf); std.log.debug("read {} bytes for stdout", .{r}); const w = try self.stdout.write(buf[0..r]); std.debug.assert(w == r); }, } } if (event.events & (EPOLL.ERR | EPOLL.HUP) != 0) { try std.os.epoll_ctl(epollfd, EPOLL.CTL_DEL, event.data.fd, null); p.close(.parent); open_fds -= 1; } } } } const Pipe = struct { read: std.os.fd_t, write: std.os.fd_t, mode: Mode, const Mode = enum(u1) { read, write, }; const Side = enum(u1) { parent, child, }; pub fn init(mode: Mode) !Pipe { const pipe = try std.os.pipe(); return Pipe{ .read = pipe[0], .write = pipe[1], .mode = mode, }; } pub fn get(self: Pipe, side: Side) std.os.fd_t { return if (side == .parent and self.mode == .read or side == .child and self.mode == .write) self.write else self.read; } pub fn close(self: *Pipe, side: Side) void { if (side == .parent and self.mode == .read or side == .child and self.mode == .write) { std.os.close(self.write); self.write = undefined; } else { std.os.close(self.read); self.read = undefined; } } }; }; } pub fn ioStreams(stdin: anytype, stdout: anytype, stderr: anytype) IOStreams(@TypeOf(stdin), @TypeOf(stdout), @TypeOf(stderr)) { return .{ .stdin = stdin, .stdout = stdout, .stderr = stderr }; } pub fn Container(comptime IOStreamsType: type) type { return struct { allocator: std.mem.Allocator, argv: []const []const u8, argp: []const []const u8, bind_mounts: []const struct { target: []const u8, // relative path from `dir` source: ?[]const u8, // absolute path }, dir: std.fs.Dir, cwd: []const u8, timeout: u32, streams: IOStreamsType, const Self = @This(); pub const Result = struct { exit_status: u32, user_time: f64, system_time: f64, }; pub fn run(_self: Self) !Result { var self = _self; std.log.info("creating pipes", .{}); try self.streams.initPipes(); { std.log.info("making mount paths", .{}); for (self.bind_mounts) |mount| { try self.dir.makePath(mount.target); } } std.log.info("cloning", .{}); const child_pid = try sys.clone3(.{ .flags = CLONE.NEWUSER | CLONE.NEWNS | CLONE.NEWNET | CLONE.NEWPID | CLONE.NEWIPC, }); if (child_pid == 0) { { std.log.info("bind mounting dirs", .{}); for (self.bind_mounts) |mount| { if (mount.source) |source| { var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; const target = try self.dir.realpath(mount.target, &buf); const source_c = try std.os.toPosixPath(source); const target_c = try std.os.toPosixPath(target); try sys.mount(&source_c, &target_c, null, MS.BIND | MS.REC, null); } } } { std.log.info("mounting /proc", .{}); try self.dir.makeDir("proc"); var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; const path = try self.dir.realpath("proc", &buf); const path_c = try std.os.toPosixPath(path); try sys.mount(null, &path_c, "proc", 0, null); } { var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; const path = try self.dir.realpath(".", &buf); const path_c = try std.os.toPosixPath(path); std.os.close(self.dir.fd); std.log.info("making sure target directory is a mount point", .{}); try sys.mount(&path_c, &path_c, null, MS.BIND | MS.REC, null); std.log.info("pivoting root", .{}); try sys.pivot_root(&path_c, &path_c); std.log.info("unmounting old root", .{}); try sys.umount2("/", MNT.DETACH); try std.os.chdir(self.cwd); } { std.log.info("duplicating pipes", .{}); try self.streams.setPipesAsStdio(); } { const argv = try toCStringArray(self.allocator, self.argv); const argp = try toCStringArray(self.allocator, self.argp); return std.os.execvpeZ(argv[0].?, argv, argp); } } self.streams.readPipes(self.timeout) catch |err| switch (err) { error.Timeout => { try std.os.kill(child_pid, std.os.linux.SIG.KILL); return error.Timeout; }, else => return err, }; const rc = try sys.wait4(child_pid, 0); std.debug.assert(rc.pid == child_pid); std.debug.assert(std.os.linux.W.IFEXITED(rc.status)); return Result{ .exit_status = std.os.linux.W.EXITSTATUS(rc.status), .user_time = timevalToSec(rc.rusage.utime), .system_time = timevalToSec(rc.rusage.stime), }; } }; } fn timevalToSec(tv: std.os.timeval) f64 { return @intToFloat(f64, tv.tv_sec) + @intToFloat(f64, tv.tv_usec) / 1_000_000; } fn toCStringArray(allocator: std.mem.Allocator, slice: []const []const u8) ![*:null]?[*:0]u8 { const csa = try allocator.allocSentinel(?[*:0]u8, slice.len, null); for (slice) |s, i| { csa[i] = try allocator.allocSentinel(u8, s.len, 0); std.mem.copy(u8, csa[i].?[0..s.len], s); } return csa; }
src/container.zig
const GPUData = extern union(enum) { /// The ACPI path of this GPU device, /// if possible to construct. /// /// Aliases: `acpiPath` ACPI: ?[]const u8, /// The ACPI path of this GPU device, /// if possible to construct. /// /// Aliases: `acpiPath` acpiPath: ?[]const u8, /// The codename of this GPU. /// For the time being, NVidia/AMD GPus are only supported. /// /// Sometimes, this data will not be reliable. /// If you wish to be 100% certain, I highly advise you to /// implement your own logic to determine this. /// /// The current implementation simply uses the data from one of my other repositories, /// which has this data hard-coded. It's not perfect, but it's better than nothing. /// /// Sources: /// - [AMD List](https://github.com/iabtw/OCSysInfo/tree/main/src/uarch/gpu/amd_gpu.json) /// - [NVidia List](https://github.com/iabtw/OCSysInfo/tree/main/src/uarch/gpu/nvidia_gpu.json) /// /// Special thanks to: /// - [khronokernel](https://github.com/khronokernel) — for allowing us to copy over their NVidia device IDs for Curie, Tesla, Fermi & Kepler cards in the first place. /// - [Flagers](https://github.com/flagersgit) — for providing us with the AMD & NVidia GPU device IDs data. codename: []const u8, /// The device ID of this GPU device in decimal. /// /// The valid representation should be converted to hex. deviceID: u32, /// The vendor ID of this GPU device in decimal. /// /// The valid representation should be converted to hex. vendorID: u32, /// The model of this GPU. model: []const u8, /// The PCI path of this GPU device, /// if possible to construct. /// /// Aliases: `pciPath` PCI: ?[]const u8, /// The PCI path of this GPU device, /// if possible to construct. /// /// Aliases: `PCI` pciPath: ?[]const u8, /// The total amount of video RAM (VRAM) available for this GPU. /// /// Sometimes this won't be available. /// Most notably, in cases of integrated graphics, where the VRAM is /// dynamically allocated from system memory. vram: u32, };
lib/core/gpu.zig
const std = @import("std"); usingnamespace @import("zalgebra"); pub const Aabb = struct { const Self = @This(); position: vec3, half_extent: vec3, pub fn init(pos: vec3, extent: vec3) Self { return Self { .position = pos, .half_extent = extent, }; } pub fn testPoint(self: *const Self, point: *const vec3) bool { return (point.x >= (self.position.x - self.half_extent.x) and point.x <= (self.position.x + self.half_extent.x)) and (point.y >= (self.position.y - self.half_extent.y) and point.y <= (self.position.y + self.half_extent.y)) and (point.z >= (self.position.z - self.half_extent.z) and point.z <= (self.position.z + self.half_extent.z)); } pub fn testAabb(self: *const Self, other: *const Self) bool { const a_min = self.position.sub(self.half_extent); const a_max = self.position.add(self.half_extent); const b_min = other.position.sub(other.half_extent); const b_max = other.position.add(other.half_extent); return (a_min.x <= b_max.x and a_max.x >= b_min.x) and (a_min.y <= b_max.y and a_max.y >= b_min.y) and (a_min.z <= b_max.z and a_max.z >= b_min.z); } fn calcOffset(a_min: f32, a_max: f32, b_min: f32, b_max: f32) f32 { if (a_min < b_max and a_max > b_min) { var offset1 = b_max - a_min; var offset2 = b_min - a_max; if (offset1 < -offset2) { return offset1; } else { return offset2; } } return 0.0; } pub fn calcPenetration(self: *const Self, other: *const Self) vec3 { const a_min = self.position.sub(self.half_extent); const a_max = self.position.add(self.half_extent); const b_min = other.position.sub(other.half_extent); const b_max = other.position.add(other.half_extent); var offset = vec3.new( calcOffset(a_min.x, a_max.x, b_min.x, b_max.x), calcOffset(a_min.y, a_max.y, b_min.y, b_max.y), calcOffset(a_min.z, a_max.z, b_min.z, b_max.z), ); var abs_x = @fabs(offset.x); var abs_y = @fabs(offset.y); var abs_z = @fabs(offset.z); if(abs_x < abs_y and abs_x < abs_z and abs_x != 0.0) { return vec3.right().scale(offset.x); } else if(abs_y < abs_x and abs_y < abs_z and abs_y != 0.0) { return vec3.up().scale(offset.y); } else if(abs_z < abs_x and abs_z < abs_y and abs_z != 0.0) { return vec3.forward().scale(offset.z); } //Shouldn't be called not really sure what todo here return offset; } pub fn testRay(self: *const Self, start: *const vec3, end: *const vec3) bool { return false; } };
src/collision/aabb.zig
const std = @import("std"); const with_trace = true; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } fn findoradd(cities: [][]const u8, nb: *u32, name: []const u8) u32 { var i: u32 = 0; while (i < nb.*) : (i += 1) { const c = cities[i]; if (std.mem.eql(u8, c, name)) return i; } cities[nb.*] = name; nb.* += 1; return nb.* - 1; } fn swap(a: *u32, b: *u32) void { const t = a.*; a.* = b.*; b.* = t; } pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const limit = 1 * 1024 * 1024 * 1024; const text = try std.fs.cwd().readFileAlloc(allocator, "day9.txt", limit); const maxcities = 10; var cities: [maxcities][]const u8 = undefined; var nb_cities: u32 = 0; var links: [maxcities * maxcities]?u32 = [1]?u32{null} ** (maxcities * maxcities); var totdist: u32 = 0; var it = std.mem.split(u8, text, "\n"); while (it.next()) |line_full| { const line = std.mem.trim(u8, line_full, " \n\r\t"); if (line.len < 2) continue; const sep1 = std.mem.indexOf(u8, line, " to "); const sep2 = std.mem.indexOf(u8, line, " = "); const name1 = line[0..sep1.?]; const name2 = line[sep1.? + 4 .. sep2.?]; const distance_str = line[sep2.? + 3 ..]; const distance = std.fmt.parseInt(u32, distance_str, 10) catch unreachable; const city1 = findoradd(&cities, &nb_cities, name1); const city2 = findoradd(&cities, &nb_cities, name2); links[city1 + maxcities * city2] = distance; links[city2 + maxcities * city1] = distance; totdist += distance; } var permutations_mem: [maxcities]u32 = undefined; const perm = permutations_mem[0..nb_cities]; var permuts: usize = 1; for (perm) |p, i| { permuts *= (i + 1); } var mindist: u32 = totdist; var maxdist: u32 = 0; var j: u32 = 0; while (j < permuts) : (j += 1) { for (perm) |*p, i| { p.* = @intCast(u32, i); } var mod = nb_cities; var k = j; for (perm) |*p, i| { swap(p, &perm[i + k % mod]); k /= mod; mod -= 1; } var dist: ?u32 = 0; var prev = perm[0]; trace("{}", cities[prev]); for (perm[1..]) |p| { const link = links[prev * maxcities + p]; trace(" -> {}", cities[p]); if (link) |l| { dist.? += l; } else { dist = null; break; } prev = p; } trace(": {}\n", dist); if (dist) |d| { if (d < mindist) mindist = d; if (d > maxdist) maxdist = d; } } const out = std.io.getStdOut().writer(); try out.print("min {}, max {}, tot {} (for {} permutations)\n", mindist, maxdist, totdist, permuts); // return error.SolutionNotFound; }
2015/day9.zig
const std = @import("std"); const fs = std.fs; const hm = std.hash_map; const mem = std.mem; const print = std.debug.print; const assert = std.debug.assert; const IngredientMap = hm.HashMap([]const u8, Ingredient, hm.hashString, hm.eqlString, 80); const AllergenMap = hm.HashMap([]const u8, Allergen, hm.hashString, hm.eqlString, 80); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = &gpa.allocator; const input = try fs.cwd().readFileAlloc(allocator, "data/input_21_1.txt", std.math.maxInt(usize)); var ingredients_map = IngredientMap.init(allocator); defer { var it = ingredients_map.iterator(); while (it.next()) |kv| { kv.value.deinit(); } ingredients_map.deinit(); } var allergens_map = AllergenMap.init(allocator); defer { var it = allergens_map.iterator(); while (it.next()) |kv| { kv.value.deinit(); } allergens_map.deinit(); } var lists = std.ArrayList(List).init(allocator); defer { for (lists.items) |_, li| { lists.items[li].deinit(); } defer lists.deinit(); } { // Process input var lines = std.mem.tokenize(input, "\n"); while (lines.next()) |raw_line| { const line = std.mem.trim(u8, raw_line, " \r\n"); if (line.len == 0) continue; const list = try List.init(allocator, line); try lists.append(list); const list_index = lists.items.len - 1; for (list.ingredients.items) |ing| { var res = try ingredients_map.getOrPut(ing); if (!res.found_existing) res.entry.value = Ingredient.init(allocator, ing); try res.entry.value.lists.append(list_index); } for (list.allergenes.items) |all| { var res = try allergens_map.getOrPut(all); if (!res.found_existing) res.entry.value = Allergen.init(allocator, all); try res.entry.value.lists.append(list_index); } } } var first_allergen: []const u8 = ""; var first_ingredient: [] const u8 = ""; { // Solution 1 var allergen_it = allergens_map.iterator(); while (allergen_it.next()) |all_entry| { const all = all_entry.value; assert(all.lists.items.len > 0); if (all.lists.items.len == 1) { const list = lists.items[all.lists.items[0]]; for (list.ingredients.items) |ing_name| { var entry = ingredients_map.getEntry(ing_name).?; entry.value.safe = false; try all_entry.value.ingredients.append(ing_name); } } else { // Make a running list of items that could contain the allergen var unsafe_for_this = std.ArrayList([]const u8).init(allocator); defer unsafe_for_this.deinit(); for (lists.items[all.lists.items[0]].ingredients.items) |ing_name| { try unsafe_for_this.append(ing_name); } for (all.lists.items[1..]) |list_index| { const list = lists.items[list_index]; var i: usize = 0; outer: while (i < unsafe_for_this.items.len) { const unsafe_ing = unsafe_for_this.items[i]; for (list.ingredients.items) |ing| { if (std.mem.eql(u8, unsafe_ing, ing)) { i += 1; continue :outer; } } // Remove last swap unsafe_for_this.items[i] = unsafe_for_this.items[unsafe_for_this.items.len - 1]; try unsafe_for_this.resize(unsafe_for_this.items.len - 1); } } if (unsafe_for_this.items.len == 1) { first_allergen = all_entry.value.name; first_ingredient = unsafe_for_this.items[0]; } for (unsafe_for_this.items) |ing| { try all_entry.value.ingredients.append(ing); var entry = ingredients_map.getEntry(ing).?; entry.value.safe = false; } } } var ing_it = ingredients_map.iterator(); var count: usize = 0; while (ing_it.next()) |ing| { if (ing.value.safe) { count += ing.value.lists.items.len; } } print("Day 21 - Solution 1: {}\n", .{count}); } assert(first_allergen.len > 0); { // Solution 2 var matched = std.ArrayList(Match).init(allocator); defer matched.deinit(); try matched.append(Match{ .all = first_allergen, .ing = first_ingredient }); ingredients_map.getEntry(first_ingredient).?.value.matched = true; _ = allergens_map.remove(first_allergen); while (true) { if (allergens_map.count() == 0) break; var it = allergens_map.iterator(); while (it.next()) |all_entry| { var ings = &all_entry.value.ingredients; var i: usize = 0; while (i < ings.items.len) { const ing_entry = ingredients_map.getEntry(ings.items[i]).?; if (ing_entry.value.matched == true) { ings.items[i] = ings.items[ings.items.len - 1]; try ings.resize(ings.items.len - 1); } else { i += 1; } } if (ings.items.len == 1) { const all = all_entry.value.name; const ing = all_entry.value.ingredients.items[0]; try matched.append(Match{ .all = all, .ing = ing }); _ = allergens_map.remove(all); ingredients_map.getEntry(ing).?.value.matched = true; break; } } } std.sort.sort(Match, matched.items, {}, matchLT); print("Day 21 - Solution 2: ", .{}); for (matched.items) |m, mi| { if (mi == matched.items.len - 1) { print("{}\n", .{m.ing}); } else { print("{},", .{m.ing}); } } } } const List = struct { ingredients: std.ArrayList([]const u8), allergenes: std.ArrayList([]const u8), const Self = @This(); pub fn init(a: *mem.Allocator, txt: []const u8) !Self { var res = Self{ .ingredients = std.ArrayList([]const u8).init(a), .allergenes = std.ArrayList([]const u8).init(a) }; var txt_it = std.mem.tokenize(txt, "("); var ing_txt = txt_it.next().?; var all_txt = txt_it.next().?; var ing_it = std.mem.tokenize(ing_txt, " \r\n"); while (ing_it.next()) |ing| { try res.ingredients.append(std.mem.trim(u8, ing, " \r\n")); } all_txt = all_txt["(contains".len..all_txt.len - 1]; var all_it = std.mem.tokenize(all_txt, ","); while (all_it.next()) |all| { try res.allergenes.append(std.mem.trim(u8, all, " \r\n")); } return res; } pub fn deinit(self: *Self) void { self.ingredients.deinit(); self.allergenes.deinit(); } }; const Ingredient = struct { name: []const u8, lists: std.ArrayList(usize), safe: bool = true, matched: bool = false, const Self = @This(); pub fn init(a: *mem.Allocator, name: []const u8) Self { return .{ .name = name, .lists = std.ArrayList(usize).init(a), }; } pub fn deinit(self: *Self) void { self.lists.deinit(); } }; const Allergen = struct { name: []const u8, lists: std.ArrayList(usize), ingredients: std.ArrayList([]const u8), const Self = @This(); pub fn init(a: *mem.Allocator, name: []const u8) Self { return .{ .name = name, .lists = std.ArrayList(usize).init(a), .ingredients = std.ArrayList([]const u8).init(a) }; } pub fn deinit(self: *Self) void { self.lists.deinit(); } }; const Match = struct { all: []const u8, ing: []const u8 }; fn matchLT(context: void, lhs: Match, rhs: Match) bool { return std.mem.lessThan(u8, lhs.all, rhs.all); }
2020/src/day_21.zig
const std = @import("../std.zig"); const builtin = @import("builtin"); const Mutex = @This(); const os = std.os; const assert = std.debug.assert; const testing = std.testing; const Atomic = std.atomic.Atomic; const Futex = std.Thread.Futex; impl: Impl = .{}, /// Tries to acquire the mutex without blocking the caller's thread. /// Returns `false` if the calling thread would have to block to acquire it. /// Otherwise, returns `true` and the caller should `unlock()` the Mutex to release it. pub fn tryLock(self: *Mutex) bool { return self.impl.tryLock(); } /// Acquires the mutex, blocking the caller's thread until it can. /// It is undefined behavior if the mutex is already held by the caller's thread. /// Once acquired, call `unlock()` on the Mutex to release it. pub fn lock(self: *Mutex) void { self.impl.lock(); } /// Releases the mutex which was previously acquired with `lock()` or `tryLock()`. /// It is undefined behavior if the mutex is unlocked from a different thread that it was locked from. pub fn unlock(self: *Mutex) void { self.impl.unlock(); } const Impl = if (builtin.single_threaded) SingleThreadedImpl else if (builtin.os.tag == .windows) WindowsImpl else if (builtin.os.tag.isDarwin()) DarwinImpl else FutexImpl; const SingleThreadedImpl = struct { is_locked: bool = false, fn tryLock(self: *Impl) bool { if (self.is_locked) return false; self.is_locked = true; return true; } fn lock(self: *Impl) void { if (!self.tryLock()) { unreachable; // deadlock detected } } fn unlock(self: *Impl) void { assert(self.is_locked); self.is_locked = false; } }; // SRWLOCK on windows is almost always faster than Futex solution. // It also implements an efficient Condition with requeue support for us. const WindowsImpl = struct { srwlock: os.windows.SRWLOCK = .{}, fn tryLock(self: *Impl) bool { return os.windows.kernel32.TryAcquireSRWLockExclusive(&self.srwlock) != os.windows.FALSE; } fn lock(self: *Impl) void { os.windows.kernel32.AcquireSRWLockExclusive(&self.srwlock); } fn unlock(self: *Impl) void { os.windows.kernel32.ReleaseSRWLockExclusive(&self.srwlock); } }; // os_unfair_lock on darwin supports priority inheritance and is generally faster than Futex solutions. const DarwinImpl = struct { oul: os.darwin.os_unfair_lock = .{}, fn tryLock(self: *Impl) bool { return os.darwin.os_unfair_lock_trylock(&self.oul); } fn lock(self: *Impl) void { os.darwin.os_unfair_lock_lock(&self.oul); } fn unlock(self: *Impl) void { os.darwin.os_unfair_lock_unlock(&self.oul); } }; const FutexImpl = struct { state: Atomic(u32) = Atomic(u32).init(unlocked), const unlocked = 0b00; const locked = 0b01; const contended = 0b11; // must contain the `locked` bit for x86 optimization below fn tryLock(self: *Impl) bool { // Lock with compareAndSwap instead of tryCompareAndSwap to avoid reporting spurious CAS failure. return self.lockFast("compareAndSwap"); } fn lock(self: *Impl) void { // Lock with tryCompareAndSwap instead of compareAndSwap due to being more inline-able on LL/SC archs like ARM. if (!self.lockFast("tryCompareAndSwap")) { self.lockSlow(); } } inline fn lockFast(self: *Impl, comptime casFn: []const u8) bool { // On x86, use `lock bts` instead of `lock cmpxchg` as: // - they both seem to mark the cache-line as modified regardless: https://stackoverflow.com/a/63350048 // - `lock bts` is smaller instruction-wise which makes it better for inlining if (comptime builtin.target.cpu.arch.isX86()) { const locked_bit = @ctz(u32, @as(u32, locked)); return self.state.bitSet(locked_bit, .Acquire) == 0; } // Acquire barrier ensures grabbing the lock happens before the critical section // and that the previous lock holder's critical section happens before we grab the lock. return @field(self.state, casFn)(unlocked, locked, .Acquire, .Monotonic) == null; } fn lockSlow(self: *Impl) void { @setCold(true); // Avoid doing an atomic swap below if we already know the state is contended. // An atomic swap unconditionally stores which marks the cache-line as modified unnecessarily. if (self.state.load(.Monotonic) == contended) { Futex.wait(&self.state, contended); } // Try to acquire the lock while also telling the existing lock holder that there are threads waiting. // // Once we sleep on the Futex, we must acquire the mutex using `contended` rather than `locked`. // If not, threads sleeping on the Futex wouldn't see the state change in unlock and potentially deadlock. // The downside is that the last mutex unlocker will see `contended` and do an unnecessary Futex wake // but this is better than having to wake all waiting threads on mutex unlock. // // Acquire barrier ensures grabbing the lock happens before the critical section // and that the previous lock holder's critical section happens before we grab the lock. while (self.state.swap(contended, .Acquire) != unlocked) { Futex.wait(&self.state, contended); } } fn unlock(self: *Impl) void { // Unlock the mutex and wake up a waiting thread if any. // // A waiting thread will acquire with `contended` instead of `locked` // which ensures that it wakes up another thread on the next unlock(). // // Release barrier ensures the critical section happens before we let go of the lock // and that our critical section happens before the next lock holder grabs the lock. const state = self.state.swap(unlocked, .Release); assert(state != unlocked); if (state == contended) { Futex.wake(&self.state, 1); } } }; test "Mutex - smoke test" { var mutex = Mutex{}; try testing.expect(mutex.tryLock()); try testing.expect(!mutex.tryLock()); mutex.unlock(); mutex.lock(); try testing.expect(!mutex.tryLock()); mutex.unlock(); } // A counter which is incremented without atomic instructions const NonAtomicCounter = struct { // direct u128 could maybe use xmm ops on x86 which are atomic value: [2]u64 = [_]u64{ 0, 0 }, fn get(self: NonAtomicCounter) u128 { return @bitCast(u128, self.value); } fn inc(self: *NonAtomicCounter) void { for (@bitCast([2]u64, self.get() + 1)) |v, i| { @ptrCast(*volatile u64, &self.value[i]).* = v; } } }; test "Mutex - many uncontended" { // This test requires spawning threads. if (builtin.single_threaded) { return error.SkipZigTest; } const num_threads = 4; const num_increments = 1000; const Runner = struct { mutex: Mutex = .{}, thread: std.Thread = undefined, counter: NonAtomicCounter = .{}, fn run(self: *@This()) void { var i: usize = num_increments; while (i > 0) : (i -= 1) { self.mutex.lock(); defer self.mutex.unlock(); self.counter.inc(); } } }; var runners = [_]Runner{.{}} ** num_threads; for (runners) |*r| r.thread = try std.Thread.spawn(.{}, Runner.run, .{r}); for (runners) |r| r.thread.join(); for (runners) |r| try testing.expectEqual(r.counter.get(), num_increments); } test "Mutex - many contended" { // This test requires spawning threads. if (builtin.single_threaded) { return error.SkipZigTest; } const num_threads = 4; const num_increments = 1000; const Runner = struct { mutex: Mutex = .{}, counter: NonAtomicCounter = .{}, fn run(self: *@This()) void { var i: usize = num_increments; while (i > 0) : (i -= 1) { // Occasionally hint to let another thread run. defer if (i % 100 == 0) std.Thread.yield() catch {}; self.mutex.lock(); defer self.mutex.unlock(); self.counter.inc(); } } }; var runner = Runner{}; var threads: [num_threads]std.Thread = undefined; for (threads) |*t| t.* = try std.Thread.spawn(.{}, Runner.run, .{&runner}); for (threads) |t| t.join(); try testing.expectEqual(runner.counter.get(), num_increments * num_threads); }
lib/std/Thread/Mutex.zig
const std = @import("std"); usingnamespace (@import("../machine.zig")); usingnamespace (@import("../util.zig")); test "bit manipulation" { const m32 = Machine.init(.x86_32); const m64 = Machine.init(.x64); const reg = Operand.register; const regRm = Operand.registerRm; const imm = Operand.immediate; debugPrint(false); const rm16 = Operand.memoryRm(.DefaultSeg, .WORD, .EAX, 0); const rm32 = Operand.memoryRm(.DefaultSeg, .DWORD, .EAX, 0); const rm64 = Operand.memoryRm(.DefaultSeg, .QWORD, .EAX, 0); { const reg16 = Operand.register(.AX); const reg32 = Operand.register(.EAX); const reg64 = Operand.register(.RAX); // LZCNT testOp2(m32, .LZCNT, reg16, rm16, "66 F3 0F BD 00"); testOp2(m32, .LZCNT, reg32, rm32, "F3 0F BD 00"); testOp2(m32, .LZCNT, reg64, rm64, AsmError.InvalidOperand); // POPCNT testOp2(m32, .POPCNT, reg16, rm16, "66 F3 0F B8 00"); testOp2(m32, .POPCNT, reg32, rm32, "F3 0F B8 00"); testOp2(m32, .POPCNT, reg64, rm64, AsmError.InvalidOperand); // TZCNT testOp2(m32, .TZCNT, reg16, rm16, "66 F3 0F BC 00"); testOp2(m32, .TZCNT, reg32, rm32, "F3 0F BC 00"); testOp2(m32, .TZCNT, reg64, rm64, AsmError.InvalidOperand); // LZCNT testOp2(m64, .LZCNT, reg16, rm16, "66 67 F3 0F BD 00"); testOp2(m64, .LZCNT, reg32, rm32, "67 F3 0F BD 00"); testOp2(m64, .LZCNT, reg64, rm64, "67 F3 48 0F BD 00"); // POPCNT testOp2(m64, .POPCNT, reg16, rm16, "66 67 F3 0F B8 00"); testOp2(m64, .POPCNT, reg32, rm32, "67 F3 0F B8 00"); testOp2(m64, .POPCNT, reg64, rm64, "67 F3 48 0F B8 00"); // TZCNT testOp2(m64, .TZCNT, reg16, rm16, "66 67 F3 0F BC 00"); testOp2(m64, .TZCNT, reg32, rm32, "67 F3 0F BC 00"); testOp2(m64, .TZCNT, reg64, rm64, "67 F3 48 0F BC 00"); } testOp3(m64, .ANDN, reg(.EAX), reg(.EAX), rm32, "67 c4 e2 78 f2 00"); testOp3(m64, .ANDN, reg(.RAX), reg(.RAX), rm64, "67 c4 e2 f8 f2 00"); testOp3(m64, .BEXTR, reg(.EAX), rm32, reg(.EAX), "67 c4 e2 78 f7 00"); testOp3(m64, .BEXTR, reg(.RAX), rm64, reg(.RAX), "67 c4 e2 f8 f7 00"); testOp2(m64, .BLSI, reg(.EAX), rm32, "67 c4 e2 78 f3 18"); testOp2(m64, .BLSI, reg(.RAX), rm64, "67 c4 e2 f8 f3 18"); testOp2(m64, .BLSMSK, reg(.EAX), rm32, "67 c4 e2 78 f3 10"); testOp2(m64, .BLSMSK, reg(.RAX), rm64, "67 c4 e2 f8 f3 10"); testOp2(m64, .BLSR, reg(.EAX), rm32, "67 c4 e2 78 f3 08"); testOp2(m64, .BLSR, reg(.RAX), rm64, "67 c4 e2 f8 f3 08"); testOp3(m64, .BZHI, reg(.EAX), rm32, reg(.EAX), "67 c4 e2 78 f5 00"); testOp3(m64, .BZHI, reg(.RAX), rm64, reg(.RAX), "67 c4 e2 f8 f5 00"); testOp3(m64, .MULX, reg(.EAX), reg(.EAX), rm32, "67 c4 e2 7b f6 00"); testOp3(m64, .MULX, reg(.RAX), reg(.RAX), rm64, "67 c4 e2 fb f6 00"); testOp3(m64, .PDEP, reg(.EAX), reg(.EAX), rm32, "67 c4 e2 7b f5 00"); testOp3(m64, .PDEP, reg(.RAX), reg(.RAX), rm64, "67 c4 e2 fb f5 00"); testOp3(m64, .PEXT, reg(.EAX), reg(.EAX), rm32, "67 c4 e2 7a f5 00"); testOp3(m64, .PEXT, reg(.RAX), reg(.RAX), rm64, "67 c4 e2 fa f5 00"); testOp3(m64, .RORX, reg(.EAX), rm32, imm(0), "67 c4 e3 7b f0 00 00"); testOp3(m64, .RORX, reg(.RAX), rm64, imm(0), "67 c4 e3 fb f0 00 00"); testOp3(m64, .SARX, reg(.EAX), rm32, reg(.EAX), "67 c4 e2 7a f7 00"); testOp3(m64, .SARX, reg(.RAX), rm64, reg(.RAX), "67 c4 e2 fa f7 00"); testOp3(m64, .SHLX, reg(.EAX), rm32, reg(.EAX), "67 c4 e2 79 f7 00"); testOp3(m64, .SHLX, reg(.RAX), rm64, reg(.RAX), "67 c4 e2 f9 f7 00"); testOp3(m64, .SHRX, reg(.EAX), rm32, reg(.EAX), "67 c4 e2 7b f7 00"); testOp3(m64, .SHRX, reg(.RAX), rm64, reg(.RAX), "67 c4 e2 fb f7 00"); }
src/x86/tests/bit_manipulation.zig
const Audio = @This(); const SDL = @import("sdl2"); const std = @import("std"); const ROM = @import("ROM.zig"); const SAMPLE_RATE = 48000; const SAMPLE_CHUNK_SIZE = SAMPLE_RATE / 60; const AMP_FACTOR = 64; // arbitrary value so sound isn't so quiet const Wave = [32]u8; fn setVoiceNybble(value: u20, index: u3, nybble_value: u4) u20 { const shift = @as(u5, index) << 2; return value & ~(@as(u20, 0xf) << shift) | (@as(u20, nybble_value) << shift); } const Voice = struct { acc: u20 = 0, wave: u4 = 0, freq: u20 = 0, vol: u4 = 0, pub fn setAccNybble(self: *Voice, index: u3, value: u4) void { self.acc = setVoiceNybble(self.acc, index, value); } pub fn setFreqNybble(self: *Voice, index: u3, value: u4) void { self.freq = setVoiceNybble(self.freq, index, value); } }; device: SDL.AudioDevice, enabled: bool, voices: [3]Voice, waves: *[8]Wave, pub fn init(allocator: std.mem.Allocator, rom: *const ROM) !Audio { const device = (try SDL.openAudioDevice(.{ .desired_spec = .{ .sample_rate = SAMPLE_RATE, .buffer_format = SDL.AudioFormat.s16_sys, .channel_count = 1, .buffer_size_in_frames = SAMPLE_CHUNK_SIZE, .callback = null, .userdata = null, } })).device; errdefer device.close(); device.pause(false); const waves = try allocator.create([8]Wave); errdefer allocator.destroy(waves); waves.* = @bitCast([8]Wave, rom.waves); return Audio{ .device = device, .enabled = false, .voices = [_]Voice{.{}} ** 3, .waves = waves, }; } pub fn deinit(self: Audio, allocator: std.mem.Allocator) void { allocator.destroy(self.waves); self.device.close(); } pub fn update(self: *Audio) !void { var buf = std.mem.zeroes([SAMPLE_CHUNK_SIZE]u16); if (self.enabled) { for (self.voices) |*voice| { if (voice.vol == 0) continue; for (buf) |*b| { voice.acc +%= voice.freq *% 2; b.* += @as(u16, AMP_FACTOR) * voice.vol * self.waves[voice.wave][voice.acc >> 15]; } } } if (SDL.c.SDL_QueueAudio(self.device.id, &buf, SAMPLE_CHUNK_SIZE * @sizeOf(u16)) != 0) { return SDL.makeError(); } }
src/Audio.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const Value = @import("./value.zig").Value; const VM = @import("./vm.zig").VM; const Chunk = @import("./chunk.zig").Chunk; const debug = @import("./debug.zig"); const Table = @import("./table.zig").Table; pub const Obj = struct { next: ?*Obj, objType: Type, isMarked: bool, pub const Type = enum { String, Function, NativeFunction, Closure, Upvalue, Class, Instance, BoundMethod }; pub fn allocate(vm: *VM, comptime T: type, objType: Type) !*Obj { const ptr = try vm.allocator.create(T); ptr.obj = Obj{ .next = vm.objects, .objType = objType, .isMarked = false, }; vm.objects = &ptr.obj; if (debug.LOG_GC) { std.debug.warn("{} allocate {} for {}\n", .{ @ptrToInt(&ptr.obj), @sizeOf(T), @typeName(T) }); } return &ptr.obj; } pub fn destroy(self: *Obj, vm: *VM) void { if (debug.LOG_GC) { std.debug.warn("{} free {} {}\n", .{ @ptrToInt(self), self.objType, self.value() }); } switch (self.objType) { .String => self.asString().destroy(vm), .Function => self.asFunction().destroy(vm), .NativeFunction => self.asNativeFunction().destroy(vm), .Closure => self.asClosure().destroy(vm), .Upvalue => self.asUpvalue().destroy(vm), .Class => self.asClass().destroy(vm), .Instance => self.asInstance().destroy(vm), .BoundMethod => self.asBoundMethod().destroy(vm), } } pub fn isString(self: *Obj) bool { return self.objType == .String; } pub fn isFunction(self: *Obj) bool { return self.objType == .Function; } pub fn isNativeFunction(self: *Obj) bool { return self.objType == .NativeFunction; } pub fn isClosure(self: *Obj) bool { return self.objType == .Closure; } pub fn isUpvalue(self: *Obj) bool { return self.objType == .Upvalue; } pub fn isClass(self: *Obj) bool { return self.objType == .Class; } pub fn isInstance(self: *Obj) bool { return self.objType == .Instance; } pub fn isBoundMethod(self: *Obj) bool { return self.objType == .BoundMethod; } pub fn asString(self: *Obj) *String { return @fieldParentPtr(String, "obj", self); } pub fn asFunction(self: *Obj) *Function { return @fieldParentPtr(Function, "obj", self); } pub fn asNativeFunction(self: *Obj) *NativeFunction { return @fieldParentPtr(NativeFunction, "obj", self); } pub fn asClosure(self: *Obj) *Closure { return @fieldParentPtr(Closure, "obj", self); } pub fn asUpvalue(self: *Obj) *Upvalue { return @fieldParentPtr(Upvalue, "obj", self); } pub fn asClass(self: *Obj) *Class { return @fieldParentPtr(Class, "obj", self); } pub fn asInstance(self: *Obj) *Instance { return @fieldParentPtr(Instance, "obj", self); } pub fn asBoundMethod(self: *Obj) *BoundMethod { return @fieldParentPtr(BoundMethod, "obj", self); } pub fn value(self: *Obj) Value { return Value.fromObj(self); } pub const String = struct { obj: Obj, hash: u32, bytes: []const u8, pub fn create(vm: *VM, bytes: []const u8) !*String { const hash = hashFn(bytes); if (vm.strings.findString(bytes, hash)) |interned| { vm.allocator.free(bytes); return interned; } else { const obj = try Obj.allocate(vm, String, .String); const out = obj.asString(); out.* = String{ .obj = obj.*, .hash = hash, .bytes = bytes, }; // Make sure string is visible to the GC, since adding // to the table may allocate vm.push(out.obj.value()); _ = try vm.strings.set(out, Value.fromBool(true)); _ = vm.pop(); return out; } } pub fn copy(vm: *VM, source: []const u8) !*String { const buffer = try vm.allocator.alloc(u8, source.len); std.mem.copy(u8, buffer, source); return String.create(vm, buffer); } pub fn destroy(self: *String, vm: *VM) void { vm.allocator.free(self.bytes); vm.allocator.destroy(self); } fn hashFn(bytes: []const u8) u32 { // NOTE zig standard library has its own implementation of this // FNV-1a hash function already, in std.hash.fnv var hash: u32 = 2166136261; for (bytes) |byte| { hash ^= byte; // NOTE Zig makes you use a special operator when you want // wraparound on overflow. hash *%= 16777619; } return hash; } }; pub const Function = struct { obj: Obj, arity: u9, upvalueCount: u9, chunk: Chunk, name: ?*String, pub fn create(vm: *VM) !*Function { const obj = try Obj.allocate(vm, Function, .Function); const out = obj.asFunction(); out.* = Function{ .obj = obj.*, .arity = 0, .upvalueCount = 0, .name = null, .chunk = Chunk.init(vm.allocator), }; return out; } pub fn destroy(self: *Function, vm: *VM) void { self.chunk.deinit(); vm.allocator.destroy(self); } }; pub const NativeFunction = struct { obj: Obj, function: NativeFunctionType, pub const NativeFunctionType = fn (args: []Value) Value; pub fn create(vm: *VM, function: NativeFunctionType) !*NativeFunction { const obj = try Obj.allocate(vm, NativeFunction, .NativeFunction); const out = obj.asNativeFunction(); out.* = NativeFunction{ .obj = obj.*, .function = function, }; return out; } pub fn destroy(self: *NativeFunction, vm: *VM) void { vm.allocator.destroy(self); } }; pub const Closure = struct { obj: Obj, function: *Function, upvalues: []?*Upvalue, pub fn create(vm: *VM, function: *Function) !*Closure { const upvalues = try vm.allocator.alloc(?*Upvalue, function.upvalueCount); // Need to null this out rather than leaving it // uninitialized becaue the GC might try to look at it // before it gets filled in with values for (upvalues) |*upvalue| upvalue.* = null; const obj = try Obj.allocate(vm, Closure, .Closure); const out = obj.asClosure(); out.* = Closure{ .obj = obj.*, .function = function, .upvalues = upvalues, }; return out; } pub fn destroy(self: *Closure, vm: *VM) void { vm.allocator.free(self.upvalues); vm.allocator.destroy(self); } }; pub const Upvalue = struct { obj: Obj, location: *Value, closed: Value, next: ?*Upvalue, pub fn create(vm: *VM, location: *Value) !*Upvalue { const obj = try Obj.allocate(vm, Upvalue, .Upvalue); const out = obj.asUpvalue(); out.* = Upvalue{ .obj = obj.*, .location = location, .closed = Value.nil(), .next = null, }; return out; } pub fn destroy(self: *Upvalue, vm: *VM) void { vm.allocator.destroy(self); } }; pub const Class = struct { obj: Obj, name: *String, methods: Table, pub fn create(vm: *VM, name: *String) !*Class { const obj = try Obj.allocate(vm, Class, .Class); const out = obj.asClass(); out.* = Class{ .obj = obj.*, .name = name, .methods = Table.init(vm.allocator), }; return out; } pub fn destroy(self: *Class, vm: *VM) void { self.methods.deinit(); vm.allocator.destroy(self); } }; pub const Instance = struct { obj: Obj, class: *Class, fields: Table, pub fn create(vm: *VM, class: *Class) !*Instance { const obj = try Obj.allocate(vm, Instance, .Instance); const out = obj.asInstance(); out.* = Instance{ .obj = obj.*, .class = class, .fields = Table.init(vm.allocator), }; return out; } pub fn destroy(self: *Instance, vm: *VM) void { self.fields.deinit(); vm.allocator.destroy(self); } }; pub const BoundMethod = struct { obj: Obj, receiver: Value, method: *Closure, pub fn create(vm: *VM, receiver: Value, method: *Closure) !*BoundMethod { const obj = try Obj.allocate(vm, BoundMethod, .BoundMethod); const out = obj.asBoundMethod(); out.* = BoundMethod{ .obj = obj.*, .receiver = receiver, .method = method, }; return out; } pub fn destroy(self: *BoundMethod, vm: *VM) void { vm.allocator.destroy(self); } }; };
src/object.zig
const std = @import("std"); const builtin = @import("builtin"); const stdx = @import("stdx"); const Timer = stdx.time.Timer; const sdl = @import("sdl"); const log = std.log.scoped(.fps); pub const DefaultFpsLimiter = FpsLimiter(20); pub fn FpsLimiter(comptime NumSamples: u32) type { return struct { const Self = @This(); target_fps: u32, target_us_per_frame: u64, start_time_us: u64, timer: Timer, // Result. fps: u64, // Samples. frame_time_samples: [NumSamples]u64, frame_time_samples_idx: usize, frame_time_samples_sum: u64, last_update_time_us: u64, last_frame_time_us: u64, pub fn init(target_fps: u32) Self { var timer = Timer.start() catch unreachable; return .{ .target_fps = target_fps, .target_us_per_frame = 1000000 / target_fps, .timer = timer, .start_time_us = timer.read() / 1000, .frame_time_samples = std.mem.zeroes([NumSamples]u64), .frame_time_samples_idx = 0, .frame_time_samples_sum = 0, .fps = 0, .last_update_time_us = 0, .last_frame_time_us = 0, }; } /// Measures the frame time: the time it took to update the last frame and any delays. /// We do the measure here so user code has a more relevant frame delta to use since user code starts immediately after. pub fn beginFrame(self: *Self) void { var now_us = self.timer.read() / 1000; // Frame time includes any sleeping so it can be used to calculate fps. const frame_time_us = now_us - self.start_time_us; self.last_frame_time_us = frame_time_us; self.start_time_us = now_us; // remove oldest sample from sum first. self.frame_time_samples_sum -= self.frame_time_samples[self.frame_time_samples_idx]; self.frame_time_samples_sum += frame_time_us; self.frame_time_samples[self.frame_time_samples_idx] = frame_time_us; self.frame_time_samples_idx += 1; if (self.frame_time_samples_idx == NumSamples) { self.frame_time_samples_idx = 0; } const frame_time_avg = self.frame_time_samples_sum / NumSamples; if (frame_time_avg != 0) { // Compute fps even when we don't have all samples yet. It's not much different than waiting since the first // few frames will be super fast since vsync hasn't kicked in yet. self.fps = 1000000 / frame_time_avg; // Round to target_fps if close. The original measurement isn't very accurate anyway since we are using integers for the calculations. if (std.math.absInt(@intCast(i32, self.target_fps) - @intCast(i32, self.fps)) catch unreachable < 5) { self.fps = self.target_fps; } } } /// Measures the user update time and returns delay amount in microseconds to achieve target fps. pub fn endFrame(self: *Self) u64 { var now_us = self.timer.read() / 1000; // Frame update time does not include the delay time. const update_time_us = now_us - self.start_time_us; self.last_update_time_us = update_time_us; if (update_time_us < self.target_us_per_frame) { return self.target_us_per_frame - update_time_us; } else { return 0; } } /// How long the last frame took including pre-start frame and post-end frame. (eg. sleeping/syncing) /// Duration in microseconds. pub fn getLastFrameDelta(self: *const Self) u64 { return self.last_frame_time_us; } pub fn getLastFrameDeltaMs(self: *const Self) f32 { return @intToFloat(f32, self.getLastFrameDelta()) / 1000; } /// How long the last frame took between start and end frame. pub fn getLastUpdateDelta(self: *const Self) u64 { return self.last_update_time_us; } pub fn getFps(self: *const Self) u64 { return self.fps; } }; }
graphics/src/fps.zig
const std = @import("../std.zig"); const math = std.math; const mem = std.mem; const assert = std.debug.assert; const testing = std.testing; const maxInt = math.maxInt; const Vector = std.meta.Vector; const Poly1305 = std.crypto.onetimeauth.Poly1305; // Vectorized implementation of the core function const ChaCha20VecImpl = struct { const Lane = Vector(4, u32); const BlockVec = [4]Lane; fn initContext(key: [8]u32, d: [4]u32) BlockVec { const c = "expand 32-byte k"; const constant_le = comptime Lane{ mem.readIntLittle(u32, c[0..4]), mem.readIntLittle(u32, c[4..8]), mem.readIntLittle(u32, c[8..12]), mem.readIntLittle(u32, c[12..16]), }; return BlockVec{ constant_le, Lane{ key[0], key[1], key[2], key[3] }, Lane{ key[4], key[5], key[6], key[7] }, Lane{ d[0], d[1], d[2], d[3] }, }; } inline fn chacha20Core(x: *BlockVec, input: BlockVec) void { x.* = input; var r: usize = 0; while (r < 20) : (r += 2) { x[0] +%= x[1]; x[3] ^= x[0]; x[3] = math.rotl(Lane, x[3], 16); x[2] +%= x[3]; x[1] ^= x[2]; x[1] = math.rotl(Lane, x[1], 12); x[0] +%= x[1]; x[3] ^= x[0]; x[0] = @shuffle(u32, x[0], undefined, [_]i32{ 3, 0, 1, 2 }); x[3] = math.rotl(Lane, x[3], 8); x[2] +%= x[3]; x[3] = @shuffle(u32, x[3], undefined, [_]i32{ 2, 3, 0, 1 }); x[1] ^= x[2]; x[2] = @shuffle(u32, x[2], undefined, [_]i32{ 1, 2, 3, 0 }); x[1] = math.rotl(Lane, x[1], 7); x[0] +%= x[1]; x[3] ^= x[0]; x[3] = math.rotl(Lane, x[3], 16); x[2] +%= x[3]; x[1] ^= x[2]; x[1] = math.rotl(Lane, x[1], 12); x[0] +%= x[1]; x[3] ^= x[0]; x[0] = @shuffle(u32, x[0], undefined, [_]i32{ 1, 2, 3, 0 }); x[3] = math.rotl(Lane, x[3], 8); x[2] +%= x[3]; x[3] = @shuffle(u32, x[3], undefined, [_]i32{ 2, 3, 0, 1 }); x[1] ^= x[2]; x[2] = @shuffle(u32, x[2], undefined, [_]i32{ 3, 0, 1, 2 }); x[1] = math.rotl(Lane, x[1], 7); } } inline fn hashToBytes(out: *[64]u8, x: BlockVec) void { var i: usize = 0; while (i < 4) : (i += 1) { mem.writeIntLittle(u32, out[16 * i + 0 ..][0..4], x[i][0]); mem.writeIntLittle(u32, out[16 * i + 4 ..][0..4], x[i][1]); mem.writeIntLittle(u32, out[16 * i + 8 ..][0..4], x[i][2]); mem.writeIntLittle(u32, out[16 * i + 12 ..][0..4], x[i][3]); } } inline fn contextFeedback(x: *BlockVec, ctx: BlockVec) void { x[0] +%= ctx[0]; x[1] +%= ctx[1]; x[2] +%= ctx[2]; x[3] +%= ctx[3]; } fn chacha20Xor(out: []u8, in: []const u8, key: [8]u32, counter: [4]u32) void { var ctx = initContext(key, counter); var x: BlockVec = undefined; var buf: [64]u8 = undefined; var i: usize = 0; while (i + 64 <= in.len) : (i += 64) { chacha20Core(x[0..], ctx); contextFeedback(&x, ctx); hashToBytes(buf[0..], x); var xout = out[i..]; const xin = in[i..]; var j: usize = 0; while (j < 64) : (j += 1) { xout[j] = xin[j]; } j = 0; while (j < 64) : (j += 1) { xout[j] ^= buf[j]; } ctx[3][0] += 1; } if (i < in.len) { chacha20Core(x[0..], ctx); contextFeedback(&x, ctx); hashToBytes(buf[0..], x); var xout = out[i..]; const xin = in[i..]; var j: usize = 0; while (j < in.len % 64) : (j += 1) { xout[j] = xin[j] ^ buf[j]; } } } fn hchacha20(input: [16]u8, key: [32]u8) [32]u8 { var c: [4]u32 = undefined; for (c) |_, i| { c[i] = mem.readIntLittle(u32, input[4 * i ..][0..4]); } const ctx = initContext(keyToWords(key), c); var x: BlockVec = undefined; chacha20Core(x[0..], ctx); var out: [32]u8 = undefined; mem.writeIntLittle(u32, out[0..4], x[0][0]); mem.writeIntLittle(u32, out[4..8], x[0][1]); mem.writeIntLittle(u32, out[8..12], x[0][2]); mem.writeIntLittle(u32, out[12..16], x[0][3]); mem.writeIntLittle(u32, out[16..20], x[3][0]); mem.writeIntLittle(u32, out[20..24], x[3][1]); mem.writeIntLittle(u32, out[24..28], x[3][2]); mem.writeIntLittle(u32, out[28..32], x[3][3]); return out; } }; // Non-vectorized implementation of the core function const ChaCha20NonVecImpl = struct { const BlockVec = [16]u32; fn initContext(key: [8]u32, d: [4]u32) BlockVec { const c = "expand 32-byte k"; const constant_le = comptime [4]u32{ mem.readIntLittle(u32, c[0..4]), mem.readIntLittle(u32, c[4..8]), mem.readIntLittle(u32, c[8..12]), mem.readIntLittle(u32, c[12..16]), }; return BlockVec{ constant_le[0], constant_le[1], constant_le[2], constant_le[3], key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7], d[0], d[1], d[2], d[3], }; } const QuarterRound = struct { a: usize, b: usize, c: usize, d: usize, }; fn Rp(a: usize, b: usize, c: usize, d: usize) QuarterRound { return QuarterRound{ .a = a, .b = b, .c = c, .d = d, }; } inline fn chacha20Core(x: *BlockVec, input: BlockVec) void { x.* = input; const rounds = comptime [_]QuarterRound{ Rp(0, 4, 8, 12), Rp(1, 5, 9, 13), Rp(2, 6, 10, 14), Rp(3, 7, 11, 15), Rp(0, 5, 10, 15), Rp(1, 6, 11, 12), Rp(2, 7, 8, 13), Rp(3, 4, 9, 14), }; comptime var j: usize = 0; inline while (j < 20) : (j += 2) { inline for (rounds) |r| { x[r.a] +%= x[r.b]; x[r.d] = math.rotl(u32, x[r.d] ^ x[r.a], @as(u32, 16)); x[r.c] +%= x[r.d]; x[r.b] = math.rotl(u32, x[r.b] ^ x[r.c], @as(u32, 12)); x[r.a] +%= x[r.b]; x[r.d] = math.rotl(u32, x[r.d] ^ x[r.a], @as(u32, 8)); x[r.c] +%= x[r.d]; x[r.b] = math.rotl(u32, x[r.b] ^ x[r.c], @as(u32, 7)); } } } inline fn hashToBytes(out: *[64]u8, x: BlockVec) void { var i: usize = 0; while (i < 4) : (i += 1) { mem.writeIntLittle(u32, out[16 * i + 0 ..][0..4], x[i * 4 + 0]); mem.writeIntLittle(u32, out[16 * i + 4 ..][0..4], x[i * 4 + 1]); mem.writeIntLittle(u32, out[16 * i + 8 ..][0..4], x[i * 4 + 2]); mem.writeIntLittle(u32, out[16 * i + 12 ..][0..4], x[i * 4 + 3]); } } inline fn contextFeedback(x: *BlockVec, ctx: BlockVec) void { var i: usize = 0; while (i < 16) : (i += 1) { x[i] +%= ctx[i]; } } fn chacha20Xor(out: []u8, in: []const u8, key: [8]u32, counter: [4]u32) void { var ctx = initContext(key, counter); var x: BlockVec = undefined; var buf: [64]u8 = undefined; var i: usize = 0; while (i + 64 <= in.len) : (i += 64) { chacha20Core(x[0..], ctx); contextFeedback(&x, ctx); hashToBytes(buf[0..], x); var xout = out[i..]; const xin = in[i..]; var j: usize = 0; while (j < 64) : (j += 1) { xout[j] = xin[j]; } j = 0; while (j < 64) : (j += 1) { xout[j] ^= buf[j]; } ctx[12] += 1; } if (i < in.len) { chacha20Core(x[0..], ctx); contextFeedback(&x, ctx); hashToBytes(buf[0..], x); var xout = out[i..]; const xin = in[i..]; var j: usize = 0; while (j < in.len % 64) : (j += 1) { xout[j] = xin[j] ^ buf[j]; } } } fn hchacha20(input: [16]u8, key: [32]u8) [32]u8 { var c: [4]u32 = undefined; for (c) |_, i| { c[i] = mem.readIntLittle(u32, input[4 * i ..][0..4]); } const ctx = initContext(keyToWords(key), c); var x: BlockVec = undefined; chacha20Core(x[0..], ctx); var out: [32]u8 = undefined; mem.writeIntLittle(u32, out[0..4], x[0]); mem.writeIntLittle(u32, out[4..8], x[1]); mem.writeIntLittle(u32, out[8..12], x[2]); mem.writeIntLittle(u32, out[12..16], x[3]); mem.writeIntLittle(u32, out[16..20], x[12]); mem.writeIntLittle(u32, out[20..24], x[13]); mem.writeIntLittle(u32, out[24..28], x[14]); mem.writeIntLittle(u32, out[28..32], x[15]); return out; } }; const ChaCha20Impl = if (std.Target.current.cpu.arch == .x86_64) ChaCha20VecImpl else ChaCha20NonVecImpl; fn keyToWords(key: [32]u8) [8]u32 { var k: [8]u32 = undefined; var i: usize = 0; while (i < 8) : (i += 1) { k[i] = mem.readIntLittle(u32, key[i * 4 ..][0..4]); } return k; } /// ChaCha20 avoids the possibility of timing attacks, as there are no branches /// on secret key data. /// /// in and out should be the same length. /// counter should generally be 0 or 1 /// /// ChaCha20 is self-reversing. To decrypt just run the cipher with the same /// counter, nonce, and key. pub const ChaCha20IETF = struct { pub fn xor(out: []u8, in: []const u8, counter: u32, key: [32]u8, nonce: [12]u8) void { assert(in.len == out.len); assert((in.len >> 6) + counter <= maxInt(u32)); var c: [4]u32 = undefined; c[0] = counter; c[1] = mem.readIntLittle(u32, nonce[0..4]); c[2] = mem.readIntLittle(u32, nonce[4..8]); c[3] = mem.readIntLittle(u32, nonce[8..12]); ChaCha20Impl.chacha20Xor(out, in, keyToWords(key), c); } }; /// This is the original ChaCha20 before RFC 7539, which recommends using the /// orgininal version on applications such as disk or file encryption that might /// exceed the 256 GiB limit of the 96-bit nonce version. pub const ChaCha20With64BitNonce = struct { pub fn xor(out: []u8, in: []const u8, counter: u64, key: [32]u8, nonce: [8]u8) void { assert(in.len == out.len); assert(counter +% (in.len >> 6) >= counter); var cursor: usize = 0; const k = keyToWords(key); var c: [4]u32 = undefined; c[0] = @truncate(u32, counter); c[1] = @truncate(u32, counter >> 32); c[2] = mem.readIntLittle(u32, nonce[0..4]); c[3] = mem.readIntLittle(u32, nonce[4..8]); const block_length = (1 << 6); // The full block size is greater than the address space on a 32bit machine const big_block = if (@sizeOf(usize) > 4) (block_length << 32) else maxInt(usize); // first partial big block if (((@intCast(u64, maxInt(u32) - @truncate(u32, counter)) + 1) << 6) < in.len) { ChaCha20Impl.chacha20Xor(out[cursor..big_block], in[cursor..big_block], k, c); cursor = big_block - cursor; c[1] += 1; if (comptime @sizeOf(usize) > 4) { // A big block is giant: 256 GiB, but we can avoid this limitation var remaining_blocks: u32 = @intCast(u32, (in.len / big_block)); var i: u32 = 0; while (remaining_blocks > 0) : (remaining_blocks -= 1) { ChaCha20Impl.chacha20Xor(out[cursor .. cursor + big_block], in[cursor .. cursor + big_block], k, c); c[1] += 1; // upper 32-bit of counter, generic chacha20Xor() doesn't know about this. cursor += big_block; } } } ChaCha20Impl.chacha20Xor(out[cursor..], in[cursor..], k, c); } }; // https://tools.ietf.org/html/rfc7539#section-2.4.2 test "crypto.chacha20 test vector sunscreen" { const expected_result = [_]u8{ 0x6e, 0x2e, 0x35, 0x9a, 0x25, 0x68, 0xf9, 0x80, 0x41, 0xba, 0x07, 0x28, 0xdd, 0x0d, 0x69, 0x81, 0xe9, 0x7e, 0x7a, 0xec, 0x1d, 0x43, 0x60, 0xc2, 0x0a, 0x27, 0xaf, 0xcc, 0xfd, 0x9f, 0xae, 0x0b, 0xf9, 0x1b, 0x65, 0xc5, 0x52, 0x47, 0x33, 0xab, 0x8f, 0x59, 0x3d, 0xab, 0xcd, 0x62, 0xb3, 0x57, 0x16, 0x39, 0xd6, 0x24, 0xe6, 0x51, 0x52, 0xab, 0x8f, 0x53, 0x0c, 0x35, 0x9f, 0x08, 0x61, 0xd8, 0x07, 0xca, 0x0d, 0xbf, 0x50, 0x0d, 0x6a, 0x61, 0x56, 0xa3, 0x8e, 0x08, 0x8a, 0x22, 0xb6, 0x5e, 0x52, 0xbc, 0x51, 0x4d, 0x16, 0xcc, 0xf8, 0x06, 0x81, 0x8c, 0xe9, 0x1a, 0xb7, 0x79, 0x37, 0x36, 0x5a, 0xf9, 0x0b, 0xbf, 0x74, 0xa3, 0x5b, 0xe6, 0xb4, 0x0b, 0x8e, 0xed, 0xf2, 0x78, 0x5e, 0x42, 0x87, 0x4d, }; const input = "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."; var result: [114]u8 = undefined; const key = [_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, }; const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0x4a, 0, 0, 0, 0, }; ChaCha20IETF.xor(result[0..], input[0..], 1, key, nonce); testing.expectEqualSlices(u8, &expected_result, &result); // Chacha20 is self-reversing. var plaintext: [114]u8 = undefined; ChaCha20IETF.xor(plaintext[0..], result[0..], 1, key, nonce); testing.expect(mem.order(u8, input, &plaintext) == .eq); } // https://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-7 test "crypto.chacha20 test vector 1" { const expected_result = [_]u8{ 0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90, 0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28, 0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a, 0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7, 0xda, 0x41, 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d, 0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37, 0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, 0xa1, 0x1c, 0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86, }; const input = [_]u8{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; var result: [64]u8 = undefined; const key = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0 }; ChaCha20With64BitNonce.xor(result[0..], input[0..], 0, key, nonce); testing.expectEqualSlices(u8, &expected_result, &result); } test "crypto.chacha20 test vector 2" { const expected_result = [_]u8{ 0x45, 0x40, 0xf0, 0x5a, 0x9f, 0x1f, 0xb2, 0x96, 0xd7, 0x73, 0x6e, 0x7b, 0x20, 0x8e, 0x3c, 0x96, 0xeb, 0x4f, 0xe1, 0x83, 0x46, 0x88, 0xd2, 0x60, 0x4f, 0x45, 0x09, 0x52, 0xed, 0x43, 0x2d, 0x41, 0xbb, 0xe2, 0xa0, 0xb6, 0xea, 0x75, 0x66, 0xd2, 0xa5, 0xd1, 0xe7, 0xe2, 0x0d, 0x42, 0xaf, 0x2c, 0x53, 0xd7, 0x92, 0xb1, 0xc4, 0x3f, 0xea, 0x81, 0x7e, 0x9a, 0xd2, 0x75, 0xae, 0x54, 0x69, 0x63, }; const input = [_]u8{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; var result: [64]u8 = undefined; const key = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, }; const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0 }; ChaCha20With64BitNonce.xor(result[0..], input[0..], 0, key, nonce); testing.expectEqualSlices(u8, &expected_result, &result); } test "crypto.chacha20 test vector 3" { const expected_result = [_]u8{ 0xde, 0x9c, 0xba, 0x7b, 0xf3, 0xd6, 0x9e, 0xf5, 0xe7, 0x86, 0xdc, 0x63, 0x97, 0x3f, 0x65, 0x3a, 0x0b, 0x49, 0xe0, 0x15, 0xad, 0xbf, 0xf7, 0x13, 0x4f, 0xcb, 0x7d, 0xf1, 0x37, 0x82, 0x10, 0x31, 0xe8, 0x5a, 0x05, 0x02, 0x78, 0xa7, 0x08, 0x45, 0x27, 0x21, 0x4f, 0x73, 0xef, 0xc7, 0xfa, 0x5b, 0x52, 0x77, 0x06, 0x2e, 0xb7, 0xa0, 0x43, 0x3e, 0x44, 0x5f, 0x41, 0xe3, }; const input = [_]u8{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; var result: [60]u8 = undefined; const key = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 1 }; ChaCha20With64BitNonce.xor(result[0..], input[0..], 0, key, nonce); testing.expectEqualSlices(u8, &expected_result, &result); } test "crypto.chacha20 test vector 4" { const expected_result = [_]u8{ 0xef, 0x3f, 0xdf, 0xd6, 0xc6, 0x15, 0x78, 0xfb, 0xf5, 0xcf, 0x35, 0xbd, 0x3d, 0xd3, 0x3b, 0x80, 0x09, 0x63, 0x16, 0x34, 0xd2, 0x1e, 0x42, 0xac, 0x33, 0x96, 0x0b, 0xd1, 0x38, 0xe5, 0x0d, 0x32, 0x11, 0x1e, 0x4c, 0xaf, 0x23, 0x7e, 0xe5, 0x3c, 0xa8, 0xad, 0x64, 0x26, 0x19, 0x4a, 0x88, 0x54, 0x5d, 0xdc, 0x49, 0x7a, 0x0b, 0x46, 0x6e, 0x7d, 0x6b, 0xbd, 0xb0, 0x04, 0x1b, 0x2f, 0x58, 0x6b, }; const input = [_]u8{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; var result: [64]u8 = undefined; const key = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; const nonce = [_]u8{ 1, 0, 0, 0, 0, 0, 0, 0 }; ChaCha20With64BitNonce.xor(result[0..], input[0..], 0, key, nonce); testing.expectEqualSlices(u8, &expected_result, &result); } test "crypto.chacha20 test vector 5" { const expected_result = [_]u8{ 0xf7, 0x98, 0xa1, 0x89, 0xf1, 0x95, 0xe6, 0x69, 0x82, 0x10, 0x5f, 0xfb, 0x64, 0x0b, 0xb7, 0x75, 0x7f, 0x57, 0x9d, 0xa3, 0x16, 0x02, 0xfc, 0x93, 0xec, 0x01, 0xac, 0x56, 0xf8, 0x5a, 0xc3, 0xc1, 0x34, 0xa4, 0x54, 0x7b, 0x73, 0x3b, 0x46, 0x41, 0x30, 0x42, 0xc9, 0x44, 0x00, 0x49, 0x17, 0x69, 0x05, 0xd3, 0xbe, 0x59, 0xea, 0x1c, 0x53, 0xf1, 0x59, 0x16, 0x15, 0x5c, 0x2b, 0xe8, 0x24, 0x1a, 0x38, 0x00, 0x8b, 0x9a, 0x26, 0xbc, 0x35, 0x94, 0x1e, 0x24, 0x44, 0x17, 0x7c, 0x8a, 0xde, 0x66, 0x89, 0xde, 0x95, 0x26, 0x49, 0x86, 0xd9, 0x58, 0x89, 0xfb, 0x60, 0xe8, 0x46, 0x29, 0xc9, 0xbd, 0x9a, 0x5a, 0xcb, 0x1c, 0xc1, 0x18, 0xbe, 0x56, 0x3e, 0xb9, 0xb3, 0xa4, 0xa4, 0x72, 0xf8, 0x2e, 0x09, 0xa7, 0xe7, 0x78, 0x49, 0x2b, 0x56, 0x2e, 0xf7, 0x13, 0x0e, 0x88, 0xdf, 0xe0, 0x31, 0xc7, 0x9d, 0xb9, 0xd4, 0xf7, 0xc7, 0xa8, 0x99, 0x15, 0x1b, 0x9a, 0x47, 0x50, 0x32, 0xb6, 0x3f, 0xc3, 0x85, 0x24, 0x5f, 0xe0, 0x54, 0xe3, 0xdd, 0x5a, 0x97, 0xa5, 0xf5, 0x76, 0xfe, 0x06, 0x40, 0x25, 0xd3, 0xce, 0x04, 0x2c, 0x56, 0x6a, 0xb2, 0xc5, 0x07, 0xb1, 0x38, 0xdb, 0x85, 0x3e, 0x3d, 0x69, 0x59, 0x66, 0x09, 0x96, 0x54, 0x6c, 0xc9, 0xc4, 0xa6, 0xea, 0xfd, 0xc7, 0x77, 0xc0, 0x40, 0xd7, 0x0e, 0xaf, 0x46, 0xf7, 0x6d, 0xad, 0x39, 0x79, 0xe5, 0xc5, 0x36, 0x0c, 0x33, 0x17, 0x16, 0x6a, 0x1c, 0x89, 0x4c, 0x94, 0xa3, 0x71, 0x87, 0x6a, 0x94, 0xdf, 0x76, 0x28, 0xfe, 0x4e, 0xaa, 0xf2, 0xcc, 0xb2, 0x7d, 0x5a, 0xaa, 0xe0, 0xad, 0x7a, 0xd0, 0xf9, 0xd4, 0xb6, 0xad, 0x3b, 0x54, 0x09, 0x87, 0x46, 0xd4, 0x52, 0x4d, 0x38, 0x40, 0x7a, 0x6d, 0xeb, 0x3a, 0xb7, 0x8f, 0xab, 0x78, 0xc9, }; const input = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; var result: [256]u8 = undefined; const key = [_]u8{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, }; const nonce = [_]u8{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, }; ChaCha20With64BitNonce.xor(result[0..], input[0..], 0, key, nonce); testing.expectEqualSlices(u8, &expected_result, &result); } pub const chacha20poly1305_tag_length = 16; fn chacha20poly1305SealDetached(ciphertext: []u8, tag: *[chacha20poly1305_tag_length]u8, plaintext: []const u8, data: []const u8, key: [32]u8, nonce: [12]u8) void { assert(ciphertext.len == plaintext.len); // derive poly1305 key var polyKey = [_]u8{0} ** 32; ChaCha20IETF.xor(polyKey[0..], polyKey[0..], 0, key, nonce); // encrypt plaintext ChaCha20IETF.xor(ciphertext[0..plaintext.len], plaintext, 1, key, nonce); // construct mac var mac = Poly1305.init(polyKey[0..]); mac.update(data); if (data.len % 16 != 0) { const zeros = [_]u8{0} ** 16; const padding = 16 - (data.len % 16); mac.update(zeros[0..padding]); } mac.update(ciphertext[0..plaintext.len]); if (plaintext.len % 16 != 0) { const zeros = [_]u8{0} ** 16; const padding = 16 - (plaintext.len % 16); mac.update(zeros[0..padding]); } var lens: [16]u8 = undefined; mem.writeIntLittle(u64, lens[0..8], data.len); mem.writeIntLittle(u64, lens[8..16], plaintext.len); mac.update(lens[0..]); mac.final(tag); } fn chacha20poly1305Seal(ciphertextAndTag: []u8, plaintext: []const u8, data: []const u8, key: [32]u8, nonce: [12]u8) void { return chacha20poly1305SealDetached(ciphertextAndTag[0..plaintext.len], ciphertextAndTag[plaintext.len..][0..chacha20poly1305_tag_length], plaintext, data, key, nonce); } /// Verifies and decrypts an authenticated message produced by chacha20poly1305SealDetached. fn chacha20poly1305OpenDetached(dst: []u8, ciphertext: []const u8, tag: *const [chacha20poly1305_tag_length]u8, data: []const u8, key: [32]u8, nonce: [12]u8) !void { // split ciphertext and tag assert(dst.len == ciphertext.len); // derive poly1305 key var polyKey = [_]u8{0} ** 32; ChaCha20IETF.xor(polyKey[0..], polyKey[0..], 0, key, nonce); // construct mac var mac = Poly1305.init(polyKey[0..]); mac.update(data); if (data.len % 16 != 0) { const zeros = [_]u8{0} ** 16; const padding = 16 - (data.len % 16); mac.update(zeros[0..padding]); } mac.update(ciphertext); if (ciphertext.len % 16 != 0) { const zeros = [_]u8{0} ** 16; const padding = 16 - (ciphertext.len % 16); mac.update(zeros[0..padding]); } var lens: [16]u8 = undefined; mem.writeIntLittle(u64, lens[0..8], data.len); mem.writeIntLittle(u64, lens[8..16], ciphertext.len); mac.update(lens[0..]); var computedTag: [16]u8 = undefined; mac.final(computedTag[0..]); // verify mac in constant time // TODO: we can't currently guarantee that this will run in constant time. // See https://github.com/ziglang/zig/issues/1776 var acc: u8 = 0; for (computedTag) |_, i| { acc |= computedTag[i] ^ tag[i]; } if (acc != 0) { return error.AuthenticationFailed; } // decrypt ciphertext ChaCha20IETF.xor(dst[0..ciphertext.len], ciphertext, 1, key, nonce); } /// Verifies and decrypts an authenticated message produced by chacha20poly1305Seal. fn chacha20poly1305Open(dst: []u8, ciphertextAndTag: []const u8, data: []const u8, key: [32]u8, nonce: [12]u8) !void { if (ciphertextAndTag.len < chacha20poly1305_tag_length) { return error.InvalidMessage; } const ciphertextLen = ciphertextAndTag.len - chacha20poly1305_tag_length; return try chacha20poly1305OpenDetached(dst, ciphertextAndTag[0..ciphertextLen], ciphertextAndTag[ciphertextLen..][0..chacha20poly1305_tag_length], data, key, nonce); } fn extend(key: [32]u8, nonce: [24]u8) struct { key: [32]u8, nonce: [12]u8 } { var subnonce: [12]u8 = undefined; mem.set(u8, subnonce[0..4], 0); mem.copy(u8, subnonce[4..], nonce[16..24]); return .{ .key = ChaCha20Impl.hchacha20(nonce[0..16].*, key), .nonce = subnonce, }; } pub const XChaCha20IETF = struct { pub fn xor(out: []u8, in: []const u8, counter: u32, key: [32]u8, nonce: [24]u8) void { const extended = extend(key, nonce); ChaCha20IETF.xor(out, in, counter, extended.key, extended.nonce); } }; pub const xchacha20poly1305_tag_length = 16; fn xchacha20poly1305SealDetached(ciphertext: []u8, tag: *[chacha20poly1305_tag_length]u8, plaintext: []const u8, data: []const u8, key: [32]u8, nonce: [24]u8) void { const extended = extend(key, nonce); return chacha20poly1305SealDetached(ciphertext, tag, plaintext, data, extended.key, extended.nonce); } fn xchacha20poly1305Seal(ciphertextAndTag: []u8, plaintext: []const u8, data: []const u8, key: [32]u8, nonce: [24]u8) void { const extended = extend(key, nonce); return chacha20poly1305Seal(ciphertextAndTag, plaintext, data, extended.key, extended.nonce); } /// Verifies and decrypts an authenticated message produced by xchacha20poly1305SealDetached. fn xchacha20poly1305OpenDetached(plaintext: []u8, ciphertext: []const u8, tag: *const [chacha20poly1305_tag_length]u8, data: []const u8, key: [32]u8, nonce: [24]u8) !void { const extended = extend(key, nonce); return try chacha20poly1305OpenDetached(plaintext, ciphertext, tag, data, extended.key, extended.nonce); } /// Verifies and decrypts an authenticated message produced by xchacha20poly1305Seal. fn xchacha20poly1305Open(ciphertextAndTag: []u8, msgAndTag: []const u8, data: []const u8, key: [32]u8, nonce: [24]u8) !void { const extended = extend(key, nonce); return try chacha20poly1305Open(ciphertextAndTag, msgAndTag, data, extended.key, extended.nonce); } test "seal" { { const plaintext = ""; const data = ""; const key = [_]u8{ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, }; const nonce = [_]u8{ 0x7, 0x0, 0x0, 0x0, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 }; const exp_out = [_]u8{ 0xa0, 0x78, 0x4d, 0x7a, 0x47, 0x16, 0xf3, 0xfe, 0xb4, 0xf6, 0x4e, 0x7f, 0x4b, 0x39, 0xbf, 0x4 }; var out: [exp_out.len]u8 = undefined; chacha20poly1305Seal(out[0..], plaintext, data, key, nonce); testing.expectEqualSlices(u8, exp_out[0..], out[0..]); } { const plaintext = [_]u8{ 0x4c, 0x61, 0x64, 0x69, 0x65, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x47, 0x65, 0x6e, 0x74, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x27, 0x39, 0x39, 0x3a, 0x20, 0x49, 0x66, 0x20, 0x49, 0x20, 0x63, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x6f, 0x66, 0x66, 0x65, 0x72, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6f, 0x6e, 0x6c, 0x79, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x74, 0x69, 0x70, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x75, 0x74, 0x75, 0x72, 0x65, 0x2c, 0x20, 0x73, 0x75, 0x6e, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x20, 0x77, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x69, 0x74, 0x2e, }; const data = [_]u8{ 0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7 }; const key = [_]u8{ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, }; const nonce = [_]u8{ 0x7, 0x0, 0x0, 0x0, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 }; const exp_out = [_]u8{ 0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb, 0x7b, 0x86, 0xaf, 0xbc, 0x53, 0xef, 0x7e, 0xc2, 0xa4, 0xad, 0xed, 0x51, 0x29, 0x6e, 0x8, 0xfe, 0xa9, 0xe2, 0xb5, 0xa7, 0x36, 0xee, 0x62, 0xd6, 0x3d, 0xbe, 0xa4, 0x5e, 0x8c, 0xa9, 0x67, 0x12, 0x82, 0xfa, 0xfb, 0x69, 0xda, 0x92, 0x72, 0x8b, 0x1a, 0x71, 0xde, 0xa, 0x9e, 0x6, 0xb, 0x29, 0x5, 0xd6, 0xa5, 0xb6, 0x7e, 0xcd, 0x3b, 0x36, 0x92, 0xdd, 0xbd, 0x7f, 0x2d, 0x77, 0x8b, 0x8c, 0x98, 0x3, 0xae, 0xe3, 0x28, 0x9, 0x1b, 0x58, 0xfa, 0xb3, 0x24, 0xe4, 0xfa, 0xd6, 0x75, 0x94, 0x55, 0x85, 0x80, 0x8b, 0x48, 0x31, 0xd7, 0xbc, 0x3f, 0xf4, 0xde, 0xf0, 0x8e, 0x4b, 0x7a, 0x9d, 0xe5, 0x76, 0xd2, 0x65, 0x86, 0xce, 0xc6, 0x4b, 0x61, 0x16, 0x1a, 0xe1, 0xb, 0x59, 0x4f, 0x9, 0xe2, 0x6a, 0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60, 0x6, 0x91, }; var out: [exp_out.len]u8 = undefined; chacha20poly1305Seal(out[0..], plaintext[0..], data[0..], key, nonce); testing.expectEqualSlices(u8, exp_out[0..], out[0..]); } } test "open" { { const ciphertext = [_]u8{ 0xa0, 0x78, 0x4d, 0x7a, 0x47, 0x16, 0xf3, 0xfe, 0xb4, 0xf6, 0x4e, 0x7f, 0x4b, 0x39, 0xbf, 0x4 }; const data = ""; const key = [_]u8{ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, }; const nonce = [_]u8{ 0x7, 0x0, 0x0, 0x0, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 }; const exp_out = ""; var out: [exp_out.len]u8 = undefined; try chacha20poly1305Open(out[0..], ciphertext[0..], data, key, nonce); testing.expectEqualSlices(u8, exp_out[0..], out[0..]); } { const ciphertext = [_]u8{ 0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb, 0x7b, 0x86, 0xaf, 0xbc, 0x53, 0xef, 0x7e, 0xc2, 0xa4, 0xad, 0xed, 0x51, 0x29, 0x6e, 0x8, 0xfe, 0xa9, 0xe2, 0xb5, 0xa7, 0x36, 0xee, 0x62, 0xd6, 0x3d, 0xbe, 0xa4, 0x5e, 0x8c, 0xa9, 0x67, 0x12, 0x82, 0xfa, 0xfb, 0x69, 0xda, 0x92, 0x72, 0x8b, 0x1a, 0x71, 0xde, 0xa, 0x9e, 0x6, 0xb, 0x29, 0x5, 0xd6, 0xa5, 0xb6, 0x7e, 0xcd, 0x3b, 0x36, 0x92, 0xdd, 0xbd, 0x7f, 0x2d, 0x77, 0x8b, 0x8c, 0x98, 0x3, 0xae, 0xe3, 0x28, 0x9, 0x1b, 0x58, 0xfa, 0xb3, 0x24, 0xe4, 0xfa, 0xd6, 0x75, 0x94, 0x55, 0x85, 0x80, 0x8b, 0x48, 0x31, 0xd7, 0xbc, 0x3f, 0xf4, 0xde, 0xf0, 0x8e, 0x4b, 0x7a, 0x9d, 0xe5, 0x76, 0xd2, 0x65, 0x86, 0xce, 0xc6, 0x4b, 0x61, 0x16, 0x1a, 0xe1, 0xb, 0x59, 0x4f, 0x9, 0xe2, 0x6a, 0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60, 0x6, 0x91, }; const data = [_]u8{ 0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7 }; const key = [_]u8{ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, }; const nonce = [_]u8{ 0x7, 0x0, 0x0, 0x0, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 }; const exp_out = [_]u8{ 0x4c, 0x61, 0x64, 0x69, 0x65, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x47, 0x65, 0x6e, 0x74, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x27, 0x39, 0x39, 0x3a, 0x20, 0x49, 0x66, 0x20, 0x49, 0x20, 0x63, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x6f, 0x66, 0x66, 0x65, 0x72, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6f, 0x6e, 0x6c, 0x79, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x74, 0x69, 0x70, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x75, 0x74, 0x75, 0x72, 0x65, 0x2c, 0x20, 0x73, 0x75, 0x6e, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x20, 0x77, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x69, 0x74, 0x2e, }; var out: [exp_out.len]u8 = undefined; try chacha20poly1305Open(out[0..], ciphertext[0..], data[0..], key, nonce); testing.expectEqualSlices(u8, exp_out[0..], out[0..]); // corrupting the ciphertext, data, key, or nonce should cause a failure var bad_ciphertext = ciphertext; bad_ciphertext[0] ^= 1; testing.expectError(error.AuthenticationFailed, chacha20poly1305Open(out[0..], bad_ciphertext[0..], data[0..], key, nonce)); var bad_data = data; bad_data[0] ^= 1; testing.expectError(error.AuthenticationFailed, chacha20poly1305Open(out[0..], ciphertext[0..], bad_data[0..], key, nonce)); var bad_key = key; bad_key[0] ^= 1; testing.expectError(error.AuthenticationFailed, chacha20poly1305Open(out[0..], ciphertext[0..], data[0..], bad_key, nonce)); var bad_nonce = nonce; bad_nonce[0] ^= 1; testing.expectError(error.AuthenticationFailed, chacha20poly1305Open(out[0..], ciphertext[0..], data[0..], key, bad_nonce)); // a short ciphertext should result in a different error testing.expectError(error.InvalidMessage, chacha20poly1305Open(out[0..], "", data[0..], key, bad_nonce)); } } test "crypto.xchacha20" { const key = [_]u8{69} ** 32; const nonce = [_]u8{42} ** 24; const input = "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."; { var ciphertext: [input.len]u8 = undefined; XChaCha20IETF.xor(ciphertext[0..], input[0..], 0, key, nonce); var buf: [2 * ciphertext.len]u8 = undefined; testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{ciphertext}), "E0A1BCF939654AFDBDC1746EC49832647C19D891F0D1A81FC0C1703B4514BDEA584B512F6908C2C5E9DD18D5CBC1805DE5803FE3B9CA5F193FB8359E91FAB0C3BB40309A292EB1CF49685C65C4A3ADF4F11DB0CD2B6B67FBC174BC2E860E8F769FD3565BBFAD1C845E05A0FED9BE<KEY>"); } { const data = "Additional data"; var ciphertext: [input.len + xchacha20poly1305_tag_length]u8 = undefined; xchacha20poly1305Seal(ciphertext[0..], input, data, key, nonce); var out: [input.len]u8 = undefined; try xchacha20poly1305Open(out[0..], ciphertext[0..], data, key, nonce); var buf: [2 * ciphertext.len]u8 = undefined; testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{ciphertext}), "994D2DD32333F48E53650C02C7A2ABB8E018B0836D7175AEC779F52E961780768F815C58F1AA52D211498DB89B9216763F569C9433A6BBFCEFB4D4A49387A4C5207FBB3B5A92B5941294DF30588C6740D39DC16FA1F0E634F7246CF7CDCB978E44347D89381B7A74EB7084F754B90BDE9AAF5A94B8F2A85EFD0B50692AE2D425E234"); testing.expectEqualSlices(u8, out[0..], input); ciphertext[0] += 1; testing.expectError(error.AuthenticationFailed, xchacha20poly1305Open(out[0..], ciphertext[0..], data, key, nonce)); } } pub const Chacha20Poly1305 = struct { pub const tag_length = 16; pub const nonce_length = 12; pub const key_length = 32; /// c: ciphertext: output buffer should be of size m.len /// tag: authentication tag: output MAC /// m: message /// ad: Associated Data /// npub: public nonce /// k: private key pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) void { assert(c.len == m.len); return chacha20poly1305SealDetached(c, tag, m, ad, k, npub); } /// m: message: output buffer should be of size c.len /// c: ciphertext /// tag: authentication tag /// ad: Associated Data /// npub: public nonce /// k: private key /// NOTE: the check of the authentication tag is currently not done in constant time pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) !void { assert(c.len == m.len); return try chacha20poly1305OpenDetached(m, c, tag[0..], ad, k, npub); } }; pub const XChacha20Poly1305 = struct { pub const tag_length = 16; pub const nonce_length = 24; pub const key_length = 32; /// c: ciphertext: output buffer should be of size m.len /// tag: authentication tag: output MAC /// m: message /// ad: Associated Data /// npub: public nonce /// k: private key pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) void { assert(c.len == m.len); return xchacha20poly1305SealDetached(c, tag, m, ad, k, npub); } /// m: message: output buffer should be of size c.len /// c: ciphertext /// tag: authentication tag /// ad: Associated Data /// npub: public nonce /// k: private key /// NOTE: the check of the authentication tag is currently not done in constant time pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) !void { assert(c.len == m.len); return try xchacha20poly1305OpenDetached(m, c, tag[0..], ad, k, npub); } }; test "chacha20 AEAD API" { const aeads = [_]type{ Chacha20Poly1305, XChacha20Poly1305 }; const input = "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."; const data = "Additional data"; inline for (aeads) |aead| { const key = [_]u8{69} ** aead.key_length; const nonce = [_]u8{42} ** aead.nonce_length; var ciphertext: [input.len]u8 = undefined; var tag: [aead.tag_length]u8 = undefined; var out: [input.len]u8 = undefined; aead.encrypt(ciphertext[0..], tag[0..], input, data, nonce, key); try aead.decrypt(out[0..], ciphertext[0..], tag, data[0..], nonce, key); testing.expectEqualSlices(u8, out[0..], input); ciphertext[0] += 1; testing.expectError(error.AuthenticationFailed, aead.decrypt(out[0..], ciphertext[0..], tag, data[0..], nonce, key)); } }
lib/std/crypto/chacha20.zig
const std = @import("std.zig"); const builtin = @import("builtin"); const assert = std.debug.assert; const net = @This(); const mem = std.mem; const os = std.os; const fs = std.fs; test "" { _ = @import("net/test.zig"); } const has_unix_sockets = @hasDecl(os, "sockaddr_un"); pub const Address = extern union { any: os.sockaddr, in: os.sockaddr_in, in6: os.sockaddr_in6, un: if (has_unix_sockets) os.sockaddr_un else void, // TODO this crashed the compiler. https://github.com/ziglang/zig/issues/3512 //pub const localhost = initIp4(parseIp4("127.0.0.1") catch unreachable, 0); pub fn parseIp(name: []const u8, port: u16) !Address { if (parseIp4(name, port)) |ip4| return ip4 else |err| switch (err) { error.Overflow, error.InvalidEnd, error.InvalidCharacter, error.Incomplete, => {}, } if (parseIp6(name, port)) |ip6| return ip6 else |err| switch (err) { error.Overflow, error.InvalidEnd, error.InvalidCharacter, error.Incomplete, error.InvalidIpv4Mapping, => {}, } return error.InvalidIPAddressFormat; } pub fn parseExpectingFamily(name: []const u8, family: os.sa_family_t, port: u16) !Address { switch (family) { os.AF_INET => return parseIp4(name, port), os.AF_INET6 => return parseIp6(name, port), os.AF_UNSPEC => return parseIp(name, port), else => unreachable, } } pub fn parseIp6(buf: []const u8, port: u16) !Address { var result = Address{ .in6 = os.sockaddr_in6{ .scope_id = 0, .port = mem.nativeToBig(u16, port), .flowinfo = 0, .addr = undefined, }, }; var ip_slice = result.in6.addr[0..]; var tail: [16]u8 = undefined; var x: u16 = 0; var saw_any_digits = false; var index: u8 = 0; var scope_id = false; var abbrv = false; for (buf) |c, i| { if (scope_id) { if (c >= '0' and c <= '9') { const digit = c - '0'; if (@mulWithOverflow(u32, result.in6.scope_id, 10, &result.in6.scope_id)) { return error.Overflow; } if (@addWithOverflow(u32, result.in6.scope_id, digit, &result.in6.scope_id)) { return error.Overflow; } } else { return error.InvalidCharacter; } } else if (c == ':') { if (!saw_any_digits) { if (abbrv) return error.InvalidCharacter; // ':::' if (i != 0) abbrv = true; mem.set(u8, ip_slice[index..], 0); ip_slice = tail[0..]; index = 0; continue; } if (index == 14) { return error.InvalidEnd; } ip_slice[index] = @truncate(u8, x >> 8); index += 1; ip_slice[index] = @truncate(u8, x); index += 1; x = 0; saw_any_digits = false; } else if (c == '%') { if (!saw_any_digits) { return error.InvalidCharacter; } scope_id = true; saw_any_digits = false; } else if (c == '.') { if (!abbrv or ip_slice[0] != 0xff or ip_slice[1] != 0xff) { // must start with '::ffff:' return error.InvalidIpv4Mapping; } const start_index = mem.lastIndexOfScalar(u8, buf[0..i], ':').? + 1; const addr = (parseIp4(buf[start_index..], 0) catch { return error.InvalidIpv4Mapping; }).in.addr; ip_slice = result.in6.addr[0..]; ip_slice[10] = 0xff; ip_slice[11] = 0xff; const ptr = mem.sliceAsBytes(@as(*const [1]u32, &addr)[0..]); ip_slice[12] = ptr[0]; ip_slice[13] = ptr[1]; ip_slice[14] = ptr[2]; ip_slice[15] = ptr[3]; return result; } else { const digit = try std.fmt.charToDigit(c, 16); if (@mulWithOverflow(u16, x, 16, &x)) { return error.Overflow; } if (@addWithOverflow(u16, x, digit, &x)) { return error.Overflow; } saw_any_digits = true; } } if (!saw_any_digits and !abbrv) { return error.Incomplete; } if (index == 14) { ip_slice[14] = @truncate(u8, x >> 8); ip_slice[15] = @truncate(u8, x); return result; } else { ip_slice[index] = @truncate(u8, x >> 8); index += 1; ip_slice[index] = @truncate(u8, x); index += 1; mem.copy(u8, result.in6.addr[16 - index ..], ip_slice[0..index]); return result; } } pub fn parseIp4(buf: []const u8, port: u16) !Address { var result = Address{ .in = os.sockaddr_in{ .port = mem.nativeToBig(u16, port), .addr = undefined, }, }; const out_ptr = mem.sliceAsBytes(@as(*[1]u32, &result.in.addr)[0..]); var x: u8 = 0; var index: u8 = 0; var saw_any_digits = false; for (buf) |c| { if (c == '.') { if (!saw_any_digits) { return error.InvalidCharacter; } if (index == 3) { return error.InvalidEnd; } out_ptr[index] = x; index += 1; x = 0; saw_any_digits = false; } else if (c >= '0' and c <= '9') { saw_any_digits = true; x = try std.math.mul(u8, x, 10); x = try std.math.add(u8, x, c - '0'); } else { return error.InvalidCharacter; } } if (index == 3 and saw_any_digits) { out_ptr[index] = x; return result; } return error.Incomplete; } pub fn initIp4(addr: [4]u8, port: u16) Address { return Address{ .in = os.sockaddr_in{ .port = mem.nativeToBig(u16, port), .addr = @ptrCast(*align(1) const u32, &addr).*, }, }; } pub fn initIp6(addr: [16]u8, port: u16, flowinfo: u32, scope_id: u32) Address { return Address{ .in6 = os.sockaddr_in6{ .addr = addr, .port = mem.nativeToBig(u16, port), .flowinfo = flowinfo, .scope_id = scope_id, }, }; } pub fn initUnix(path: []const u8) !Address { var sock_addr = os.sockaddr_un{ .family = os.AF_UNIX, .path = undefined, }; // this enables us to have the proper length of the socket in getOsSockLen mem.set(u8, &sock_addr.path, 0); if (path.len > sock_addr.path.len) return error.NameTooLong; mem.copy(u8, &sock_addr.path, path); return Address{ .un = sock_addr }; } /// Returns the port in native endian. /// Asserts that the address is ip4 or ip6. pub fn getPort(self: Address) u16 { const big_endian_port = switch (self.any.family) { os.AF_INET => self.in.port, os.AF_INET6 => self.in6.port, else => unreachable, }; return mem.bigToNative(u16, big_endian_port); } /// `port` is native-endian. /// Asserts that the address is ip4 or ip6. pub fn setPort(self: *Address, port: u16) void { const ptr = switch (self.any.family) { os.AF_INET => &self.in.port, os.AF_INET6 => &self.in6.port, else => unreachable, }; ptr.* = mem.nativeToBig(u16, port); } /// Asserts that `addr` is an IP address. /// This function will read past the end of the pointer, with a size depending /// on the address family. pub fn initPosix(addr: *align(4) const os.sockaddr) Address { switch (addr.family) { os.AF_INET => return Address{ .in = @ptrCast(*const os.sockaddr_in, addr).* }, os.AF_INET6 => return Address{ .in6 = @ptrCast(*const os.sockaddr_in6, addr).* }, else => unreachable, } } pub fn format( self: Address, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: var, ) !void { switch (self.any.family) { os.AF_INET => { const port = mem.bigToNative(u16, self.in.port); const bytes = @ptrCast(*const [4]u8, &self.in.addr); try std.fmt.format(out_stream, "{}.{}.{}.{}:{}", .{ bytes[0], bytes[1], bytes[2], bytes[3], port, }); }, os.AF_INET6 => { const port = mem.bigToNative(u16, self.in6.port); if (mem.eql(u8, self.in6.addr[0..12], &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff })) { try std.fmt.format(out_stream, "[::ffff:{}.{}.{}.{}]:{}", .{ self.in6.addr[12], self.in6.addr[13], self.in6.addr[14], self.in6.addr[15], port, }); return; } const big_endian_parts = @ptrCast(*align(1) const [8]u16, &self.in6.addr); const native_endian_parts = switch (builtin.endian) { .Big => big_endian_parts.*, .Little => blk: { var buf: [8]u16 = undefined; for (big_endian_parts) |part, i| { buf[i] = mem.bigToNative(u16, part); } break :blk buf; }, }; try out_stream.writeAll("["); var i: usize = 0; var abbrv = false; while (i < native_endian_parts.len) : (i += 1) { if (native_endian_parts[i] == 0) { if (!abbrv) { try out_stream.writeAll(if (i == 0) "::" else ":"); abbrv = true; } continue; } try std.fmt.format(out_stream, "{x}", .{native_endian_parts[i]}); if (i != native_endian_parts.len - 1) { try out_stream.writeAll(":"); } } try std.fmt.format(out_stream, "]:{}", .{port}); }, os.AF_UNIX => { if (!has_unix_sockets) { unreachable; } try std.fmt.format(out_stream, "{}", .{&self.un.path}); }, else => unreachable, } } pub fn eql(a: Address, b: Address) bool { const a_bytes = @ptrCast([*]const u8, &a.any)[0..a.getOsSockLen()]; const b_bytes = @ptrCast([*]const u8, &b.any)[0..b.getOsSockLen()]; return mem.eql(u8, a_bytes, b_bytes); } fn getOsSockLen(self: Address) os.socklen_t { switch (self.any.family) { os.AF_INET => return @sizeOf(os.sockaddr_in), os.AF_INET6 => return @sizeOf(os.sockaddr_in6), os.AF_UNIX => { if (!has_unix_sockets) { unreachable; } const path_len = std.mem.len(@ptrCast([*:0]const u8, &self.un.path)); return @intCast(os.socklen_t, @sizeOf(os.sockaddr_un) - self.un.path.len + path_len); }, else => unreachable, } } }; pub fn connectUnixSocket(path: []const u8) !fs.File { const opt_non_block = if (std.io.is_async) os.SOCK_NONBLOCK else 0; const sockfd = try os.socket( os.AF_UNIX, os.SOCK_STREAM | os.SOCK_CLOEXEC | opt_non_block, 0, ); errdefer os.close(sockfd); var addr = try std.net.Address.initUnix(path); try os.connect( sockfd, &addr.any, addr.getOsSockLen(), ); return fs.File{ .handle = sockfd, .io_mode = std.io.mode, }; } pub const AddressList = struct { arena: std.heap.ArenaAllocator, addrs: []Address, canon_name: ?[]u8, fn deinit(self: *AddressList) void { // Here we copy the arena allocator into stack memory, because // otherwise it would destroy itself while it was still working. var arena = self.arena; arena.deinit(); // self is destroyed } }; /// All memory allocated with `allocator` will be freed before this function returns. pub fn tcpConnectToHost(allocator: *mem.Allocator, name: []const u8, port: u16) !fs.File { const list = try getAddressList(allocator, name, port); defer list.deinit(); if (list.addrs.len == 0) return error.UnknownHostName; return tcpConnectToAddress(list.addrs[0]); } pub fn tcpConnectToAddress(address: Address) !fs.File { const nonblock = if (std.io.is_async) os.SOCK_NONBLOCK else 0; const sock_flags = os.SOCK_STREAM | os.SOCK_CLOEXEC | nonblock; const sockfd = try os.socket(address.any.family, sock_flags, os.IPPROTO_TCP); errdefer os.close(sockfd); try os.connect(sockfd, &address.any, address.getOsSockLen()); return fs.File{ .handle = sockfd }; } /// Call `AddressList.deinit` on the result. pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*AddressList { const result = blk: { var arena = std.heap.ArenaAllocator.init(allocator); errdefer arena.deinit(); const result = try arena.allocator.create(AddressList); result.* = AddressList{ .arena = arena, .addrs = undefined, .canon_name = null, }; break :blk result; }; const arena = &result.arena.allocator; errdefer result.arena.deinit(); if (builtin.link_libc) { const c = std.c; const name_c = try std.cstr.addNullByte(allocator, name); defer allocator.free(name_c); const port_c = try std.fmt.allocPrint(allocator, "{}\x00", .{port}); defer allocator.free(port_c); const hints = os.addrinfo{ .flags = c.AI_NUMERICSERV, .family = os.AF_UNSPEC, .socktype = os.SOCK_STREAM, .protocol = os.IPPROTO_TCP, .canonname = null, .addr = null, .addrlen = 0, .next = null, }; var res: *os.addrinfo = undefined; switch (os.system.getaddrinfo(name_c.ptr, @ptrCast([*:0]const u8, port_c.ptr), &hints, &res)) { @intToEnum(os.system.EAI, 0) => {}, .ADDRFAMILY => return error.HostLacksNetworkAddresses, .AGAIN => return error.TemporaryNameServerFailure, .BADFLAGS => unreachable, // Invalid hints .FAIL => return error.NameServerFailure, .FAMILY => return error.AddressFamilyNotSupported, .MEMORY => return error.OutOfMemory, .NODATA => return error.HostLacksNetworkAddresses, .NONAME => return error.UnknownHostName, .SERVICE => return error.ServiceUnavailable, .SOCKTYPE => unreachable, // Invalid socket type requested in hints .SYSTEM => switch (os.errno(-1)) { else => |e| return os.unexpectedErrno(e), }, else => unreachable, } defer os.system.freeaddrinfo(res); const addr_count = blk: { var count: usize = 0; var it: ?*os.addrinfo = res; while (it) |info| : (it = info.next) { if (info.addr != null) { count += 1; } } break :blk count; }; result.addrs = try arena.alloc(Address, addr_count); var it: ?*os.addrinfo = res; var i: usize = 0; while (it) |info| : (it = info.next) { const addr = info.addr orelse continue; result.addrs[i] = Address.initPosix(@alignCast(4, addr)); if (info.canonname) |n| { if (result.canon_name == null) { result.canon_name = try mem.dupe(arena, u8, mem.spanZ(n)); } } i += 1; } return result; } if (builtin.os.tag == .linux) { const flags = std.c.AI_NUMERICSERV; const family = os.AF_UNSPEC; var lookup_addrs = std.ArrayList(LookupAddr).init(allocator); defer lookup_addrs.deinit(); var canon = std.ArrayListSentineled(u8, 0).initNull(arena); defer canon.deinit(); try linuxLookupName(&lookup_addrs, &canon, name, family, flags, port); result.addrs = try arena.alloc(Address, lookup_addrs.items.len); if (!canon.isNull()) { result.canon_name = canon.toOwnedSlice(); } for (lookup_addrs.span()) |lookup_addr, i| { result.addrs[i] = lookup_addr.addr; assert(result.addrs[i].getPort() == port); } return result; } @compileError("std.net.getAddresses unimplemented for this OS"); } const LookupAddr = struct { addr: Address, sortkey: i32 = 0, }; const DAS_USABLE = 0x40000000; const DAS_MATCHINGSCOPE = 0x20000000; const DAS_MATCHINGLABEL = 0x10000000; const DAS_PREC_SHIFT = 20; const DAS_SCOPE_SHIFT = 16; const DAS_PREFIX_SHIFT = 8; const DAS_ORDER_SHIFT = 0; fn linuxLookupName( addrs: *std.ArrayList(LookupAddr), canon: *std.ArrayListSentineled(u8, 0), opt_name: ?[]const u8, family: os.sa_family_t, flags: u32, port: u16, ) !void { if (opt_name) |name| { // reject empty name and check len so it fits into temp bufs try canon.replaceContents(name); if (Address.parseExpectingFamily(name, family, port)) |addr| { try addrs.append(LookupAddr{ .addr = addr }); } else |name_err| if ((flags & std.c.AI_NUMERICHOST) != 0) { return name_err; } else { try linuxLookupNameFromHosts(addrs, canon, name, family, port); if (addrs.items.len == 0) { try linuxLookupNameFromDnsSearch(addrs, canon, name, family, port); } } } else { try canon.resize(0); try linuxLookupNameFromNull(addrs, family, flags, port); } if (addrs.items.len == 0) return error.UnknownHostName; // No further processing is needed if there are fewer than 2 // results or if there are only IPv4 results. if (addrs.items.len == 1 or family == os.AF_INET) return; const all_ip4 = for (addrs.span()) |addr| { if (addr.addr.any.family != os.AF_INET) break false; } else true; if (all_ip4) return; // The following implements a subset of RFC 3484/6724 destination // address selection by generating a single 31-bit sort key for // each address. Rules 3, 4, and 7 are omitted for having // excessive runtime and code size cost and dubious benefit. // So far the label/precedence table cannot be customized. // This implementation is ported from musl libc. // A more idiomatic "ziggy" implementation would be welcome. for (addrs.span()) |*addr, i| { var key: i32 = 0; var sa6: os.sockaddr_in6 = undefined; @memset(@ptrCast([*]u8, &sa6), 0, @sizeOf(os.sockaddr_in6)); var da6 = os.sockaddr_in6{ .family = os.AF_INET6, .scope_id = addr.addr.in6.scope_id, .port = 65535, .flowinfo = 0, .addr = [1]u8{0} ** 16, }; var sa4: os.sockaddr_in = undefined; @memset(@ptrCast([*]u8, &sa4), 0, @sizeOf(os.sockaddr_in)); var da4 = os.sockaddr_in{ .family = os.AF_INET, .port = 65535, .addr = 0, .zero = [1]u8{0} ** 8, }; var sa: *align(4) os.sockaddr = undefined; var da: *align(4) os.sockaddr = undefined; var salen: os.socklen_t = undefined; var dalen: os.socklen_t = undefined; if (addr.addr.any.family == os.AF_INET6) { mem.copy(u8, &da6.addr, &addr.addr.in6.addr); da = @ptrCast(*os.sockaddr, &da6); dalen = @sizeOf(os.sockaddr_in6); sa = @ptrCast(*os.sockaddr, &sa6); salen = @sizeOf(os.sockaddr_in6); } else { mem.copy(u8, &sa6.addr, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff"); mem.copy(u8, &da6.addr, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff"); mem.writeIntNative(u32, da6.addr[12..], addr.addr.in.addr); da4.addr = addr.addr.in.addr; da = @ptrCast(*os.sockaddr, &da4); dalen = @sizeOf(os.sockaddr_in); sa = @ptrCast(*os.sockaddr, &sa4); salen = @sizeOf(os.sockaddr_in); } const dpolicy = policyOf(da6.addr); const dscope: i32 = scopeOf(da6.addr); const dlabel = dpolicy.label; const dprec: i32 = dpolicy.prec; const MAXADDRS = 3; var prefixlen: i32 = 0; const sock_flags = os.SOCK_DGRAM | os.SOCK_CLOEXEC; if (os.socket(addr.addr.any.family, sock_flags, os.IPPROTO_UDP)) |fd| syscalls: { defer os.close(fd); os.connect(fd, da, dalen) catch break :syscalls; key |= DAS_USABLE; os.getsockname(fd, sa, &salen) catch break :syscalls; if (addr.addr.any.family == os.AF_INET) { // TODO sa6.addr[12..16] should return *[4]u8, making this cast unnecessary. mem.writeIntNative(u32, @ptrCast(*[4]u8, &sa6.addr[12]), sa4.addr); } if (dscope == @as(i32, scopeOf(sa6.addr))) key |= DAS_MATCHINGSCOPE; if (dlabel == labelOf(sa6.addr)) key |= DAS_MATCHINGLABEL; prefixlen = prefixMatch(sa6.addr, da6.addr); } else |_| {} key |= dprec << DAS_PREC_SHIFT; key |= (15 - dscope) << DAS_SCOPE_SHIFT; key |= prefixlen << DAS_PREFIX_SHIFT; key |= (MAXADDRS - @intCast(i32, i)) << DAS_ORDER_SHIFT; addr.sortkey = key; } std.sort.sort(LookupAddr, addrs.span(), addrCmpLessThan); } const Policy = struct { addr: [16]u8, len: u8, mask: u8, prec: u8, label: u8, }; const defined_policies = [_]Policy{ Policy{ .addr = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01".*, .len = 15, .mask = 0xff, .prec = 50, .label = 0, }, Policy{ .addr = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x00\x00".*, .len = 11, .mask = 0xff, .prec = 35, .label = 4, }, Policy{ .addr = "\x20\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00".*, .len = 1, .mask = 0xff, .prec = 30, .label = 2, }, Policy{ .addr = "\x20\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00".*, .len = 3, .mask = 0xff, .prec = 5, .label = 5, }, Policy{ .addr = "\xfc\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00".*, .len = 0, .mask = 0xfe, .prec = 3, .label = 13, }, // These are deprecated and/or returned to the address // pool, so despite the RFC, treating them as special // is probably wrong. // { "", 11, 0xff, 1, 3 }, // { "\xfe\xc0", 1, 0xc0, 1, 11 }, // { "\x3f\xfe", 1, 0xff, 1, 12 }, // Last rule must match all addresses to stop loop. Policy{ .addr = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00".*, .len = 0, .mask = 0, .prec = 40, .label = 1, }, }; fn policyOf(a: [16]u8) *const Policy { for (defined_policies) |*policy| { if (!mem.eql(u8, a[0..policy.len], policy.addr[0..policy.len])) continue; if ((a[policy.len] & policy.mask) != policy.addr[policy.len]) continue; return policy; } unreachable; } fn scopeOf(a: [16]u8) u8 { if (IN6_IS_ADDR_MULTICAST(a)) return a[1] & 15; if (IN6_IS_ADDR_LINKLOCAL(a)) return 2; if (IN6_IS_ADDR_LOOPBACK(a)) return 2; if (IN6_IS_ADDR_SITELOCAL(a)) return 5; return 14; } fn prefixMatch(s: [16]u8, d: [16]u8) u8 { // TODO: This FIXME inherited from porting from musl libc. // I don't want this to go into zig std lib 1.0.0. // FIXME: The common prefix length should be limited to no greater // than the nominal length of the prefix portion of the source // address. However the definition of the source prefix length is // not clear and thus this limiting is not yet implemented. var i: u8 = 0; while (i < 128 and ((s[i / 8] ^ d[i / 8]) & (@as(u8, 128) >> @intCast(u3, i % 8))) == 0) : (i += 1) {} return i; } fn labelOf(a: [16]u8) u8 { return policyOf(a).label; } fn IN6_IS_ADDR_MULTICAST(a: [16]u8) bool { return a[0] == 0xff; } fn IN6_IS_ADDR_LINKLOCAL(a: [16]u8) bool { return a[0] == 0xfe and (a[1] & 0xc0) == 0x80; } fn IN6_IS_ADDR_LOOPBACK(a: [16]u8) bool { return a[0] == 0 and a[1] == 0 and a[2] == 0 and a[12] == 0 and a[13] == 0 and a[14] == 0 and a[15] == 1; } fn IN6_IS_ADDR_SITELOCAL(a: [16]u8) bool { return a[0] == 0xfe and (a[1] & 0xc0) == 0xc0; } // Parameters `b` and `a` swapped to make this descending. fn addrCmpLessThan(b: LookupAddr, a: LookupAddr) bool { return a.sortkey < b.sortkey; } fn linuxLookupNameFromNull( addrs: *std.ArrayList(LookupAddr), family: os.sa_family_t, flags: u32, port: u16, ) !void { if ((flags & std.c.AI_PASSIVE) != 0) { if (family != os.AF_INET6) { (try addrs.addOne()).* = LookupAddr{ .addr = Address.initIp4([1]u8{0} ** 4, port), }; } if (family != os.AF_INET) { (try addrs.addOne()).* = LookupAddr{ .addr = Address.initIp6([1]u8{0} ** 16, port, 0, 0), }; } } else { if (family != os.AF_INET6) { (try addrs.addOne()).* = LookupAddr{ .addr = Address.initIp4([4]u8{ 127, 0, 0, 1 }, port), }; } if (family != os.AF_INET) { (try addrs.addOne()).* = LookupAddr{ .addr = Address.initIp6(([1]u8{0} ** 15) ++ [1]u8{1}, port, 0, 0), }; } } } fn linuxLookupNameFromHosts( addrs: *std.ArrayList(LookupAddr), canon: *std.ArrayListSentineled(u8, 0), name: []const u8, family: os.sa_family_t, port: u16, ) !void { const file = fs.openFileAbsoluteZ("/etc/hosts", .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.AccessDenied, => return, else => |e| return e, }; defer file.close(); const stream = std.io.bufferedInStream(file.inStream()).inStream(); var line_buf: [512]u8 = undefined; while (stream.readUntilDelimiterOrEof(&line_buf, '\n') catch |err| switch (err) { error.StreamTooLong => blk: { // Skip to the delimiter in the stream, to fix parsing try stream.skipUntilDelimiterOrEof('\n'); // Use the truncated line. A truncated comment or hostname will be handled correctly. break :blk &line_buf; }, else => |e| return e, }) |line| { const no_comment_line = mem.split(line, "#").next().?; var line_it = mem.tokenize(no_comment_line, " \t"); const ip_text = line_it.next() orelse continue; var first_name_text: ?[]const u8 = null; while (line_it.next()) |name_text| { if (first_name_text == null) first_name_text = name_text; if (mem.eql(u8, name_text, name)) { break; } } else continue; const addr = Address.parseExpectingFamily(ip_text, family, port) catch |err| switch (err) { error.Overflow, error.InvalidEnd, error.InvalidCharacter, error.Incomplete, error.InvalidIPAddressFormat, error.InvalidIpv4Mapping, => continue, }; try addrs.append(LookupAddr{ .addr = addr }); // first name is canonical name const name_text = first_name_text.?; if (isValidHostName(name_text)) { try canon.replaceContents(name_text); } } } pub fn isValidHostName(hostname: []const u8) bool { if (hostname.len >= 254) return false; if (!std.unicode.utf8ValidateSlice(hostname)) return false; for (hostname) |byte| { if (byte >= 0x80 or byte == '.' or byte == '-' or std.ascii.isAlNum(byte)) { continue; } return false; } return true; } fn linuxLookupNameFromDnsSearch( addrs: *std.ArrayList(LookupAddr), canon: *std.ArrayListSentineled(u8, 0), name: []const u8, family: os.sa_family_t, port: u16, ) !void { var rc: ResolvConf = undefined; try getResolvConf(addrs.allocator, &rc); defer rc.deinit(); // Count dots, suppress search when >=ndots or name ends in // a dot, which is an explicit request for global scope. var dots: usize = 0; for (name) |byte| { if (byte == '.') dots += 1; } const search = if (rc.search.isNull() or dots >= rc.ndots or mem.endsWith(u8, name, ".")) &[_]u8{} else rc.search.span(); var canon_name = name; // Strip final dot for canon, fail if multiple trailing dots. if (mem.endsWith(u8, canon_name, ".")) canon_name.len -= 1; if (mem.endsWith(u8, canon_name, ".")) return error.UnknownHostName; // Name with search domain appended is setup in canon[]. This both // provides the desired default canonical name (if the requested // name is not a CNAME record) and serves as a buffer for passing // the full requested name to name_from_dns. try canon.resize(canon_name.len); mem.copy(u8, canon.span(), canon_name); try canon.append('.'); var tok_it = mem.tokenize(search, " \t"); while (tok_it.next()) |tok| { canon.shrink(canon_name.len + 1); try canon.appendSlice(tok); try linuxLookupNameFromDns(addrs, canon, canon.span(), family, rc, port); if (addrs.items.len != 0) return; } canon.shrink(canon_name.len); return linuxLookupNameFromDns(addrs, canon, name, family, rc, port); } const dpc_ctx = struct { addrs: *std.ArrayList(LookupAddr), canon: *std.ArrayListSentineled(u8, 0), port: u16, }; fn linuxLookupNameFromDns( addrs: *std.ArrayList(LookupAddr), canon: *std.ArrayListSentineled(u8, 0), name: []const u8, family: os.sa_family_t, rc: ResolvConf, port: u16, ) !void { var ctx = dpc_ctx{ .addrs = addrs, .canon = canon, .port = port, }; const AfRr = struct { af: os.sa_family_t, rr: u8, }; const afrrs = [_]AfRr{ AfRr{ .af = os.AF_INET6, .rr = os.RR_A }, AfRr{ .af = os.AF_INET, .rr = os.RR_AAAA }, }; var qbuf: [2][280]u8 = undefined; var abuf: [2][512]u8 = undefined; var qp: [2][]const u8 = undefined; const apbuf = [2][]u8{ &abuf[0], &abuf[1] }; var nq: usize = 0; for (afrrs) |afrr| { if (family != afrr.af) { const len = os.res_mkquery(0, name, 1, afrr.rr, &[_]u8{}, null, &qbuf[nq]); qp[nq] = qbuf[nq][0..len]; nq += 1; } } var ap = [2][]u8{ apbuf[0], apbuf[1] }; ap[0].len = 0; ap[1].len = 0; try resMSendRc(qp[0..nq], ap[0..nq], apbuf[0..nq], rc); var i: usize = 0; while (i < nq) : (i += 1) { dnsParse(ap[i], ctx, dnsParseCallback) catch {}; } if (addrs.items.len != 0) return; if (ap[0].len < 4 or (ap[0][3] & 15) == 2) return error.TemporaryNameServerFailure; if ((ap[0][3] & 15) == 0) return error.UnknownHostName; if ((ap[0][3] & 15) == 3) return; return error.NameServerFailure; } const ResolvConf = struct { attempts: u32, ndots: u32, timeout: u32, search: std.ArrayListSentineled(u8, 0), ns: std.ArrayList(LookupAddr), fn deinit(rc: *ResolvConf) void { rc.ns.deinit(); rc.search.deinit(); rc.* = undefined; } }; /// Ignores lines longer than 512 bytes. /// TODO: https://github.com/ziglang/zig/issues/2765 and https://github.com/ziglang/zig/issues/2761 fn getResolvConf(allocator: *mem.Allocator, rc: *ResolvConf) !void { rc.* = ResolvConf{ .ns = std.ArrayList(LookupAddr).init(allocator), .search = std.ArrayListSentineled(u8, 0).initNull(allocator), .ndots = 1, .timeout = 5, .attempts = 2, }; errdefer rc.deinit(); const file = fs.openFileAbsoluteZ("/etc/resolv.conf", .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.AccessDenied, => return linuxLookupNameFromNumericUnspec(&rc.ns, "127.0.0.1", 53), else => |e| return e, }; defer file.close(); const stream = std.io.bufferedInStream(file.inStream()).inStream(); var line_buf: [512]u8 = undefined; while (stream.readUntilDelimiterOrEof(&line_buf, '\n') catch |err| switch (err) { error.StreamTooLong => blk: { // Skip to the delimiter in the stream, to fix parsing try stream.skipUntilDelimiterOrEof('\n'); // Give an empty line to the while loop, which will be skipped. break :blk line_buf[0..0]; }, else => |e| return e, }) |line| { const no_comment_line = mem.split(line, "#").next().?; var line_it = mem.tokenize(no_comment_line, " \t"); const token = line_it.next() orelse continue; if (mem.eql(u8, token, "options")) { while (line_it.next()) |sub_tok| { var colon_it = mem.split(sub_tok, ":"); const name = colon_it.next().?; const value_txt = colon_it.next() orelse continue; const value = std.fmt.parseInt(u8, value_txt, 10) catch |err| switch (err) { error.Overflow => 255, error.InvalidCharacter => continue, }; if (mem.eql(u8, name, "ndots")) { rc.ndots = std.math.min(value, 15); } else if (mem.eql(u8, name, "attempts")) { rc.attempts = std.math.min(value, 10); } else if (mem.eql(u8, name, "timeout")) { rc.timeout = std.math.min(value, 60); } } } else if (mem.eql(u8, token, "nameserver")) { const ip_txt = line_it.next() orelse continue; try linuxLookupNameFromNumericUnspec(&rc.ns, ip_txt, 53); } else if (mem.eql(u8, token, "domain") or mem.eql(u8, token, "search")) { try rc.search.replaceContents(line_it.rest()); } } if (rc.ns.items.len == 0) { return linuxLookupNameFromNumericUnspec(&rc.ns, "127.0.0.1", 53); } } fn linuxLookupNameFromNumericUnspec( addrs: *std.ArrayList(LookupAddr), name: []const u8, port: u16, ) !void { const addr = try Address.parseIp(name, port); (try addrs.addOne()).* = LookupAddr{ .addr = addr }; } fn resMSendRc( queries: []const []const u8, answers: [][]u8, answer_bufs: []const []u8, rc: ResolvConf, ) !void { const timeout = 1000 * rc.timeout; const attempts = rc.attempts; var sl: os.socklen_t = @sizeOf(os.sockaddr_in); var family: os.sa_family_t = os.AF_INET; var ns_list = std.ArrayList(Address).init(rc.ns.allocator); defer ns_list.deinit(); try ns_list.resize(rc.ns.items.len); const ns = ns_list.span(); for (rc.ns.span()) |iplit, i| { ns[i] = iplit.addr; assert(ns[i].getPort() == 53); if (iplit.addr.any.family != os.AF_INET) { sl = @sizeOf(os.sockaddr_in6); family = os.AF_INET6; } } // Get local address and open/bind a socket var sa: Address = undefined; @memset(@ptrCast([*]u8, &sa), 0, @sizeOf(Address)); sa.any.family = family; const flags = os.SOCK_DGRAM | os.SOCK_CLOEXEC | os.SOCK_NONBLOCK; const fd = os.socket(family, flags, 0) catch |err| switch (err) { error.AddressFamilyNotSupported => blk: { // Handle case where system lacks IPv6 support if (family == os.AF_INET6) { family = os.AF_INET; break :blk try os.socket(os.AF_INET, flags, 0); } return err; }, else => |e| return e, }; defer os.close(fd); try os.bind(fd, &sa.any, sl); // Past this point, there are no errors. Each individual query will // yield either no reply (indicated by zero length) or an answer // packet which is up to the caller to interpret. // Convert any IPv4 addresses in a mixed environment to v4-mapped // TODO //if (family == AF_INET6) { // setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &(int){0}, sizeof 0); // for (i=0; i<nns; i++) { // if (ns[i].sin.sin_family != AF_INET) continue; // memcpy(ns[i].sin6.sin6_addr.s6_addr+12, // &ns[i].sin.sin_addr, 4); // memcpy(ns[i].sin6.sin6_addr.s6_addr, // "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12); // ns[i].sin6.sin6_family = AF_INET6; // ns[i].sin6.sin6_flowinfo = 0; // ns[i].sin6.sin6_scope_id = 0; // } //} var pfd = [1]os.pollfd{os.pollfd{ .fd = fd, .events = os.POLLIN, .revents = undefined, }}; const retry_interval = timeout / attempts; var next: u32 = 0; var t2: u64 = std.time.milliTimestamp(); var t0 = t2; var t1 = t2 - retry_interval; var servfail_retry: usize = undefined; outer: while (t2 - t0 < timeout) : (t2 = std.time.milliTimestamp()) { if (t2 - t1 >= retry_interval) { // Query all configured nameservers in parallel var i: usize = 0; while (i < queries.len) : (i += 1) { if (answers[i].len == 0) { var j: usize = 0; while (j < ns.len) : (j += 1) { _ = os.sendto(fd, queries[i], os.MSG_NOSIGNAL, &ns[j].any, sl) catch undefined; } } } t1 = t2; servfail_retry = 2 * queries.len; } // Wait for a response, or until time to retry const clamped_timeout = std.math.min(@as(u31, std.math.maxInt(u31)), t1 + retry_interval - t2); const nevents = os.poll(&pfd, clamped_timeout) catch 0; if (nevents == 0) continue; while (true) { var sl_copy = sl; const rlen = os.recvfrom(fd, answer_bufs[next], 0, &sa.any, &sl_copy) catch break; // Ignore non-identifiable packets if (rlen < 4) continue; // Ignore replies from addresses we didn't send to var j: usize = 0; while (j < ns.len and !ns[j].eql(sa)) : (j += 1) {} if (j == ns.len) continue; // Find which query this answer goes with, if any var i: usize = next; while (i < queries.len and (answer_bufs[next][0] != queries[i][0] or answer_bufs[next][1] != queries[i][1])) : (i += 1) {} if (i == queries.len) continue; if (answers[i].len != 0) continue; // Only accept positive or negative responses; // retry immediately on server failure, and ignore // all other codes such as refusal. switch (answer_bufs[next][3] & 15) { 0, 3 => {}, 2 => if (servfail_retry != 0) { servfail_retry -= 1; _ = os.sendto(fd, queries[i], os.MSG_NOSIGNAL, &ns[j].any, sl) catch undefined; }, else => continue, } // Store answer in the right slot, or update next // available temp slot if it's already in place. answers[i].len = rlen; if (i == next) { while (next < queries.len and answers[next].len != 0) : (next += 1) {} } else { mem.copy(u8, answer_bufs[i], answer_bufs[next][0..rlen]); } if (next == queries.len) break :outer; } } } fn dnsParse( r: []const u8, ctx: var, comptime callback: var, ) !void { // This implementation is ported from musl libc. // A more idiomatic "ziggy" implementation would be welcome. if (r.len < 12) return error.InvalidDnsPacket; if ((r[3] & 15) != 0) return; var p = r.ptr + 12; var qdcount = r[4] * @as(usize, 256) + r[5]; var ancount = r[6] * @as(usize, 256) + r[7]; if (qdcount + ancount > 64) return error.InvalidDnsPacket; while (qdcount != 0) { qdcount -= 1; while (@ptrToInt(p) - @ptrToInt(r.ptr) < r.len and p[0] -% 1 < 127) p += 1; if (p[0] > 193 or (p[0] == 193 and p[1] > 254) or @ptrToInt(p) > @ptrToInt(r.ptr) + r.len - 6) return error.InvalidDnsPacket; p += @as(usize, 5) + @boolToInt(p[0] != 0); } while (ancount != 0) { ancount -= 1; while (@ptrToInt(p) - @ptrToInt(r.ptr) < r.len and p[0] -% 1 < 127) p += 1; if (p[0] > 193 or (p[0] == 193 and p[1] > 254) or @ptrToInt(p) > @ptrToInt(r.ptr) + r.len - 6) return error.InvalidDnsPacket; p += @as(usize, 1) + @boolToInt(p[0] != 0); const len = p[8] * @as(usize, 256) + p[9]; if (@ptrToInt(p) + len > @ptrToInt(r.ptr) + r.len) return error.InvalidDnsPacket; try callback(ctx, p[1], p[10 .. 10 + len], r); p += 10 + len; } } fn dnsParseCallback(ctx: dpc_ctx, rr: u8, data: []const u8, packet: []const u8) !void { switch (rr) { os.RR_A => { if (data.len != 4) return error.InvalidDnsARecord; const new_addr = try ctx.addrs.addOne(); new_addr.* = LookupAddr{ // TODO slice [0..4] to make this *[4]u8 without @ptrCast .addr = Address.initIp4(@ptrCast(*const [4]u8, data.ptr).*, ctx.port), }; }, os.RR_AAAA => { if (data.len != 16) return error.InvalidDnsAAAARecord; const new_addr = try ctx.addrs.addOne(); new_addr.* = LookupAddr{ // TODO slice [0..16] to make this *[16]u8 without @ptrCast .addr = Address.initIp6(@ptrCast(*const [16]u8, data.ptr).*, ctx.port, 0, 0), }; }, os.RR_CNAME => { var tmp: [256]u8 = undefined; // Returns len of compressed name. strlen to get canon name. _ = try os.dn_expand(packet, data, &tmp); const canon_name = mem.spanZ(@ptrCast([*:0]const u8, &tmp)); if (isValidHostName(canon_name)) { try ctx.canon.replaceContents(canon_name); } }, else => return, } } pub const StreamServer = struct { /// Copied from `Options` on `init`. kernel_backlog: u32, reuse_address: bool, /// `undefined` until `listen` returns successfully. listen_address: Address, sockfd: ?os.fd_t, pub const Options = struct { /// How many connections the kernel will accept on the application's behalf. /// If more than this many connections pool in the kernel, clients will start /// seeing "Connection refused". kernel_backlog: u32 = 128, /// Enable SO_REUSEADDR on the socket. reuse_address: bool = false, }; /// After this call succeeds, resources have been acquired and must /// be released with `deinit`. pub fn init(options: Options) StreamServer { return StreamServer{ .sockfd = null, .kernel_backlog = options.kernel_backlog, .reuse_address = options.reuse_address, .listen_address = undefined, }; } /// Release all resources. The `StreamServer` memory becomes `undefined`. pub fn deinit(self: *StreamServer) void { self.close(); self.* = undefined; } pub fn listen(self: *StreamServer, address: Address) !void { const nonblock = if (std.io.is_async) os.SOCK_NONBLOCK else 0; const sock_flags = os.SOCK_STREAM | os.SOCK_CLOEXEC | nonblock; const proto = if (address.any.family == os.AF_UNIX) @as(u32, 0) else os.IPPROTO_TCP; const sockfd = try os.socket(address.any.family, sock_flags, proto); self.sockfd = sockfd; errdefer { os.close(sockfd); self.sockfd = null; } if (self.reuse_address) { try os.setsockopt( self.sockfd.?, os.SOL_SOCKET, os.SO_REUSEADDR, &mem.toBytes(@as(c_int, 1)), ); } var socklen = address.getOsSockLen(); try os.bind(sockfd, &address.any, socklen); try os.listen(sockfd, self.kernel_backlog); try os.getsockname(sockfd, &self.listen_address.any, &socklen); } /// Stop listening. It is still necessary to call `deinit` after stopping listening. /// Calling `deinit` will automatically call `close`. It is safe to call `close` when /// not listening. pub fn close(self: *StreamServer) void { if (self.sockfd) |fd| { os.close(fd); self.sockfd = null; self.listen_address = undefined; } } pub const AcceptError = error{ ConnectionAborted, /// The per-process limit on the number of open file descriptors has been reached. ProcessFdQuotaExceeded, /// The system-wide limit on the total number of open files has been reached. SystemFdQuotaExceeded, /// Not enough free memory. This often means that the memory allocation is limited /// by the socket buffer limits, not by the system memory. SystemResources, ProtocolFailure, /// Firewall rules forbid connection. BlockedByFirewall, /// Permission to create a socket of the specified type and/or /// protocol is denied. PermissionDenied, } || os.UnexpectedError; pub const Connection = struct { file: fs.File, address: Address, }; /// If this function succeeds, the returned `Connection` is a caller-managed resource. pub fn accept(self: *StreamServer) AcceptError!Connection { const nonblock = if (std.io.is_async) os.SOCK_NONBLOCK else 0; const accept_flags = nonblock | os.SOCK_CLOEXEC; var accepted_addr: Address = undefined; var adr_len: os.socklen_t = @sizeOf(Address); if (os.accept(self.sockfd.?, &accepted_addr.any, &adr_len, accept_flags)) |fd| { return Connection{ .file = fs.File{ .handle = fd }, .address = accepted_addr, }; } else |err| switch (err) { // We only give SOCK_NONBLOCK when I/O mode is async, in which case this error // is handled by os.accept4. error.WouldBlock => unreachable, else => |e| return e, } } };
lib/std/net.zig
const std = @import("std"); const builtin = @import("builtin"); const Arch = builtin.Arch; const Abi = builtin.Abi; const Os = builtin.Os; const assert = std.debug.assert; const LibCTarget = struct { name: []const u8, arch: MultiArch, abi: MultiAbi, }; const MultiArch = union(enum) { aarch64, arm, mips, mips64, powerpc64, specific: @TagType(Arch), fn eql(a: MultiArch, b: MultiArch) bool { if (@enumToInt(a) != @enumToInt(b)) return false; if (@TagType(MultiArch)(a) != .specific) return true; return a.specific == b.specific; } }; const MultiAbi = union(enum) { musl, specific: Abi, fn eql(a: MultiAbi, b: MultiAbi) bool { if (@enumToInt(a) != @enumToInt(b)) return false; if (@TagType(MultiAbi)(a) != .specific) return true; return a.specific == b.specific; } }; const glibc_targets = [_]LibCTarget{ LibCTarget{ .name = "aarch64_be-linux-gnu", .arch = MultiArch{ .specific = Arch.aarch64_be }, .abi = MultiAbi{ .specific = Abi.gnu }, }, LibCTarget{ .name = "aarch64-linux-gnu", .arch = MultiArch{ .specific = Arch.aarch64 }, .abi = MultiAbi{ .specific = Abi.gnu }, }, LibCTarget{ .name = "armeb-linux-gnueabi", .arch = MultiArch{ .specific = Arch.armeb }, .abi = MultiAbi{ .specific = Abi.gnueabi }, }, LibCTarget{ .name = "armeb-linux-gnueabihf", .arch = MultiArch{ .specific = Arch.armeb }, .abi = MultiAbi{ .specific = Abi.gnueabihf }, }, LibCTarget{ .name = "arm-linux-gnueabi", .arch = MultiArch{ .specific = Arch.arm }, .abi = MultiAbi{ .specific = Abi.gnueabi }, }, LibCTarget{ .name = "arm-linux-gnueabihf", .arch = MultiArch{ .specific = Arch.arm }, .abi = MultiAbi{ .specific = Abi.gnueabihf }, }, LibCTarget{ .name = "i686-linux-gnu", .arch = MultiArch{ .specific = Arch.i386 }, .abi = MultiAbi{ .specific = Abi.gnu }, }, LibCTarget{ .name = "mips64el-linux-gnu-n32", .arch = MultiArch{ .specific = Arch.mips64el }, .abi = MultiAbi{ .specific = Abi.gnuabin32 }, }, LibCTarget{ .name = "mips64el-linux-gnu-n64", .arch = MultiArch{ .specific = Arch.mips64el }, .abi = MultiAbi{ .specific = Abi.gnuabi64 }, }, LibCTarget{ .name = "mips64-linux-gnu-n32", .arch = MultiArch{ .specific = Arch.mips64 }, .abi = MultiAbi{ .specific = Abi.gnuabin32 }, }, LibCTarget{ .name = "mips64-linux-gnu-n64", .arch = MultiArch{ .specific = Arch.mips64 }, .abi = MultiAbi{ .specific = Abi.gnuabi64 }, }, LibCTarget{ .name = "mipsel-linux-gnu", .arch = MultiArch{ .specific = Arch.mipsel }, .abi = MultiAbi{ .specific = Abi.gnu }, }, LibCTarget{ .name = "mips-linux-gnu", .arch = MultiArch{ .specific = Arch.mips }, .abi = MultiAbi{ .specific = Abi.gnu }, }, LibCTarget{ .name = "powerpc64le-linux-gnu", .arch = MultiArch{ .specific = Arch.powerpc64le }, .abi = MultiAbi{ .specific = Abi.gnu }, }, LibCTarget{ .name = "powerpc64-linux-gnu", .arch = MultiArch{ .specific = Arch.powerpc64 }, .abi = MultiAbi{ .specific = Abi.gnu }, }, LibCTarget{ .name = "powerpc-linux-gnu", .arch = MultiArch{ .specific = Arch.powerpc }, .abi = MultiAbi{ .specific = Abi.gnu }, }, LibCTarget{ .name = "riscv64-linux-gnu-rv64imac-lp64", .arch = MultiArch{ .specific = Arch.riscv64 }, .abi = MultiAbi{ .specific = Abi.gnu }, }, LibCTarget{ .name = "s390x-linux-gnu", .arch = MultiArch{ .specific = Arch.s390x }, .abi = MultiAbi{ .specific = Abi.gnu }, }, LibCTarget{ .name = "sparc64-linux-gnu", .arch = MultiArch{ .specific = Arch.sparc }, .abi = MultiAbi{ .specific = Abi.gnu }, }, LibCTarget{ .name = "sparcv9-linux-gnu", .arch = MultiArch{ .specific = Arch.sparcv9 }, .abi = MultiAbi{ .specific = Abi.gnu }, }, LibCTarget{ .name = "x86_64-linux-gnu", .arch = MultiArch{ .specific = Arch.x86_64 }, .abi = MultiAbi{ .specific = Abi.gnu }, }, LibCTarget{ .name = "x86_64-linux-gnu-x32", .arch = MultiArch{ .specific = Arch.x86_64 }, .abi = MultiAbi{ .specific = Abi.gnux32 }, }, }; const musl_targets = [_]LibCTarget{ LibCTarget{ .name = "aarch64", .arch = MultiArch.aarch64, .abi = MultiAbi.musl, }, LibCTarget{ .name = "arm", .arch = MultiArch.arm, .abi = MultiAbi.musl, }, LibCTarget{ .name = "i386", .arch = MultiArch{ .specific = .i386 }, .abi = MultiAbi.musl, }, LibCTarget{ .name = "mips", .arch = MultiArch.mips, .abi = MultiAbi.musl, }, LibCTarget{ .name = "mips64", .arch = MultiArch.mips64, .abi = MultiAbi.musl, }, LibCTarget{ .name = "powerpc", .arch = MultiArch{ .specific = .powerpc }, .abi = MultiAbi.musl, }, LibCTarget{ .name = "powerpc64", .arch = MultiArch.powerpc64, .abi = MultiAbi.musl, }, LibCTarget{ .name = "riscv64", .arch = MultiArch{ .specific = .riscv64 }, .abi = MultiAbi.musl, }, LibCTarget{ .name = "s390x", .arch = MultiArch{ .specific = .s390x }, .abi = MultiAbi.musl, }, LibCTarget{ .name = "x86_64", .arch = MultiArch{ .specific = .x86_64 }, .abi = MultiAbi.musl, }, }; const DestTarget = struct { arch: MultiArch, os: Os, abi: Abi, fn hash(a: DestTarget) u32 { return @enumToInt(a.arch) +% (@enumToInt(a.os) *% @as(u32, 4202347608)) +% (@enumToInt(a.abi) *% @as(u32, 4082223418)); } fn eql(a: DestTarget, b: DestTarget) bool { return a.arch.eql(b.arch) and a.os == b.os and a.abi == b.abi; } }; const Contents = struct { bytes: []const u8, hit_count: usize, hash: []const u8, is_generic: bool, fn hitCountLessThan(lhs: *const Contents, rhs: *const Contents) bool { return lhs.hit_count < rhs.hit_count; } }; const HashToContents = std.StringHashMap(Contents); const TargetToHash = std.HashMap(DestTarget, []const u8, DestTarget.hash, DestTarget.eql); const PathTable = std.StringHashMap(*TargetToHash); const LibCVendor = enum { musl, glibc, }; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; const args = try std.process.argsAlloc(allocator); var search_paths = std.ArrayList([]const u8).init(allocator); var opt_out_dir: ?[]const u8 = null; var opt_abi: ?[]const u8 = null; var arg_i: usize = 1; while (arg_i < args.len) : (arg_i += 1) { if (std.mem.eql(u8, args[arg_i], "--help")) usageAndExit(args[0]); if (arg_i + 1 >= args.len) { std.debug.warn("expected argument after '{}'\n", args[arg_i]); usageAndExit(args[0]); } if (std.mem.eql(u8, args[arg_i], "--search-path")) { try search_paths.append(args[arg_i + 1]); } else if (std.mem.eql(u8, args[arg_i], "--out")) { assert(opt_out_dir == null); opt_out_dir = args[arg_i + 1]; } else if (std.mem.eql(u8, args[arg_i], "--abi")) { assert(opt_abi == null); opt_abi = args[arg_i + 1]; } else { std.debug.warn("unrecognized argument: {}\n", args[arg_i]); usageAndExit(args[0]); } arg_i += 1; } const out_dir = opt_out_dir orelse usageAndExit(args[0]); const abi_name = opt_abi orelse usageAndExit(args[0]); const vendor = if (std.mem.eql(u8, abi_name, "musl")) LibCVendor.musl else if (std.mem.eql(u8, abi_name, "glibc")) LibCVendor.glibc else { std.debug.warn("unrecognized C ABI: {}\n", abi_name); usageAndExit(args[0]); }; const generic_name = try std.fmt.allocPrint(allocator, "generic-{}", abi_name); // TODO compiler crashed when I wrote this the canonical way var libc_targets: []const LibCTarget = undefined; switch (vendor) { .musl => libc_targets = musl_targets, .glibc => libc_targets = glibc_targets, } var path_table = PathTable.init(allocator); var hash_to_contents = HashToContents.init(allocator); var max_bytes_saved: usize = 0; var total_bytes: usize = 0; var hasher = std.crypto.Sha256.init(); for (libc_targets) |libc_target| { const dest_target = DestTarget{ .arch = libc_target.arch, .abi = switch (vendor) { .musl => .musl, .glibc => libc_target.abi.specific, }, .os = .linux, }; search: for (search_paths.toSliceConst()) |search_path| { var sub_path: []const []const u8 = undefined; switch (vendor) { .musl => { sub_path = &[_][]const u8{ search_path, libc_target.name, "usr", "local", "musl", "include" }; }, .glibc => { sub_path = &[_][]const u8{ search_path, libc_target.name, "usr", "include" }; }, } const target_include_dir = try std.fs.path.join(allocator, sub_path); var dir_stack = std.ArrayList([]const u8).init(allocator); try dir_stack.append(target_include_dir); while (dir_stack.popOrNull()) |full_dir_name| { var dir = std.fs.Dir.cwd().openDirList(full_dir_name) catch |err| switch (err) { error.FileNotFound => continue :search, error.AccessDenied => continue :search, else => return err, }; defer dir.close(); while (try dir.next()) |entry| { const full_path = try std.fs.path.join(allocator, [_][]const u8{ full_dir_name, entry.name }); switch (entry.kind) { .Directory => try dir_stack.append(full_path), .File => { const rel_path = try std.fs.path.relative(allocator, target_include_dir, full_path); const raw_bytes = try std.io.readFileAlloc(allocator, full_path); const trimmed = std.mem.trim(u8, raw_bytes, " \r\n\t"); total_bytes += raw_bytes.len; const hash = try allocator.alloc(u8, 32); hasher.reset(); hasher.update(rel_path); hasher.update(trimmed); hasher.final(hash); const gop = try hash_to_contents.getOrPut(hash); if (gop.found_existing) { max_bytes_saved += raw_bytes.len; gop.kv.value.hit_count += 1; std.debug.warn( "duplicate: {} {} ({Bi:2})\n", libc_target.name, rel_path, raw_bytes.len, ); } else { gop.kv.value = Contents{ .bytes = trimmed, .hit_count = 1, .hash = hash, .is_generic = false, }; } const path_gop = try path_table.getOrPut(rel_path); const target_to_hash = if (path_gop.found_existing) path_gop.kv.value else blk: { const ptr = try allocator.create(TargetToHash); ptr.* = TargetToHash.init(allocator); path_gop.kv.value = ptr; break :blk ptr; }; assert((try target_to_hash.put(dest_target, hash)) == null); }, else => std.debug.warn("warning: weird file: {}\n", full_path), } } } break; } else { std.debug.warn("warning: libc target not found: {}\n", libc_target.name); } } std.debug.warn("summary: {Bi:2} could be reduced to {Bi:2}\n", total_bytes, total_bytes - max_bytes_saved); try std.fs.makePath(allocator, out_dir); var missed_opportunity_bytes: usize = 0; // iterate path_table. for each path, put all the hashes into a list. sort by hit_count. // the hash with the highest hit_count gets to be the "generic" one. everybody else // gets their header in a separate arch directory. var path_it = path_table.iterator(); while (path_it.next()) |path_kv| { var contents_list = std.ArrayList(*Contents).init(allocator); { var hash_it = path_kv.value.iterator(); while (hash_it.next()) |hash_kv| { const contents = &hash_to_contents.get(hash_kv.value).?.value; try contents_list.append(contents); } } std.sort.sort(*Contents, contents_list.toSlice(), Contents.hitCountLessThan); var best_contents = contents_list.popOrNull().?; if (best_contents.hit_count > 1) { // worth it to make it generic const full_path = try std.fs.path.join(allocator, [_][]const u8{ out_dir, generic_name, path_kv.key }); try std.fs.makePath(allocator, std.fs.path.dirname(full_path).?); try std.io.writeFile(full_path, best_contents.bytes); best_contents.is_generic = true; while (contents_list.popOrNull()) |contender| { if (contender.hit_count > 1) { const this_missed_bytes = contender.hit_count * contender.bytes.len; missed_opportunity_bytes += this_missed_bytes; std.debug.warn("Missed opportunity ({Bi:2}): {}\n", this_missed_bytes, path_kv.key); } else break; } } var hash_it = path_kv.value.iterator(); while (hash_it.next()) |hash_kv| { const contents = &hash_to_contents.get(hash_kv.value).?.value; if (contents.is_generic) continue; const dest_target = hash_kv.key; const arch_name = switch (dest_target.arch) { .specific => |a| @tagName(a), else => @tagName(dest_target.arch), }; const out_subpath = try std.fmt.allocPrint( allocator, "{}-{}-{}", arch_name, @tagName(dest_target.os), @tagName(dest_target.abi), ); const full_path = try std.fs.path.join(allocator, [_][]const u8{ out_dir, out_subpath, path_kv.key }); try std.fs.makePath(allocator, std.fs.path.dirname(full_path).?); try std.io.writeFile(full_path, contents.bytes); } } } fn usageAndExit(arg0: []const u8) noreturn { std.debug.warn("Usage: {} [--search-path <dir>] --out <dir> --abi <name>\n", arg0); std.debug.warn("--search-path can be used any number of times.\n"); std.debug.warn(" subdirectories of search paths look like, e.g. x86_64-linux-gnu\n"); std.debug.warn("--out is a dir that will be created, and populated with the results\n"); std.debug.warn("--abi is either musl or glibc\n"); std.process.exit(1); }
tools/process_headers.zig
const std = @import("std"); const builtin = std.builtin; const assert = std.debug.assert; const Allocator = std.mem.Allocator; const ines = @import("ines.zig"); const console_ = @import("console.zig"); const Config = console_.Config; const Console = console_.Console; /// Avoids recursion in GenericMapper fn MapperInitFn(comptime config: Config) type { return MapperInitFnSafe(GenericMapper(config), config); } fn MapperInitFnSafe(comptime T: type, comptime config: Config) type { return fn (*Allocator, *Console(config), *ines.RomInfo) Allocator.Error!?T; } pub fn GenericMapper(comptime config: Config) type { return struct { const Self = @This(); mapper_ptr: OpaquePtr, deinitFn: fn (Self, *Allocator) void, cpuCycledFn: ?(fn (*Self) void), mirrorNametableFn: fn (Self, u16) u12, readPrgFn: fn (Self, u16) ?u8, readChrFn: fn (Self, u16) u8, writePrgFn: fn (*Self, u16, u8) void, writeChrFn: fn (*Self, u16, u8) void, const OpaquePtr = *align(@alignOf(usize)) opaque {}; fn setup(comptime T: type) MapperInitFnSafe(Self, config) { //Self.validateMapper(T); return (struct { pub fn init( allocator: *Allocator, console: *Console(config), info: *ines.RomInfo, ) Allocator.Error!?Self { if (@hasField(T, "dummy_is_not_implemented")) { return null; } const ptr = try allocator.create(T); try T.initMem(ptr, allocator, console, info); return Self{ .mapper_ptr = @ptrCast(OpaquePtr, ptr), .deinitFn = T.deinitMem, .cpuCycledFn = if (@hasDecl(T, "cpuCycled")) T.cpuCycled else null, .mirrorNametableFn = T.mirrorNametable, .readPrgFn = T.readPrg, .readChrFn = T.readChr, .writePrgFn = T.writePrg, .writeChrFn = T.writeChr, }; } }).init; } pub fn deinit(self: Self, allocator: *Allocator) void { self.deinitFn(self, allocator); } }; } pub fn UnimplementedMapper(comptime config: Config, comptime number: u8) type { const G = GenericMapper(config); var buf = [1]u8{undefined} ** 3; buf[2] = '0' + (number % 10); buf[1] = '0' + (number % 100) / 10; buf[0] = '0' + number / 100; const msg = "Mapper " ++ buf ++ " not implemented"; return struct { dummy_is_not_implemented: u64, fn initMem(_: *@This(), _: *Allocator, _: *Console(config), _: *ines.RomInfo) Allocator.Error!void { @panic(msg); } fn deinitMem(_: G, _: *Allocator) void { @panic(msg); } fn mirrorNametable(_: G, _: u16) u12 { @panic(msg); } fn readPrg(_: G, _: u16) ?u8 { @panic(msg); } fn readChr(_: G, _: u16) u8 { @panic(msg); } fn writePrg(_: *G, _: u16, _: u8) void { @panic(msg); } fn writeChr(_: *G, _: u16, _: u8) void { @panic(msg); } }; } pub fn inits(comptime config: Config) [255]MapperInitFn(config) { @setEvalBranchQuota(2000); var types = [_]?type{null} ** 255; types[0] = @import("mapper/nrom.zig").Mapper(config); types[1] = @import("mapper/mmc1.zig").Mapper(config); types[2] = @import("mapper/uxrom.zig").Mapper(config); types[4] = @import("mapper/mmc3.zig").Mapper(config); var result = [_]MapperInitFn(config){undefined} ** 255; for (types) |To, i| { if (To) |T| { result[i] = GenericMapper(config).setup(T); } else { result[i] = GenericMapper(config).setup(UnimplementedMapper(config, i)); } } return result; }
src/mapper.zig
const std = @import("std"); const global_gc = &@import("main.zig").global_gc; const Allocator = std.mem.Allocator; const Collectible = struct { freeFn: fn() void, }; pub const GarbageCollector = struct { child_allocator: Allocator, collectibles: std.ArrayList(Collectible), pub fn init(child_allocator: Allocator) GarbageCollector { return GarbageCollector { .child_allocator = child_allocator, .collectibles = std.ArrayList(Collectible).init(child_allocator) }; } pub fn createCollectible(self: *GarbageCollector, comptime T: type) !*T { const ptr = try self.child_allocator.create(T); return ptr; } pub fn create(self: *GarbageCollector, comptime T: type) !*T { return try self.child_allocator.create(T); } }; /// A reference counter for objects. /// This assumes T has a deinit() function and that the reference counter /// is placed in an `rc` field. pub fn ReferenceCounter(comptime T: type) type { return struct { count: u32 = 1, const Self = @This(); pub fn reference(self: *Self) void { if (std.debug.runtime_safety and self.count == 0) { @panic("Cannot reference an object that has already been dereferenced"); } _ = @atomicRmw(u32, &self.count, .Add, 1, .SeqCst); std.log.info("ref now rc = {}", .{ self.count }); } pub fn dereference(self: *Self) void { if (std.debug.runtime_safety and self.count == 0) { @panic("Cannot dereference an object with no references"); } _ = @atomicRmw(u32, &self.count, .Sub, 1, .SeqCst); std.log.info("deref now rc = {}", .{ self.count }); if (self.count == 0) { // TODO: defer the freeing using GarbageCollector const selfT = @fieldParentPtr(T, "rc", self); selfT.deinit(global_gc.child_allocator); } } /// The object has had its deinit() function explicitely called, /// so disable reference counting pub fn deinit(self: *Self) void { @atomicStore(u32, &self.count, 0, .SeqCst); } }; }
src/gc.zig
const std = @import("../std.zig"); const builtin = @import("builtin"); const maxInt = std.math.maxInt; const iovec = std.os.iovec; const iovec_const = std.os.iovec_const; const timezone = std.c.timezone; extern "c" fn ___errno() *c_int; pub const _errno = ___errno; pub const dl_iterate_phdr_callback = fn (info: *dl_phdr_info, size: usize, data: ?*anyopaque) callconv(.C) c_int; pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*anyopaque) c_int; pub extern "c" fn getdents(fd: c_int, buf_ptr: [*]u8, nbytes: usize) usize; pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int; pub extern "c" fn pipe2(fds: *[2]fd_t, flags: u32) c_int; pub extern "c" fn arc4random_buf(buf: [*]u8, len: usize) void; pub extern "c" fn posix_memalign(memptr: *?*anyopaque, alignment: usize, size: usize) c_int; pub extern "c" fn sysconf(sc: c_int) i64; pub extern "c" fn signalfd(fd: fd_t, mask: *const sigset_t, flags: u32) c_int; pub extern "c" fn madvise(address: [*]u8, len: usize, advise: u32) c_int; pub const pthread_mutex_t = extern struct { flag1: u16 = 0, flag2: u8 = 0, ceiling: u8 = 0, @"type": u16 = 0, magic: u16 = 0x4d58, lock: u64 = 0, data: u64 = 0, }; pub const pthread_cond_t = extern struct { flag: [4]u8 = [_]u8{0} ** 4, @"type": u16 = 0, magic: u16 = 0x4356, data: u64 = 0, }; pub const pthread_rwlock_t = extern struct { readers: i32 = 0, @"type": u16 = 0, magic: u16 = 0x5257, mutex: pthread_mutex_t = .{}, readercv: pthread_cond_t = .{}, writercv: pthread_cond_t = .{}, }; pub const pthread_attr_t = extern struct { mutexattr: ?*anyopaque = null, }; pub const pthread_key_t = c_int; pub const sem_t = extern struct { count: u32 = 0, @"type": u16 = 0, magic: u16 = 0x534d, __pad1: [3]u64 = [_]u64{0} ** 3, __pad2: [2]u64 = [_]u64{0} ** 2, }; pub extern "c" fn pthread_setname_np(thread: std.c.pthread_t, name: [*:0]const u8, arg: ?*anyopaque) E; pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E; pub const blkcnt_t = i64; pub const blksize_t = i32; pub const clock_t = i64; pub const dev_t = i32; pub const fd_t = c_int; pub const gid_t = u32; pub const ino_t = u64; pub const mode_t = u32; pub const nlink_t = u32; pub const off_t = i64; pub const pid_t = i32; pub const socklen_t = u32; pub const time_t = i64; pub const suseconds_t = i64; pub const uid_t = u32; pub const major_t = u32; pub const minor_t = u32; pub const port_t = c_int; pub const nfds_t = usize; pub const id_t = i32; pub const taskid_t = id_t; pub const projid_t = id_t; pub const poolid_t = id_t; pub const zoneid_t = id_t; pub const ctid_t = id_t; pub const dl_phdr_info = extern struct { dlpi_addr: std.elf.Addr, dlpi_name: ?[*:0]const u8, dlpi_phdr: [*]std.elf.Phdr, dlpi_phnum: std.elf.Half, /// Incremented when a new object is mapped into the process. dlpi_adds: u64, /// Incremented when an object is unmapped from the process. dlpi_subs: u64, }; pub const RTLD = struct { pub const LAZY = 0x00001; pub const NOW = 0x00002; pub const NOLOAD = 0x00004; pub const GLOBAL = 0x00100; pub const LOCAL = 0x00000; pub const PARENT = 0x00200; pub const GROUP = 0x00400; pub const WORLD = 0x00800; pub const NODELETE = 0x01000; pub const FIRST = 0x02000; pub const CONFGEN = 0x10000; pub const NEXT = @intToPtr(*anyopaque, @bitCast(usize, @as(isize, -1))); pub const DEFAULT = @intToPtr(*anyopaque, @bitCast(usize, @as(isize, -2))); pub const SELF = @intToPtr(*anyopaque, @bitCast(usize, @as(isize, -3))); pub const PROBE = @intToPtr(*anyopaque, @bitCast(usize, @as(isize, -4))); }; pub const Flock = extern struct { type: c_short, whence: c_short, start: off_t, // len == 0 means until end of file. len: off_t, sysid: c_int, pid: pid_t, __pad: [4]c_long, }; pub const utsname = extern struct { sysname: [256:0]u8, nodename: [256:0]u8, release: [256:0]u8, version: [256:0]u8, machine: [256:0]u8, domainname: [256:0]u8, }; pub const addrinfo = extern struct { flags: i32, family: i32, socktype: i32, protocol: i32, addrlen: socklen_t, canonname: ?[*:0]u8, addr: ?*sockaddr, next: ?*addrinfo, }; pub const EAI = enum(c_int) { /// address family for hostname not supported ADDRFAMILY = 1, /// name could not be resolved at this time AGAIN = 2, /// flags parameter had an invalid value BADFLAGS = 3, /// non-recoverable failure in name resolution FAIL = 4, /// address family not recognized FAMILY = 5, /// memory allocation failure MEMORY = 6, /// no address associated with hostname NODATA = 7, /// name does not resolve NONAME = 8, /// service not recognized for socket type SERVICE = 9, /// intended socket type was not recognized SOCKTYPE = 10, /// system error returned in errno SYSTEM = 11, /// argument buffer overflow OVERFLOW = 12, /// resolved protocol is unknown PROTOCOL = 13, _, }; pub const EAI_MAX = 14; pub const msghdr = extern struct { /// optional address msg_name: ?*sockaddr, /// size of address msg_namelen: socklen_t, /// scatter/gather array msg_iov: [*]iovec, /// # elements in msg_iov msg_iovlen: i32, /// ancillary data msg_control: ?*anyopaque, /// ancillary data buffer len msg_controllen: socklen_t, /// flags on received message msg_flags: i32, }; pub const msghdr_const = extern struct { /// optional address msg_name: ?*const sockaddr, /// size of address msg_namelen: socklen_t, /// scatter/gather array msg_iov: [*]const iovec_const, /// # elements in msg_iov msg_iovlen: i32, /// ancillary data msg_control: ?*const anyopaque, /// ancillary data buffer len msg_controllen: socklen_t, /// flags on received message msg_flags: i32, }; pub const cmsghdr = extern struct { cmsg_len: socklen_t, cmsg_level: i32, cmsg_type: i32, }; /// The stat structure used by libc. pub const Stat = extern struct { dev: dev_t, ino: ino_t, mode: mode_t, nlink: nlink_t, uid: uid_t, gid: gid_t, rdev: dev_t, size: off_t, atim: timespec, mtim: timespec, ctim: timespec, blksize: blksize_t, blocks: blkcnt_t, fstype: [16]u8, pub fn atime(self: @This()) timespec { return self.atim; } pub fn mtime(self: @This()) timespec { return self.mtim; } pub fn ctime(self: @This()) timespec { return self.ctim; } }; pub const timespec = extern struct { tv_sec: i64, tv_nsec: isize, }; pub const timeval = extern struct { /// seconds tv_sec: time_t, /// microseconds tv_usec: suseconds_t, }; pub const MAXNAMLEN = 511; pub const dirent = extern struct { /// Inode number of entry. d_ino: ino_t, /// Offset of this entry on disk. d_off: off_t, /// Length of this record. d_reclen: u16, /// File name. d_name: [MAXNAMLEN:0]u8, pub fn reclen(self: dirent) u16 { return self.d_reclen; } }; pub const SOCK = struct { /// Datagram. pub const DGRAM = 1; /// STREAM. pub const STREAM = 2; /// Raw-protocol interface. pub const RAW = 4; /// Reliably-delivered message. pub const RDM = 5; /// Sequenced packed stream. pub const SEQPACKET = 6; pub const NONBLOCK = 0x100000; pub const NDELAY = 0x200000; pub const CLOEXEC = 0x080000; }; pub const SO = struct { pub const DEBUG = 0x0001; pub const ACCEPTCONN = 0x0002; pub const REUSEADDR = 0x0004; pub const KEEPALIVE = 0x0008; pub const DONTROUTE = 0x0010; pub const BROADCAST = 0x0020; pub const USELOOPBACK = 0x0040; pub const LINGER = 0x0080; pub const OOBINLINE = 0x0100; pub const DGRAM_ERRIND = 0x0200; pub const RECVUCRED = 0x0400; pub const SNDBUF = 0x1001; pub const RCVBUF = 0x1002; pub const SNDLOWAT = 0x1003; pub const RCVLOWAT = 0x1004; pub const SNDTIMEO = 0x1005; pub const RCVTIMEO = 0x1006; pub const ERROR = 0x1007; pub const TYPE = 0x1008; pub const PROTOTYPE = 0x1009; pub const ANON_MLP = 0x100a; pub const MAC_EXEMPT = 0x100b; pub const DOMAIN = 0x100c; pub const RCVPSH = 0x100d; pub const SECATTR = 0x1011; pub const TIMESTAMP = 0x1013; pub const ALLZONES = 0x1014; pub const EXCLBIND = 0x1015; pub const MAC_IMPLICIT = 0x1016; pub const VRRP = 0x1017; }; pub const SOMAXCONN = 128; pub const SCM = struct { pub const UCRED = 0x1012; pub const RIGHTS = 0x1010; pub const TIMESTAMP = SO.TIMESTAMP; }; pub const AF = struct { pub const UNSPEC = 0; pub const UNIX = 1; pub const LOCAL = UNIX; pub const FILE = UNIX; pub const INET = 2; pub const IMPLINK = 3; pub const PUP = 4; pub const CHAOS = 5; pub const NS = 6; pub const NBS = 7; pub const ECMA = 8; pub const DATAKIT = 9; pub const CCITT = 10; pub const SNA = 11; pub const DECnet = 12; pub const DLI = 13; pub const LAT = 14; pub const HYLINK = 15; pub const APPLETALK = 16; pub const NIT = 17; pub const @"802" = 18; pub const OSI = 19; pub const X25 = 20; pub const OSINET = 21; pub const GOSIP = 22; pub const IPX = 23; pub const ROUTE = 24; pub const LINK = 25; pub const INET6 = 26; pub const KEY = 27; pub const NCA = 28; pub const POLICY = 29; pub const INET_OFFLOAD = 30; pub const TRILL = 31; pub const PACKET = 32; pub const LX_NETLINK = 33; pub const MAX = 33; }; pub const SOL = struct { pub const SOCKET = 0xffff; pub const ROUTE = 0xfffe; pub const PACKET = 0xfffd; pub const FILTER = 0xfffc; }; pub const PF = struct { pub const UNSPEC = AF.UNSPEC; pub const UNIX = AF.UNIX; pub const LOCAL = UNIX; pub const FILE = UNIX; pub const INET = AF.INET; pub const IMPLINK = AF.IMPLINK; pub const PUP = AF.PUP; pub const CHAOS = AF.CHAOS; pub const NS = AF.NS; pub const NBS = AF.NBS; pub const ECMA = AF.ECMA; pub const DATAKIT = AF.DATAKIT; pub const CCITT = AF.CCITT; pub const SNA = AF.SNA; pub const DECnet = AF.DECnet; pub const DLI = AF.DLI; pub const LAT = AF.LAT; pub const HYLINK = AF.HYLINK; pub const APPLETALK = AF.APPLETALK; pub const NIT = AF.NIT; pub const @"802" = AF.@"802"; pub const OSI = AF.OSI; pub const X25 = AF.X25; pub const OSINET = AF.OSINET; pub const GOSIP = AF.GOSIP; pub const IPX = AF.IPX; pub const ROUTE = AF.ROUTE; pub const LINK = AF.LINK; pub const INET6 = AF.INET6; pub const KEY = AF.KEY; pub const NCA = AF.NCA; pub const POLICY = AF.POLICY; pub const TRILL = AF.TRILL; pub const PACKET = AF.PACKET; pub const LX_NETLINK = AF.LX_NETLINK; pub const MAX = AF.MAX; }; pub const in_port_t = u16; pub const sa_family_t = u16; pub const sockaddr = extern struct { /// address family family: sa_family_t, /// actually longer; address value data: [14]u8, pub const SS_MAXSIZE = 256; pub const storage = std.x.os.Socket.Address.Native.Storage; pub const in = extern struct { family: sa_family_t = AF.INET, port: in_port_t, addr: u32, zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 }, }; pub const in6 = extern struct { family: sa_family_t = AF.INET6, port: in_port_t, flowinfo: u32, addr: [16]u8, scope_id: u32, __src_id: u32 = 0, }; /// Definitions for UNIX IPC domain. pub const un = extern struct { family: sa_family_t = AF.UNIX, path: [108]u8, }; }; pub const AI = struct { /// IPv4-mapped IPv6 address pub const V4MAPPED = 0x0001; pub const ALL = 0x0002; /// only if any address is assigned pub const ADDRCONFIG = 0x0004; /// get address to use bind() pub const PASSIVE = 0x0008; /// fill ai_canonname pub const CANONNAME = 0x0010; /// prevent host name resolution pub const NUMERICHOST = 0x0020; /// prevent service name resolution pub const NUMERICSERV = 0x0040; }; pub const NI = struct { pub const NOFQDN = 0x0001; pub const NUMERICHOST = 0x0002; pub const NAMEREQD = 0x0004; pub const NUMERICSERV = 0x0008; pub const DGRAM = 0x0010; pub const WITHSCOPEID = 0x0020; pub const NUMERICSCOPE = 0x0040; pub const MAXHOST = 1025; pub const MAXSERV = 32; }; pub const PATH_MAX = 1024; pub const IOV_MAX = 1024; pub const STDIN_FILENO = 0; pub const STDOUT_FILENO = 1; pub const STDERR_FILENO = 2; pub const PROT = struct { pub const NONE = 0; pub const READ = 1; pub const WRITE = 2; pub const EXEC = 4; }; pub const CLOCK = struct { pub const VIRTUAL = 1; pub const THREAD_CPUTIME_ID = 2; pub const REALTIME = 3; pub const MONOTONIC = 4; pub const PROCESS_CPUTIME_ID = 5; pub const HIGHRES = MONOTONIC; pub const PROF = THREAD_CPUTIME_ID; }; pub const MAP = struct { pub const FAILED = @intToPtr(*anyopaque, maxInt(usize)); pub const SHARED = 0x0001; pub const PRIVATE = 0x0002; pub const TYPE = 0x000f; pub const FILE = 0x0000; pub const FIXED = 0x0010; // Unimplemented pub const RENAME = 0x0020; pub const NORESERVE = 0x0040; /// Force mapping in lower 4G address space pub const @"32BIT" = 0x0080; pub const ANON = 0x0100; pub const ANONYMOUS = ANON; pub const ALIGN = 0x0200; pub const TEXT = 0x0400; pub const INITDATA = 0x0800; }; pub const MSF = struct { pub const ASYNC = 1; pub const INVALIDATE = 2; pub const SYNC = 4; }; pub const MADV = struct { /// no further special treatment pub const NORMAL = 0; /// expect random page references pub const RANDOM = 1; /// expect sequential page references pub const SEQUENTIAL = 2; /// will need these pages pub const WILLNEED = 3; /// don't need these pages pub const DONTNEED = 4; /// contents can be freed pub const FREE = 5; /// default access pub const ACCESS_DEFAULT = 6; /// next LWP to access heavily pub const ACCESS_LWP = 7; /// many processes to access heavily pub const ACCESS_MANY = 8; /// contents will be purged pub const PURGE = 9; }; pub const W = struct { pub const EXITED = 0o001; pub const TRAPPED = 0o002; pub const UNTRACED = 0o004; pub const STOPPED = UNTRACED; pub const CONTINUED = 0o010; pub const NOHANG = 0o100; pub const NOWAIT = 0o200; pub fn EXITSTATUS(s: u32) u8 { return @intCast(u8, (s >> 8) & 0xff); } pub fn TERMSIG(s: u32) u32 { return s & 0x7f; } pub fn STOPSIG(s: u32) u32 { return EXITSTATUS(s); } pub fn IFEXITED(s: u32) bool { return TERMSIG(s) == 0; } pub fn IFCONTINUED(s: u32) bool { return ((s & 0o177777) == 0o177777); } pub fn IFSTOPPED(s: u32) bool { return (s & 0x00ff != 0o177) and !(s & 0xff00 != 0); } pub fn IFSIGNALED(s: u32) bool { return s & 0x00ff > 0 and s & 0xff00 == 0; } }; pub const SA = struct { pub const ONSTACK = 0x00000001; pub const RESETHAND = 0x00000002; pub const RESTART = 0x00000004; pub const SIGINFO = 0x00000008; pub const NODEFER = 0x00000010; pub const NOCLDWAIT = 0x00010000; }; // access function pub const F_OK = 0; // test for existence of file pub const X_OK = 1; // test for execute or search permission pub const W_OK = 2; // test for write permission pub const R_OK = 4; // test for read permission pub const F = struct { /// Unlock a previously locked region pub const ULOCK = 0; /// Lock a region for exclusive use pub const LOCK = 1; /// Test and lock a region for exclusive use pub const TLOCK = 2; /// Test a region for other processes locks pub const TEST = 3; /// Duplicate fildes pub const DUPFD = 0; /// Get fildes flags pub const GETFD = 1; /// Set fildes flags pub const SETFD = 2; /// Get file flags pub const GETFL = 3; /// Get file flags including open-only flags pub const GETXFL = 45; /// Set file flags pub const SETFL = 4; /// Unused pub const CHKFL = 8; /// Duplicate fildes at third arg pub const DUP2FD = 9; /// Like DUP2FD with O_CLOEXEC set EINVAL is fildes matches arg1 pub const DUP2FD_CLOEXEC = 36; /// Like DUPFD with O_CLOEXEC set pub const DUPFD_CLOEXEC = 37; /// Is the file desc. a stream ? pub const ISSTREAM = 13; /// Turn on private access to file pub const PRIV = 15; /// Turn off private access to file pub const NPRIV = 16; /// UFS quota call pub const QUOTACTL = 17; /// Get number of BLKSIZE blocks allocated pub const BLOCKS = 18; /// Get optimal I/O block size pub const BLKSIZE = 19; /// Get owner (socket emulation) pub const GETOWN = 23; /// Set owner (socket emulation) pub const SETOWN = 24; /// Object reuse revoke access to file desc. pub const REVOKE = 25; /// Does vp have NFS locks private to lock manager pub const HASREMOTELOCKS = 26; /// Set file lock pub const SETLK = 6; /// Set file lock and wait pub const SETLKW = 7; /// Allocate file space pub const ALLOCSP = 10; /// Free file space pub const FREESP = 11; /// Get file lock pub const GETLK = 14; /// Get file lock owned by file pub const OFD_GETLK = 47; /// Set file lock owned by file pub const OFD_SETLK = 48; /// Set file lock owned by file and wait pub const OFD_SETLKW = 49; /// Set a file share reservation pub const SHARE = 40; /// Remove a file share reservation pub const UNSHARE = 41; /// Create Poison FD pub const BADFD = 46; /// Read lock pub const RDLCK = 1; /// Write lock pub const WRLCK = 2; /// Remove lock(s) pub const UNLCK = 3; /// remove remote locks for a given system pub const UNLKSYS = 4; // f_access values /// Read-only share access pub const RDACC = 0x1; /// Write-only share access pub const WRACC = 0x2; /// Read-Write share access pub const RWACC = 0x3; // f_deny values /// Don't deny others access pub const NODNY = 0x0; /// Deny others read share access pub const RDDNY = 0x1; /// Deny others write share access pub const WRDNY = 0x2; /// Deny others read or write share access pub const RWDNY = 0x3; /// private flag: Deny delete share access pub const RMDNY = 0x4; }; pub const O = struct { pub const RDONLY = 0; pub const WRONLY = 1; pub const RDWR = 2; pub const SEARCH = 0x200000; pub const EXEC = 0x400000; pub const NDELAY = 0x04; pub const APPEND = 0x08; pub const SYNC = 0x10; pub const DSYNC = 0x40; pub const RSYNC = 0x8000; pub const NONBLOCK = 0x80; pub const LARGEFILE = 0x2000; pub const CREAT = 0x100; pub const TRUNC = 0x200; pub const EXCL = 0x400; pub const NOCTTY = 0x800; pub const XATTR = 0x4000; pub const NOFOLLOW = 0x20000; pub const NOLINKS = 0x40000; pub const CLOEXEC = 0x800000; pub const DIRECTORY = 0x1000000; pub const DIRECT = 0x2000000; }; pub const LOCK = struct { pub const SH = 1; pub const EX = 2; pub const NB = 4; pub const UN = 8; }; pub const FD_CLOEXEC = 1; pub const SEEK = struct { pub const SET = 0; pub const CUR = 1; pub const END = 2; pub const DATA = 3; pub const HOLE = 4; }; pub const tcflag_t = c_uint; pub const cc_t = u8; pub const speed_t = c_uint; pub const NCCS = 19; pub const termios = extern struct { c_iflag: tcflag_t, c_oflag: tcflag_t, c_cflag: tcflag_t, c_lflag: tcflag_t, c_cc: [NCCS]cc_t, }; fn tioc(t: u16, num: u8) u16 { return (t << 8) | num; } pub const T = struct { pub const CGETA = tioc('T', 1); pub const CSETA = tioc('T', 2); pub const CSETAW = tioc('T', 3); pub const CSETAF = tioc('T', 4); pub const CSBRK = tioc('T', 5); pub const CXONC = tioc('T', 6); pub const CFLSH = tioc('T', 7); pub const IOCGWINSZ = tioc('T', 104); pub const IOCSWINSZ = tioc('T', 103); // Softcarrier ioctls pub const IOCGSOFTCAR = tioc('T', 105); pub const IOCSSOFTCAR = tioc('T', 106); // termios ioctls pub const CGETS = tioc('T', 13); pub const CSETS = tioc('T', 14); pub const CSANOW = tioc('T', 14); pub const CSETSW = tioc('T', 15); pub const CSADRAIN = tioc('T', 15); pub const CSETSF = tioc('T', 16); pub const IOCSETLD = tioc('T', 123); pub const IOCGETLD = tioc('T', 124); // NTP PPS ioctls pub const IOCGPPS = tioc('T', 125); pub const IOCSPPS = tioc('T', 126); pub const IOCGPPSEV = tioc('T', 127); pub const IOCGETD = tioc('t', 0); pub const IOCSETD = tioc('t', 1); pub const IOCHPCL = tioc('t', 2); pub const IOCGETP = tioc('t', 8); pub const IOCSETP = tioc('t', 9); pub const IOCSETN = tioc('t', 10); pub const IOCEXCL = tioc('t', 13); pub const IOCNXCL = tioc('t', 14); pub const IOCFLUSH = tioc('t', 16); pub const IOCSETC = tioc('t', 17); pub const IOCGETC = tioc('t', 18); /// bis local mode bits pub const IOCLBIS = tioc('t', 127); /// bic local mode bits pub const IOCLBIC = tioc('t', 126); /// set entire local mode word pub const IOCLSET = tioc('t', 125); /// get local modes pub const IOCLGET = tioc('t', 124); /// set break bit pub const IOCSBRK = tioc('t', 123); /// clear break bit pub const IOCCBRK = tioc('t', 122); /// set data terminal ready pub const IOCSDTR = tioc('t', 121); /// clear data terminal ready pub const IOCCDTR = tioc('t', 120); /// set local special chars pub const IOCSLTC = tioc('t', 117); /// get local special chars pub const IOCGLTC = tioc('t', 116); /// driver output queue size pub const IOCOUTQ = tioc('t', 115); /// void tty association pub const IOCNOTTY = tioc('t', 113); /// get a ctty pub const IOCSCTTY = tioc('t', 132); /// stop output, like ^S pub const IOCSTOP = tioc('t', 111); /// start output, like ^Q pub const IOCSTART = tioc('t', 110); /// get pgrp of tty pub const IOCGPGRP = tioc('t', 20); /// set pgrp of tty pub const IOCSPGRP = tioc('t', 21); /// get session id on ctty pub const IOCGSID = tioc('t', 22); /// simulate terminal input pub const IOCSTI = tioc('t', 23); /// set all modem bits pub const IOCMSET = tioc('t', 26); /// bis modem bits pub const IOCMBIS = tioc('t', 27); /// bic modem bits pub const IOCMBIC = tioc('t', 28); /// get all modem bits pub const IOCMGET = tioc('t', 29); }; pub const winsize = extern struct { ws_row: u16, ws_col: u16, ws_xpixel: u16, ws_ypixel: u16, }; const NSIG = 75; pub const SIG = struct { pub const DFL = @intToPtr(?Sigaction.sigaction_fn, 0); pub const ERR = @intToPtr(?Sigaction.sigaction_fn, maxInt(usize)); pub const IGN = @intToPtr(?Sigaction.sigaction_fn, 1); pub const HOLD = @intToPtr(?Sigaction.sigaction_fn, 2); pub const WORDS = 4; pub const MAXSIG = 75; pub const SIG_BLOCK = 1; pub const SIG_UNBLOCK = 2; pub const SIG_SETMASK = 3; pub const HUP = 1; pub const INT = 2; pub const QUIT = 3; pub const ILL = 4; pub const TRAP = 5; pub const IOT = 6; pub const ABRT = 6; pub const EMT = 7; pub const FPE = 8; pub const KILL = 9; pub const BUS = 10; pub const SEGV = 11; pub const SYS = 12; pub const PIPE = 13; pub const ALRM = 14; pub const TERM = 15; pub const USR1 = 16; pub const USR2 = 17; pub const CLD = 18; pub const CHLD = 18; pub const PWR = 19; pub const WINCH = 20; pub const URG = 21; pub const POLL = 22; pub const IO = .POLL; pub const STOP = 23; pub const TSTP = 24; pub const CONT = 25; pub const TTIN = 26; pub const TTOU = 27; pub const VTALRM = 28; pub const PROF = 29; pub const XCPU = 30; pub const XFSZ = 31; pub const WAITING = 32; pub const LWP = 33; pub const FREEZE = 34; pub const THAW = 35; pub const CANCEL = 36; pub const LOST = 37; pub const XRES = 38; pub const JVM1 = 39; pub const JVM2 = 40; pub const INFO = 41; pub const RTMIN = 42; pub const RTMAX = 74; pub inline fn IDX(sig: usize) usize { return sig - 1; } pub inline fn WORD(sig: usize) usize { return IDX(sig) >> 5; } pub inline fn BIT(sig: usize) usize { return 1 << (IDX(sig) & 31); } pub inline fn VALID(sig: usize) usize { return sig <= MAXSIG and sig > 0; } }; /// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall. pub const Sigaction = extern struct { pub const handler_fn = fn (c_int) callconv(.C) void; pub const sigaction_fn = fn (c_int, *const siginfo_t, ?*const anyopaque) callconv(.C) void; /// signal options flags: c_uint, /// signal handler handler: extern union { handler: ?handler_fn, sigaction: ?sigaction_fn, }, /// signal mask to apply mask: sigset_t, }; pub const sigval_t = extern union { int: c_int, ptr: ?*anyopaque, }; pub const siginfo_t = extern struct { signo: c_int, code: c_int, errno: c_int, // 64bit architectures insert 4bytes of padding here, this is done by // correctly aligning the reason field reason: extern union { proc: extern struct { pid: pid_t, pdata: extern union { kill: extern struct { uid: uid_t, value: sigval_t, }, cld: extern struct { utime: clock_t, status: c_int, stime: clock_t, }, }, contract: ctid_t, zone: zoneid_t, }, fault: extern struct { addr: ?*anyopaque, trapno: c_int, pc: ?*anyopaque, }, file: extern struct { // fd not currently available for SIGPOLL. fd: c_int, band: c_long, }, prof: extern struct { addr: ?*anyopaque, timestamp: timespec, syscall: c_short, sysarg: u8, fault: u8, args: [8]c_long, state: [10]c_int, }, rctl: extern struct { entity: i32, }, __pad: [256 - 4 * @sizeOf(c_int)]u8, } align(@sizeOf(usize)), }; comptime { std.debug.assert(@sizeOf(siginfo_t) == 256); std.debug.assert(@alignOf(siginfo_t) == @sizeOf(usize)); } pub const sigset_t = extern struct { __bits: [SIG.WORDS]u32, }; pub const empty_sigset = sigset_t{ .__bits = [_]u32{0} ** SIG.WORDS }; pub const fpregset_t = extern union { regs: [130]u32, chip_state: extern struct { cw: u16, sw: u16, fctw: u8, __fx_rsvd: u8, fop: u16, rip: u64, rdp: u64, mxcsr: u32, mxcsr_mask: u32, st: [8]extern union { fpr_16: [5]u16, __fpr_pad: u128, }, xmm: [16]u128, __fx_ign2: [6]u128, status: u32, xstatus: u32, }, }; pub const mcontext_t = extern struct { gregs: [28]u64, fpregs: fpregset_t, }; pub const REG = struct { pub const RBP = 10; pub const RIP = 17; pub const RSP = 20; }; pub const ucontext_t = extern struct { flags: u64, link: ?*ucontext_t, sigmask: sigset_t, stack: stack_t, mcontext: mcontext_t, brand_data: [3]?*anyopaque, filler: [2]i64, }; pub const GETCONTEXT = 0; pub const SETCONTEXT = 1; pub const GETUSTACK = 2; pub const SETUSTACK = 3; pub const E = enum(u16) { /// No error occurred. SUCCESS = 0, /// Not super-user PERM = 1, /// No such file or directory NOENT = 2, /// No such process SRCH = 3, /// interrupted system call INTR = 4, /// I/O error IO = 5, /// No such device or address NXIO = 6, /// Arg list too long @"2BIG" = 7, /// Exec format error NOEXEC = 8, /// Bad file number BADF = 9, /// No children CHILD = 10, /// Resource temporarily unavailable. /// also: WOULDBLOCK: Operation would block. AGAIN = 11, /// Not enough core NOMEM = 12, /// Permission denied ACCES = 13, /// Bad address FAULT = 14, /// Block device required NOTBLK = 15, /// Mount device busy BUSY = 16, /// File exists EXIST = 17, /// Cross-device link XDEV = 18, /// No such device NODEV = 19, /// Not a directory NOTDIR = 20, /// Is a directory ISDIR = 21, /// Invalid argument INVAL = 22, /// File table overflow NFILE = 23, /// Too many open files MFILE = 24, /// Inappropriate ioctl for device NOTTY = 25, /// Text file busy TXTBSY = 26, /// File too large FBIG = 27, /// No space left on device NOSPC = 28, /// Illegal seek SPIPE = 29, /// Read only file system ROFS = 30, /// Too many links MLINK = 31, /// Broken pipe PIPE = 32, /// Math arg out of domain of func DOM = 33, /// Math result not representable RANGE = 34, /// No message of desired type NOMSG = 35, /// Identifier removed IDRM = 36, /// Channel number out of range CHRNG = 37, /// Level 2 not synchronized L2NSYNC = 38, /// Level 3 halted L3HLT = 39, /// Level 3 reset L3RST = 40, /// Link number out of range LNRNG = 41, /// Protocol driver not attached UNATCH = 42, /// No CSI structure available NOCSI = 43, /// Level 2 halted L2HLT = 44, /// Deadlock condition. DEADLK = 45, /// No record locks available. NOLCK = 46, /// Operation canceled CANCELED = 47, /// Operation not supported NOTSUP = 48, // Filesystem Quotas /// Disc quota exceeded DQUOT = 49, // Convergent Error Returns /// invalid exchange BADE = 50, /// invalid request descriptor BADR = 51, /// exchange full XFULL = 52, /// no anode NOANO = 53, /// invalid request code BADRQC = 54, /// invalid slot BADSLT = 55, /// file locking deadlock error DEADLOCK = 56, /// bad font file fmt BFONT = 57, // Interprocess Robust Locks /// process died with the lock OWNERDEAD = 58, /// lock is not recoverable NOTRECOVERABLE = 59, /// locked lock was unmapped LOCKUNMAPPED = 72, /// Facility is not active NOTACTIVE = 73, /// multihop attempted MULTIHOP = 74, /// trying to read unreadable message BADMSG = 77, /// path name is too long NAMETOOLONG = 78, /// value too large to be stored in data type OVERFLOW = 79, /// given log. name not unique NOTUNIQ = 80, /// f.d. invalid for this operation BADFD = 81, /// Remote address changed REMCHG = 82, // Stream Problems /// Device not a stream NOSTR = 60, /// no data (for no delay io) NODATA = 61, /// timer expired TIME = 62, /// out of streams resources NOSR = 63, /// Machine is not on the network NONET = 64, /// Package not installed NOPKG = 65, /// The object is remote REMOTE = 66, /// the link has been severed NOLINK = 67, /// advertise error ADV = 68, /// srmount error SRMNT = 69, /// Communication error on send COMM = 70, /// Protocol error PROTO = 71, // Shared Library Problems /// Can't access a needed shared lib. LIBACC = 83, /// Accessing a corrupted shared lib. LIBBAD = 84, /// .lib section in a.out corrupted. LIBSCN = 85, /// Attempting to link in too many libs. LIBMAX = 86, /// Attempting to exec a shared library. LIBEXEC = 87, /// Illegal byte sequence. ILSEQ = 88, /// Unsupported file system operation NOSYS = 89, /// Symbolic link loop LOOP = 90, /// Restartable system call RESTART = 91, /// if pipe/FIFO, don't sleep in stream head STRPIPE = 92, /// directory not empty NOTEMPTY = 93, /// Too many users (for UFS) USERS = 94, // BSD Networking Software // Argument Errors /// Socket operation on non-socket NOTSOCK = 95, /// Destination address required DESTADDRREQ = 96, /// Message too long MSGSIZE = 97, /// Protocol wrong type for socket PROTOTYPE = 98, /// Protocol not available NOPROTOOPT = 99, /// Protocol not supported PROTONOSUPPORT = 120, /// Socket type not supported SOCKTNOSUPPORT = 121, /// Operation not supported on socket OPNOTSUPP = 122, /// Protocol family not supported PFNOSUPPORT = 123, /// Address family not supported by AFNOSUPPORT = 124, /// Address already in use ADDRINUSE = 125, /// Can't assign requested address ADDRNOTAVAIL = 126, // Operational Errors /// Network is down NETDOWN = 127, /// Network is unreachable NETUNREACH = 128, /// Network dropped connection because NETRESET = 129, /// Software caused connection abort CONNABORTED = 130, /// Connection reset by peer CONNRESET = 131, /// No buffer space available NOBUFS = 132, /// Socket is already connected ISCONN = 133, /// Socket is not connected NOTCONN = 134, /// Can't send after socket shutdown SHUTDOWN = 143, /// Too many references: can't splice TOOMANYREFS = 144, /// Connection timed out TIMEDOUT = 145, /// Connection refused CONNREFUSED = 146, /// Host is down HOSTDOWN = 147, /// No route to host HOSTUNREACH = 148, /// operation already in progress ALREADY = 149, /// operation now in progress INPROGRESS = 150, // SUN Network File System /// Stale NFS file handle STALE = 151, _, }; pub const MINSIGSTKSZ = 2048; pub const SIGSTKSZ = 8192; pub const SS_ONSTACK = 0x1; pub const SS_DISABLE = 0x2; pub const stack_t = extern struct { sp: [*]u8, size: isize, flags: i32, }; pub const S = struct { pub const IFMT = 0o170000; pub const IFIFO = 0o010000; pub const IFCHR = 0o020000; pub const IFDIR = 0o040000; pub const IFBLK = 0o060000; pub const IFREG = 0o100000; pub const IFLNK = 0o120000; pub const IFSOCK = 0o140000; /// SunOS 2.6 Door pub const IFDOOR = 0o150000; /// Solaris 10 Event Port pub const IFPORT = 0o160000; pub const ISUID = 0o4000; pub const ISGID = 0o2000; pub const ISVTX = 0o1000; pub const IRWXU = 0o700; pub const IRUSR = 0o400; pub const IWUSR = 0o200; pub const IXUSR = 0o100; pub const IRWXG = 0o070; pub const IRGRP = 0o040; pub const IWGRP = 0o020; pub const IXGRP = 0o010; pub const IRWXO = 0o007; pub const IROTH = 0o004; pub const IWOTH = 0o002; pub const IXOTH = 0o001; pub fn ISFIFO(m: u32) bool { return m & IFMT == IFIFO; } pub fn ISCHR(m: u32) bool { return m & IFMT == IFCHR; } pub fn ISDIR(m: u32) bool { return m & IFMT == IFDIR; } pub fn ISBLK(m: u32) bool { return m & IFMT == IFBLK; } pub fn ISREG(m: u32) bool { return m & IFMT == IFREG; } pub fn ISLNK(m: u32) bool { return m & IFMT == IFLNK; } pub fn ISSOCK(m: u32) bool { return m & IFMT == IFSOCK; } pub fn ISDOOR(m: u32) bool { return m & IFMT == IFDOOR; } pub fn ISPORT(m: u32) bool { return m & IFMT == IFPORT; } }; pub const AT = struct { /// Magic value that specify the use of the current working directory /// to determine the target of relative file paths in the openat() and /// similar syscalls. pub const FDCWD = @bitCast(fd_t, @as(u32, 0xffd19553)); /// Do not follow symbolic links pub const SYMLINK_NOFOLLOW = 0x1000; /// Follow symbolic link pub const SYMLINK_FOLLOW = 0x2000; /// Remove directory instead of file pub const REMOVEDIR = 0x1; pub const TRIGGER = 0x2; /// Check access using effective user and group ID pub const EACCESS = 0x4; }; pub const POSIX_FADV = struct { pub const NORMAL = 0; pub const RANDOM = 1; pub const SEQUENTIAL = 2; pub const WILLNEED = 3; pub const DONTNEED = 4; pub const NOREUSE = 5; }; pub const HOST_NAME_MAX = 255; pub const IPPROTO = struct { /// dummy for IP pub const IP = 0; /// Hop by hop header for IPv6 pub const HOPOPTS = 0; /// control message protocol pub const ICMP = 1; /// group control protocol pub const IGMP = 2; /// gateway^2 (deprecated) pub const GGP = 3; /// IP in IP encapsulation pub const ENCAP = 4; /// tcp pub const TCP = 6; /// exterior gateway protocol pub const EGP = 8; /// pup pub const PUP = 12; /// user datagram protocol pub const UDP = 17; /// xns idp pub const IDP = 22; /// IPv6 encapsulated in IP pub const IPV6 = 41; /// Routing header for IPv6 pub const ROUTING = 43; /// Fragment header for IPv6 pub const FRAGMENT = 44; /// rsvp pub const RSVP = 46; /// IPsec Encap. Sec. Payload pub const ESP = 50; /// IPsec Authentication Hdr. pub const AH = 51; /// ICMP for IPv6 pub const ICMPV6 = 58; /// No next header for IPv6 pub const NONE = 59; /// Destination options pub const DSTOPTS = 60; /// "hello" routing protocol pub const HELLO = 63; /// UNOFFICIAL net disk proto pub const ND = 77; /// ISO clnp pub const EON = 80; /// OSPF pub const OSPF = 89; /// PIM routing protocol pub const PIM = 103; /// Stream Control pub const SCTP = 132; /// raw IP packet pub const RAW = 255; /// Sockets Direct Protocol pub const PROTO_SDP = 257; }; pub const priority = enum(c_int) { PROCESS = 0, PGRP = 1, USER = 2, GROUP = 3, SESSION = 4, LWP = 5, TASK = 6, PROJECT = 7, ZONE = 8, CONTRACT = 9, }; pub const rlimit_resource = enum(c_int) { CPU = 0, FSIZE = 1, DATA = 2, STACK = 3, CORE = 4, NOFILE = 5, VMEM = 6, _, pub const AS: rlimit_resource = .VMEM; }; pub const rlim_t = u64; pub const RLIM = struct { /// No limit pub const INFINITY: rlim_t = (1 << 63) - 3; pub const SAVED_MAX: rlim_t = (1 << 63) - 2; pub const SAVED_CUR: rlim_t = (1 << 63) - 1; }; pub const rlimit = extern struct { /// Soft limit cur: rlim_t, /// Hard limit max: rlim_t, }; pub const rusage = extern struct { utime: timeval, stime: timeval, maxrss: isize, ixrss: isize, idrss: isize, isrss: isize, minflt: isize, majflt: isize, nswap: isize, inblock: isize, oublock: isize, msgsnd: isize, msgrcv: isize, nsignals: isize, nvcsw: isize, nivcsw: isize, pub const SELF = 0; pub const CHILDREN = -1; pub const THREAD = 1; }; pub const SHUT = struct { pub const RD = 0; pub const WR = 1; pub const RDWR = 2; }; pub const pollfd = extern struct { fd: fd_t, events: i16, revents: i16, }; /// Testable events (may be specified in ::pollfd::events). pub const POLL = struct { pub const IN = 0x0001; pub const PRI = 0x0002; pub const OUT = 0x0004; pub const RDNORM = 0x0040; pub const WRNORM = .OUT; pub const RDBAND = 0x0080; pub const WRBAND = 0x0100; /// Read-side hangup. pub const RDHUP = 0x4000; /// Non-testable events (may not be specified in events). pub const ERR = 0x0008; pub const HUP = 0x0010; pub const NVAL = 0x0020; /// Events to control `/dev/poll` (not specified in revents) pub const REMOVE = 0x0800; pub const ONESHOT = 0x1000; pub const ET = 0x2000; }; /// Extensions to the ELF auxiliary vector. pub const AT_SUN = struct { /// effective user id pub const UID = 2000; /// real user id pub const RUID = 2001; /// effective group id pub const GID = 2002; /// real group id pub const RGID = 2003; /// dynamic linker's ELF header pub const LDELF = 2004; /// dynamic linker's section headers pub const LDSHDR = 2005; /// name of dynamic linker pub const LDNAME = 2006; /// large pagesize pub const LPAGESZ = 2007; /// platform name pub const PLATFORM = 2008; /// hints about hardware capabilities. pub const HWCAP = 2009; pub const HWCAP2 = 2023; /// flush icache? pub const IFLUSH = 2010; /// cpu name pub const CPU = 2011; /// exec() path name in the auxv, null terminated. pub const EXECNAME = 2014; /// mmu module name pub const MMU = 2015; /// dynamic linkers data segment pub const LDDATA = 2016; /// AF_SUN_ flags passed from the kernel pub const AUXFLAGS = 2017; /// name of the emulation binary for the linker pub const EMULATOR = 2018; /// name of the brand library for the linker pub const BRANDNAME = 2019; /// vectors for brand modules. pub const BRAND_AUX1 = 2020; pub const BRAND_AUX2 = 2021; pub const BRAND_AUX3 = 2022; pub const BRAND_AUX4 = 2025; pub const BRAND_NROOT = 2024; /// vector for comm page. pub const COMMPAGE = 2026; /// information about the x86 FPU. pub const FPTYPE = 2027; pub const FPSIZE = 2028; }; /// ELF auxiliary vector flags. pub const AF_SUN = struct { /// tell ld.so.1 to run "secure" and ignore the environment. pub const SETUGID = 0x00000001; /// hardware capabilities can be verified against AT_SUN_HWCAP pub const HWCAPVERIFY = 0x00000002; pub const NOPLM = 0x00000004; }; // TODO: Add sysconf numbers when the other OSs do. pub const _SC = struct { pub const NPROCESSORS_ONLN = 15; }; pub const procfs = struct { pub const misc_header = extern struct { size: u32, @"type": enum(u32) { Pathname, Socketname, Peersockname, SockoptsBoolOpts, SockoptLinger, SockoptSndbuf, SockoptRcvbuf, SockoptIpNexthop, SockoptIpv6Nexthop, SockoptType, SockoptTcpCongestion, SockfiltersPriv = 14, }, }; pub const fdinfo = extern struct { fd: fd_t, mode: mode_t, ino: ino_t, size: off_t, offset: off_t, uid: uid_t, gid: gid_t, dev_major: major_t, dev_minor: minor_t, special_major: major_t, special_minor: minor_t, fileflags: i32, fdflags: i32, locktype: i16, lockpid: pid_t, locksysid: i32, peerpid: pid_t, __filler: [25]c_int, peername: [15:0]u8, misc: [1]u8, }; }; pub const SFD = struct { pub const CLOEXEC = 0o2000000; pub const NONBLOCK = 0o4000; }; pub const signalfd_siginfo = extern struct { signo: u32, errno: i32, code: i32, pid: u32, uid: uid_t, fd: i32, tid: u32, // unused band: u32, overrun: u32, // unused trapno: u32, status: i32, int: i32, // unused ptr: u64, // unused utime: u64, stime: u64, addr: u64, __pad: [48]u8, }; pub const PORT_SOURCE = struct { pub const AIO = 1; pub const TIMER = 2; pub const USER = 3; pub const FD = 4; pub const ALERT = 5; pub const MQ = 6; pub const FILE = 7; }; pub const PORT_ALERT = struct { pub const SET = 0x01; pub const UPDATE = 0x02; }; /// User watchable file events. pub const FILE_EVENT = struct { pub const ACCESS = 0x00000001; pub const MODIFIED = 0x00000002; pub const ATTRIB = 0x00000004; pub const DELETE = 0x00000010; pub const RENAME_TO = 0x00000020; pub const RENAME_FROM = 0x00000040; pub const TRUNC = 0x00100000; pub const NOFOLLOW = 0x10000000; /// The filesystem holding the watched file was unmounted. pub const UNMOUNTED = 0x20000000; /// Some other file/filesystem got mounted over the watched file/directory. pub const MOUNTEDOVER = 0x40000000; pub fn isException(event: u32) bool { return event & (UNMOUNTED | DELETE | RENAME_TO | RENAME_FROM | MOUNTEDOVER) > 0; } }; pub const port_event = extern struct { events: u32, /// Event source. source: u16, __pad: u16, /// Source-specific object. object: ?*anyopaque, /// User cookie. cookie: ?*anyopaque, }; pub const port_notify = extern struct { /// Bind request(s) to port. port: u32, /// User defined variable. user: ?*void, }; pub const file_obj = extern struct { /// Access time. atim: timespec, /// Modification time mtim: timespec, /// Change time ctim: timespec, __pad: [3]usize, name: [*:0]u8, }; // struct ifreq is marked obsolete, with struct lifreq prefered for interface requests. // Here we alias lifreq to ifreq to avoid chainging existing code in os and x.os.IPv6. pub const SIOCGLIFINDEX = IOWR('i', 133, lifreq); pub const SIOCGIFINDEX = SIOCGLIFINDEX; pub const MAX_HDW_LEN = 64; pub const IFNAMESIZE = 32; pub const lif_nd_req = extern struct { addr: sockaddr.storage, state_create: u8, state_same_lla: u8, state_diff_lla: u8, hdw_len: i32, flags: i32, __pad: i32, hdw_addr: [MAX_HDW_LEN]u8, }; pub const lif_ifinfo_req = extern struct { maxhops: u8, reachtime: u32, reachretrans: u32, maxmtu: u32, }; /// IP interface request. See if_tcp(7p) for more info. pub const lifreq = extern struct { // Not actually in a union, but the stdlib expects one for ifreq ifrn: extern union { /// Interface name, e.g. "lo0", "en0". name: [IFNAMESIZE]u8, }, ru1: extern union { /// For subnet/token etc. addrlen: i32, /// Driver's PPA (physical point of attachment). ppa: u32, }, /// One of the IFT types, e.g. IFT_ETHER. @"type": u32, ifru: extern union { /// Address. addr: sockaddr.storage, /// Other end of a peer-to-peer link. dstaddr: sockaddr.storage, /// Broadcast address. broadaddr: sockaddr.storage, /// Address token. token: sockaddr.storage, /// Subnet prefix. subnet: sockaddr.storage, /// Interface index. ivalue: i32, /// Flags for SIOC?LIFFLAGS. flags: u64, /// Hop count metric metric: i32, /// Maximum transmission unit mtu: u32, // Technically [2]i32 muxid: packed struct { ip: i32, arp: i32 }, /// Neighbor reachability determination entries nd_req: lif_nd_req, /// Link info ifinfo_req: lif_ifinfo_req, /// Name of the multipath interface group groupname: [IFNAMESIZE]u8, binding: [IFNAMESIZE]u8, /// Zone id associated with this interface. zoneid: zoneid_t, /// Duplicate address detection state. Either in progress or completed. dadstate: u32, }, }; pub const ifreq = lifreq; const IoCtlCommand = enum(u32) { none = 0x20000000, // no parameters write = 0x40000000, // copy out parameters read = 0x80000000, // copy in parameters read_write = 0xc0000000, }; fn ioImpl(cmd: IoCtlCommand, io_type: u8, nr: u8, comptime IOT: type) i32 { const size = @intCast(u32, @truncate(u8, @sizeOf(IOT))) << 16; const t = @intCast(u32, io_type) << 8; return @bitCast(i32, @enumToInt(cmd) | size | t | nr); } pub fn IO(io_type: u8, nr: u8) i32 { return ioImpl(.none, io_type, nr, void); } pub fn IOR(io_type: u8, nr: u8, comptime IOT: type) i32 { return ioImpl(.write, io_type, nr, IOT); } pub fn IOW(io_type: u8, nr: u8, comptime IOT: type) i32 { return ioImpl(.read, io_type, nr, IOT); } pub fn IOWR(io_type: u8, nr: u8, comptime IOT: type) i32 { return ioImpl(.read_write, io_type, nr, IOT); }
lib/std/c/solaris.zig
const std = @import("std"); const json = @import("../json.zig"); const PathToken = union(enum) { index: u32, key: []const u8, fn tokenize(string: []const u8) Tokenizer { return .{ .string = string, .index = 0 }; } const Tokenizer = struct { string: []const u8, index: usize, fn next(self: *Tokenizer) !?PathToken { if (self.index >= self.string.len) return null; var token_start = self.index; switch (self.string[self.index]) { '[' => { self.index += 1; switch (self.string[self.index]) { '\'' => { self.index += 1; const start = self.index; while (self.index < self.string.len) : (self.index += 1) { switch (self.string[self.index]) { '\\' => return error.InvalidToken, '\'' => { defer self.index += 2; if (self.string[self.index + 1] != ']') { return error.InvalidToken; } return PathToken{ .key = self.string[start..self.index] }; }, else => {}, } } return error.InvalidToken; }, '0'...'9' => { const start = self.index; while (self.index < self.string.len) : (self.index += 1) { switch (self.string[self.index]) { '0'...'9' => {}, ']' => { defer self.index += 1; return PathToken{ .index = std.fmt.parseInt(u32, self.string[start..self.index], 10) catch unreachable }; }, else => return error.InvalidToken, } } return error.InvalidToken; }, else => return error.InvalidToken, } }, 'a'...'z', 'A'...'Z', '_', '$' => { const start = self.index; while (self.index < self.string.len) : (self.index += 1) { switch (self.string[self.index]) { 'a'...'z', 'A'...'Z', '0'...'9', '_', '$' => {}, '.' => { defer self.index += 1; return PathToken{ .key = self.string[start..self.index] }; }, '[' => return PathToken{ .key = self.string[start..self.index] }, else => return error.InvalidToken, } } return PathToken{ .key = self.string[start..self.index] }; }, else => return error.InvalidToken, } } }; }; test "PathToken" { var iter = PathToken.tokenize("foo.bar.baz"); std.testing.expectEqualStrings("foo", (try iter.next()).?.key); std.testing.expectEqualStrings("bar", (try iter.next()).?.key); std.testing.expectEqualStrings("baz", (try iter.next()).?.key); std.testing.expectEqual(@as(?PathToken, null), try iter.next()); iter = PathToken.tokenize("[1][2][3]"); std.testing.expectEqual(@as(u32, 1), (try iter.next()).?.index); std.testing.expectEqual(@as(u32, 2), (try iter.next()).?.index); std.testing.expectEqual(@as(u32, 3), (try iter.next()).?.index); std.testing.expectEqual(@as(?PathToken, null), try iter.next()); iter = PathToken.tokenize("['foo']['bar']['baz']"); std.testing.expectEqualStrings("foo", (try iter.next()).?.key); std.testing.expectEqualStrings("bar", (try iter.next()).?.key); std.testing.expectEqualStrings("baz", (try iter.next()).?.key); std.testing.expectEqual(@as(?PathToken, null), try iter.next()); } const AstNode = struct { initial_path: []const u8, data: union(enum) { empty: void, atom: type, object: []const Object, array: []const Array, } = .empty, const Object = struct { key: []const u8, node: AstNode }; const Array = struct { index: usize, node: AstNode }; fn init(comptime T: type) !AstNode { var result = AstNode{ .initial_path = "" }; for (std.meta.fields(T)) |field| { var tokenizer = PathToken.tokenize(field.name); try result.insert(field.field_type, &tokenizer); } return result; } fn insert(comptime self: *AstNode, comptime T: type, tokenizer: *PathToken.Tokenizer) error{Collision}!void { const token = (try tokenizer.next()) orelse { if (self.data != .empty) return error.Collision; self.data = .{ .atom = T }; return; }; switch (token) { .index => |index| { switch (self.data) { .array => {}, .empty => { self.data = .{ .array = &.{} }; }, else => return error.Collision, } for (self.data.array) |elem| { if (elem.index == index) { // TODO: replace this awful copy with comptime allocators var copy = self.data.array[0..self.data.array.len].*; try copy[i].node.insert(T, tokenizer); self.data.array = &copy; break; } } else { var new_node = AstNode{ .initial_path = tokenizer.string }; try new_node.insert(T, tokenizer); self.data.object = self.data.object ++ [_]Object{ .{ .key = key, .node = new_node }, }; } }, .key => |key| { switch (self.data) { .object => {}, .empty => { self.data = .{ .object = &.{} }; }, else => return error.Collision, } for (self.data.object) |elem, i| { if (std.mem.eql(u8, elem.key, key)) { // TODO: replace this awful copy with comptime allocators var copy = self.data.object[0..self.data.object.len].*; try copy[i].node.insert(T, tokenizer); self.data.object = &copy; break; } } else { var new_node = AstNode{ .initial_path = tokenizer.string }; try new_node.insert(T, tokenizer); self.data.object = self.data.object ++ [_]Object{ .{ .key = key, .node = new_node }, }; } }, } } fn apply(comptime self: AstNode, allocator: ?*std.mem.Allocator, json_element: anytype, matches: anytype, result: anytype) !void { switch (self.data) { .empty => unreachable, .atom => |AtomType| { @field(result, self.initial_path) = switch (AtomType) { bool => try json_element.boolean(), ?bool => try json_element.optionalBoolean(), []const u8, []u8 => try (try json_element.stringReader()).readAllAlloc(allocator.?, std.math.maxInt(usize)), ?[]const u8, ?[]u8 => blk: { const reader = (try json_element.optionalStringReader()) orelse break :blk null; break :blk try reader.readAllAlloc(allocator.?, std.math.maxInt(usize)); }, else => switch (@typeInfo(AtomType)) { .Float, .Int => try json_element.number(AtomType), .Optional => |o_info| switch (@typeInfo(o_info.child)) { .Float, .Int => try json_element.optionalNumber(o_info.child), else => @compileError("Type not supported " ++ @typeName(AtomType)), }, else => @compileError("Type not supported " ++ @typeName(AtomType)), }, }; if (@hasField(std.meta.Child(@TypeOf(matches)), self.initial_path)) { @field(matches, self.initial_path) = true; } }, .object => |object| { comptime var keys: [object.len][]const u8 = undefined; comptime for (object) |directive, i| { keys[i] = directive.key; }; while (try json_element.objectMatchAny(&keys)) |item| match: { inline for (object) |directive| { if (std.mem.eql(u8, directive.key, item.key)) { try directive.node.apply(allocator, item.value, matches, result); break :match; } } unreachable; } }, .array => |array| { var i: usize = 0; while (try json_element.arrayNext()) |item| : (i += 1) match: { inline for (array) |child| { if (child.index == i) { try child.node.apply(json_element, matches, result); break :match; } } } }, } } }; fn RequiredMatches(comptime T: type) type { var required_fields: []const std.builtin.TypeInfo.StructField = &.{}; for (std.meta.fields(T)) |field| { if (@typeInfo(field.field_type) != .Optional) { required_fields = required_fields ++ [_]std.builtin.TypeInfo.StructField{ .{ .name = field.name, .field_type = bool, .default_value = false, .is_comptime = false, .alignment = 1 }, }; } } return @Type(.{ .Struct = .{ .layout = .Auto, .fields = required_fields, .decls = &.{}, .is_tuple = false, }, }); } pub fn match(allocator: ?*std.mem.Allocator, json_element: anytype, comptime T: type) !T { comptime const ast = try AstNode.init(T); var result: T = undefined; inline for (std.meta.fields(T)) |field| { if (@typeInfo(field.field_type) == .Optional) { @field(result, field.name) = null; } } var matches: RequiredMatches(T) = .{}; errdefer { inline for (std.meta.fields(@TypeOf(result))) |field| { switch (field.field_type) { ?[]const u8, ?[]u8 => { if (@field(result, field.name)) |str| { allocator.?.free(str); } }, []const u8, []u8 => { if (@field(matches, field.name)) { allocator.?.free(@field(result, field.name)); } }, else => {}, } } } try ast.apply(allocator, json_element, &matches, &result); inline for (std.meta.fields(@TypeOf(matches))) |field| { if (!@field(matches, field.name)) { return error.Required; } } return result; } pub fn freeMatch(allocator: *std.mem.Allocator, value: anytype) void { inline for (std.meta.fields(@TypeOf(value))) |field| { if (field.field_type == []const u8) { allocator.free(@field(value, field.name)); } } } test "simple match" { var fbs = std.io.fixedBufferStream( \\{"foo": true, "bar": 2, "baz": "nop"} ); var str = json.stream(fbs.reader()); const root = try str.root(); expectEqual(root.kind, .Object); const m = try match(std.testing.allocator, root, struct { @"foo": bool, @"bar": u32, @"baz": []const u8, }); defer freeMatch(std.testing.allocator, m); expectEqual(m.@"foo", true); expectEqual(m.@"bar", 2); std.testing.expectEqualStrings(m.@"baz", "nop"); } test "nested" { var fbs = std.io.fixedBufferStream( \\{"nest": { "foo": 1, "bar": false } } ); var str = json.stream(fbs.reader()); const root = try str.root(); expectEqual(root.kind, .Object); const m = try match(std.testing.allocator, root, struct { @"nest.foo": u32, @"nest.bar": bool, }); expectEqual(m.@"nest.foo", 1); expectEqual(m.@"nest.bar", false); } fn expectEqual(actual: anytype, expected: @TypeOf(actual)) void { std.testing.expectEqual(expected, actual); } test "optionals" { var fbs = std.io.fixedBufferStream("{}"); var str = json.stream(fbs.reader()); const root = try str.root(); expectEqual(root.kind, .Object); const m = try match(std.testing.allocator, root, struct { @"foo": ?bool, @"bar": ?u32, @"baz": ?[]const u8, }); defer freeMatch(std.testing.allocator, m); expectEqual(m.@"foo", null); expectEqual(m.@"bar", null); expectEqual(m.@"baz", null); } test "requireds" { var fbs = std.io.fixedBufferStream("{}"); var str = json.stream(fbs.reader()); const root = try str.root(); expectEqual(root.kind, .Object); std.testing.expectError(error.Required, match(std.testing.allocator, root, struct { @"foo": bool, @"bar": u32, @"baz": []const u8, })); }
src/json/path.zig
const std = @import("std"); const mem = @import("./mem.zig"); const traps = @import("./traps.zig"); const Registers = mem.Registers; const ConditionFlags = mem.ConditionFlags; pub const Opcodes = enum(u16) { BR, // 0: branch ADD, // 1: add LD, // 10: load ST, // 11: store JSR, // 100: jump register AND, // 101: bitwise and LDR, // 110: load register STR, // 111: store register RTI, // 1000: unused NOT, // 1001: bitwise not LDI, // 1010: load indirect STI, // 1011: store indirect JMP, // 1100: jump RES, // 1101: reserved (unused) LEA, // 1110: load effective address TRAP, // 1111: execute trap pub fn val(self: Opcodes) u16 { return @enumToInt(self); } }; fn signExtend(x: u16, comptime bit_count: u4) u16 { var a = x; if ((a >> (bit_count - 1)) & 1 == 1) { a |= (@intCast(u16, 0xFFFF) << bit_count); } return a; } test "signExtend" { const one: u16 = 0x0001; try std.testing.expectEqual(signExtend(one, 3), 1); try std.testing.expectEqual(signExtend(one, 1), 0xFFFF); const neg_eight: i5 = -8; const neg_eight_u16: u16 = @as(u16, @bitCast(u5, neg_eight)); try std.testing.expectEqual(signExtend(neg_eight_u16, 4), 0xFFF8); } fn updateFlags(register: u16) void { if (mem.reg[register] == 0) { mem.reg[Registers.COND.val()] = ConditionFlags.ZRO.val(); } else if (mem.reg[register] >> 15 == 1) { mem.reg[Registers.COND.val()] = ConditionFlags.NEG.val(); } else { mem.reg[Registers.COND.val()] = ConditionFlags.POS.val(); } } test "updateFlags" { mem.clearMemory(); const expected = [_]u16{0} ** 10; try std.testing.expectEqualSlices(u16, expected[0..], mem.reg[0..]); mem.reg[Registers.R0.val()] = signExtend(@bitCast(u16, @as(i16, -1)), 1); updateFlags(Registers.R0.val()); try std.testing.expectEqual(mem.reg[Registers.COND.val()], ConditionFlags.NEG.val()); } pub fn addOp(instr: u16) void { const destination_register: u16 = (instr >> 9) & 0b111; const first_operand_register: u16 = (instr >> 6) & 0b111; const imm_mode: u16 = (instr >> 5) & 1; if (imm_mode == 0) { const second_operand_register: u16 = instr & 0b111; var sum: u16 = undefined; _ = @addWithOverflow(u16, mem.reg[first_operand_register], mem.reg[second_operand_register], &sum); mem.reg[destination_register] = sum; } else { // Since in immediate mode, we directly get the value to commit // the add operation against but we only get 5 bits. We should // extend the sign (Two's complement) if we're going to // convert that value to 16 bits. const imm_operand: u16 = signExtend(instr & 0b11111, 5); var sum: u16 = undefined; _ = @addWithOverflow(u16, mem.reg[first_operand_register], imm_operand, &sum); mem.reg[destination_register] = sum; } updateFlags(destination_register); } test "addOp" { mem.clearMemory(); mem.reg[1] = 8; mem.reg[2] = 5; // Add these 2 registers and save to register 0 const instruction_one: u16 = 0b0001000001000010; addOp(instruction_one); const expected_one = [_]u16{13, 8, 5}; try std.testing.expectEqualSlices(u16, expected_one[0..], mem.reg[0..3]); try std.testing.expectEqual(mem.reg[Registers.COND.val()], ConditionFlags.POS.val()); mem.clearMemory(); mem.reg[4] = 50; mem.reg[6] = 32; // Save the sum to register 7 const instruction_two: u16 = 0b0001111100000110; addOp(instruction_two); const expected_two = [_]u16{50, 0, 32, 82}; try std.testing.expectEqualSlices(u16, expected_two[0..], mem.reg[4..8]); try std.testing.expectEqual (mem.reg[Registers.COND.val()], ConditionFlags.POS.val()); mem.clearMemory(); mem.reg[5] = 41; // Adds -5 in immediate mode const instruction_three: u16 = 0b0001000011110101; addOp(instruction_three); const expected_three = [_]u16{65525, 0, 0, 0, 0, 41}; try std.testing.expectEqualSlices(u16, expected_three[0..], mem.reg[0..6]); try std.testing.expectEqual (mem.reg[Registers.COND.val()], ConditionFlags.NEG.val()); } pub fn ldiOp(instr: u16) void { const destination_register = instr >> 9 & 0b111; const pc_offset9: u16 = signExtend(instr & 0x1FF, 9); const pc: u16 = mem.reg[Registers.PC.val()]; mem.reg[destination_register] = mem.read(mem.read(pc_offset9 + pc)); updateFlags(destination_register); } test "ldiOp" { mem.clearMemory(); // LDI op to register 3 from pc_offset9 010010010 mem.memory[147] = 91; mem.memory[146] = 147; const instruction_one = 0b1010011010010010; ldiOp(instruction_one); try std.testing.expectEqual(@as(u16, 91), mem.reg[Registers.R3.val()]); } pub fn andOp(instr: u16) void { const destination_register = instr >> 9 & 0b111; const source_register_1 = instr >> 6 & 0b111; const imm_mode = instr >> 5 & 1; if (imm_mode == 0) { const source_register_2 = instr & 0b111; mem.reg[destination_register] = mem.reg[source_register_1] & mem.reg[source_register_2]; } else { // imm_mode const imm_value = signExtend(instr & 0x1F, 5); mem.reg[destination_register] = mem.reg[source_register_1] & imm_value; } updateFlags(destination_register); } test "andOp" { mem.clearMemory(); // mem.reg 3 = mem.reg 2 AND mem.reg 1 const test_instruction1 = 0b0101011010000001; mem.reg[Registers.R2.val()] = 0b011; mem.reg[Registers.R1.val()] = 0b110; andOp(test_instruction1); try std.testing.expectEqual(@as(u16, 0b010), mem.reg[Registers.R3.val()]); mem.clearMemory(); // mem.reg 0 = mem.reg 1 AND 10101; const test_instruction2 = 0b0101000001110101; mem.reg[Registers.R1.val()] = 60000; andOp(test_instruction2); try std.testing.expectEqual(@as(u16, 0b1110101001100000), mem.reg[Registers.R0.val()]); } pub fn brOp(instr: u16) void { const negative_conditional = instr >> 11 & 1; const zero_conditional = instr >> 10 & 1; const positive_conditional = instr >> 9 & 1; const last_instruction_flag = mem.reg[Registers.COND.val()]; const is_negative = (negative_conditional == 1) and (last_instruction_flag == ConditionFlags.NEG.val()); const is_zero = (zero_conditional == 1) and (last_instruction_flag == ConditionFlags.ZRO.val()); const is_positive = (positive_conditional == 1) and (last_instruction_flag == ConditionFlags.POS.val()); if (is_negative or is_zero or is_positive) { const pc_offset9 = instr & 0x1FF; var sum: u16 = undefined; _ = @addWithOverflow(u16, mem.reg[Registers.PC.val()], signExtend(pc_offset9, 9), &sum); mem.reg[Registers.PC.val()] = sum; } } test "brOp" { mem.clearMemory(); const test_instruction1 = 0b0000010000010000; mem.reg[Registers.COND.val()] = ConditionFlags.ZRO.val(); brOp(test_instruction1); try std.testing.expectEqual(@as(u16, 0b000010000), mem.reg[Registers.PC.val()]); } pub fn rtiOp(_: u16) void { std.os.abort(); } pub fn resOp(_: u16) void { std.os.abort(); } pub fn jmpOp(instr: u16) void { const base_register = instr >> 6 & 0b111; mem.reg[Registers.PC.val()] = mem.reg[base_register]; } // special case of jmp pub fn retOp() void { jmpOp(0b0000000111000000); } test "jmpOp" { mem.clearMemory(); mem.reg[Registers.R3.val()] = 0b0000111100000000; const test_instruction1 = 0b1100000011000000; jmpOp(test_instruction1); try std.testing.expectEqual(@as(u16, 0b0000111100000000), mem.reg[Registers.PC.val()]); } pub fn jsrOp(instr: u16) void { const current_pc = mem.reg[Registers.PC.val()]; mem.reg[Registers.R7.val()] = current_pc; const offset_mode = instr >> 11 & 1; if (offset_mode == 0) { const base_register = instr >> 6 & 0x7; mem.reg[Registers.PC.val()] = mem.reg[base_register]; } else { const pc_offset11 = instr & 0x7FF; var sum: u16 = undefined; _ = @addWithOverflow(u16, current_pc, signExtend(pc_offset11, 11), &sum); mem.reg[Registers.PC.val()] = sum; } } test "jsrOp" { mem.clearMemory(); mem.reg[Registers.R3.val()] = 22222; const test_instruction1 = 0b0100000011000000; jsrOp(test_instruction1); try std.testing.expectEqual(@as(u16, 22222), mem.reg[Registers.PC.val()]); mem.clearMemory(); mem.reg[Registers.PC.val()] = 80; const test_instruction2 = 0b0100100000001111; jsrOp(test_instruction2); try std.testing.expectEqual(@as(u16, 80), mem.reg[Registers.R7.val()]); try std.testing.expectEqual(@as(u16, 95), mem.reg[Registers.PC.val()]); } pub fn ldOp(instr: u16) void { const destination_register = instr >> 9 & 0x7; const pc_offset9 = instr & 0xFF; const current_pc = mem.reg[Registers.PC.val()]; mem.reg[destination_register] = mem.read(current_pc + signExtend(pc_offset9, 9)); updateFlags(destination_register); } test "ldOp" { mem.clearMemory(); mem.memory[15] = 151; const test_instruction1 = 0b0010100000001111; ldOp(test_instruction1); try std.testing.expectEqual(@as(u16, 151), mem.reg[Registers.R4.val()]); } pub fn ldrOp(instr: u16) void { const destination_register = instr >> 9 & 0x7; const base_register = instr >> 6 & 0x7; const offset6 = signExtend(instr & 0x3F, 6); mem.reg[destination_register] = mem.read(mem.reg[base_register] + offset6); updateFlags(destination_register); } test "ldrOp" { mem.clearMemory(); mem.memory[32118] = 6; mem.reg[Registers.R3.val()] = 32100; const test_instruction1 = 0b0110101011010010; ldrOp(test_instruction1); try std.testing.expectEqual(@as(u16, 6), mem.reg[Registers.R5.val()]); } pub fn trapOp(instr: u16) void { const trap_vector = instr & 0xFF; traps.run(trap_vector); // mem.reg[Registers.R7.val()] = mem.reg[Registers.PC.val()]; // const trap_vector = instr & 0xFF; // const start_address = mem.read(trap_vector); // mem.reg[Registers.PC.val()] = start_address; // // run // mem.reg[Registers.PC.val()] = mem.reg[Registers.R7.val()]; } // TODO test "trapOp" {} pub fn stOp(instr: u16) void { const source_register = instr >> 9 & 0x7; const pc_offset9 = instr & 0x1FF; const current_pc = mem.reg[Registers.PC.val()]; var sum: u16 = undefined; _ = @addWithOverflow(u16, current_pc, signExtend(pc_offset9, 9), &sum); mem.write(sum, mem.reg[source_register]); } // TODO test "stOp" {} pub fn stiOp(instr: u16) void { const source_register = instr >> 8 & 0x7; const pc_offset9 = instr & 0x1FF; const current_pc = mem.reg[Registers.PC.val()]; mem.write(mem.read(current_pc + signExtend(pc_offset9, 9)), source_register); } // TODO test "stiOp" {} pub fn strOp(instr: u16) void { const source_register = instr >> 9 & 0x7; const base_register = instr >> 6 & 0x7; const base_value = mem.reg[base_register]; const source_value = mem.reg[source_register]; const offset6 = instr & 0x3F; var sum: u16 = undefined; _ = @addWithOverflow(u16, base_value, signExtend(offset6, 6), &sum); mem.write(sum, source_value); } // TODO test "strOp" {} pub fn leaOp(instr: u16) void { const destination_register = instr >> 9 & 0x7; const pc_offset9 = instr & 0x1FF; const current_pc = mem.reg[Registers.PC.val()]; mem.reg[destination_register] = current_pc + signExtend(pc_offset9, 9); updateFlags(destination_register); } // TODO test "leaOp" {} pub fn notOp(instr: u16) void { const destination_register = instr >> 9 & 0x7; const source_register = instr >> 6 & 0x7; const source_value = mem.reg[source_register]; mem.reg[destination_register] = ~source_value; updateFlags(destination_register); } // TODO test "notOp" {} fn assert_instr_fn(comptime instr_fn: anytype) void { // try std.testing.expect(@typeInfo(instr_fn).Fn.args.len == 1); // try std.testing.expect(@typeInfo(instr_fn).Fn.args[0].arg_type.? == u16); try std.testing.expectEqual(@typeInfo(@TypeOf(instr_fn)), @typeInfo(@TypeOf(trapOp))); } comptime { assert_instr_fn(addOp); assert_instr_fn(brOp); assert_instr_fn(ldOp); assert_instr_fn(jsrOp); assert_instr_fn(andOp); assert_instr_fn(ldrOp); assert_instr_fn(rtiOp); assert_instr_fn(ldiOp); assert_instr_fn(jmpOp); assert_instr_fn(resOp); assert_instr_fn(trapOp); assert_instr_fn(stOp); assert_instr_fn(stiOp); assert_instr_fn(strOp); assert_instr_fn(leaOp); assert_instr_fn(notOp); }
src/ops.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); const Registers = [4]u32; const Opcode = enum { addi, addr, muli, mulr, bani, banr, bori, borr, setr, seti, gtir, gtri, gtrr, eqir, eqri, eqrr }; fn eval(op: Opcode, par: [3]u32, r: Registers) Registers { var o = r; switch (op) { .addi => o[par[2]] = r[par[0]] + par[1], .addr => o[par[2]] = r[par[0]] + r[par[1]], .muli => o[par[2]] = r[par[0]] * par[1], .mulr => o[par[2]] = r[par[0]] * r[par[1]], .bani => o[par[2]] = r[par[0]] & par[1], .banr => o[par[2]] = r[par[0]] & r[par[1]], .bori => o[par[2]] = r[par[0]] | par[1], .borr => o[par[2]] = r[par[0]] | r[par[1]], .setr => o[par[2]] = r[par[0]], .seti => o[par[2]] = par[0], .gtir => o[par[2]] = if (par[0] > r[par[1]]) @as(u32, 1) else @as(u32, 0), .gtri => o[par[2]] = if (r[par[0]] > par[1]) @as(u32, 1) else @as(u32, 0), .gtrr => o[par[2]] = if (r[par[0]] > r[par[1]]) @as(u32, 1) else @as(u32, 0), .eqir => o[par[2]] = if (par[0] == r[par[1]]) @as(u32, 1) else @as(u32, 0), .eqri => o[par[2]] = if (r[par[0]] == par[1]) @as(u32, 1) else @as(u32, 0), .eqrr => o[par[2]] = if (r[par[0]] == r[par[1]]) @as(u32, 1) else @as(u32, 0), } return o; } pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); var opcode_table = [_][16]bool{[_]bool{true} ** 16} ** 16; var it = std.mem.tokenize(u8, input_text, "\n\r"); const ans1 = ans: { var nb_triple_abiguous: u32 = 0; var it_rollback = it; while (it.next()) |line0| { var before: Registers = undefined; var after: Registers = undefined; var op: u4 = undefined; var par: [3]u32 = undefined; if (tools.match_pattern("Before: [{}, {}, {}, {}]", line0)) |fields| { before[0] = @intCast(u32, fields[0].imm); before[1] = @intCast(u32, fields[1].imm); before[2] = @intCast(u32, fields[2].imm); before[3] = @intCast(u32, fields[3].imm); } else { break; } const line1 = it.next().?; if (tools.match_pattern("{} {} {} {}", line1)) |fields| { op = @intCast(u4, fields[0].imm); par[0] = @intCast(u32, fields[1].imm); par[1] = @intCast(u32, fields[2].imm); par[2] = @intCast(u32, fields[3].imm); } else unreachable; const line2 = it.next().?; if (tools.match_pattern("After: [{}, {}, {}, {}]", line2)) |fields| { after[0] = @intCast(u32, fields[0].imm); after[1] = @intCast(u32, fields[1].imm); after[2] = @intCast(u32, fields[2].imm); after[3] = @intCast(u32, fields[3].imm); } else unreachable; var nb: u32 = 0; for (opcode_table[op]) |*b, i| { const res = eval(@intToEnum(Opcode, @intCast(u4, i)), par, before); if (!std.mem.eql(u32, &res, &after)) { b.* = false; } else { nb += 1; } } if (nb >= 3) nb_triple_abiguous += 1; it_rollback = it; } it = it_rollback; break :ans nb_triple_abiguous; }; const ans2 = ans: { var opcodes: [16]Opcode = undefined; var done = false; while (!done) { done = true; for (opcode_table) |table, op| { var code: u4 = undefined; var nb: u32 = 0; for (table) |b, i| { if (b) { nb += 1; code = @intCast(u4, i); } } if (nb == 1) { opcodes[op] = @intToEnum(Opcode, code); for (opcode_table) |*t| { t[code] = false; } } else if (nb > 1) { done = false; } } } //for (opcodes) |op, code| { // std.debug.print("opcode n°{} = {}\n", .{ code, op }); //} var reg: Registers = .{ 0, 0, 0, 0 }; while (it.next()) |line| { if (tools.match_pattern("{} {} {} {}", line)) |fields| { const op = @intCast(u4, fields[0].imm); const par = [3]u32{ @intCast(u32, fields[1].imm), @intCast(u32, fields[2].imm), @intCast(u32, fields[3].imm), }; reg = eval(opcodes[op], par, reg); } else unreachable; } break :ans reg[0]; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2018/input_day16.txt", run);
2018/day16.zig
const std = @import("std"); const tools = @import("tools"); const with_trace = true; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } pub fn main() anyerror!void { const stdout = std.io.getStdOut().writer(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const md5 = std.crypto.Md5.init(); const Vec2 = tools.Vec2; const BFS = tools.BestFirstSearch([]const u8, Vec2); var bfs = BFS.init(allocator); try bfs.insert(.{ .rating = 0, .steps = 0, .state = "", .trace = Vec2{ .x = 0, .y = 0 }, }); var longest: usize = 0; var shortestfound = false; while (bfs.pop()) |node| { const p: Vec2 = node.trace; if (p.x == 3 and p.y == 3) { if (!shortestfound) { shortestfound = true; try stdout.print("shortest='{}'\n", .{node.state}); } longest = if (node.state.len > longest) node.state.len else longest; continue; } const doors = blk: { var buf: [4096]u8 = undefined; var input = std.fmt.bufPrint(&buf, "ulqzkmiv{}", .{node.state}) catch unreachable; var hash: [std.crypto.Md5.digest_length]u8 = undefined; std.crypto.Md5.hash(input, &hash); break :blk [4]bool{ ((hash[0] >> 4) & 0xF) >= 11, ((hash[0] >> 0) & 0xF) >= 11, ((hash[1] >> 4) & 0xF) >= 11, ((hash[1] >> 0) & 0xF) >= 11, }; }; for (doors) |d, i| { if (!d) continue; const dirs = [4]Vec2{ .{ .x = 0, .y = -1 }, .{ .x = 0, .y = 1 }, .{ .x = -1, .y = 0 }, .{ .x = 1, .y = 0 } }; const letters = [4]u8{ 'U', 'D', 'L', 'R' }; const p1 = Vec2{ .x = p.x + dirs[i].x, .y = p.y + dirs[i].y }; if (p1.x < 0 or p1.y < 0 or p1.x > 3 or p1.y > 3) continue; const seq = try allocator.alloc(u8, node.state.len + 1); std.mem.copy(u8, seq[0 .. seq.len - 1], node.state); seq[seq.len - 1] = letters[i]; try bfs.insert(.{ .rating = node.rating + 1, .steps = node.steps + 1, .state = seq, .trace = p1, }); } } try stdout.print("longest={}\n", .{longest}); }
2016/day17.zig
const std = @import("std"); const Pkg = std.build.Pkg; const pkgs = struct { const util = Pkg { .name = "util", .path = "src/util/_.zig", }; const compile = Pkg { .name = "compile", .path = "src/compile/_.zig", .dependencies = &.{ util }, }; const cli = Pkg { .name = "cli", .path = "src/cli/_.zig", .dependencies = &.{ util, compile }, }; }; const pkg_list: []const Pkg = blk: { const decls = std.meta.declarations(pkgs); var result: [decls.len]Pkg = undefined; inline for (decls) |decl, i| { result[i] = @field(pkgs, decl.name); } break :blk &result; }; pub fn build(b: *std.build.Builder) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const exe = b.addExecutable("umbra", "src/main.zig"); exe.setTarget(target); for (pkg_list) |pkg| { exe.addPackage(pkg); } exe.setBuildMode(mode); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const test_step = b.step("test", "Run library tests"); for (pkg_list) |pkg| { var pkg_test_step = b.addTest(pkg.path); pkg_test_step.setBuildMode(mode); var log_name_step = b.addLog("\x1b[7mTesting Package {s} ({s})\x1b[0m\n", .{pkg.name, pkg.path}); pkg_test_step.step.dependOn(&log_name_step.step); if (pkg.dependencies) |dependencies| { for (dependencies) |dep| { pkg_test_step.addPackage(dep); } } test_step.dependOn(&pkg_test_step.step); } } fn createPackageTestStep(b: *std.build.Builder, pkg: std.build.Pkg) *std.build.Step { }
build.zig
const vk = @import("vk.zig"); pub const GLFWmonitor = @OpaqueType(); pub const GLFWwindow = @OpaqueType(); pub const GLFWcursor = @OpaqueType(); pub const GLFWglproc = ?extern fn () void; pub const GLFWvkproc = ?extern fn () void; pub const GLFWerrorfun = ?extern fn (c_int, ?[*:0]const u8) void; pub const GLFWwindowposfun = ?extern fn (?*GLFWwindow, c_int, c_int) void; pub const GLFWwindowsizefun = ?extern fn (?*GLFWwindow, c_int, c_int) void; pub const GLFWwindowclosefun = ?extern fn (?*GLFWwindow) void; pub const GLFWwindowrefreshfun = ?extern fn (?*GLFWwindow) void; pub const GLFWwindowfocusfun = ?extern fn (?*GLFWwindow, c_int) void; pub const GLFWwindowiconifyfun = ?extern fn (?*GLFWwindow, c_int) void; pub const GLFWframebuffersizefun = ?extern fn (?*GLFWwindow, c_int, c_int) void; pub const GLFWmousebuttonfun = ?extern fn (?*GLFWwindow, c_int, c_int, c_int) void; pub const GLFWcursorposfun = ?extern fn (?*GLFWwindow, f64, f64) void; pub const GLFWcursorenterfun = ?extern fn (?*GLFWwindow, c_int) void; pub const GLFWscrollfun = ?extern fn (?*GLFWwindow, f64, f64) void; pub const GLFWkeyfun = ?extern fn (?*GLFWwindow, c_int, c_int, c_int, c_int) void; pub const GLFWcharfun = ?extern fn (?*GLFWwindow, c_uint) void; pub const GLFWcharmodsfun = ?extern fn (?*GLFWwindow, c_uint, c_int) void; pub const GLFWdropfun = ?extern fn (?*GLFWwindow, c_int, ?[*](?[*:0]const u8)) void; pub const GLFWmonitorfun = ?extern fn (?*GLFWmonitor, c_int) void; pub const GLFWjoystickfun = ?extern fn (c_int, c_int) void; pub const GLFWvidmode = extern struct { width: c_int, height: c_int, redBits: c_int, greenBits: c_int, blueBits: c_int, refreshRate: c_int, }; pub const GLFWgammaramp = extern struct { red: ?[*]c_ushort, green: ?[*]c_ushort, blue: ?[*]c_ushort, size: c_uint, }; pub const GLFWimage = extern struct { width: c_int, height: c_int, pixels: ?[*]u8, }; pub extern fn glfwInit() c_int; pub extern fn glfwTerminate() void; pub extern fn glfwGetVersion(major: ?[*]c_int, minor: ?[*]c_int, rev: ?[*]c_int) void; pub extern fn glfwGetVersionString() ?[*:0]const u8; pub extern fn glfwSetErrorCallback(cbfun: GLFWerrorfun) GLFWerrorfun; pub extern fn glfwGetMonitors(count: ?[*]c_int) ?[*](?*GLFWmonitor); pub extern fn glfwGetPrimaryMonitor() ?*GLFWmonitor; pub extern fn glfwGetMonitorPos(monitor: ?*GLFWmonitor, xpos: ?[*]c_int, ypos: ?[*]c_int) void; pub extern fn glfwGetMonitorPhysicalSize(monitor: ?*GLFWmonitor, widthMM: ?[*]c_int, heightMM: ?[*]c_int) void; pub extern fn glfwGetMonitorName(monitor: ?*GLFWmonitor) ?[*:0]const u8; pub extern fn glfwSetMonitorCallback(cbfun: GLFWmonitorfun) GLFWmonitorfun; pub extern fn glfwGetVideoModes(monitor: ?*GLFWmonitor, count: ?[*]c_int) ?[*]const GLFWvidmode; pub extern fn glfwGetVideoMode(monitor: ?*GLFWmonitor) ?[*]const GLFWvidmode; pub extern fn glfwSetGamma(monitor: ?*GLFWmonitor, gamma: f32) void; pub extern fn glfwGetGammaRamp(monitor: ?*GLFWmonitor) ?[*]const GLFWgammaramp; pub extern fn glfwSetGammaRamp(monitor: ?*GLFWmonitor, ramp: ?[*]const GLFWgammaramp) void; pub extern fn glfwDefaultWindowHints() void; pub extern fn glfwWindowHint(hint: c_int, value: c_int) void; pub extern fn glfwCreateWindow(width: c_int, height: c_int, title: ?[*:0]const u8, monitor: ?*GLFWmonitor, share: ?*GLFWwindow) ?*GLFWwindow; pub extern fn glfwDestroyWindow(window: ?*GLFWwindow) void; pub extern fn glfwWindowShouldClose(window: ?*GLFWwindow) c_int; pub extern fn glfwSetWindowShouldClose(window: ?*GLFWwindow, value: c_int) void; pub extern fn glfwSetWindowTitle(window: ?*GLFWwindow, title: ?[*:0]const u8) void; pub extern fn glfwSetWindowIcon(window: ?*GLFWwindow, count: c_int, images: ?[*]const GLFWimage) void; pub extern fn glfwGetWindowPos(window: ?*GLFWwindow, xpos: ?[*]c_int, ypos: ?[*]c_int) void; pub extern fn glfwSetWindowPos(window: ?*GLFWwindow, xpos: c_int, ypos: c_int) void; pub extern fn glfwGetWindowSize(window: ?*GLFWwindow, width: ?[*]c_int, height: ?[*]c_int) void; pub extern fn glfwSetWindowSizeLimits(window: ?*GLFWwindow, minwidth: c_int, minheight: c_int, maxwidth: c_int, maxheight: c_int) void; pub extern fn glfwSetWindowAspectRatio(window: ?*GLFWwindow, numer: c_int, denom: c_int) void; pub extern fn glfwSetWindowSize(window: ?*GLFWwindow, width: c_int, height: c_int) void; pub extern fn glfwGetFramebufferSize(window: ?*GLFWwindow, width: ?[*]c_int, height: ?[*]c_int) void; pub extern fn glfwGetWindowFrameSize(window: ?*GLFWwindow, left: ?[*]c_int, top: ?[*]c_int, right: ?[*]c_int, bottom: ?[*]c_int) void; pub extern fn glfwIconifyWindow(window: ?*GLFWwindow) void; pub extern fn glfwRestoreWindow(window: ?*GLFWwindow) void; pub extern fn glfwMaximizeWindow(window: ?*GLFWwindow) void; pub extern fn glfwShowWindow(window: ?*GLFWwindow) void; pub extern fn glfwHideWindow(window: ?*GLFWwindow) void; pub extern fn glfwFocusWindow(window: ?*GLFWwindow) void; pub extern fn glfwGetWindowMonitor(window: ?*GLFWwindow) ?*GLFWmonitor; pub extern fn glfwSetWindowMonitor(window: ?*GLFWwindow, monitor: ?*GLFWmonitor, xpos: c_int, ypos: c_int, width: c_int, height: c_int, refreshRate: c_int) void; pub extern fn glfwGetWindowAttrib(window: ?*GLFWwindow, attrib: c_int) c_int; pub extern fn glfwSetWindowUserPointer(window: ?*GLFWwindow, pointer: ?*c_void) void; pub extern fn glfwGetWindowUserPointer(window: ?*GLFWwindow) ?*c_void; pub extern fn glfwSetWindowPosCallback(window: ?*GLFWwindow, cbfun: GLFWwindowposfun) GLFWwindowposfun; pub extern fn glfwSetWindowSizeCallback(window: ?*GLFWwindow, cbfun: GLFWwindowsizefun) GLFWwindowsizefun; pub extern fn glfwSetWindowCloseCallback(window: ?*GLFWwindow, cbfun: GLFWwindowclosefun) GLFWwindowclosefun; pub extern fn glfwSetWindowRefreshCallback(window: ?*GLFWwindow, cbfun: GLFWwindowrefreshfun) GLFWwindowrefreshfun; pub extern fn glfwSetWindowFocusCallback(window: ?*GLFWwindow, cbfun: GLFWwindowfocusfun) GLFWwindowfocusfun; pub extern fn glfwSetWindowIconifyCallback(window: ?*GLFWwindow, cbfun: GLFWwindowiconifyfun) GLFWwindowiconifyfun; pub extern fn glfwSetFramebufferSizeCallback(window: ?*GLFWwindow, cbfun: GLFWframebuffersizefun) GLFWframebuffersizefun; pub extern fn glfwPollEvents() void; pub extern fn glfwWaitEvents() void; pub extern fn glfwWaitEventsTimeout(timeout: f64) void; pub extern fn glfwPostEmptyEvent() void; pub extern fn glfwGetInputMode(window: ?*GLFWwindow, mode: c_int) c_int; pub extern fn glfwSetInputMode(window: ?*GLFWwindow, mode: c_int, value: c_int) void; pub extern fn glfwGetKeyName(key: c_int, scancode: c_int) ?[*:0]const u8; pub extern fn glfwGetKey(window: ?*GLFWwindow, key: c_int) c_int; pub extern fn glfwGetMouseButton(window: ?*GLFWwindow, button: c_int) c_int; pub extern fn glfwGetCursorPos(window: ?*GLFWwindow, xpos: ?[*]f64, ypos: ?[*]f64) void; pub extern fn glfwSetCursorPos(window: ?*GLFWwindow, xpos: f64, ypos: f64) void; pub extern fn glfwCreateCursor(image: ?[*]const GLFWimage, xhot: c_int, yhot: c_int) ?*GLFWcursor; pub extern fn glfwCreateStandardCursor(shape: c_int) ?*GLFWcursor; pub extern fn glfwDestroyCursor(cursor: ?*GLFWcursor) void; pub extern fn glfwSetCursor(window: ?*GLFWwindow, cursor: ?*GLFWcursor) void; pub extern fn glfwSetKeyCallback(window: ?*GLFWwindow, cbfun: GLFWkeyfun) GLFWkeyfun; pub extern fn glfwSetCharCallback(window: ?*GLFWwindow, cbfun: GLFWcharfun) GLFWcharfun; pub extern fn glfwSetCharModsCallback(window: ?*GLFWwindow, cbfun: GLFWcharmodsfun) GLFWcharmodsfun; pub extern fn glfwSetMouseButtonCallback(window: ?*GLFWwindow, cbfun: GLFWmousebuttonfun) GLFWmousebuttonfun; pub extern fn glfwSetCursorPosCallback(window: ?*GLFWwindow, cbfun: GLFWcursorposfun) GLFWcursorposfun; pub extern fn glfwSetCursorEnterCallback(window: ?*GLFWwindow, cbfun: GLFWcursorenterfun) GLFWcursorenterfun; pub extern fn glfwSetScrollCallback(window: ?*GLFWwindow, cbfun: GLFWscrollfun) GLFWscrollfun; pub extern fn glfwSetDropCallback(window: ?*GLFWwindow, cbfun: GLFWdropfun) GLFWdropfun; pub extern fn glfwJoystickPresent(joy: c_int) c_int; pub extern fn glfwGetJoystickAxes(joy: c_int, count: ?[*]c_int) ?[*]const f32; pub extern fn glfwGetJoystickButtons(joy: c_int, count: ?[*]c_int) ?[*]const u8; pub extern fn glfwGetJoystickName(joy: c_int) ?[*:0]const u8; pub extern fn glfwSetJoystickCallback(cbfun: GLFWjoystickfun) GLFWjoystickfun; pub extern fn glfwSetClipboardString(window: ?*GLFWwindow, string: ?[*:0]const u8) void; pub extern fn glfwGetClipboardString(window: ?*GLFWwindow) ?[*:0]const u8; pub extern fn glfwGetTime() f64; pub extern fn glfwSetTime(time: f64) void; pub extern fn glfwGetTimerValue() u64; pub extern fn glfwGetTimerFrequency() u64; pub extern fn glfwMakeContextCurrent(window: ?*GLFWwindow) void; pub extern fn glfwGetCurrentContext() ?*GLFWwindow; pub extern fn glfwSwapBuffers(window: ?*GLFWwindow) void; pub extern fn glfwSwapInterval(interval: c_int) void; pub extern fn glfwExtensionSupported(extension: ?[*:0]const u8) c_int; pub extern fn glfwGetProcAddress(procname: ?[*:0]const u8) GLFWglproc; pub extern fn glfwVulkanSupported() c_int; pub extern fn glfwGetRequiredInstanceExtensions(count: *u32) [*]const [*:0]const u8; pub extern fn glfwGetInstanceProcAddress(instance: vk.Instance, procname: ?[*:0]const u8) GLFWvkproc; pub extern fn glfwGetPhysicalDevicePresentationSupport(instance: vk.Instance, device: vk.PhysicalDevice, queuefamily: u32) c_int; pub extern fn glfwCreateWindowSurface(instance: vk.Instance, window: *GLFWwindow, allocator: ?*const vk.AllocationCallbacks, surface: *vk.SurfaceKHR) vk.Result; pub const GLFW_ACCUM_ALPHA_BITS = 135178; pub const GLFW_ACCUM_BLUE_BITS = 135177; pub const GLFW_ACCUM_GREEN_BITS = 135176; pub const GLFW_ACCUM_RED_BITS = 135175; pub const GLFW_ALPHA_BITS = 135172; pub const GLFW_ANY_RELEASE_BEHAVIOR = 0; pub const GLFW_API_UNAVAILABLE = 65542; pub const GLFW_ARROW_CURSOR = 221185; pub const GLFW_AUTO_ICONIFY = 131078; pub const GLFW_AUX_BUFFERS = 135179; pub const GLFW_BLUE_BITS = 135171; pub const GLFW_CLIENT_API = 139265; pub const GLFW_CONNECTED = 262145; pub const GLFW_CONTEXT_CREATION_API = 139275; pub const GLFW_CONTEXT_NO_ERROR = 139274; pub const GLFW_CONTEXT_RELEASE_BEHAVIOR = 139273; pub const GLFW_CONTEXT_REVISION = 139268; pub const GLFW_CONTEXT_ROBUSTNESS = 139269; pub const GLFW_CONTEXT_VERSION_MAJOR = 139266; pub const GLFW_CONTEXT_VERSION_MINOR = 139267; pub const GLFW_CROSSHAIR_CURSOR = 221187; pub const GLFW_CURSOR = 208897; pub const GLFW_CURSOR_DISABLED = 212995; pub const GLFW_CURSOR_HIDDEN = 212994; pub const GLFW_CURSOR_NORMAL = 212993; pub const GLFW_DECORATED = 131077; pub const GLFW_DEPTH_BITS = 135173; pub const GLFW_DISCONNECTED = 262146; pub const GLFW_DONT_CARE = -1; pub const GLFW_DOUBLEBUFFER = 135184; pub const GLFW_EGL_CONTEXT_API = 221186; pub const GLFW_FALSE = 0; pub const GLFW_FLOATING = 131079; pub const GLFW_FOCUSED = 131073; pub const GLFW_FORMAT_UNAVAILABLE = 65545; pub const GLFW_GREEN_BITS = 135170; pub const GLFW_HAND_CURSOR = 221188; pub const GLFW_HRESIZE_CURSOR = 221189; pub const GLFW_IBEAM_CURSOR = 221186; pub const GLFW_ICONIFIED = 131074; pub const GLFW_INVALID_ENUM = 65539; pub const GLFW_INVALID_VALUE = 65540; pub const GLFW_JOYSTICK_1 = 0; pub const GLFW_JOYSTICK_10 = 9; pub const GLFW_JOYSTICK_11 = 10; pub const GLFW_JOYSTICK_12 = 11; pub const GLFW_JOYSTICK_13 = 12; pub const GLFW_JOYSTICK_14 = 13; pub const GLFW_JOYSTICK_15 = 14; pub const GLFW_JOYSTICK_16 = 15; pub const GLFW_JOYSTICK_2 = 1; pub const GLFW_JOYSTICK_3 = 2; pub const GLFW_JOYSTICK_4 = 3; pub const GLFW_JOYSTICK_5 = 4; pub const GLFW_JOYSTICK_6 = 5; pub const GLFW_JOYSTICK_7 = 6; pub const GLFW_JOYSTICK_8 = 7; pub const GLFW_JOYSTICK_9 = 8; pub const GLFW_JOYSTICK_LAST = GLFW_JOYSTICK_16; pub const GLFW_KEY_0 = 48; pub const GLFW_KEY_1 = 49; pub const GLFW_KEY_2 = 50; pub const GLFW_KEY_3 = 51; pub const GLFW_KEY_4 = 52; pub const GLFW_KEY_5 = 53; pub const GLFW_KEY_6 = 54; pub const GLFW_KEY_7 = 55; pub const GLFW_KEY_8 = 56; pub const GLFW_KEY_9 = 57; pub const GLFW_KEY_A = 65; pub const GLFW_KEY_APOSTROPHE = 39; pub const GLFW_KEY_B = 66; pub const GLFW_KEY_BACKSLASH = 92; pub const GLFW_KEY_BACKSPACE = 259; pub const GLFW_KEY_C = 67; pub const GLFW_KEY_CAPS_LOCK = 280; pub const GLFW_KEY_COMMA = 44; pub const GLFW_KEY_D = 68; pub const GLFW_KEY_DELETE = 261; pub const GLFW_KEY_DOWN = 264; pub const GLFW_KEY_E = 69; pub const GLFW_KEY_END = 269; pub const GLFW_KEY_ENTER = 257; pub const GLFW_KEY_EQUAL = 61; pub const GLFW_KEY_ESCAPE = 256; pub const GLFW_KEY_F = 70; pub const GLFW_KEY_F1 = 290; pub const GLFW_KEY_F10 = 299; pub const GLFW_KEY_F11 = 300; pub const GLFW_KEY_F12 = 301; pub const GLFW_KEY_F13 = 302; pub const GLFW_KEY_F14 = 303; pub const GLFW_KEY_F15 = 304; pub const GLFW_KEY_F16 = 305; pub const GLFW_KEY_F17 = 306; pub const GLFW_KEY_F18 = 307; pub const GLFW_KEY_F19 = 308; pub const GLFW_KEY_F2 = 291; pub const GLFW_KEY_F20 = 309; pub const GLFW_KEY_F21 = 310; pub const GLFW_KEY_F22 = 311; pub const GLFW_KEY_F23 = 312; pub const GLFW_KEY_F24 = 313; pub const GLFW_KEY_F25 = 314; pub const GLFW_KEY_F3 = 292; pub const GLFW_KEY_F4 = 293; pub const GLFW_KEY_F5 = 294; pub const GLFW_KEY_F6 = 295; pub const GLFW_KEY_F7 = 296; pub const GLFW_KEY_F8 = 297; pub const GLFW_KEY_F9 = 298; pub const GLFW_KEY_G = 71; pub const GLFW_KEY_GRAVE_ACCENT = 96; pub const GLFW_KEY_H = 72; pub const GLFW_KEY_HOME = 268; pub const GLFW_KEY_I = 73; pub const GLFW_KEY_INSERT = 260; pub const GLFW_KEY_J = 74; pub const GLFW_KEY_K = 75; pub const GLFW_KEY_KP_0 = 320; pub const GLFW_KEY_KP_1 = 321; pub const GLFW_KEY_KP_2 = 322; pub const GLFW_KEY_KP_3 = 323; pub const GLFW_KEY_KP_4 = 324; pub const GLFW_KEY_KP_5 = 325; pub const GLFW_KEY_KP_6 = 326; pub const GLFW_KEY_KP_7 = 327; pub const GLFW_KEY_KP_8 = 328; pub const GLFW_KEY_KP_9 = 329; pub const GLFW_KEY_KP_ADD = 334; pub const GLFW_KEY_KP_DECIMAL = 330; pub const GLFW_KEY_KP_DIVIDE = 331; pub const GLFW_KEY_KP_ENTER = 335; pub const GLFW_KEY_KP_EQUAL = 336; pub const GLFW_KEY_KP_MULTIPLY = 332; pub const GLFW_KEY_KP_SUBTRACT = 333; pub const GLFW_KEY_L = 76; pub const GLFW_KEY_LAST = GLFW_KEY_MENU; pub const GLFW_KEY_LEFT = 263; pub const GLFW_KEY_LEFT_ALT = 342; pub const GLFW_KEY_LEFT_BRACKET = 91; pub const GLFW_KEY_LEFT_CONTROL = 341; pub const GLFW_KEY_LEFT_SHIFT = 340; pub const GLFW_KEY_LEFT_SUPER = 343; pub const GLFW_KEY_M = 77; pub const GLFW_KEY_MENU = 348; pub const GLFW_KEY_MINUS = 45; pub const GLFW_KEY_N = 78; pub const GLFW_KEY_NUM_LOCK = 282; pub const GLFW_KEY_O = 79; pub const GLFW_KEY_P = 80; pub const GLFW_KEY_PAGE_DOWN = 267; pub const GLFW_KEY_PAGE_UP = 266; pub const GLFW_KEY_PAUSE = 284; pub const GLFW_KEY_PERIOD = 46; pub const GLFW_KEY_PRINT_SCREEN = 283; pub const GLFW_KEY_Q = 81; pub const GLFW_KEY_R = 82; pub const GLFW_KEY_RIGHT = 262; pub const GLFW_KEY_RIGHT_ALT = 346; pub const GLFW_KEY_RIGHT_BRACKET = 93; pub const GLFW_KEY_RIGHT_CONTROL = 345; pub const GLFW_KEY_RIGHT_SHIFT = 344; pub const GLFW_KEY_RIGHT_SUPER = 347; pub const GLFW_KEY_S = 83; pub const GLFW_KEY_SCROLL_LOCK = 281; pub const GLFW_KEY_SEMICOLON = 59; pub const GLFW_KEY_SLASH = 47; pub const GLFW_KEY_SPACE = 32; pub const GLFW_KEY_T = 84; pub const GLFW_KEY_TAB = 258; pub const GLFW_KEY_U = 85; pub const GLFW_KEY_UNKNOWN = -1; pub const GLFW_KEY_UP = 265; pub const GLFW_KEY_V = 86; pub const GLFW_KEY_W = 87; pub const GLFW_KEY_WORLD_1 = 161; pub const GLFW_KEY_WORLD_2 = 162; pub const GLFW_KEY_X = 88; pub const GLFW_KEY_Y = 89; pub const GLFW_KEY_Z = 90; pub const GLFW_LOSE_CONTEXT_ON_RESET = 200706; pub const GLFW_MAXIMIZED = 131080; pub const GLFW_MOD_ALT = 4; pub const GLFW_MOD_CONTROL = 2; pub const GLFW_MOD_SHIFT = 1; pub const GLFW_MOD_SUPER = 8; pub const GLFW_MOUSE_BUTTON_1 = 0; pub const GLFW_MOUSE_BUTTON_2 = 1; pub const GLFW_MOUSE_BUTTON_3 = 2; pub const GLFW_MOUSE_BUTTON_4 = 3; pub const GLFW_MOUSE_BUTTON_5 = 4; pub const GLFW_MOUSE_BUTTON_6 = 5; pub const GLFW_MOUSE_BUTTON_7 = 6; pub const GLFW_MOUSE_BUTTON_8 = 7; pub const GLFW_MOUSE_BUTTON_LAST = GLFW_MOUSE_BUTTON_8; pub const GLFW_MOUSE_BUTTON_LEFT = GLFW_MOUSE_BUTTON_1; pub const GLFW_MOUSE_BUTTON_MIDDLE = GLFW_MOUSE_BUTTON_3; pub const GLFW_MOUSE_BUTTON_RIGHT = GLFW_MOUSE_BUTTON_2; pub const GLFW_NATIVE_CONTEXT_API = 221185; pub const GLFW_NOT_INITIALIZED = 65537; pub const GLFW_NO_API = 0; pub const GLFW_NO_CURRENT_CONTEXT = 65538; pub const GLFW_NO_RESET_NOTIFICATION = 200705; pub const GLFW_NO_ROBUSTNESS = 0; pub const GLFW_NO_WINDOW_CONTEXT = 65546; pub const GLFW_OPENGL_ANY_PROFILE = 0; pub const GLFW_OPENGL_API = 196609; pub const GLFW_OPENGL_COMPAT_PROFILE = 204802; pub const GLFW_OPENGL_CORE_PROFILE = 204801; pub const GLFW_OPENGL_DEBUG_CONTEXT = 139271; pub const GLFW_OPENGL_ES_API = 196610; pub const GLFW_OPENGL_FORWARD_COMPAT = 139270; pub const GLFW_OPENGL_PROFILE = 139272; pub const GLFW_OUT_OF_MEMORY = 65541; pub const GLFW_PLATFORM_ERROR = 65544; pub const GLFW_PRESS = 1; pub const GLFW_RED_BITS = 135169; pub const GLFW_REFRESH_RATE = 135183; pub const GLFW_RELEASE = 0; pub const GLFW_RELEASE_BEHAVIOR_FLUSH = 217089; pub const GLFW_RELEASE_BEHAVIOR_NONE = 217090; pub const GLFW_REPEAT = 2; pub const GLFW_RESIZABLE = 131075; pub const GLFW_SAMPLES = 135181; pub const GLFW_SRGB_CAPABLE = 135182; pub const GLFW_STENCIL_BITS = 135174; pub const GLFW_STEREO = 135180; pub const GLFW_STICKY_KEYS = 208898; pub const GLFW_STICKY_MOUSE_BUTTONS = 208899; pub const GLFW_TRUE = 1; pub const GLFW_VERSION_MAJOR = 3; pub const GLFW_VERSION_MINOR = 2; pub const GLFW_VERSION_REVISION = 1; pub const GLFW_VERSION_UNAVAILABLE = 65543; pub const GLFW_VISIBLE = 131076; pub const GLFW_VRESIZE_CURSOR = 221190;
src/glfw.zig
const std = @import("std"); const string = []const u8; const http = @import("apple_pie"); const files = @import("self/files"); const pek = @import("pek"); const uri = @import("uri"); const zfetch = @import("zfetch"); const json = @import("json"); const extras = @import("extras"); pub const Provider = struct { id: string, authorize_url: string, token_url: string, me_url: string, scope: string = "", name_prop: string, name_prefix: string = "", id_prop: string = "id", logo: string, color: string, pub fn domain(self: Provider) string { if (std.mem.indexOfScalar(u8, self.id, ',')) |_| { var iter = std.mem.split(u8, self.id, ","); _ = iter.next(); return iter.next().?; } return self.id; } }; pub const Client = struct { provider: Provider, id: string, secret: string, }; fn icon_url(comptime name: string) string { return "https://unpkg.com/simple-icons@" ++ "5.13.0" ++ "/icons/" ++ name ++ ".svg"; } pub const providers = struct { pub var amazon = Provider{ .id = "amazon", .authorize_url = "https://www.amazon.com/ap/oa", .token_url = "https://api.amazon.com/auth/o2/token", .me_url = "https://api.amazon.com/user/profile", .scope = "profile", .name_prop = "name", .id_prop = "user_id", .logo = icon_url("amazon"), .color = "#FF9900", }; pub var battle_net = Provider{ .id = "battle.net", .authorize_url = "https://us.battle.net/oauth/authorize", .token_url = "https://us.battle.net/oauth/token", .me_url = "https://us.battle.net/oauth/userinfo", .scope = "openid", .name_prop = "battletag", .logo = icon_url("battle-dot-net"), .color = "#00AEFF", }; pub var discord = Provider{ .id = "discord", .authorize_url = "https://discordapp.com/api/oauth2/authorize", .token_url = "https://discordapp.com/api/oauth2/token", .me_url = "https://discordapp.com/api/users/@me", .scope = "identify", .name_prop = "username", .name_prefix = "@", .logo = icon_url("discord"), .color = "#7289DA", }; pub var facebook = Provider{ .id = "facebook", .authorize_url = "https://graph.facebook.com/oauth/authorize", .token_url = "https://graph.facebook.com/oauth/access_token", .me_url = "https://graph.facebook.com/me", .name_prop = "name", .logo = icon_url("facebook"), .color = "#1877F2", }; pub var github = Provider{ .id = "github", .authorize_url = "https://github.com/login/oauth/authorize", .token_url = "https://github.com/login/oauth/access_token", .me_url = "https://api.github.com/user", .scope = "read:user", .name_prop = "login", .name_prefix = "@", .logo = icon_url("github"), .color = "#181717", }; pub var google = Provider{ .id = "google", .authorize_url = "https://accounts.google.com/o/oauth2/v2/auth", .token_url = "https://www.googleapis.com/oauth2/v4/token", .me_url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json", .scope = "profile", .name_prop = "name", .logo = icon_url("google"), .color = "#4285F4", }; pub var microsoft = Provider{ .id = "microsoft", .authorize_url = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", .token_url = "https://login.microsoftonline.com/common/oauth2/v2.0/token", .me_url = "https://graph.microsoft.com/v1.0/me/", .scope = "https://graph.microsoft.com/user.read", .name_prop = "displayName", .logo = icon_url("microsoft"), .color = "#666666", }; pub var reddit = Provider{ .id = "reddit", .authorize_url = "https://old.reddit.com/api/v1/authorize", .token_url = "https://old.reddit.com/api/v1/access_token", .me_url = "https://oauth.reddit.com/api/v1/me", .scope = "identity", .name_prop = "name", .name_prefix = "u/", .logo = icon_url("reddit"), .color = "#FF4500", }; }; pub const dynamic_providers = struct { pub const _gitea = Provider{ .id = "_gitea", .authorize_url = "https://{domain}/login/oauth/authorize", .token_url = "https://{domain}/login/oauth/access_token", .me_url = "https://{domain}/api/v1/user", .name_prop = "username", .name_prefix = "@", .logo = icon_url("gitea"), .color = "#609926", }; pub const _gitlab = Provider{ .id = "_gitlab", .authorize_url = "https://{domain}/oauth/authorize", .token_url = "https://{domain}/oauth/token", .me_url = "https://{domain}/api/v4/user", .scope = "read_user", .name_prop = "username", .name_prefix = "@", .logo = icon_url("gitlab"), .color = "#FCA121", }; pub const _mastodon = Provider{ .id = "_mastodon", .authorize_url = "https://{domain}/oauth/authorize", .token_url = "https://{domain}/oauth/token", .me_url = "https://{domain}/api/v1/accounts/verify_credentials", .scope = "read:accounts", .name_prop = "username", .name_prefix = "@", .logo = icon_url("mastodon"), .color = "#3088D4", }; pub const _pleroma = Provider{ .id = "_pleroma", .authorize_url = "https://{domain}/oauth/authorize", .token_url = "https://{domain}/oauth/token", .me_url = "https://{domain}/api/v1/accounts/verify_credentials", .scope = "read:accounts", .name_prop = "username", .name_prefix = "@", .logo = icon_url("pleroma"), .color = "#FBA457", }; }; pub fn providerById(name: string) ?Provider { inline for (std.meta.declarations(providers)) |item| { const p = @field(providers, item.name); if (std.mem.eql(u8, p.id, name)) { return p; } } return null; } pub fn clientByProviderId(clients: []const Client, name: string) ?Client { for (clients) |item| { if (std.mem.eql(u8, name, item.provider.id)) { return item; } } return null; } pub const IsLoggedInFn = fn (http.Request) anyerror!bool; pub fn Handlers(comptime T: type) type { comptime std.debug.assert(@hasDecl(T, "Ctx")); comptime std.debug.assert(@hasDecl(T, "isLoggedIn")); comptime std.debug.assert(@hasDecl(T, "doneUrl")); comptime std.debug.assert(@hasDecl(T, "saveInfo")); return struct { const Self = @This(); pub var clients: []Client = &.{}; pub var callbackPath: string = ""; pub fn login(_: T.Ctx, response: *http.Response, request: http.Request, args: struct {}) !void { _ = args; const alloc = request.arena; const query = try request.context.url.queryParameters(alloc); if (query.get("with")) |with| { const client = clientByProviderId(Self.clients, with) orelse return try fail(response, "Client with that ID not found!\n", .{}); return try loginOne(response, request, T, client, Self.callbackPath); } if (Self.clients.len == 1) { return try loginOne(response, request, T, clients[0], Self.callbackPath); } try response.headers.put("Content-Type", "text/html"); const page = files.@"/selector.pek"; const tmpl = comptime pek.parse(page); try pek.compile(alloc, response.writer(), tmpl, .{ .clients = Self.clients, }); } pub fn callback(_: T.Ctx, response: *http.Response, request: http.Request, args: struct {}) !void { _ = args; const alloc = request.arena; const query = try request.context.url.queryParameters(alloc); const state = query.get("state") orelse return try fail(response, "", .{}); const client = clientByProviderId(Self.clients, state) orelse return try fail(response, "error: No handler found for provider: {s}\n", .{state}); const code = query.get("code") orelse return try fail(response, "", .{}); var params = UrlValues.init(alloc); try params.add("client_id", client.id); try params.add("client_secret", client.secret); try params.add("grant_type", "authorization_code"); try params.add("code", code); try params.add("redirect_uri", try redirectUri(alloc, request, callbackPath)); try params.add("state", "none"); const req = try zfetch.Request.init(alloc, client.provider.token_url, null); var headers = zfetch.Headers.init(alloc); try headers.appendValue("Content-Type", "application/x-www-form-urlencoded"); try headers.appendValue("Authorization", try std.fmt.allocPrint(alloc, "Basic {s}", .{try extras.base64EncodeAlloc(alloc, try std.mem.join(alloc, ":", &.{ client.id, client.secret }))})); try headers.appendValue("Accept", "application/json"); // TODO print error message to response if this fails try req.do(.POST, headers, try params.encode()); const r = req.reader(); const body_content = try r.readAllAlloc(alloc, 1024 * 1024 * 5); const val = try json.parse(alloc, body_content); const at = val.get("access_token") orelse return try fail(response, "Identity Provider Login Error!\n{s}", .{body_content}); const req2 = try zfetch.Request.init(alloc, client.provider.me_url, null); var headers2 = zfetch.Headers.init(alloc); try headers2.appendValue("Authorization", try std.fmt.allocPrint(alloc, "Bearer {s}", .{at.String})); try headers2.appendValue("Accept", "application/json"); // TODO print error message if this fails try req2.do(.GET, headers2, null); const r2 = req2.reader(); const body_content2 = try r2.readAllAlloc(alloc, 1024 * 1024 * 5); const val2 = try json.parse(alloc, body_content2); const id = try fixId(alloc, val2.get(client.provider.id_prop).?); const name = val2.get(client.provider.name_prop).?.String; try T.saveInfo(response, request, client.provider, id, name, val, val2); try response.headers.put("Location", T.doneUrl); try response.writeHeader(.found); } }; } fn loginOne(response: *http.Response, request: http.Request, comptime T: type, client: Client, callbackPath: string) !void { if (try T.isLoggedIn(request)) { try response.headers.put("Location", T.doneUrl); } else { const alloc = request.arena; const idp = client.provider; var params = UrlValues.init(alloc); try params.add("client_id", client.id); try params.add("redirect_uri", try redirectUri(alloc, request, callbackPath)); try params.add("response_type", "code"); try params.add("scope", idp.scope); try params.add("duration", "temporary"); try params.add("state", idp.id); const authurl = try std.mem.join(alloc, "?", &.{ idp.authorize_url, try params.encode() }); try response.headers.put("Location", authurl); } try response.writeHeader(.found); } fn fail(response: *http.Response, comptime err: string, args: anytype) !void { try response.writeHeader(.bad_request); try response.writer().print(err, args); } fn redirectUri(alloc: std.mem.Allocator, request: http.Request, callbackPath: string) !string { return try std.fmt.allocPrint(alloc, "http://{s}{s}", .{ request.host().?, callbackPath }); } fn fixId(alloc: std.mem.Allocator, id: json.Value) !string { return switch (id) { .String => |v| return v, .Int => |v| return try std.fmt.allocPrint(alloc, "{d}", .{v}), .Float => |v| return try std.fmt.allocPrint(alloc, "{d}", .{v}), else => unreachable, }; } // // // TODO make this its own library const UrlValues = struct { inner: std.StringArrayHashMap(string), pub fn init(alloc: std.mem.Allocator) UrlValues { return .{ .inner = std.StringArrayHashMap(string).init(alloc), }; } pub fn add(self: *UrlValues, key: string, value: string) !void { try self.inner.putNoClobber(key, value); } pub fn encode(self: UrlValues) !string { const alloc = self.inner.allocator; var list = std.ArrayList(u8).init(alloc); var iter = self.inner.iterator(); var i: usize = 0; while (iter.next()) |entry| : (i += 1) { if (i > 0) try list.writer().writeAll("&"); try list.writer().print("{s}={s}", .{ entry.key_ptr.*, uri.escapeString(alloc, entry.value_ptr.*) }); } return list.toOwnedSlice(); } };
src/lib.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; const data = @embedFile("data/day17.txt"); const EntriesList = std.ArrayList(Record); const Record = struct { x: usize = 0, }; const Pos = struct { x: i32, y: i32, z: i32, w: i32 }; const Map = std.AutoHashMap(Pos, void); pub fn main() !void { const time = try std.time.Timer.start(); defer print("Time elapsed: {}\n", .{time.read()}); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const ally = &arena.allocator; var lines = std.mem.tokenize(data, "\r\n"); var entries = EntriesList.init(ally); try entries.ensureCapacity(400); var result: usize = 0; var map = Map.init(ally); var width: i32 = 7; var min: Pos = .{ .x = 0, .y = 0, .z = 0, .w = 0 }; var max: Pos = .{ .x = width, .y = width, .z = 0, .w = 0 }; var y: i32 = 0; while (lines.next()) |line| { if (line.len == 0) continue; for (line) |char, i| { if (char == '#') { try map.put(.{.x = @intCast(i32, i), .y = y, .z = 0, .w = 0}, {}); } } y += 1; } var iter: u32 = 0; while (iter < 6) : (iter += 1) { print("iter {}: {}\n", .{iter, map.count()}); var next_map = Map.init(ally); defer { map.deinit(); map = next_map; } //print("min=({} {} {}) max=({} {} {})\n", .{min.x, min.y, min.z, max.x, max.y, max.z}); var d = min.w - 1; while (d <= max.w + 1) : (d += 1) { var c = min.z - 1; while (c <= max.z + 1) : (c += 1) { //print("z={}\n", .{c}); var b = min.y - 1; while (b <= max.y + 1) : (b += 1) { var a = min.x - 1; while (a <= max.x + 1) : (a += 1) { var neighbors: u32 = 0; var ao: i32 = -1; while (ao <= 1) : (ao += 1) { var bo: i32 = -1; while (bo <= 1) : (bo += 1) { var co: i32 = -1; while (co <= 1) : (co += 1) { var do: i32 = -1; while (do <= 1) : (do += 1) { if (ao != 0 or bo != 0 or co != 0 or do != 0) { if (map.contains(.{.x = a + ao, .y = b + bo, .z = c + co, .w = d + do})) { neighbors += 1; } } } } } } if (map.contains(.{ .x = a, .y = b, .z = c, .w = d })) { //print("#", .{}); if (neighbors == 2 or neighbors == 3) { try next_map.put(.{.x = a, .y = b, .z = c, .w = d}, {}); } } else { //print(".", .{}); if (neighbors == 3) { try next_map.put(.{.x = a, .y = b, .z = c, .w = d}, {}); } } } //print("\n", .{}); } //print("\n", .{}); } } min.x -= 1; min.y -= 1; min.z -= 1; min.w -= 1; max.x += 1; max.y += 1; max.z += 1; max.w += 1; } print("count: {}\n", .{map.count()}); }
src/day17.zig
const Types = @import("json_grammar.types.zig"); const Errors = @import("json_grammar.errors.zig"); const Tokens = @import("json_grammar.tokens.zig"); usingnamespace Types; usingnamespace Errors; usingnamespace Tokens; pub const StackItem = struct { item: usize, state: i16, value: StackValue, }; pub const StackValue = union(enum) { Token: Id, Terminal: TerminalId, }; pub fn reduce_actions(comptime Parser: type, parser: *Parser, rule: isize, state: i16) !TerminalId { switch (rule) { 1 => { // Symbol: Object var result: *Variant = undefined; // Symbol: LBrace const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?; // Symbol: MaybeFields const arg2 = @intToPtr(?*Variant.Object, parser.stack.items[parser.stack.len - 2].item).?; // Symbol: RBrace const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?; // Adjust the parse stack and current state parser.stack.len -= 2; parser.state = parser.stack.items[parser.stack.len - 1].state; { result = &arg2.base; } parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Object }; parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result); return TerminalId.Object; }, 2 => { // Symbol: MaybeFields var result: *Variant.Object = undefined; { result = try parser.createVariant(Variant.Object); result.fields = VariantMap.init(parser.arena_allocator); } // Push the result of the reduce action try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeFields } }); return TerminalId.MaybeFields; }, 3 => { // Symbol: MaybeFields var result: *Variant.Object = undefined; // Symbol: Fields const arg1 = @intToPtr(?*Variant.Object, parser.stack.items[parser.stack.len - 1].item).?; parser.state = parser.stack.items[parser.stack.len - 1].state; parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeFields }; return TerminalId.MaybeFields; }, 4 => { // Symbol: Fields var result: *Variant.Object = undefined; // Symbol: StringLiteral const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?; // Symbol: Colon const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?; // Symbol: Element const arg3 = @intToPtr(?*Variant, parser.stack.items[parser.stack.len - 1].item).?; // Adjust the parse stack and current state parser.stack.len -= 2; parser.state = parser.stack.items[parser.stack.len - 1].state; { result = try parser.createVariant(Variant.Object); result.fields = VariantMap.init(parser.arena_allocator); const r = try result.fields.insert(parser.tokenString(arg1)); if (!r.is_new) return error.JsonDuplicateKeyError; r.kv.value = arg3; } parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Fields }; parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result); return TerminalId.Fields; }, 5 => { // Symbol: Fields var result: *Variant.Object = undefined; // Symbol: Fields const arg1 = @intToPtr(?*Variant.Object, parser.stack.items[parser.stack.len - 5].item).?; // Symbol: Comma const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?; // Symbol: StringLiteral const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?; // Symbol: Colon const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?; // Symbol: Element const arg5 = @intToPtr(?*Variant, parser.stack.items[parser.stack.len - 1].item).?; // Adjust the parse stack and current state parser.stack.len -= 4; parser.state = parser.stack.items[parser.stack.len - 1].state; { result = arg1; const r = try result.fields.insert(parser.tokenString(arg3)); if (!r.is_new) return error.JsonDuplicateKeyError; r.kv.value = arg5; } parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Fields }; parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result); return TerminalId.Fields; }, 6 => { // Symbol: Array var result: *Variant = undefined; // Symbol: LBracket const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?; // Symbol: MaybeElements const arg2 = @intToPtr(?*VariantList, parser.stack.items[parser.stack.len - 2].item); // Symbol: RBracket const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?; // Adjust the parse stack and current state parser.stack.len -= 2; parser.state = parser.stack.items[parser.stack.len - 1].state; { const variant = try parser.createVariant(Variant.Array); variant.elements = if (arg2) |l| l.* else VariantList.init(parser.arena_allocator); result = &variant.base; } parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Array }; parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result); return TerminalId.Array; }, 7 => { // Symbol: MaybeElements var result: ?*VariantList = null; // Push the result of the reduce action try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeElements } }); return TerminalId.MaybeElements; }, 8 => { // Symbol: MaybeElements var result: ?*VariantList = null; // Symbol: Elements const arg1 = @intToPtr(?*VariantList, parser.stack.items[parser.stack.len - 1].item).?; parser.state = parser.stack.items[parser.stack.len - 1].state; parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeElements }; return TerminalId.MaybeElements; }, 9 => { // Symbol: Elements var result: *VariantList = undefined; // Symbol: Element const arg1 = @intToPtr(?*Variant, parser.stack.items[parser.stack.len - 1].item).?; parser.state = parser.stack.items[parser.stack.len - 1].state; { result = try parser.createVariantList(VariantList); try result.append(arg1); } parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Elements }; parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result); return TerminalId.Elements; }, 10 => { // Symbol: Elements var result: *VariantList = undefined; // Symbol: Elements const arg1 = @intToPtr(?*VariantList, parser.stack.items[parser.stack.len - 3].item).?; // Symbol: Comma const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?; // Symbol: Element const arg3 = @intToPtr(?*Variant, parser.stack.items[parser.stack.len - 1].item).?; // Adjust the parse stack and current state parser.stack.len -= 2; parser.state = parser.stack.items[parser.stack.len - 1].state; { result = arg1; try result.append(arg3); } parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Elements }; parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result); return TerminalId.Elements; }, 11 => { // Symbol: Element var result: *Variant = undefined; // Symbol: StringLiteral const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?; parser.state = parser.stack.items[parser.stack.len - 1].state; { const variant = try parser.createVariant(Variant.StringLiteral); variant.value = try parser.unescapeTokenString(arg1); result = &variant.base; } parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Element }; parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result); return TerminalId.Element; }, 12 => { // Symbol: Element var result: *Variant = undefined; // Symbol: Keyword_null const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?; parser.state = parser.stack.items[parser.stack.len - 1].state; { const variant = try parser.createVariant(Variant.NullLiteral); result = &variant.base; } parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Element }; parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result); return TerminalId.Element; }, 13 => { // Symbol: Element var result: *Variant = undefined; // Symbol: Keyword_true const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?; parser.state = parser.stack.items[parser.stack.len - 1].state; { const variant = try parser.createVariant(Variant.BoolLiteral); variant.value = true; result = &variant.base; } parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Element }; parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result); return TerminalId.Element; }, 14 => { // Symbol: Element var result: *Variant = undefined; // Symbol: Keyword_false const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?; parser.state = parser.stack.items[parser.stack.len - 1].state; { const variant = try parser.createVariant(Variant.BoolLiteral); variant.value = false; result = &variant.base; } parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Element }; parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result); return TerminalId.Element; }, 15 => { // Symbol: Element var result: *Variant = undefined; // Symbol: IntegerLiteral const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?; parser.state = parser.stack.items[parser.stack.len - 1].state; { const variant = try parser.createVariant(Variant.IntegerLiteral); const str = parser.tokenString(arg1); var value: isize = 0; var signed: bool = str[0] == '-'; // TODO: integer overflow for (str) |c| { if (c == '-') continue; value = value * 10 + (@bitCast(i8, c) - '0'); } variant.value = if (signed) -value else value; result = &variant.base; } parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Element }; parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result); return TerminalId.Element; }, 16 => { // Symbol: Element var result: *Variant = undefined; // Symbol: Object const arg1 = @intToPtr(?*Variant, parser.stack.items[parser.stack.len - 1].item).?; parser.state = parser.stack.items[parser.stack.len - 1].state; parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Element }; return TerminalId.Element; }, 17 => { // Symbol: Element var result: *Variant = undefined; // Symbol: Array const arg1 = @intToPtr(?*Variant, parser.stack.items[parser.stack.len - 1].item).?; parser.state = parser.stack.items[parser.stack.len - 1].state; parser.stack.items[parser.stack.len - 1].state = parser.state; parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Element }; return TerminalId.Element; }, else => unreachable, } return error.ReduceError; }
json/json_grammar.actions.zig
const std = @import("std"); const builtin = @import("builtin"); const math = std.math; const native_os = builtin.os.tag; const long_double_is_f128 = builtin.target.longDoubleIsF128(); comptime { // When the self-hosted compiler is further along, all the logic from c_stage1.zig will // be migrated to this file and then c_stage1.zig will be deleted. Until then we have a // simpler implementation of c.zig that only uses features already implemented in self-hosted. if (builtin.zig_backend == .stage1) { _ = @import("c_stage1.zig"); } @export(memset, .{ .name = "memset", .linkage = .Strong }); @export(__memset, .{ .name = "__memset", .linkage = .Strong }); @export(memcpy, .{ .name = "memcpy", .linkage = .Strong }); @export(trunc, .{ .name = "trunc", .linkage = .Strong }); @export(truncf, .{ .name = "truncf", .linkage = .Strong }); @export(truncl, .{ .name = "truncl", .linkage = .Strong }); @export(log, .{ .name = "log", .linkage = .Strong }); @export(logf, .{ .name = "logf", .linkage = .Strong }); } // Avoid dragging in the runtime safety mechanisms into this .o file, // unless we're trying to test this file. pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn { @setCold(true); _ = error_return_trace; if (builtin.zig_backend != .stage1) { while (true) { @breakpoint(); } } if (builtin.is_test) { std.debug.panic("{s}", .{msg}); } if (native_os != .freestanding and native_os != .other) { std.os.abort(); } while (true) {} } fn memset(dest: ?[*]u8, c: u8, len: usize) callconv(.C) ?[*]u8 { @setRuntimeSafety(false); if (len != 0) { var d = dest.?; var n = len; while (true) { d.* = c; n -= 1; if (n == 0) break; d += 1; } } return dest; } fn __memset(dest: ?[*]u8, c: u8, n: usize, dest_n: usize) callconv(.C) ?[*]u8 { if (dest_n < n) @panic("buffer overflow"); return memset(dest, c, n); } fn memcpy(noalias dest: ?[*]u8, noalias src: ?[*]const u8, len: usize) callconv(.C) ?[*]u8 { @setRuntimeSafety(false); if (len != 0) { var d = dest.?; var s = src.?; var n = len; while (true) { d[0] = s[0]; n -= 1; if (n == 0) break; d += 1; s += 1; } } return dest; } fn trunc(a: f64) callconv(.C) f64 { return math.trunc(a); } fn truncf(a: f32) callconv(.C) f32 { return math.trunc(a); } fn truncl(a: c_longdouble) callconv(.C) c_longdouble { if (!long_double_is_f128) { @panic("TODO implement this"); } return math.trunc(a); } fn log(a: f64) callconv(.C) f64 { return math.ln(a); } fn logf(a: f32) callconv(.C) f32 { return math.ln(a); }
lib/std/special/c.zig
const std = @import("std"); const crypto = std.crypto; const mem = std.mem; const Sha512 = crypto.hash.sha2.Sha512; const Curve = crypto.ecc.Edwards25519; const Scalar = Curve.scalar.Scalar; const Ed25519 = crypto.sign.Ed25519; const CompressedScalar = Curve.scalar.CompressedScalar; /// Ed25519 signatures with blind keys. pub const BlindEd25519 = struct { /// Length (in bytes) of optional random bytes, for non-deterministic signatures. pub const noise_length = Ed25519.noise_length; /// Length (in bytes) of a signature. pub const signature_length = Ed25519.signature_length; /// Length (in bytes) of a compressed public key. pub const public_key_length = Ed25519.public_length; /// Length (in bytes) of a blinding seed. pub const blind_seed_length = 32; /// A blind secret key. pub const BlindSecretKey = struct { prefix: [64]u8, blind_scalar: CompressedScalar, blind_public_key: CompressedScalar, }; /// A blind key pair. pub const BlindKeyPair = struct { blind_public_key: [public_key_length]u8, blind_secret_key: BlindSecretKey, }; /// Blind an existing key pair with a blinding seed. pub fn blind(key_pair: Ed25519.KeyPair, blind_seed: [blind_seed_length]u8) !BlindKeyPair { var h: [Sha512.digest_length]u8 = undefined; Sha512.hash(key_pair.secret_key[0..32], &h, .{}); Curve.scalar.clamp(h[0..32]); const scalar = Curve.scalar.reduce(h[0..32].*); var blind_h: [Sha512.digest_length]u8 = undefined; Sha512.hash(blind_seed[0..], &blind_h, .{}); const blind_factor = Curve.scalar.reduce(blind_h[0..32].*); const blind_scalar = Curve.scalar.mul(scalar, blind_factor); const blind_public_key = (Curve.basePoint.mul(blind_scalar) catch return error.IdentityElement).toBytes(); var prefix: [64]u8 = undefined; mem.copy(u8, prefix[0..32], h[32..64]); mem.copy(u8, prefix[32..64], blind_h[32..64]); const blind_secret_key = .{ .prefix = prefix, .blind_scalar = blind_scalar, .blind_public_key = blind_public_key, }; return BlindKeyPair{ .blind_public_key = blind_public_key, .blind_secret_key = blind_secret_key, }; } /// Recover a public key from a blind version of it. pub fn unblind_public_key(blind_public_key: [public_key_length]u8, blind_seed: [blind_seed_length]u8) ![public_key_length]u8 { var blind_h: [Sha512.digest_length]u8 = undefined; Sha512.hash(&blind_seed, &blind_h, .{}); const inv_blind_factor = Scalar.fromBytes(blind_h[0..32].*).invert().toBytes(); const public_key = try (try Curve.fromBytes(blind_public_key)).mul(inv_blind_factor); return public_key.toBytes(); } /// Sign a message using a blind key pair, and optional random noise. /// Having noise creates non-standard, non-deterministic signatures, /// but has been proven to increase resilience against fault attacks. pub fn sign(msg: []const u8, key_pair: BlindKeyPair, noise: ?[noise_length]u8) ![signature_length]u8 { var h = Sha512.init(.{}); if (noise) |*z| { h.update(z); } h.update(&key_pair.blind_secret_key.prefix); h.update(msg); var nonce64: [64]u8 = undefined; h.final(&nonce64); const nonce = Curve.scalar.reduce64(nonce64); const r = try Curve.basePoint.mul(nonce); var sig: [signature_length]u8 = undefined; mem.copy(u8, sig[0..32], &r.toBytes()); mem.copy(u8, sig[32..], &key_pair.blind_public_key); h = Sha512.init(.{}); h.update(&sig); h.update(msg); var hram64: [Sha512.digest_length]u8 = undefined; h.final(&hram64); const hram = Curve.scalar.reduce64(hram64); const s = Curve.scalar.mulAdd(hram, key_pair.blind_secret_key.blind_scalar, nonce); mem.copy(u8, sig[32..], s[0..]); return sig; } }; test "Blind key EdDSA signature" { // Create a standard Ed25519 key pair const kp = try Ed25519.KeyPair.create(null); // Create a random blinding seed var blind: [32]u8 = undefined; crypto.random.bytes(&blind); // Blind the key pair const blind_kp = try BlindEd25519.blind(kp, blind); // Sign a message and check that it can be verified with the blind public key const msg = "test"; const sig = try BlindEd25519.sign(msg, blind_kp, null); try Ed25519.verify(sig, msg, blind_kp.blind_public_key); // Unblind the public key const pk = try BlindEd25519.unblind_public_key(blind_kp.blind_public_key, blind); try std.testing.expectEqualSlices(u8, &pk, &kp.public_key); }
src/main.zig
const std = @import("std"); const mem = std.mem; const Builder = std.build.Builder; const LibExeObjStep = std.build.LibExeObjStep; const Pkg = std.build.Pkg; const RunStep = std.build.RunStep; const Step = std.build.Step; const Target = std.zig.CrossTarget; const core_exes = [_][]const u8{ "tm35-apply", "tm35-disassemble-scripts", "tm35-gen3-offsets", "tm35-identify", "tm35-load", "tm35-nds-extract", }; const randomizer_exes = [_][]const u8{ "tm35-rand-learned-moves", "tm35-rand-machines", "tm35-rand-names", "tm35-rand-parties", "tm35-rand-pokeball-items", "tm35-rand-starters", "tm35-rand-static", "tm35-rand-stats", "tm35-rand-wild", "tm35-random-stones", }; const other_exes = [_][]const u8{ "tm35-generate-site", "tm35-misc", "tm35-noop", "tm35-no-trade-evolutions", }; const gui_exes = [_][]const u8{ "tm35-randomizer", }; const clap_pkg = Pkg{ .name = "clap", .path = .{ .path = "lib/zig-clap/clap.zig" } }; const crc_pkg = Pkg{ .name = "crc", .path = .{ .path = "lib/zig-crc/crc.zig" } }; const folders_pkg = Pkg{ .name = "folders", .path = .{ .path = "lib/known-folders/known-folders.zig" } }; const mecha_pkg = Pkg{ .name = "mecha", .path = .{ .path = "lib/mecha/mecha.zig" } }; const ston_pkg = Pkg{ .name = "ston", .path = .{ .path = "lib/ston/ston.zig" } }; const ziter_pkg = Pkg{ .name = "ziter", .path = .{ .path = "lib/ziter/ziter.zig" } }; const util_pkg = Pkg{ .name = "util", .path = .{ .path = "src/common/util.zig" }, .dependencies = &[_]Pkg{ clap_pkg, folders_pkg, mecha_pkg, }, }; const format_pkg = Pkg{ .name = "format", .path = .{ .path = "src/core/format.zig" }, .dependencies = &[_]Pkg{ mecha_pkg, ston_pkg, util_pkg, }, }; const pkgs = [_]Pkg{ clap_pkg, crc_pkg, folders_pkg, format_pkg, mecha_pkg, ston_pkg, util_pkg, ziter_pkg, }; pub fn build(b: *Builder) void { b.setPreferredReleaseMode(.ReleaseFast); const mode = b.standardReleaseOptions(); const target = b.standardTargetOptions(.{}); const strip = b.option(bool, "strip", "") orelse false; const test_step = b.step("test", "Run all tests"); testIt(b, test_step, mode, "src/test.zig"); const options = BuildProgramOptions{ .strip = strip, .target = target, .mode = mode }; for (core_exes) |name| _ = buildProgram(b, name, b.fmt("src/core/{s}.zig", .{name}), options); for (randomizer_exes) |name| _ = buildProgram(b, name, b.fmt("src/randomizers/{s}.zig", .{name}), options); for (other_exes) |name| _ = buildProgram(b, name, b.fmt("src/other/{s}.zig", .{name}), options); const lib_cflags = &[_][]const u8{ "-D_POSIX_C_SOURCE=200809L", "-fno-sanitize=undefined", // Nuklear trips the undefined sanitizer https://github.com/Immediate-Mode-UI/Nuklear/issues/94 }; for (gui_exes) |tool| { const source = b.fmt("src/gui/{s}.zig", .{tool}); const exe = buildProgram(b, tool, source, options); switch (target.getOsTag()) { .windows => { exe.addIncludeDir("lib/nuklear/demo/gdi"); exe.addCSourceFile("src/gui/nuklear/gdi.c", lib_cflags); exe.addCSourceFile("lib/nativefiledialog/src/nfd_win.cpp", lib_cflags); exe.linkSystemLibrary("user32"); exe.linkSystemLibrary("gdi32"); exe.linkSystemLibrary("uuid"); exe.linkSystemLibrary("msimg32"); }, .linux => { exe.addIncludeDir("lib/nuklear/demo/x11_xft"); exe.addSystemIncludeDir("/usr/include/freetype2"); exe.addSystemIncludeDir("/usr/include/"); exe.addLibPath("/usr/lib/"); exe.addLibPath("/usr/lib/x86_64-linux-gnu"); exe.linkSystemLibrary("X11"); exe.linkSystemLibrary("Xft"); exe.addCSourceFile("src/gui/nuklear/x11.c", lib_cflags); exe.addCSourceFile("lib/nativefiledialog/src/nfd_zenity.c", lib_cflags); }, else => unreachable, // TODO: More os support } exe.addIncludeDir("lib/nativefiledialog/src/include"); exe.addIncludeDir("lib/nuklear"); exe.addIncludeDir("src/gui/nuklear"); exe.addCSourceFile("src/gui/nuklear/impl.c", lib_cflags); exe.addCSourceFile("lib/nativefiledialog/src/nfd_common.c", lib_cflags); exe.linkLibC(); exe.linkSystemLibrary("m"); } } const BuildProgramOptions = struct { install: bool = true, strip: bool = false, mode: std.builtin.Mode = .Debug, target: Target, }; fn buildProgram( b: *Builder, name: []const u8, src: []const u8, opt: BuildProgramOptions, ) *LibExeObjStep { const step = b.step(name, ""); const exe = b.addExecutable(name, src); for (pkgs) |pkg| exe.addPackage(pkg); if (opt.install) step.dependOn(&b.addInstallArtifact(exe).step); exe.setTarget(opt.target); exe.setBuildMode(opt.mode); exe.single_threaded = true; exe.strip = opt.strip; step.dependOn(&exe.step); b.default_step.dependOn(step); return exe; } fn testIt(b: *Builder, parent_step: *Step, mode: std.builtin.Mode, src: []const u8) void { const exe_test = b.addTest(src); for (pkgs) |pkg| exe_test.addPackage(pkg); exe_test.setBuildMode(mode); exe_test.single_threaded = true; parent_step.dependOn(&exe_test.step); }
build.zig
pub const PspUtilityDialogCommon = extern struct { size: c_uint, language: c_int, buttonSwap: c_int, graphicsThread: c_int, accessThread: c_int, fontThread: c_int, soundThread: c_int, result: c_int, reserved: [4]c_int, }; pub const PspUtilityMsgDialogMode = extern enum(c_int) { Error = 0, Text = 1, _, }; const PspUtilityMsgDialogOption = extern enum(c_int) { Error = 0, Text = 1, YesNoButtons = 16, DefaultNo = 256, }; pub const PspUtilityMsgDialogPressed = extern enum(c_int) { Unknown1 = 0, Yes = 1, No = 2, Back = 3, }; pub const PspUtilityMsgDialogParams = extern struct { base: PspUtilityDialogCommon, unknown: c_int, mode: PspUtilityMsgDialogMode, errorValue: c_uint, message: [512]u8, options: c_int, buttonPressed: PspUtilityMsgDialogPressed, }; pub extern fn sceUtilityMsgDialogInitStart(params: *PspUtilityMsgDialogParams) c_int; pub extern fn sceUtilityMsgDialogShutdownStart() void; pub extern fn sceUtilityMsgDialogGetStatus() c_int; pub extern fn sceUtilityMsgDialogUpdate(n: c_int) void; pub extern fn sceUtilityMsgDialogAbort() c_int; pub const PspUtilityNetconfActions = extern enum(c_int) { ConnectAp, DisplayStatus, ConnectAdhoc, }; pub const PspUtilityNetconfAdhoc = extern struct { name: [8]u8, timeout: c_uint, }; pub const PspUtilityNetconfData = extern struct { base: PspUtilityDialogCommon, action: c_int, adhocparam: *PspUtilityNetconfAdhoc, hotspot: c_int, hotspot_connected: c_int, wifisp: c_int, }; pub extern fn sceUtilityNetconfInitStart(data: *PspUtilityNetconfData) c_int; pub extern fn sceUtilityNetconfShutdownStart() c_int; pub extern fn sceUtilityNetconfUpdate(unknown: c_int) c_int; pub extern fn sceUtilityNetconfGetStatus() c_int; const NetData = extern union { asUint: u32_7, asString: [128]u8, }; pub extern fn sceUtilityCheckNetParam(id: c_int) c_int; pub extern fn sceUtilityGetNetParam(conf: c_int, param: c_int, data: *NetData) c_int; pub extern fn sceUtilityCreateNetParam(conf: c_int) c_int; pub extern fn sceUtilitySetNetParam(param: c_int, val: ?*const c_void) c_int; pub extern fn sceUtilityCopyNetParam(src: c_int, dest: c_int) c_int; pub extern fn sceUtilityDeleteNetParam(conf: c_int) c_int; const PspUtilitySavedataMode = extern enum(c_int) { Autoload = 0, Autosave = 1, Load = 2, Save = 3, ListLoad = 4, ListSave = 5, ListDelete = 6, Delete = 7, _, }; const PspUtilitySavedataFocus = extern enum(c_int) { Unknown = 0, FirstList = 1, LastList = 2, Latest = 3, Oldest = 4, Unknown2 = 5, Unknown3 = 6, FirstEmpty = 7, LastEmpty = 8, _, }; pub const PspUtilitySavedataSFOParam = extern struct { title: [128]u8, savedataTitle: [128]u8, detail: [1024]u8, parentalLevel: u8, unknown: [3]u8, }; pub const PspUtilitySavedataFileData = extern struct { buf: ?*c_void, bufSize: SceSize, size: SceSize, unknown: c_int, }; pub const PspUtilitySavedataListSaveNewData = extern struct { icon0: PspUtilitySavedataFileData, title: [*c]u8, }; pub const SceUtilitySavedataParam = extern struct { base: PspUtilityDialogCommon, mode: PspUtilitySavedataMode, unknown1: c_int, overwrite: c_int, gameName: [13]u8, reserved: [3]u8, saveName: [20]u8, saveNameList: [*c][20]u8, fileName: [13]u8, reserved1: [3]u8, dataBuf: ?*c_void, dataBufSize: SceSize, dataSize: SceSize, sfoParam: PspUtilitySavedataSFOParam, icon0FileData: PspUtilitySavedataFileData, icon1FileData: PspUtilitySavedataFileData, pic1FileData: PspUtilitySavedataFileData, snd0FileData: PspUtilitySavedataFileData, newData: [*c]PspUtilitySavedataListSaveNewData, focus: PspUtilitySavedataFocus, unknown2: [4]c_int, }; pub extern fn sceUtilitySavedataInitStart(params: *SceUtilitySavedataParam) c_int; pub extern fn sceUtilitySavedataGetStatus() c_int; pub extern fn sceUtilitySavedataShutdownStart() c_int; pub extern fn sceUtilitySavedataUpdate(unknown: c_int) void; pub extern fn sceUtilityGameSharingInitStart(params: *PspUtilityGameSharingParams) c_int; pub extern fn sceUtilityGameSharingShutdownStart() void; pub extern fn sceUtilityGameSharingGetStatus() c_int; pub extern fn sceUtilityGameSharingUpdate(n: c_int) void; pub extern fn sceUtilityHtmlViewerInitStart(params: *PspUtilityHtmlViewerParam) c_int; pub extern fn sceUtilityHtmlViewerShutdownStart() c_int; pub extern fn sceUtilityHtmlViewerUpdate(n: c_int) c_int; pub extern fn sceUtilityHtmlViewerGetStatus() c_int; pub extern fn sceUtilitySetSystemParamInt(id: c_int, value: c_int) c_int; pub extern fn sceUtilitySetSystemParamString(id: c_int, str: [*c]const u8) c_int; pub extern fn sceUtilityGetSystemParamInt(id: c_int, value: [*c]c_int) c_int; pub extern fn sceUtilityGetSystemParamString(id: c_int, str: [*c]u8, len: c_int) c_int; pub extern fn sceUtilityOskInitStart(params: *SceUtilityOskParams) c_int; pub extern fn sceUtilityOskShutdownStart() c_int; pub extern fn sceUtilityOskUpdate(n: c_int) c_int; pub extern fn sceUtilityOskGetStatus() c_int; pub extern fn sceUtilityLoadNetModule(module: c_int) c_int; pub extern fn sceUtilityUnloadNetModule(module: c_int) c_int; pub extern fn sceUtilityLoadAvModule(module: c_int) c_int; pub extern fn sceUtilityUnloadAvModule(module: c_int) c_int; pub extern fn sceUtilityLoadUsbModule(module: c_int) c_int; pub extern fn sceUtilityUnloadUsbModule(module: c_int) c_int; pub extern fn sceUtilityLoadModule(module: c_int) c_int; pub extern fn sceUtilityUnloadModule(module: c_int) c_int; pub const PspUtilityDialogState = extern enum(c_int) { None = 0, Init = 1, Visible = 2, Quit = 3, Finished = 4, }; pub const SceUtilityOskInputType = extern enum(c_int) { All = 0, LatinDigit = 1, LatinSymbol = 2, LatinLowercase = 4, LatinUppercase = 8, JapaneseDigit = 256, JapaneseSymbol = 512, JapaneseLowercase = 1024, JapaneseUppercase = 2048, JapaneseHiragana = 4096, JapaneseHalfKatakana = 8192, JapaneseKatakana = 16384, JapaneseKanji = 32768, RussianLowercase = 65536, RussianUppercase = 131072, Korean = 262144, Url = 524288, }; pub const SceUtilityOskInputLanguage = extern enum(c_int) { Default = 0, Japanese = 1, English = 2, French = 3, Spanish = 4, German = 5, Italian = 6, Dutch = 7, Portugese = 8, Russian = 9, Korean = 10, }; pub const SceUtilityOskState = extern enum(c_int) { None = 0, Initing = 1, Inited = 2, Visible = 3, Quit = 4, Finished = 5, }; pub const SceUtilityOskResult = extern enum(c_int) { Unchanged = 0, Cancelled = 1, Changed = 2, }; pub const PspUtilityHtmlViewerDisconnectModes = extern enum(c_int) { Enable = 0, Disable = 1, Confirm = 2, _, }; pub const PspUtilityHtmlViewerInterfaceModes = extern enum(c_int) { Full = 0, Limited = 1, None = 2, _, }; pub const PspUtilityHtmlViewerCookieModes = extern enum(c_int) { Disabled = 0, Enabled = 1, Confirm = 2, Default = 3, _, }; pub const PspUtilityGameSharingMode = extern enum(c_int) { Single = 1, Multiple = 2, _, }; pub const PspUtilityGameSharingDataType = extern enum(c_int) { File = 1, Memory = 2, _, }; pub const PspUtilityGameSharingParams = extern struct { base: PspUtilityDialogCommon, unknown1: c_int, unknown2: c_int, name: [8]u8, unknown3: c_int, unknown4: c_int, unknown5: c_int, result: c_int, filepath: [*c]u8, mode: PspUtilityGameSharingMode, datatype: PspUtilityGameSharingDataType, data: ?*c_void, datasize: c_uint, }; pub const PspUtilityHtmlViewerTextSizes = extern enum(c_int) { Large = 0, Normal = 1, Small = 2, _, }; pub const PspUtilityHtmlViewerDisplayModes = extern enum(c_int) { Normal = 0, Fit = 1, SmartFit = 2, _, }; pub const PspUtilityHtmlViewerConnectModes = extern enum(c_int) { Last = 0, ManualOnce = 1, ManualAll = 2, _, }; pub const PspUtilityHtmlViewerOptions = extern enum(c_int) { OpenSceStartPage = 1, DisableStartupLimits = 2, DisableExitDialog = 4, DisableCursor = 8, DisableDownloadCompleteDialog = 16, DisableDownloadStartDialog = 32, DisableDownloadDestinationDialog = 64, LockDownloadDestinationDialog = 128, DisableTabDisplay = 256, EnableAnalogHold = 512, EnableFlash = 1024, DisableLRTrigger = 2048, }; pub const PspUtilityHtmlViewerParam = extern struct { base: PspUtilityDialogCommon, memaddr: ?*c_void, memsize: c_uint, unknown1: c_int, unknown2: c_int, initialurl: [*c]u8, numtabs: c_uint, interfacemode: c_uint, options: c_uint, dldirname: [*c]u8, dlfilename: [*c]u8, uldirname: [*c]u8, ulfilename: [*c]u8, cookiemode: c_uint, unknown3: c_uint, homeurl: [*c]u8, textsize: c_uint, displaymode: c_uint, connectmode: c_uint, disconnectmode: c_uint, memused: c_uint, unknown4: [10]c_int, }; pub const SceUtilityOskData = extern struct { unk_00: c_int, unk_04: c_int, language: c_int, unk_12: c_int, inputtype: c_int, lines: c_int, unk_24: c_int, desc: [*c]c_ushort, intext: [*c]c_ushort, outtextlength: c_int, outtext: [*c]c_ushort, result: c_int, outtextlimit: c_int, }; pub const SceUtilityOskParams = extern struct { base: PspUtilityDialogCommon, datacount: c_int, data: [*c]SceUtilityOskData, state: c_int, unk_60: c_int, }; pub const ModuleNet = extern enum(c_int) { Common = 1, Adhoc = 2, Inet = 3, Parseuri = 4, Parsehttp = 5, Http = 6, Ssl = 7 }; pub const ModuleUSB = extern enum(c_int) { Pspcm = 1, Acc = 2, Mic = 3, Cam = 4, Gps = 5, }; pub const NetParam = extern enum(c_int) { Name = 0, Ssid = 1, Secure = 2, Wepkey = 3, IsStaticIp = 4, Ip = 5, Netmask = 6, Route = 7, ManualDns = 8, Primarydns = 9, Secondarydns = 10, ProxyUser = 11, ProxyPass = 12, UseProxy = 13, ProxyServer = 14, ProxyPort = 15, Unknown1 = 16, Unknown2 = 17 }; pub const SystemParamID = extern enum(c_int) { StringNickname = 1, IntAdhocChannel = 2, IntWlanPowersave = 3, IntDateFormat = 4, IntTimeFormat = 5, IntTimezone = 6, IntDaylightsavings = 7, IntLanguage = 8, IntUnknown = 9 }; pub const ModuleAV = extern enum(c_int) { Avcodec = 0, Sascore = 1, Atrac3plus = 2, Mpegbase = 3, Mp3 = 4, Vaudio = 5, Aac = 6, G729 = 7 }; pub const SystemParamLanguage = extern enum(c_int) { Japanese = 0, English = 1, French = 2, Spanish = 3, German = 4, Italian = 5, Dutch = 6, Portuguese = 7, Russian = 8, Korean = 9, ChineseTraditional = 10, ChineseSimplified = 11, }; pub const SystemParamTime = extern enum(c_int) { Format24Hr = 0, Format12Hr = 1 }; pub const UtilityAccept = extern enum(c_int) { Circle = 0, Cross = 1 }; pub const SystemParamAdhoc = extern enum(c_int) { ChannelAutomatic = 0, Channel1 = 1, Channel6 = 6, Channel11 = 11, }; pub const NetParamError = extern enum(c_int) { BadNetconf = 0x80110601, BadParam = 0x80110604 }; pub const SystemParamWlanPowerSave = extern enum(c_int) { Off = 0, On = 1 }; pub const SystemParamDaylightSavings = extern enum(c_int) { Std = 0, Saving = 1 }; pub const SystemParamDateFormat = extern enum(c_int) { YYYYMMDD = 0, MMDDYYYY = 1, DDMMYYYY = 2 }; pub const SystemParamRetVal = extern enum(c_int) { Ok = 0, Fail = 0x80110103 }; pub const ModuleNP = extern enum(c_int) { Common = 0x0400, Service = 0x0401, Matching2 = 0x0402, Drm = 0x0500, Irda = 0x0600 };
src/psp/sdk/psputility.zig
const std = @import("std"); const api = @import("./buzz_api.zig"); export fn abs(vm: *api.VM) c_int { const n = api.Value.bz_valueToNumber(vm.bz_peek(0)); vm.bz_pushNum(std.math.absFloat(n)); return 1; } export fn acos(vm: *api.VM) c_int { const n = api.Value.bz_valueToNumber(vm.bz_peek(0)); vm.bz_pushNum(std.math.acos(n)); return 1; } export fn asin(vm: *api.VM) c_int { const n = api.Value.bz_valueToNumber(vm.bz_peek(0)); vm.bz_pushNum(std.math.asin(n)); return 1; } export fn atan(vm: *api.VM) c_int { const n = api.Value.bz_valueToNumber(vm.bz_peek(0)); vm.bz_pushNum(std.math.atan(n)); return 1; } export fn ceil(vm: *api.VM) c_int { const n = api.Value.bz_valueToNumber(vm.bz_peek(0)); vm.bz_pushNum(std.math.ceil(n)); return 1; } export fn cos(vm: *api.VM) c_int { const n = api.Value.bz_valueToNumber(vm.bz_peek(0)); vm.bz_pushNum(std.math.cos(n)); return 1; } export fn exp(vm: *api.VM) c_int { const n = api.Value.bz_valueToNumber(vm.bz_peek(0)); vm.bz_pushNum(std.math.exp(n)); return 1; } export fn floor(vm: *api.VM) c_int { const n = api.Value.bz_valueToNumber(vm.bz_peek(0)); vm.bz_pushNum(std.math.floor(n)); return 1; } export fn log(vm: *api.VM) c_int { const base = api.Value.bz_valueToNumber(vm.bz_peek(1)); const n = api.Value.bz_valueToNumber(vm.bz_peek(0)); vm.bz_pushNum(std.math.log(f64, base, n)); return 1; } export fn max(vm: *api.VM) c_int { const a = api.Value.bz_valueToNumber(vm.bz_peek(1)); const b = api.Value.bz_valueToNumber(vm.bz_peek(0)); vm.bz_pushNum(std.math.max(a, b)); return 1; } export fn min(vm: *api.VM) c_int { const a = api.Value.bz_valueToNumber(vm.bz_peek(1)); const b = api.Value.bz_valueToNumber(vm.bz_peek(0)); vm.bz_pushNum(std.math.min(a, b)); return 1; } export fn random(vm: *api.VM) c_int { vm.bz_pushNum(std.crypto.random.float(f64)); return 1; } export fn sin(vm: *api.VM) c_int { const n = api.Value.bz_valueToNumber(vm.bz_peek(0)); vm.bz_pushNum(std.math.sin(n)); return 1; } export fn sqrt(vm: *api.VM) c_int { const n = api.Value.bz_valueToNumber(vm.bz_peek(0)); vm.bz_pushNum(std.math.sqrt(n)); return 1; } export fn tan(vm: *api.VM) c_int { const n = api.Value.bz_valueToNumber(vm.bz_peek(0)); vm.bz_pushNum(std.math.tan(n)); return 1; }
lib/buzz_math.zig
const mesh_common = \\ struct DrawUniforms { \\ object_to_world: mat4x4<f32>, \\ basecolor_roughness: vec4<f32>, \\ } \\ @group(1) @binding(0) var<uniform> draw_uniforms: DrawUniforms; \\ \\ struct FrameUniforms { \\ world_to_clip: mat4x4<f32>, \\ camera_position: vec3<f32>, \\ } \\ @group(0) @binding(0) var<uniform> frame_uniforms: FrameUniforms; ; pub const mesh_vs = mesh_common ++ \\ struct VertexOut { \\ @builtin(position) position_clip: vec4<f32>, \\ @location(0) position: vec3<f32>, \\ @location(1) normal: vec3<f32>, \\ @location(2) barycentrics: vec3<f32>, \\ } \\ @stage(vertex) fn main( \\ @location(0) position: vec3<f32>, \\ @location(1) normal: vec3<f32>, \\ @builtin(vertex_index) vertex_index: u32, \\ ) -> VertexOut { \\ var output: VertexOut; \\ output.position_clip = vec4(position, 1.0) * draw_uniforms.object_to_world * frame_uniforms.world_to_clip; \\ output.position = (vec4(position, 1.0) * draw_uniforms.object_to_world).xyz; \\ output.normal = normal * mat3x3( \\ draw_uniforms.object_to_world[0].xyz, \\ draw_uniforms.object_to_world[1].xyz, \\ draw_uniforms.object_to_world[2].xyz, \\ ); \\ let index = vertex_index % 3u; \\ output.barycentrics = vec3(f32(index == 0u), f32(index == 1u), f32(index == 2u)); \\ return output; \\ } ; pub const mesh_fs = mesh_common ++ \\ let pi = 3.1415926; \\ \\ fn saturate(x: f32) -> f32 { return clamp(x, 0.0, 1.0); } \\ \\ // Trowbridge-Reitz GGX normal distribution function. \\ fn distributionGgx(n: vec3<f32>, h: vec3<f32>, alpha: f32) -> f32 { \\ let alpha_sq = alpha * alpha; \\ let n_dot_h = saturate(dot(n, h)); \\ let k = n_dot_h * n_dot_h * (alpha_sq - 1.0) + 1.0; \\ return alpha_sq / (pi * k * k); \\ } \\ \\ fn geometrySchlickGgx(x: f32, k: f32) -> f32 { \\ return x / (x * (1.0 - k) + k); \\ } \\ \\ fn geometrySmith(n: vec3<f32>, v: vec3<f32>, l: vec3<f32>, k: f32) -> f32 { \\ let n_dot_v = saturate(dot(n, v)); \\ let n_dot_l = saturate(dot(n, l)); \\ return geometrySchlickGgx(n_dot_v, k) * geometrySchlickGgx(n_dot_l, k); \\ } \\ \\ fn fresnelSchlick(h_dot_v: f32, f0: vec3<f32>) -> vec3<f32> { \\ return f0 + (vec3(1.0, 1.0, 1.0) - f0) * pow(1.0 - h_dot_v, 5.0); \\ } \\ \\ @stage(fragment) fn main( \\ @location(0) position: vec3<f32>, \\ @location(1) normal: vec3<f32>, \\ @location(2) barycentrics: vec3<f32>, \\ ) -> @location(0) vec4<f32> { \\ let v = normalize(frame_uniforms.camera_position - position); \\ let n = normalize(normal); \\ \\ let base_color = draw_uniforms.basecolor_roughness.xyz; \\ let ao = 1.0; \\ var roughness = draw_uniforms.basecolor_roughness.a; \\ var metallic: f32; \\ if (roughness < 0.0) { metallic = 1.0; } else { metallic = 0.0; } \\ roughness = abs(roughness); \\ \\ let alpha = roughness * roughness; \\ var k = alpha + 1.0; \\ k = (k * k) / 8.0; \\ var f0 = vec3(0.04); \\ f0 = mix(f0, base_color, metallic); \\ \\ // TODO: Pass those arrays via uniform buffer \\ let light_positions = array<vec3<f32>, 4>( \\ vec3(25.0, 15.0, 25.0), \\ vec3(-25.0, 15.0, 25.0), \\ vec3(25.0, 15.0, -25.0), \\ vec3(-25.0, 15.0, -25.0), \\ ); \\ let light_radiance = array<vec3<f32>, 4>( \\ 4.0 * vec3(0.0, 100.0, 250.0), \\ 8.0 * vec3(200.0, 150.0, 250.0), \\ 3.0 * vec3(200.0, 0.0, 0.0), \\ 9.0 * vec3(200.0, 150.0, 0.0), \\ ); \\ \\ var lo = vec3(0.0); \\ for (var light_index: i32 = 0; light_index < 4; light_index = light_index + 1) { \\ let lvec = light_positions[light_index] - position; \\ \\ let l = normalize(lvec); \\ let h = normalize(l + v); \\ \\ let distance_sq = dot(lvec, lvec); \\ let attenuation = 1.0 / distance_sq; \\ let radiance = light_radiance[light_index] * attenuation; \\ \\ let f = fresnelSchlick(saturate(dot(h, v)), f0); \\ \\ let ndf = distributionGgx(n, h, alpha); \\ let g = geometrySmith(n, v, l, k); \\ \\ let numerator = ndf * g * f; \\ let denominator = 4.0 * saturate(dot(n, v)) * saturate(dot(n, l)); \\ let specular = numerator / max(denominator, 0.001); \\ \\ let ks = f; \\ let kd = (vec3(1.0) - ks) * (1.0 - metallic); \\ \\ let n_dot_l = saturate(dot(n, l)); \\ lo = lo + (kd * base_color / pi + specular) * radiance * n_dot_l; \\ } \\ \\ let ambient = vec3(0.03) * base_color * ao; \\ var color = ambient + lo; \\ color = color / (color + 1.0); \\ color = pow(color, vec3(1.0 / 2.2)); \\ \\ // wireframe \\ var barys = barycentrics; \\ barys.z = 1.0 - barys.x - barys.y; \\ let deltas = fwidth(barys); \\ let smoothing = deltas * 1.0; \\ let thickness = deltas * 0.25; \\ barys = smoothstep(thickness, thickness + smoothing, barys); \\ let min_bary = min(barys.x, min(barys.y, barys.z)); \\ return vec4(min_bary * color, 1.0); \\ } ; pub const physics_debug_vs = \\ struct Uniforms { \\ world_to_clip: mat4x4<f32>, \\ } \\ @group(0) @binding(0) var<uniform> uniforms: Uniforms; \\ \\ struct VertexOut { \\ @builtin(position) position_clip: vec4<f32>, \\ @location(0) color: vec3<f32>, \\ } \\ \\ @stage(vertex) fn main( \\ @builtin(vertex_index) vertex_index: u32, \\ @location(0) position: vec3<f32>, \\ @location(1) color: u32, \\ ) -> VertexOut { \\ var output: VertexOut; \\ output.position_clip = vec4(position, 1.0) * uniforms.world_to_clip; \\ output.color = vec3( \\ f32(color & 0xFFu) / 255.0, \\ f32((color >> 8u) & 0xFFu) / 255.0, \\ f32((color >> 16u) & 0xFFu) / 255.0, \\ ); \\ return output; \\ } ; pub const physics_debug_fs = \\ @stage(fragment) fn main( \\ @location(0) color: vec3<f32>, \\ ) -> @location(0) vec4<f32> { \\ return vec4(color, 1.0); \\ } ; // zig fmt: on
samples/bullet_physics_test_wgpu/src/bullet_physics_test_wgsl.zig
const Coff = @This(); const std = @import("std"); const log = std.log.scoped(.link); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const fs = std.fs; const trace = @import("../tracy.zig").trace; const Module = @import("../Module.zig"); const codegen = @import("../codegen.zig"); const link = @import("../link.zig"); const allocation_padding = 4 / 3; const minimum_text_block_size = 64 * allocation_padding; const section_alignment = 4096; const file_alignment = 512; const image_base = 0x400_000; const section_table_size = 2 * 40; comptime { std.debug.assert(std.mem.isAligned(image_base, section_alignment)); } pub const base_tag: link.File.Tag = .coff; const msdos_stub = @embedFile("msdos-stub.bin"); base: link.File, ptr_width: enum { p32, p64 }, error_flags: link.File.ErrorFlags = .{}, text_block_free_list: std.ArrayListUnmanaged(*TextBlock) = .{}, last_text_block: ?*TextBlock = null, /// Section table file pointer. section_table_offset: u32 = 0, /// Section data file pointer. section_data_offset: u32 = 0, /// Optiona header file pointer. optional_header_offset: u32 = 0, /// Absolute virtual address of the offset table when the executable is loaded in memory. offset_table_virtual_address: u32 = 0, /// Current size of the offset table on disk, must be a multiple of `file_alignment` offset_table_size: u32 = 0, /// Contains absolute virtual addresses offset_table: std.ArrayListUnmanaged(u64) = .{}, /// Free list of offset table indices offset_table_free_list: std.ArrayListUnmanaged(u32) = .{}, /// Virtual address of the entry point procedure relative to `image_base` entry_addr: ?u32 = null, /// Absolute virtual address of the text section when the executable is loaded in memory. text_section_virtual_address: u32 = 0, /// Current size of the `.text` section on disk, must be a multiple of `file_alignment` text_section_size: u32 = 0, offset_table_size_dirty: bool = false, text_section_size_dirty: bool = false, /// This flag is set when the virtual size of the whole image file when loaded in memory has changed /// and needs to be updated in the optional header. size_of_image_dirty: bool = false, pub const TextBlock = struct { /// Offset of the code relative to the start of the text section text_offset: u32, /// Used size of the text block size: u32, /// This field is undefined for symbols with size = 0. offset_table_index: u32, /// Points to the previous and next neighbors, based on the `text_offset`. /// This can be used to find, for example, the capacity of this `TextBlock`. prev: ?*TextBlock, next: ?*TextBlock, pub const empty = TextBlock{ .text_offset = 0, .size = 0, .offset_table_index = undefined, .prev = null, .next = null, }; /// Returns how much room there is to grow in virtual address space. fn capacity(self: TextBlock) u64 { if (self.next) |next| { return next.text_offset - self.text_offset; } // This is the last block, the capacity is only limited by the address space. return std.math.maxInt(u32) - self.text_offset; } fn freeListEligible(self: TextBlock) bool { // No need to keep a free list node for the last block. const next = self.next orelse return false; const cap = next.text_offset - self.text_offset; const ideal_cap = self.size * allocation_padding; if (cap <= ideal_cap) return false; const surplus = cap - ideal_cap; return surplus >= minimum_text_block_size; } /// Absolute virtual address of the text block when the file is loaded in memory. fn getVAddr(self: TextBlock, coff: Coff) u32 { return coff.text_section_virtual_address + self.text_offset; } }; pub const SrcFn = void; pub fn openPath(allocator: *Allocator, dir: fs.Dir, sub_path: []const u8, options: link.Options) !*link.File { assert(options.object_format == .coff); const file = try dir.createFile(sub_path, .{ .truncate = false, .read = true, .mode = link.determineMode(options) }); errdefer file.close(); var coff_file = try allocator.create(Coff); errdefer allocator.destroy(coff_file); coff_file.* = openFile(allocator, file, options) catch |err| switch (err) { error.IncrFailed => try createFile(allocator, file, options), else => |e| return e, }; return &coff_file.base; } /// Returns error.IncrFailed if incremental update could not be performed. fn openFile(allocator: *Allocator, file: fs.File, options: link.Options) !Coff { switch (options.output_mode) { .Exe => {}, .Obj => return error.IncrFailed, .Lib => return error.IncrFailed, } var self: Coff = .{ .base = .{ .file = file, .tag = .coff, .options = options, .allocator = allocator, }, .ptr_width = switch (options.target.cpu.arch.ptrBitWidth()) { 32 => .p32, 64 => .p64, else => return error.UnsupportedELFArchitecture, }, }; errdefer self.deinit(); // TODO implement reading the PE/COFF file return error.IncrFailed; } /// Truncates the existing file contents and overwrites the contents. /// Returns an error if `file` is not already open with +read +write +seek abilities. fn createFile(allocator: *Allocator, file: fs.File, options: link.Options) !Coff { // TODO Write object specific relocations, COFF symbol table, then enable object file output. switch (options.output_mode) { .Exe => {}, .Obj => return error.TODOImplementWritingObjFiles, .Lib => return error.TODOImplementWritingLibFiles, } var self: Coff = .{ .base = .{ .tag = .coff, .options = options, .allocator = allocator, .file = file, }, .ptr_width = switch (options.target.cpu.arch.ptrBitWidth()) { 32 => .p32, 64 => .p64, else => return error.UnsupportedCOFFArchitecture, }, }; errdefer self.deinit(); var coff_file_header_offset: u32 = 0; if (options.output_mode == .Exe) { // Write the MS-DOS stub and the PE signature try self.base.file.?.pwriteAll(msdos_stub ++ "PE\x00\x00", 0); coff_file_header_offset = msdos_stub.len + 4; } // COFF file header const data_directory_count = 0; var hdr_data: [112 + data_directory_count * 8 + section_table_size]u8 = undefined; var index: usize = 0; const machine = self.base.options.target.cpu.arch.toCoffMachine(); if (machine == .Unknown) { return error.UnsupportedCOFFArchitecture; } std.mem.writeIntLittle(u16, hdr_data[0..2], @enumToInt(machine)); index += 2; // Number of sections (we only use .got, .text) std.mem.writeIntLittle(u16, hdr_data[index..][0..2], 2); index += 2; // TimeDateStamp (u32), PointerToSymbolTable (u32), NumberOfSymbols (u32) std.mem.set(u8, hdr_data[index..][0..12], 0); index += 12; const optional_header_size = switch (options.output_mode) { .Exe => data_directory_count * 8 + switch (self.ptr_width) { .p32 => @as(u16, 96), .p64 => 112, }, else => 0, }; const section_table_offset = coff_file_header_offset + 20 + optional_header_size; const default_offset_table_size = file_alignment; const default_size_of_code = 0; self.section_data_offset = std.mem.alignForwardGeneric(u32, self.section_table_offset + section_table_size, file_alignment); const section_data_relative_virtual_address = std.mem.alignForwardGeneric(u32, self.section_table_offset + section_table_size, section_alignment); self.offset_table_virtual_address = image_base + section_data_relative_virtual_address; self.offset_table_size = default_offset_table_size; self.section_table_offset = section_table_offset; self.text_section_virtual_address = image_base + section_data_relative_virtual_address + section_alignment; self.text_section_size = default_size_of_code; // Size of file when loaded in memory const size_of_image = std.mem.alignForwardGeneric(u32, self.text_section_virtual_address - image_base + default_size_of_code, section_alignment); std.mem.writeIntLittle(u16, hdr_data[index..][0..2], optional_header_size); index += 2; // Characteristics var characteristics: u16 = std.coff.IMAGE_FILE_DEBUG_STRIPPED | std.coff.IMAGE_FILE_RELOCS_STRIPPED; // TODO Remove debug info stripped flag when necessary if (options.output_mode == .Exe) { characteristics |= std.coff.IMAGE_FILE_EXECUTABLE_IMAGE; } switch (self.ptr_width) { .p32 => characteristics |= std.coff.IMAGE_FILE_32BIT_MACHINE, .p64 => characteristics |= std.coff.IMAGE_FILE_LARGE_ADDRESS_AWARE, } std.mem.writeIntLittle(u16, hdr_data[index..][0..2], characteristics); index += 2; assert(index == 20); try self.base.file.?.pwriteAll(hdr_data[0..index], coff_file_header_offset); if (options.output_mode == .Exe) { self.optional_header_offset = coff_file_header_offset + 20; // Optional header index = 0; std.mem.writeIntLittle(u16, hdr_data[0..2], switch (self.ptr_width) { .p32 => @as(u16, 0x10b), .p64 => 0x20b, }); index += 2; // Linker version (u8 + u8) std.mem.set(u8, hdr_data[index..][0..2], 0); index += 2; // SizeOfCode (UNUSED, u32), SizeOfInitializedData (u32), SizeOfUninitializedData (u32), AddressOfEntryPoint (u32), BaseOfCode (UNUSED, u32) std.mem.set(u8, hdr_data[index..][0..20], 0); index += 20; if (self.ptr_width == .p32) { // Base of data relative to the image base (UNUSED) std.mem.set(u8, hdr_data[index..][0..4], 0); index += 4; // Image base address std.mem.writeIntLittle(u32, hdr_data[index..][0..4], image_base); index += 4; } else { // Image base address std.mem.writeIntLittle(u64, hdr_data[index..][0..8], image_base); index += 8; } // Section alignment std.mem.writeIntLittle(u32, hdr_data[index..][0..4], section_alignment); index += 4; // File alignment std.mem.writeIntLittle(u32, hdr_data[index..][0..4], file_alignment); index += 4; // Required OS version, 6.0 is vista std.mem.writeIntLittle(u16, hdr_data[index..][0..2], 6); index += 2; std.mem.writeIntLittle(u16, hdr_data[index..][0..2], 0); index += 2; // Image version std.mem.set(u8, hdr_data[index..][0..4], 0); index += 4; // Required subsystem version, same as OS version std.mem.writeIntLittle(u16, hdr_data[index..][0..2], 6); index += 2; std.mem.writeIntLittle(u16, hdr_data[index..][0..2], 0); index += 2; // Reserved zeroes (u32) std.mem.set(u8, hdr_data[index..][0..4], 0); index += 4; std.mem.writeIntLittle(u32, hdr_data[index..][0..4], size_of_image); index += 4; std.mem.writeIntLittle(u32, hdr_data[index..][0..4], self.section_data_offset); index += 4; // CheckSum (u32) std.mem.set(u8, hdr_data[index..][0..4], 0); index += 4; // Subsystem, TODO: Let users specify the subsystem, always CUI for now std.mem.writeIntLittle(u16, hdr_data[index..][0..2], 3); index += 2; // DLL characteristics std.mem.writeIntLittle(u16, hdr_data[index..][0..2], 0x0); index += 2; switch (self.ptr_width) { .p32 => { // Size of stack reserve + commit std.mem.writeIntLittle(u32, hdr_data[index..][0..4], 0x1_000_000); index += 4; std.mem.writeIntLittle(u32, hdr_data[index..][0..4], 0x1_000); index += 4; // Size of heap reserve + commit std.mem.writeIntLittle(u32, hdr_data[index..][0..4], 0x100_000); index += 4; std.mem.writeIntLittle(u32, hdr_data[index..][0..4], 0x1_000); index += 4; }, .p64 => { // Size of stack reserve + commit std.mem.writeIntLittle(u64, hdr_data[index..][0..8], 0x1_000_000); index += 8; std.mem.writeIntLittle(u64, hdr_data[index..][0..8], 0x1_000); index += 8; // Size of heap reserve + commit std.mem.writeIntLittle(u64, hdr_data[index..][0..8], 0x100_000); index += 8; std.mem.writeIntLittle(u64, hdr_data[index..][0..8], 0x1_000); index += 8; }, } // Reserved zeroes std.mem.set(u8, hdr_data[index..][0..4], 0); index += 4; // Number of data directories std.mem.writeIntLittle(u32, hdr_data[index..][0..4], data_directory_count); index += 4; // Initialize data directories to zero std.mem.set(u8, hdr_data[index..][0 .. data_directory_count * 8], 0); index += data_directory_count * 8; assert(index == optional_header_size); } // Write section table. // First, the .got section hdr_data[index..][0..8].* = ".got\x00\x00\x00\x00".*; index += 8; if (options.output_mode == .Exe) { // Virtual size (u32) std.mem.writeIntLittle(u32, hdr_data[index..][0..4], default_offset_table_size); index += 4; // Virtual address (u32) std.mem.writeIntLittle(u32, hdr_data[index..][0..4], self.offset_table_virtual_address - image_base); index += 4; } else { std.mem.set(u8, hdr_data[index..][0..8], 0); index += 8; } // Size of raw data (u32) std.mem.writeIntLittle(u32, hdr_data[index..][0..4], default_offset_table_size); index += 4; // File pointer to the start of the section std.mem.writeIntLittle(u32, hdr_data[index..][0..4], self.section_data_offset); index += 4; // Pointer to relocations (u32), PointerToLinenumbers (u32), NumberOfRelocations (u16), NumberOfLinenumbers (u16) std.mem.set(u8, hdr_data[index..][0..12], 0); index += 12; // Section flags std.mem.writeIntLittle(u32, hdr_data[index..][0..4], std.coff.IMAGE_SCN_CNT_INITIALIZED_DATA | std.coff.IMAGE_SCN_MEM_READ); index += 4; // Then, the .text section hdr_data[index..][0..8].* = ".text\x00\x00\x00".*; index += 8; if (options.output_mode == .Exe) { // Virtual size (u32) std.mem.writeIntLittle(u32, hdr_data[index..][0..4], default_size_of_code); index += 4; // Virtual address (u32) std.mem.writeIntLittle(u32, hdr_data[index..][0..4], self.text_section_virtual_address - image_base); index += 4; } else { std.mem.set(u8, hdr_data[index..][0..8], 0); index += 8; } // Size of raw data (u32) std.mem.writeIntLittle(u32, hdr_data[index..][0..4], default_size_of_code); index += 4; // File pointer to the start of the section std.mem.writeIntLittle(u32, hdr_data[index..][0..4], self.section_data_offset + default_offset_table_size); index += 4; // Pointer to relocations (u32), PointerToLinenumbers (u32), NumberOfRelocations (u16), NumberOfLinenumbers (u16) std.mem.set(u8, hdr_data[index..][0..12], 0); index += 12; // Section flags std.mem.writeIntLittle( u32, hdr_data[index..][0..4], std.coff.IMAGE_SCN_CNT_CODE | std.coff.IMAGE_SCN_MEM_EXECUTE | std.coff.IMAGE_SCN_MEM_READ | std.coff.IMAGE_SCN_MEM_WRITE, ); index += 4; assert(index == optional_header_size + section_table_size); try self.base.file.?.pwriteAll(hdr_data[0..index], self.optional_header_offset); try self.base.file.?.setEndPos(self.section_data_offset + default_offset_table_size + default_size_of_code); return self; } pub fn allocateDeclIndexes(self: *Coff, decl: *Module.Decl) !void { try self.offset_table.ensureCapacity(self.base.allocator, self.offset_table.items.len + 1); if (self.offset_table_free_list.popOrNull()) |i| { decl.link.coff.offset_table_index = i; } else { decl.link.coff.offset_table_index = @intCast(u32, self.offset_table.items.len); _ = self.offset_table.addOneAssumeCapacity(); const entry_size = self.base.options.target.cpu.arch.ptrBitWidth() / 8; if (self.offset_table.items.len > self.offset_table_size / entry_size) { self.offset_table_size_dirty = true; } } self.offset_table.items[decl.link.coff.offset_table_index] = 0; } fn allocateTextBlock(self: *Coff, text_block: *TextBlock, new_block_size: u64, alignment: u64) !u64 { const new_block_min_capacity = new_block_size * allocation_padding; // We use these to indicate our intention to update metadata, placing the new block, // and possibly removing a free list node. // It would be simpler to do it inside the for loop below, but that would cause a // problem if an error was returned later in the function. So this action // is actually carried out at the end of the function, when errors are no longer possible. var block_placement: ?*TextBlock = null; var free_list_removal: ?usize = null; const vaddr = blk: { var i: usize = 0; while (i < self.text_block_free_list.items.len) { const free_block = self.text_block_free_list.items[i]; const next_block_text_offset = free_block.text_offset + free_block.capacity(); const new_block_text_offset = std.mem.alignForwardGeneric(u64, free_block.getVAddr(self.*) + free_block.size, alignment) - self.text_section_virtual_address; if (new_block_text_offset < next_block_text_offset and next_block_text_offset - new_block_text_offset >= new_block_min_capacity) { block_placement = free_block; const remaining_capacity = next_block_text_offset - new_block_text_offset - new_block_min_capacity; if (remaining_capacity < minimum_text_block_size) { free_list_removal = i; } break :blk new_block_text_offset + self.text_section_virtual_address; } else { if (!free_block.freeListEligible()) { _ = self.text_block_free_list.swapRemove(i); } else { i += 1; } continue; } } else if (self.last_text_block) |last| { const new_block_vaddr = std.mem.alignForwardGeneric(u64, last.getVAddr(self.*) + last.size, alignment); block_placement = last; break :blk new_block_vaddr; } else { break :blk self.text_section_virtual_address; } }; const expand_text_section = block_placement == null or block_placement.?.next == null; if (expand_text_section) { const needed_size = @intCast(u32, std.mem.alignForwardGeneric(u64, vaddr + new_block_size - self.text_section_virtual_address, file_alignment)); if (needed_size > self.text_section_size) { const current_text_section_virtual_size = std.mem.alignForwardGeneric(u32, self.text_section_size, section_alignment); const new_text_section_virtual_size = std.mem.alignForwardGeneric(u32, needed_size, section_alignment); if (current_text_section_virtual_size != new_text_section_virtual_size) { self.size_of_image_dirty = true; // Write new virtual size var buf: [4]u8 = undefined; std.mem.writeIntLittle(u32, &buf, new_text_section_virtual_size); try self.base.file.?.pwriteAll(&buf, self.section_table_offset + 40 + 8); } self.text_section_size = needed_size; self.text_section_size_dirty = true; } self.last_text_block = text_block; } text_block.text_offset = @intCast(u32, vaddr - self.text_section_virtual_address); text_block.size = @intCast(u32, new_block_size); // This function can also reallocate a text block. // In this case we need to "unplug" it from its previous location before // plugging it in to its new location. if (text_block.prev) |prev| { prev.next = text_block.next; } if (text_block.next) |next| { next.prev = text_block.prev; } if (block_placement) |big_block| { text_block.prev = big_block; text_block.next = big_block.next; big_block.next = text_block; } else { text_block.prev = null; text_block.next = null; } if (free_list_removal) |i| { _ = self.text_block_free_list.swapRemove(i); } return vaddr; } fn growTextBlock(self: *Coff, text_block: *TextBlock, new_block_size: u64, alignment: u64) !u64 { const block_vaddr = text_block.getVAddr(self.*); const align_ok = std.mem.alignBackwardGeneric(u64, block_vaddr, alignment) == block_vaddr; const need_realloc = !align_ok or new_block_size > text_block.capacity(); if (!need_realloc) return @as(u64, block_vaddr); return self.allocateTextBlock(text_block, new_block_size, alignment); } fn shrinkTextBlock(self: *Coff, text_block: *TextBlock, new_block_size: u64) void { text_block.size = @intCast(u32, new_block_size); if (text_block.capacity() - text_block.size >= minimum_text_block_size) { self.text_block_free_list.append(self.base.allocator, text_block) catch {}; } } fn freeTextBlock(self: *Coff, text_block: *TextBlock) void { var already_have_free_list_node = false; { var i: usize = 0; // TODO turn text_block_free_list into a hash map while (i < self.text_block_free_list.items.len) { if (self.text_block_free_list.items[i] == text_block) { _ = self.text_block_free_list.swapRemove(i); continue; } if (self.text_block_free_list.items[i] == text_block.prev) { already_have_free_list_node = true; } i += 1; } } if (self.last_text_block == text_block) { self.last_text_block = text_block.prev; } if (text_block.prev) |prev| { prev.next = text_block.next; if (!already_have_free_list_node and prev.freeListEligible()) { // The free list is heuristics, it doesn't have to be perfect, so we can // ignore the OOM here. self.text_block_free_list.append(self.base.allocator, prev) catch {}; } } if (text_block.next) |next| { next.prev = text_block.prev; } } fn writeOffsetTableEntry(self: *Coff, index: usize) !void { const entry_size = self.base.options.target.cpu.arch.ptrBitWidth() / 8; const endian = self.base.options.target.cpu.arch.endian(); const offset_table_start = self.section_data_offset; if (self.offset_table_size_dirty) { const current_raw_size = self.offset_table_size; const new_raw_size = self.offset_table_size * 2; log.debug("growing offset table from raw size {} to {}\n", .{ current_raw_size, new_raw_size }); // Move the text section to a new place in the executable const current_text_section_start = self.section_data_offset + current_raw_size; const new_text_section_start = self.section_data_offset + new_raw_size; const amt = try self.base.file.?.copyRangeAll(current_text_section_start, self.base.file.?, new_text_section_start, self.text_section_size); if (amt != self.text_section_size) return error.InputOutput; // Write the new raw size in the .got header var buf: [8]u8 = undefined; std.mem.writeIntLittle(u32, buf[0..4], new_raw_size); try self.base.file.?.pwriteAll(buf[0..4], self.section_table_offset + 16); // Write the new .text section file offset in the .text section header std.mem.writeIntLittle(u32, buf[0..4], new_text_section_start); try self.base.file.?.pwriteAll(buf[0..4], self.section_table_offset + 40 + 20); const current_virtual_size = std.mem.alignForwardGeneric(u32, self.offset_table_size, section_alignment); const new_virtual_size = std.mem.alignForwardGeneric(u32, new_raw_size, section_alignment); // If we had to move in the virtual address space, we need to fix the VAs in the offset table, as well as the virtual address of the `.text` section // and the virutal size of the `.got` section if (new_virtual_size != current_virtual_size) { log.debug("growing offset table from virtual size {} to {}\n", .{ current_virtual_size, new_virtual_size }); self.size_of_image_dirty = true; const va_offset = new_virtual_size - current_virtual_size; // Write .got virtual size std.mem.writeIntLittle(u32, buf[0..4], new_virtual_size); try self.base.file.?.pwriteAll(buf[0..4], self.section_table_offset + 8); // Write .text new virtual address self.text_section_virtual_address = self.text_section_virtual_address + va_offset; std.mem.writeIntLittle(u32, buf[0..4], self.text_section_virtual_address - image_base); try self.base.file.?.pwriteAll(buf[0..4], self.section_table_offset + 40 + 12); // Fix the VAs in the offset table for (self.offset_table.items) |*va, idx| { if (va.* != 0) { va.* += va_offset; switch (entry_size) { 4 => { std.mem.writeInt(u32, buf[0..4], @intCast(u32, va.*), endian); try self.base.file.?.pwriteAll(buf[0..4], offset_table_start + idx * entry_size); }, 8 => { std.mem.writeInt(u64, &buf, va.*, endian); try self.base.file.?.pwriteAll(&buf, offset_table_start + idx * entry_size); }, else => unreachable, } } } } self.offset_table_size = new_raw_size; self.offset_table_size_dirty = false; } // Write the new entry switch (entry_size) { 4 => { var buf: [4]u8 = undefined; std.mem.writeInt(u32, &buf, @intCast(u32, self.offset_table.items[index]), endian); try self.base.file.?.pwriteAll(&buf, offset_table_start + index * entry_size); }, 8 => { var buf: [8]u8 = undefined; std.mem.writeInt(u64, &buf, self.offset_table.items[index], endian); try self.base.file.?.pwriteAll(&buf, offset_table_start + index * entry_size); }, else => unreachable, } } pub fn updateDecl(self: *Coff, module: *Module, decl: *Module.Decl) !void { // TODO COFF/PE debug information // TODO Implement exports const tracy = trace(@src()); defer tracy.end(); var code_buffer = std.ArrayList(u8).init(self.base.allocator); defer code_buffer.deinit(); const typed_value = decl.typed_value.most_recent.typed_value; const res = try codegen.generateSymbol(&self.base, decl.src(), typed_value, &code_buffer, .none); const code = switch (res) { .externally_managed => |x| x, .appended => code_buffer.items, .fail => |em| { decl.analysis = .codegen_failure; try module.failed_decls.put(module.gpa, decl, em); return; }, }; const required_alignment = typed_value.ty.abiAlignment(self.base.options.target); const curr_size = decl.link.coff.size; if (curr_size != 0) { const capacity = decl.link.coff.capacity(); const need_realloc = code.len > capacity or !std.mem.isAlignedGeneric(u32, decl.link.coff.text_offset, required_alignment); if (need_realloc) { const curr_vaddr = self.getDeclVAddr(decl); const vaddr = try self.growTextBlock(&decl.link.coff, code.len, required_alignment); log.debug("growing {} from 0x{x} to 0x{x}\n", .{ decl.name, curr_vaddr, vaddr }); if (vaddr != curr_vaddr) { log.debug(" (writing new offset table entry)\n", .{}); self.offset_table.items[decl.link.coff.offset_table_index] = vaddr; try self.writeOffsetTableEntry(decl.link.coff.offset_table_index); } } else if (code.len < curr_size) { self.shrinkTextBlock(&decl.link.coff, code.len); } } else { const vaddr = try self.allocateTextBlock(&decl.link.coff, code.len, required_alignment); log.debug("allocated text block for {} at 0x{x} (size: {Bi})\n", .{ std.mem.spanZ(decl.name), vaddr, code.len }); errdefer self.freeTextBlock(&decl.link.coff); self.offset_table.items[decl.link.coff.offset_table_index] = vaddr; try self.writeOffsetTableEntry(decl.link.coff.offset_table_index); } // Write the code into the file try self.base.file.?.pwriteAll(code, self.section_data_offset + self.offset_table_size + decl.link.coff.text_offset); // Since we updated the vaddr and the size, each corresponding export symbol also needs to be updated. const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{}; return self.updateDeclExports(module, decl, decl_exports); } pub fn freeDecl(self: *Coff, decl: *Module.Decl) void { // Appending to free lists is allowed to fail because the free lists are heuristics based anyway. self.freeTextBlock(&decl.link.coff); self.offset_table_free_list.append(self.base.allocator, decl.link.coff.offset_table_index) catch {}; } pub fn updateDeclExports(self: *Coff, module: *Module, decl: *const Module.Decl, exports: []const *Module.Export) !void { for (exports) |exp| { if (exp.options.section) |section_name| { if (!std.mem.eql(u8, section_name, ".text")) { try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1); module.failed_exports.putAssumeCapacityNoClobber( exp, try Module.ErrorMsg.create(self.base.allocator, 0, "Unimplemented: ExportOptions.section", .{}), ); continue; } } if (std.mem.eql(u8, exp.options.name, "_start")) { self.entry_addr = decl.link.coff.getVAddr(self.*) - image_base; } else { try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1); module.failed_exports.putAssumeCapacityNoClobber( exp, try Module.ErrorMsg.create(self.base.allocator, 0, "Unimplemented: Exports other than '_start'", .{}), ); continue; } } } pub fn flush(self: *Coff, module: *Module) !void { if (self.text_section_size_dirty) { // Write the new raw size in the .text header var buf: [4]u8 = undefined; std.mem.writeIntLittle(u32, &buf, self.text_section_size); try self.base.file.?.pwriteAll(&buf, self.section_table_offset + 40 + 16); try self.base.file.?.setEndPos(self.section_data_offset + self.offset_table_size + self.text_section_size); self.text_section_size_dirty = false; } if (self.base.options.output_mode == .Exe and self.size_of_image_dirty) { const new_size_of_image = std.mem.alignForwardGeneric(u32, self.text_section_virtual_address - image_base + self.text_section_size, section_alignment); var buf: [4]u8 = undefined; std.mem.writeIntLittle(u32, &buf, new_size_of_image); try self.base.file.?.pwriteAll(&buf, self.optional_header_offset + 56); self.size_of_image_dirty = false; } if (self.entry_addr == null and self.base.options.output_mode == .Exe) { log.debug("flushing. no_entry_point_found = true\n", .{}); self.error_flags.no_entry_point_found = true; } else { log.debug("flushing. no_entry_point_found = false\n", .{}); self.error_flags.no_entry_point_found = false; if (self.base.options.output_mode == .Exe) { // Write AddressOfEntryPoint var buf: [4]u8 = undefined; std.mem.writeIntLittle(u32, &buf, self.entry_addr.?); try self.base.file.?.pwriteAll(&buf, self.optional_header_offset + 16); } } } pub fn getDeclVAddr(self: *Coff, decl: *const Module.Decl) u64 { return self.text_section_virtual_address + decl.link.coff.text_offset; } pub fn updateDeclLineNumber(self: *Coff, module: *Module, decl: *Module.Decl) !void { // TODO Implement this } pub fn deinit(self: *Coff) void { self.text_block_free_list.deinit(self.base.allocator); self.offset_table.deinit(self.base.allocator); self.offset_table_free_list.deinit(self.base.allocator); }
src-self-hosted/link/Coff.zig
const std = @import("std"); const utils = @import("utils"); const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const print = utils.print; const Rule = struct { pair: [2]u8, inserted: u8, }; const Input = struct { template: []u8, rules: []Rule, }; fn readInput(arena: *ArenaAllocator, lines_it: *utils.FileLineIterator) anyerror!Input { const template = lines_it.next().?; _ = lines_it.next(); // Skip empty line var rules = try std.ArrayList(Rule).initCapacity(&arena.allocator, 4096); while (lines_it.next()) |line| { var tokens = std.mem.tokenize(u8, line, " ->"); const rule = tokens.next().?; const inserted = tokens.next().?; try rules.append(Rule{ .pair = .{ rule[0], rule[1] }, .inserted = inserted[0] }); } print("File ok :) Number of inputs: {d}", .{rules.items.len}); return Input{ .template = template, .rules = rules.items, }; } fn part1(arena: *ArenaAllocator, input: Input) anyerror!i32 { var template = input.template; var step: i32 = 0; while (step < 10) : (step += 1) { var result = try std.ArrayList(u8).initCapacity(&arena.allocator, 4096); for (template) |t| { if (result.items.len == 0) { try result.append(t); continue; } const prev = result.items[result.items.len - 1]; for (input.rules) |r| { if (r.pair[0] == prev and r.pair[1] == t) { try result.append(r.inserted); break; } } try result.append(t); } template = result.items; } var counts = std.mem.zeroes([256]i32); for (template) |t| { counts[t] += 1; } var min: i32 = std.math.maxInt(i32); var max: i32 = std.math.minInt(i32); for (counts) |c| { if (c == 0) { continue; } min = std.math.min(c, min); max = std.math.max(c, max); } return max - min; } const Pair = struct { pair: [2]u8, count: i64, }; fn insertPair(pair_list: *std.ArrayList(Pair), pair: [2]u8, count: i64) anyerror!void { for (pair_list.items) |*p| { if (std.mem.eql(u8, &p.pair, &pair)) { p.count += count; break; } } else { try pair_list.append(Pair{ .pair = pair, .count = count }); } } fn part2(arena: *ArenaAllocator, input: Input) anyerror!i64 { // Pairify initial string var initial_pairs = try std.ArrayList(Pair).initCapacity(&arena.allocator, 4096); for (input.template) |t, i| { const next_t = if (i + 1 < input.template.len) input.template[i + 1] else ' '; try insertPair(&initial_pairs, .{ t, next_t }, 1); } // Run the insertion process var step: i32 = 0; var prev_pairs = initial_pairs.items; while (step < 40) : (step += 1) { var new_pairs = try std.ArrayList(Pair).initCapacity(&arena.allocator, 4096); for (prev_pairs) |prev_pair| { for (input.rules) |rule| { const p = prev_pair.pair; if (std.mem.eql(u8, &rule.pair, &p)) { try insertPair(&new_pairs, .{ p[0], rule.inserted }, prev_pair.count); try insertPair(&new_pairs, .{ rule.inserted, p[1] }, prev_pair.count); break; } } else { try insertPair(&new_pairs, prev_pair.pair, prev_pair.count); } } prev_pairs = new_pairs.items; } // Count elements var counts = std.mem.zeroes([256]i64); for (prev_pairs) |p| { counts[p.pair[0]] += p.count; } var min: i64 = std.math.maxInt(i64); var max: i64 = std.math.minInt(i64); for (counts) |c| { if (c == 0) { continue; } min = std.math.min(c, min); max = std.math.max(c, max); } const res = max - min; return res; } pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var lines_it = try utils.iterateLinesInFile(&arena.allocator, "input.txt"); defer lines_it.deinit(); const input = try readInput(&arena, &lines_it); const part1_result = try part1(&arena, input); print("Part 1: {d}", .{part1_result}); const part2_result = try part2(&arena, input); print("Part 2: {d}", .{part2_result}); }
day14/src/main.zig
const std = @import("std"); const c = @import("c.zig"); const shaderc = @import("shaderc.zig"); const Viewport = @import("viewport.zig").Viewport; pub const Blit = struct { const Self = @This(); initialized: bool = false, device: c.WGPUDeviceId, queue: c.WGPUQueueId, bind_group_layout: c.WGPUBindGroupLayoutId, bind_group: c.WGPUBindGroupId, render_pipeline: c.WGPURenderPipelineId, pub fn init( alloc: *std.mem.Allocator, device: c.WGPUDeviceId, uniform_buf: c.WGPUBufferId, image_buf: c.WGPUBufferId, image_buf_size: u32, ) !Blit { var arena = std.heap.ArenaAllocator.init(alloc); const tmp_alloc: *std.mem.Allocator = &arena.allocator; defer arena.deinit(); //////////////////////////////////////////////////////////////////////////// // Build the shaders using shaderc const blit_vert_name = "shaders/blit.vert"; const vert_spv = shaderc.build_shader_from_file(tmp_alloc, blit_vert_name) catch { std.debug.panic("Could not open file", .{}); }; const vert_shader = c.wgpu_device_create_shader_module( device, &(c.WGPUShaderModuleDescriptor){ .label = blit_vert_name, .bytes = vert_spv.ptr, .length = vert_spv.len, .flags = c.WGPUShaderFlags_VALIDATION, }, ); defer c.wgpu_shader_module_destroy(vert_shader); const blit_frag_name = "shaders/blit.frag"; const frag_spv = shaderc.build_shader_from_file(tmp_alloc, blit_frag_name) catch { std.debug.panic("Could not open file", .{}); }; const frag_shader = c.wgpu_device_create_shader_module( device, &(c.WGPUShaderModuleDescriptor){ .label = blit_frag_name, .bytes = frag_spv.ptr, .length = frag_spv.len, .flags = c.WGPUShaderFlags_VALIDATION, }, ); defer c.wgpu_shader_module_destroy(frag_shader); //////////////////////////////////////////////////////////////////////////// // Bind groups const bind_group_layout_entries = [_]c.WGPUBindGroupLayoutEntry{ (c.WGPUBindGroupLayoutEntry){ // Pseudo-texture .binding = 0, .visibility = c.WGPUShaderStage_FRAGMENT, .ty = c.WGPUBindingType_StorageBuffer, .has_dynamic_offset = false, .min_buffer_binding_size = 0, .multisampled = undefined, .filtering = undefined, .view_dimension = undefined, .texture_component_type = undefined, .storage_texture_format = undefined, .count = undefined, }, (c.WGPUBindGroupLayoutEntry){ // Uniforms buffer .binding = 1, .visibility = c.WGPUShaderStage_FRAGMENT, .ty = c.WGPUBindingType_UniformBuffer, .has_dynamic_offset = false, .min_buffer_binding_size = 0, .multisampled = undefined, .filtering = undefined, .view_dimension = undefined, .texture_component_type = undefined, .storage_texture_format = undefined, .count = undefined, }, }; const bind_group_layout = c.wgpu_device_create_bind_group_layout( device, &(c.WGPUBindGroupLayoutDescriptor){ .label = "bind group layout", .entries = &bind_group_layout_entries, .entries_length = bind_group_layout_entries.len, }, ); const bind_group_layouts = [_]c.WGPUBindGroupId{bind_group_layout}; //////////////////////////////////////////////////////////////////////////// // Render pipelines const pipeline_layout = c.wgpu_device_create_pipeline_layout( device, &(c.WGPUPipelineLayoutDescriptor){ .label = "blit pipeline", .bind_group_layouts = &bind_group_layouts, .bind_group_layouts_length = bind_group_layouts.len, }, ); defer c.wgpu_pipeline_layout_destroy(pipeline_layout); const render_pipeline = c.wgpu_device_create_render_pipeline( device, &(c.WGPURenderPipelineDescriptor){ .label = "blit render pipeline", .layout = pipeline_layout, .vertex_stage = (c.WGPUProgrammableStageDescriptor){ .module = vert_shader, .entry_point = "main", }, .fragment_stage = &(c.WGPUProgrammableStageDescriptor){ .module = frag_shader, .entry_point = "main", }, .rasterization_state = &(c.WGPURasterizationStateDescriptor){ // .front_face = c.WGPUFrontFace._Ccw, .front_face = c.WGPUFrontFace_Ccw, // .cull_mode = c.WGPUCullMode._None, .cull_mode = c.WGPUCullMode_None, .depth_bias = 0, .depth_bias_slope_scale = 0.0, .depth_bias_clamp = 0.0, // .polygon_mode = c.WGPUPolygonMode._Fill, .polygon_mode = c.WGPUPolygonMode_Fill, .clamp_depth = false, }, // .primitive_topology = c.WGPUPrimitiveTopology._TriangleList, .primitive_topology = c.WGPUPrimitiveTopology_TriangleList, .color_states = &(c.WGPUColorStateDescriptor){ // .format = c.WGPUTextureFormat._Bgra8Unorm, .format = c.WGPUTextureFormat_Bgra8Unorm, .alpha_blend = (c.WGPUBlendDescriptor){ // .src_factor = c.WGPUBlendFactor._One, .src_factor = c.WGPUBlendFactor_One, .dst_factor = c.WGPUBlendFactor_Zero, .operation = c.WGPUBlendOperation_Add, }, .color_blend = (c.WGPUBlendDescriptor){ .src_factor = c.WGPUBlendFactor_One, .dst_factor = c.WGPUBlendFactor_Zero, .operation = c.WGPUBlendOperation_Add, }, .write_mask = c.WGPUColorWrite_ALL, }, .color_states_length = 1, .depth_stencil_state = null, .vertex_state = (c.WGPUVertexStateDescriptor){ .index_format = c.WGPUIndexFormat_Undefined, .vertex_buffers = null, .vertex_buffers_length = 0, }, .sample_count = 1, .sample_mask = 0, .alpha_to_coverage = false, }, ); var out = Self{ .device = device, .queue = c.wgpu_device_get_default_queue(device), .render_pipeline = render_pipeline, .bind_group_layout = bind_group_layout, .bind_group = undefined, // Assigned in bind below }; out.bind(uniform_buf, image_buf, image_buf_size); out.initialized = true; return out; } pub fn bind( self: *Self, uniform_buf: c.WGPUBufferId, image_buf: c.WGPUBufferId, image_buf_size: u32, ) void { if (self.initialized) { c.wgpu_bind_group_destroy(self.bind_group); } const bind_group_entries = [_]c.WGPUBindGroupEntry{ (c.WGPUBindGroupEntry){ .binding = 0, .buffer = image_buf, .offset = 0, .size = image_buf_size, .sampler = 0, // None .texture_view = 0, // None }, (c.WGPUBindGroupEntry){ .binding = 1, .buffer = uniform_buf, .offset = 0, .size = @sizeOf(c.rayUniforms), .sampler = 0, // None .texture_view = 0, // None }, }; self.bind_group = c.wgpu_device_create_bind_group( self.device, &(c.WGPUBindGroupDescriptor){ .label = "bind group", .layout = self.bind_group_layout, .entries = &bind_group_entries, .entries_length = bind_group_entries.len, }, ); } pub fn deinit(self: *Self) void { c.wgpu_bind_group_layout_destroy(self.bind_group_layout); c.wgpu_bind_group_destroy(self.bind_group); } pub fn draw( self: *const Self, viewport: Viewport, next_texture: c.WGPUOption_TextureViewId, cmd_encoder: c.WGPUCommandEncoderId, ) void { const color_attachments = [_]c.WGPUColorAttachmentDescriptor{ (c.WGPUColorAttachmentDescriptor){ .attachment = next_texture, .resolve_target = 0, .channel = (c.WGPUPassChannel_Color){ .load_op = c.WGPULoadOp_Load, .store_op = c.WGPUStoreOp_Store, .clear_value = (c.WGPUColor){ .r = 0.0, .g = 0.0, .b = 0.0, .a = 1.0, }, .read_only = false, }, }, }; const rpass = c.wgpu_command_encoder_begin_render_pass( cmd_encoder, &(c.WGPURenderPassDescriptor){ .label = "blit rpass", .color_attachments = &color_attachments, .color_attachments_length = color_attachments.len, .depth_stencil_attachment = null, }, ); c.wgpu_render_pass_set_pipeline(rpass, self.render_pipeline); c.wgpu_render_pass_set_bind_group(rpass, 0, self.bind_group, null, 0); c.wgpu_render_pass_set_viewport( rpass, viewport.x, viewport.y, viewport.width, viewport.height, 0, 1, ); c.wgpu_render_pass_draw(rpass, 3, 1, 0, 0); c.wgpu_render_pass_end_pass(rpass); } };
src/blit.zig
pub const _MM_HINT_T0 = @as(u32, 1); pub const _MM_HINT_T1 = @as(u32, 2); pub const _MM_HINT_T2 = @as(u32, 3); pub const _MM_HINT_NTA = @as(u32, 0); pub const ANYSIZE_ARRAY = @as(u32, 1); pub const MEMORY_ALLOCATION_ALIGNMENT = @as(u32, 16); pub const X86_CACHE_ALIGNMENT_SIZE = @as(u32, 64); pub const ARM_CACHE_ALIGNMENT_SIZE = @as(u32, 128); pub const SYSTEM_CACHE_ALIGNMENT_SIZE = @as(u32, 64); pub const PRAGMA_DEPRECATED_DDK = @as(u32, 1); pub const UCSCHAR_INVALID_CHARACTER = @as(u32, 4294967295); pub const MIN_UCSCHAR = @as(u32, 0); pub const MAX_UCSCHAR = @as(u32, 1114111); pub const ALL_PROCESSOR_GROUPS = @as(u32, 65535); pub const MAXIMUM_PROC_PER_GROUP = @as(u32, 64); pub const MAXIMUM_PROCESSORS = @as(u32, 64); pub const APPLICATION_ERROR_MASK = @as(u32, 536870912); pub const ERROR_SEVERITY_SUCCESS = @as(u32, 0); pub const ERROR_SEVERITY_INFORMATIONAL = @as(u32, 1073741824); pub const ERROR_SEVERITY_WARNING = @as(u32, 2147483648); pub const ERROR_SEVERITY_ERROR = @as(u32, 3221225472); pub const MAXLONGLONG = @as(u64, 9223372036854775807); pub const UNICODE_STRING_MAX_CHARS = @as(u32, 32767); pub const MINCHAR = @as(u32, 128); pub const MAXCHAR = @as(u32, 127); pub const MINSHORT = @as(u32, 32768); pub const MAXSHORT = @as(u32, 32767); pub const MINLONG = @as(u32, 2147483648); pub const MAXLONG = @as(u32, 2147483647); pub const MAXBYTE = @as(u32, 255); pub const MAXWORD = @as(u32, 65535); pub const MAXDWORD = @as(u32, 4294967295); pub const ENCLAVE_SHORT_ID_LENGTH = @as(u32, 16); pub const ENCLAVE_LONG_ID_LENGTH = @as(u32, 32); pub const VER_SERVER_NT = @as(u32, 2147483648); pub const VER_WORKSTATION_NT = @as(u32, 1073741824); pub const VER_SUITE_SMALLBUSINESS = @as(u32, 1); pub const VER_SUITE_ENTERPRISE = @as(u32, 2); pub const VER_SUITE_BACKOFFICE = @as(u32, 4); pub const VER_SUITE_COMMUNICATIONS = @as(u32, 8); pub const VER_SUITE_TERMINAL = @as(u32, 16); pub const VER_SUITE_SMALLBUSINESS_RESTRICTED = @as(u32, 32); pub const VER_SUITE_EMBEDDEDNT = @as(u32, 64); pub const VER_SUITE_DATACENTER = @as(u32, 128); pub const VER_SUITE_SINGLEUSERTS = @as(u32, 256); pub const VER_SUITE_PERSONAL = @as(u32, 512); pub const VER_SUITE_BLADE = @as(u32, 1024); pub const VER_SUITE_EMBEDDED_RESTRICTED = @as(u32, 2048); pub const VER_SUITE_SECURITY_APPLIANCE = @as(u32, 4096); pub const VER_SUITE_STORAGE_SERVER = @as(u32, 8192); pub const VER_SUITE_COMPUTE_SERVER = @as(u32, 16384); pub const VER_SUITE_WH_SERVER = @as(u32, 32768); pub const VER_SUITE_MULTIUSERTS = @as(u32, 131072); pub const PRODUCT_STANDARD_SERVER_CORE = @as(u32, 13); pub const PRODUCT_SOLUTION_EMBEDDEDSERVER_CORE = @as(u32, 57); pub const PRODUCT_PROFESSIONAL_EMBEDDED = @as(u32, 58); pub const PRODUCT_EMBEDDED = @as(u32, 65); pub const PRODUCT_EMBEDDED_AUTOMOTIVE = @as(u32, 85); pub const PRODUCT_EMBEDDED_INDUSTRY_A = @as(u32, 86); pub const PRODUCT_THINPC = @as(u32, 87); pub const PRODUCT_EMBEDDED_A = @as(u32, 88); pub const PRODUCT_EMBEDDED_INDUSTRY = @as(u32, 89); pub const PRODUCT_EMBEDDED_E = @as(u32, 90); pub const PRODUCT_EMBEDDED_INDUSTRY_E = @as(u32, 91); pub const PRODUCT_EMBEDDED_INDUSTRY_A_E = @as(u32, 92); pub const PRODUCT_CORE_ARM = @as(u32, 97); pub const PRODUCT_EMBEDDED_INDUSTRY_EVAL = @as(u32, 105); pub const PRODUCT_EMBEDDED_INDUSTRY_E_EVAL = @as(u32, 106); pub const PRODUCT_EMBEDDED_EVAL = @as(u32, 107); pub const PRODUCT_EMBEDDED_E_EVAL = @as(u32, 108); pub const PRODUCT_NANO_SERVER = @as(u32, 109); pub const PRODUCT_CLOUD_STORAGE_SERVER = @as(u32, 110); pub const PRODUCT_CORE_CONNECTED = @as(u32, 111); pub const PRODUCT_PROFESSIONAL_STUDENT = @as(u32, 112); pub const PRODUCT_CORE_CONNECTED_N = @as(u32, 113); pub const PRODUCT_PROFESSIONAL_STUDENT_N = @as(u32, 114); pub const PRODUCT_CORE_CONNECTED_SINGLELANGUAGE = @as(u32, 115); pub const PRODUCT_CORE_CONNECTED_COUNTRYSPECIFIC = @as(u32, 116); pub const PRODUCT_CONNECTED_CAR = @as(u32, 117); pub const PRODUCT_INDUSTRY_HANDHELD = @as(u32, 118); pub const PRODUCT_PPI_PRO = @as(u32, 119); pub const PRODUCT_ARM64_SERVER = @as(u32, 120); pub const PRODUCT_CLOUD_HOST_INFRASTRUCTURE_SERVER = @as(u32, 124); pub const PRODUCT_PROFESSIONAL_S = @as(u32, 127); pub const PRODUCT_PROFESSIONAL_S_N = @as(u32, 128); pub const PRODUCT_HOLOGRAPHIC = @as(u32, 135); pub const PRODUCT_HOLOGRAPHIC_BUSINESS = @as(u32, 136); pub const PRODUCT_PRO_SINGLE_LANGUAGE = @as(u32, 138); pub const PRODUCT_PRO_CHINA = @as(u32, 139); pub const PRODUCT_ENTERPRISE_SUBSCRIPTION = @as(u32, 140); pub const PRODUCT_ENTERPRISE_SUBSCRIPTION_N = @as(u32, 141); pub const PRODUCT_DATACENTER_NANO_SERVER = @as(u32, 143); pub const PRODUCT_STANDARD_NANO_SERVER = @as(u32, 144); pub const PRODUCT_DATACENTER_WS_SERVER_CORE = @as(u32, 147); pub const PRODUCT_STANDARD_WS_SERVER_CORE = @as(u32, 148); pub const PRODUCT_UTILITY_VM = @as(u32, 149); pub const PRODUCT_DATACENTER_EVALUATION_SERVER_CORE = @as(u32, 159); pub const PRODUCT_STANDARD_EVALUATION_SERVER_CORE = @as(u32, 160); pub const PRODUCT_PRO_FOR_EDUCATION = @as(u32, 164); pub const PRODUCT_PRO_FOR_EDUCATION_N = @as(u32, 165); pub const PRODUCT_AZURE_SERVER_CORE = @as(u32, 168); pub const PRODUCT_AZURE_NANO_SERVER = @as(u32, 169); pub const PRODUCT_ENTERPRISEG = @as(u32, 171); pub const PRODUCT_ENTERPRISEGN = @as(u32, 172); pub const PRODUCT_SERVERRDSH = @as(u32, 175); pub const PRODUCT_CLOUD = @as(u32, 178); pub const PRODUCT_CLOUDN = @as(u32, 179); pub const PRODUCT_HUBOS = @as(u32, 180); pub const PRODUCT_ONECOREUPDATEOS = @as(u32, 182); pub const PRODUCT_CLOUDE = @as(u32, 183); pub const PRODUCT_IOTOS = @as(u32, 185); pub const PRODUCT_CLOUDEN = @as(u32, 186); pub const PRODUCT_IOTEDGEOS = @as(u32, 187); pub const PRODUCT_IOTENTERPRISE = @as(u32, 188); pub const PRODUCT_LITE = @as(u32, 189); pub const PRODUCT_IOTENTERPRISES = @as(u32, 191); pub const PRODUCT_XBOX_SYSTEMOS = @as(u32, 192); pub const PRODUCT_XBOX_NATIVEOS = @as(u32, 193); pub const PRODUCT_XBOX_GAMEOS = @as(u32, 194); pub const PRODUCT_XBOX_ERAOS = @as(u32, 195); pub const PRODUCT_XBOX_DURANGOHOSTOS = @as(u32, 196); pub const PRODUCT_XBOX_SCARLETTHOSTOS = @as(u32, 197); pub const PRODUCT_AZURE_SERVER_CLOUDHOST = @as(u32, 199); pub const PRODUCT_AZURE_SERVER_CLOUDMOS = @as(u32, 200); pub const PRODUCT_CLOUDEDITIONN = @as(u32, 202); pub const PRODUCT_CLOUDEDITION = @as(u32, 203); pub const PRODUCT_AZURESTACKHCI_SERVER_CORE = @as(u32, 406); pub const PRODUCT_DATACENTER_SERVER_AZURE_EDITION = @as(u32, 407); pub const PRODUCT_DATACENTER_SERVER_CORE_AZURE_EDITION = @as(u32, 408); pub const PRODUCT_UNLICENSED = @as(u32, 2882382797); pub const LANG_NEUTRAL = @as(u32, 0); pub const LANG_INVARIANT = @as(u32, 127); pub const LANG_AFRIKAANS = @as(u32, 54); pub const LANG_ALBANIAN = @as(u32, 28); pub const LANG_ALSATIAN = @as(u32, 132); pub const LANG_AMHARIC = @as(u32, 94); pub const LANG_ARABIC = @as(u32, 1); pub const LANG_ARMENIAN = @as(u32, 43); pub const LANG_ASSAMESE = @as(u32, 77); pub const LANG_AZERI = @as(u32, 44); pub const LANG_AZERBAIJANI = @as(u32, 44); pub const LANG_BANGLA = @as(u32, 69); pub const LANG_BASHKIR = @as(u32, 109); pub const LANG_BASQUE = @as(u32, 45); pub const LANG_BELARUSIAN = @as(u32, 35); pub const LANG_BENGALI = @as(u32, 69); pub const LANG_BRETON = @as(u32, 126); pub const LANG_BOSNIAN = @as(u32, 26); pub const LANG_BOSNIAN_NEUTRAL = @as(u32, 30746); pub const LANG_BULGARIAN = @as(u32, 2); pub const LANG_CATALAN = @as(u32, 3); pub const LANG_CENTRAL_KURDISH = @as(u32, 146); pub const LANG_CHEROKEE = @as(u32, 92); pub const LANG_CHINESE = @as(u32, 4); pub const LANG_CHINESE_SIMPLIFIED = @as(u32, 4); pub const LANG_CHINESE_TRADITIONAL = @as(u32, 31748); pub const LANG_CORSICAN = @as(u32, 131); pub const LANG_CROATIAN = @as(u32, 26); pub const LANG_CZECH = @as(u32, 5); pub const LANG_DANISH = @as(u32, 6); pub const LANG_DARI = @as(u32, 140); pub const LANG_DIVEHI = @as(u32, 101); pub const LANG_DUTCH = @as(u32, 19); pub const LANG_ENGLISH = @as(u32, 9); pub const LANG_ESTONIAN = @as(u32, 37); pub const LANG_FAEROESE = @as(u32, 56); pub const LANG_FARSI = @as(u32, 41); pub const LANG_FILIPINO = @as(u32, 100); pub const LANG_FINNISH = @as(u32, 11); pub const LANG_FRENCH = @as(u32, 12); pub const LANG_FRISIAN = @as(u32, 98); pub const LANG_FULAH = @as(u32, 103); pub const LANG_GALICIAN = @as(u32, 86); pub const LANG_GEORGIAN = @as(u32, 55); pub const LANG_GERMAN = @as(u32, 7); pub const LANG_GREEK = @as(u32, 8); pub const LANG_GREENLANDIC = @as(u32, 111); pub const LANG_GUJARATI = @as(u32, 71); pub const LANG_HAUSA = @as(u32, 104); pub const LANG_HAWAIIAN = @as(u32, 117); pub const LANG_HEBREW = @as(u32, 13); pub const LANG_HINDI = @as(u32, 57); pub const LANG_HUNGARIAN = @as(u32, 14); pub const LANG_ICELANDIC = @as(u32, 15); pub const LANG_IGBO = @as(u32, 112); pub const LANG_INDONESIAN = @as(u32, 33); pub const LANG_INUKTITUT = @as(u32, 93); pub const LANG_IRISH = @as(u32, 60); pub const LANG_ITALIAN = @as(u32, 16); pub const LANG_JAPANESE = @as(u32, 17); pub const LANG_KANNADA = @as(u32, 75); pub const LANG_KASHMIRI = @as(u32, 96); pub const LANG_KAZAK = @as(u32, 63); pub const LANG_KHMER = @as(u32, 83); pub const LANG_KICHE = @as(u32, 134); pub const LANG_KINYARWANDA = @as(u32, 135); pub const LANG_KONKANI = @as(u32, 87); pub const LANG_KOREAN = @as(u32, 18); pub const LANG_KYRGYZ = @as(u32, 64); pub const LANG_LAO = @as(u32, 84); pub const LANG_LATVIAN = @as(u32, 38); pub const LANG_LITHUANIAN = @as(u32, 39); pub const LANG_LOWER_SORBIAN = @as(u32, 46); pub const LANG_LUXEMBOURGISH = @as(u32, 110); pub const LANG_MACEDONIAN = @as(u32, 47); pub const LANG_MALAY = @as(u32, 62); pub const LANG_MALAYALAM = @as(u32, 76); pub const LANG_MALTESE = @as(u32, 58); pub const LANG_MANIPURI = @as(u32, 88); pub const LANG_MAORI = @as(u32, 129); pub const LANG_MAPUDUNGUN = @as(u32, 122); pub const LANG_MARATHI = @as(u32, 78); pub const LANG_MOHAWK = @as(u32, 124); pub const LANG_MONGOLIAN = @as(u32, 80); pub const LANG_NEPALI = @as(u32, 97); pub const LANG_NORWEGIAN = @as(u32, 20); pub const LANG_OCCITAN = @as(u32, 130); pub const LANG_ODIA = @as(u32, 72); pub const LANG_ORIYA = @as(u32, 72); pub const LANG_PASHTO = @as(u32, 99); pub const LANG_PERSIAN = @as(u32, 41); pub const LANG_POLISH = @as(u32, 21); pub const LANG_PORTUGUESE = @as(u32, 22); pub const LANG_PULAR = @as(u32, 103); pub const LANG_PUNJABI = @as(u32, 70); pub const LANG_QUECHUA = @as(u32, 107); pub const LANG_ROMANIAN = @as(u32, 24); pub const LANG_ROMANSH = @as(u32, 23); pub const LANG_RUSSIAN = @as(u32, 25); pub const LANG_SAKHA = @as(u32, 133); pub const LANG_SAMI = @as(u32, 59); pub const LANG_SANSKRIT = @as(u32, 79); pub const LANG_SCOTTISH_GAELIC = @as(u32, 145); pub const LANG_SERBIAN = @as(u32, 26); pub const LANG_SERBIAN_NEUTRAL = @as(u32, 31770); pub const LANG_SINDHI = @as(u32, 89); pub const LANG_SINHALESE = @as(u32, 91); pub const LANG_SLOVAK = @as(u32, 27); pub const LANG_SLOVENIAN = @as(u32, 36); pub const LANG_SOTHO = @as(u32, 108); pub const LANG_SPANISH = @as(u32, 10); pub const LANG_SWAHILI = @as(u32, 65); pub const LANG_SWEDISH = @as(u32, 29); pub const LANG_SYRIAC = @as(u32, 90); pub const LANG_TAJIK = @as(u32, 40); pub const LANG_TAMAZIGHT = @as(u32, 95); pub const LANG_TAMIL = @as(u32, 73); pub const LANG_TATAR = @as(u32, 68); pub const LANG_TELUGU = @as(u32, 74); pub const LANG_THAI = @as(u32, 30); pub const LANG_TIBETAN = @as(u32, 81); pub const LANG_TIGRIGNA = @as(u32, 115); pub const LANG_TIGRINYA = @as(u32, 115); pub const LANG_TSWANA = @as(u32, 50); pub const LANG_TURKISH = @as(u32, 31); pub const LANG_TURKMEN = @as(u32, 66); pub const LANG_UIGHUR = @as(u32, 128); pub const LANG_UKRAINIAN = @as(u32, 34); pub const LANG_UPPER_SORBIAN = @as(u32, 46); pub const LANG_URDU = @as(u32, 32); pub const LANG_UZBEK = @as(u32, 67); pub const LANG_VALENCIAN = @as(u32, 3); pub const LANG_VIETNAMESE = @as(u32, 42); pub const LANG_WELSH = @as(u32, 82); pub const LANG_WOLOF = @as(u32, 136); pub const LANG_XHOSA = @as(u32, 52); pub const LANG_YAKUT = @as(u32, 133); pub const LANG_YI = @as(u32, 120); pub const LANG_YORUBA = @as(u32, 106); pub const LANG_ZULU = @as(u32, 53); pub const SUBLANG_NEUTRAL = @as(u32, 0); pub const SUBLANG_DEFAULT = @as(u32, 1); pub const SUBLANG_SYS_DEFAULT = @as(u32, 2); pub const SUBLANG_CUSTOM_DEFAULT = @as(u32, 3); pub const SUBLANG_CUSTOM_UNSPECIFIED = @as(u32, 4); pub const SUBLANG_UI_CUSTOM_DEFAULT = @as(u32, 5); pub const SUBLANG_AFRIKAANS_SOUTH_AFRICA = @as(u32, 1); pub const SUBLANG_ALBANIAN_ALBANIA = @as(u32, 1); pub const SUBLANG_ALSATIAN_FRANCE = @as(u32, 1); pub const SUBLANG_AMHARIC_ETHIOPIA = @as(u32, 1); pub const SUBLANG_ARABIC_SAUDI_ARABIA = @as(u32, 1); pub const SUBLANG_ARABIC_IRAQ = @as(u32, 2); pub const SUBLANG_ARABIC_EGYPT = @as(u32, 3); pub const SUBLANG_ARABIC_LIBYA = @as(u32, 4); pub const SUBLANG_ARABIC_ALGERIA = @as(u32, 5); pub const SUBLANG_ARABIC_MOROCCO = @as(u32, 6); pub const SUBLANG_ARABIC_TUNISIA = @as(u32, 7); pub const SUBLANG_ARABIC_OMAN = @as(u32, 8); pub const SUBLANG_ARABIC_YEMEN = @as(u32, 9); pub const SUBLANG_ARABIC_SYRIA = @as(u32, 10); pub const SUBLANG_ARABIC_JORDAN = @as(u32, 11); pub const SUBLANG_ARABIC_LEBANON = @as(u32, 12); pub const SUBLANG_ARABIC_KUWAIT = @as(u32, 13); pub const SUBLANG_ARABIC_UAE = @as(u32, 14); pub const SUBLANG_ARABIC_BAHRAIN = @as(u32, 15); pub const SUBLANG_ARABIC_QATAR = @as(u32, 16); pub const SUBLANG_ARMENIAN_ARMENIA = @as(u32, 1); pub const SUBLANG_ASSAMESE_INDIA = @as(u32, 1); pub const SUBLANG_AZERI_LATIN = @as(u32, 1); pub const SUBLANG_AZERI_CYRILLIC = @as(u32, 2); pub const SUBLANG_AZERBAIJANI_AZERBAIJAN_LATIN = @as(u32, 1); pub const SUBLANG_AZERBAIJANI_AZERBAIJAN_CYRILLIC = @as(u32, 2); pub const SUBLANG_BANGLA_INDIA = @as(u32, 1); pub const SUBLANG_BANGLA_BANGLADESH = @as(u32, 2); pub const SUBLANG_BASHKIR_RUSSIA = @as(u32, 1); pub const SUBLANG_BASQUE_BASQUE = @as(u32, 1); pub const SUBLANG_BELARUSIAN_BELARUS = @as(u32, 1); pub const SUBLANG_BENGALI_INDIA = @as(u32, 1); pub const SUBLANG_BENGALI_BANGLADESH = @as(u32, 2); pub const SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_LATIN = @as(u32, 5); pub const SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_CYRILLIC = @as(u32, 8); pub const SUBLANG_BRETON_FRANCE = @as(u32, 1); pub const SUBLANG_BULGARIAN_BULGARIA = @as(u32, 1); pub const SUBLANG_CATALAN_CATALAN = @as(u32, 1); pub const SUBLANG_CENTRAL_KURDISH_IRAQ = @as(u32, 1); pub const SUBLANG_CHEROKEE_CHEROKEE = @as(u32, 1); pub const SUBLANG_CHINESE_TRADITIONAL = @as(u32, 1); pub const SUBLANG_CHINESE_SIMPLIFIED = @as(u32, 2); pub const SUBLANG_CHINESE_HONGKONG = @as(u32, 3); pub const SUBLANG_CHINESE_SINGAPORE = @as(u32, 4); pub const SUBLANG_CHINESE_MACAU = @as(u32, 5); pub const SUBLANG_CORSICAN_FRANCE = @as(u32, 1); pub const SUBLANG_CZECH_CZECH_REPUBLIC = @as(u32, 1); pub const SUBLANG_CROATIAN_CROATIA = @as(u32, 1); pub const SUBLANG_CROATIAN_BOSNIA_HERZEGOVINA_LATIN = @as(u32, 4); pub const SUBLANG_DANISH_DENMARK = @as(u32, 1); pub const SUBLANG_DARI_AFGHANISTAN = @as(u32, 1); pub const SUBLANG_DIVEHI_MALDIVES = @as(u32, 1); pub const SUBLANG_DUTCH = @as(u32, 1); pub const SUBLANG_DUTCH_BELGIAN = @as(u32, 2); pub const SUBLANG_ENGLISH_US = @as(u32, 1); pub const SUBLANG_ENGLISH_UK = @as(u32, 2); pub const SUBLANG_ENGLISH_AUS = @as(u32, 3); pub const SUBLANG_ENGLISH_CAN = @as(u32, 4); pub const SUBLANG_ENGLISH_NZ = @as(u32, 5); pub const SUBLANG_ENGLISH_EIRE = @as(u32, 6); pub const SUBLANG_ENGLISH_SOUTH_AFRICA = @as(u32, 7); pub const SUBLANG_ENGLISH_JAMAICA = @as(u32, 8); pub const SUBLANG_ENGLISH_CARIBBEAN = @as(u32, 9); pub const SUBLANG_ENGLISH_BELIZE = @as(u32, 10); pub const SUBLANG_ENGLISH_TRINIDAD = @as(u32, 11); pub const SUBLANG_ENGLISH_ZIMBABWE = @as(u32, 12); pub const SUBLANG_ENGLISH_PHILIPPINES = @as(u32, 13); pub const SUBLANG_ENGLISH_INDIA = @as(u32, 16); pub const SUBLANG_ENGLISH_MALAYSIA = @as(u32, 17); pub const SUBLANG_ENGLISH_SINGAPORE = @as(u32, 18); pub const SUBLANG_ESTONIAN_ESTONIA = @as(u32, 1); pub const SUBLANG_FAEROESE_FAROE_ISLANDS = @as(u32, 1); pub const SUBLANG_FILIPINO_PHILIPPINES = @as(u32, 1); pub const SUBLANG_FINNISH_FINLAND = @as(u32, 1); pub const SUBLANG_FRENCH = @as(u32, 1); pub const SUBLANG_FRENCH_BELGIAN = @as(u32, 2); pub const SUBLANG_FRENCH_CANADIAN = @as(u32, 3); pub const SUBLANG_FRENCH_SWISS = @as(u32, 4); pub const SUBLANG_FRENCH_LUXEMBOURG = @as(u32, 5); pub const SUBLANG_FRENCH_MONACO = @as(u32, 6); pub const SUBLANG_FRISIAN_NETHERLANDS = @as(u32, 1); pub const SUBLANG_FULAH_SENEGAL = @as(u32, 2); pub const SUBLANG_GALICIAN_GALICIAN = @as(u32, 1); pub const SUBLANG_GEORGIAN_GEORGIA = @as(u32, 1); pub const SUBLANG_GERMAN = @as(u32, 1); pub const SUBLANG_GERMAN_SWISS = @as(u32, 2); pub const SUBLANG_GERMAN_AUSTRIAN = @as(u32, 3); pub const SUBLANG_GERMAN_LUXEMBOURG = @as(u32, 4); pub const SUBLANG_GERMAN_LIECHTENSTEIN = @as(u32, 5); pub const SUBLANG_GREEK_GREECE = @as(u32, 1); pub const SUBLANG_GREENLANDIC_GREENLAND = @as(u32, 1); pub const SUBLANG_GUJARATI_INDIA = @as(u32, 1); pub const SUBLANG_HAUSA_NIGERIA_LATIN = @as(u32, 1); pub const SUBLANG_HAWAIIAN_US = @as(u32, 1); pub const SUBLANG_HEBREW_ISRAEL = @as(u32, 1); pub const SUBLANG_HINDI_INDIA = @as(u32, 1); pub const SUBLANG_HUNGARIAN_HUNGARY = @as(u32, 1); pub const SUBLANG_ICELANDIC_ICELAND = @as(u32, 1); pub const SUBLANG_IGBO_NIGERIA = @as(u32, 1); pub const SUBLANG_INDONESIAN_INDONESIA = @as(u32, 1); pub const SUBLANG_INUKTITUT_CANADA = @as(u32, 1); pub const SUBLANG_INUKTITUT_CANADA_LATIN = @as(u32, 2); pub const SUBLANG_IRISH_IRELAND = @as(u32, 2); pub const SUBLANG_ITALIAN = @as(u32, 1); pub const SUBLANG_ITALIAN_SWISS = @as(u32, 2); pub const SUBLANG_JAPANESE_JAPAN = @as(u32, 1); pub const SUBLANG_KANNADA_INDIA = @as(u32, 1); pub const SUBLANG_KASHMIRI_SASIA = @as(u32, 2); pub const SUBLANG_KASHMIRI_INDIA = @as(u32, 2); pub const SUBLANG_KAZAK_KAZAKHSTAN = @as(u32, 1); pub const SUBLANG_KHMER_CAMBODIA = @as(u32, 1); pub const SUBLANG_KICHE_GUATEMALA = @as(u32, 1); pub const SUBLANG_KINYARWANDA_RWANDA = @as(u32, 1); pub const SUBLANG_KONKANI_INDIA = @as(u32, 1); pub const SUBLANG_KOREAN = @as(u32, 1); pub const SUBLANG_KYRGYZ_KYRGYZSTAN = @as(u32, 1); pub const SUBLANG_LAO_LAO = @as(u32, 1); pub const SUBLANG_LATVIAN_LATVIA = @as(u32, 1); pub const SUBLANG_LITHUANIAN = @as(u32, 1); pub const SUBLANG_LOWER_SORBIAN_GERMANY = @as(u32, 2); pub const SUBLANG_LUXEMBOURGISH_LUXEMBOURG = @as(u32, 1); pub const SUBLANG_MACEDONIAN_MACEDONIA = @as(u32, 1); pub const SUBLANG_MALAY_MALAYSIA = @as(u32, 1); pub const SUBLANG_MALAY_BRUNEI_DARUSSALAM = @as(u32, 2); pub const SUBLANG_MALAYALAM_INDIA = @as(u32, 1); pub const SUBLANG_MALTESE_MALTA = @as(u32, 1); pub const SUBLANG_MAORI_NEW_ZEALAND = @as(u32, 1); pub const SUBLANG_MAPUDUNGUN_CHILE = @as(u32, 1); pub const SUBLANG_MARATHI_INDIA = @as(u32, 1); pub const SUBLANG_MOHAWK_MOHAWK = @as(u32, 1); pub const SUBLANG_MONGOLIAN_CYRILLIC_MONGOLIA = @as(u32, 1); pub const SUBLANG_MONGOLIAN_PRC = @as(u32, 2); pub const SUBLANG_NEPALI_INDIA = @as(u32, 2); pub const SUBLANG_NEPALI_NEPAL = @as(u32, 1); pub const SUBLANG_NORWEGIAN_BOKMAL = @as(u32, 1); pub const SUBLANG_NORWEGIAN_NYNORSK = @as(u32, 2); pub const SUBLANG_OCCITAN_FRANCE = @as(u32, 1); pub const SUBLANG_ODIA_INDIA = @as(u32, 1); pub const SUBLANG_ORIYA_INDIA = @as(u32, 1); pub const SUBLANG_PASHTO_AFGHANISTAN = @as(u32, 1); pub const SUBLANG_PERSIAN_IRAN = @as(u32, 1); pub const SUBLANG_POLISH_POLAND = @as(u32, 1); pub const SUBLANG_PORTUGUESE = @as(u32, 2); pub const SUBLANG_PORTUGUESE_BRAZILIAN = @as(u32, 1); pub const SUBLANG_PULAR_SENEGAL = @as(u32, 2); pub const SUBLANG_PUNJABI_INDIA = @as(u32, 1); pub const SUBLANG_PUNJABI_PAKISTAN = @as(u32, 2); pub const SUBLANG_QUECHUA_BOLIVIA = @as(u32, 1); pub const SUBLANG_QUECHUA_ECUADOR = @as(u32, 2); pub const SUBLANG_QUECHUA_PERU = @as(u32, 3); pub const SUBLANG_ROMANIAN_ROMANIA = @as(u32, 1); pub const SUBLANG_ROMANSH_SWITZERLAND = @as(u32, 1); pub const SUBLANG_RUSSIAN_RUSSIA = @as(u32, 1); pub const SUBLANG_SAKHA_RUSSIA = @as(u32, 1); pub const SUBLANG_SAMI_NORTHERN_NORWAY = @as(u32, 1); pub const SUBLANG_SAMI_NORTHERN_SWEDEN = @as(u32, 2); pub const SUBLANG_SAMI_NORTHERN_FINLAND = @as(u32, 3); pub const SUBLANG_SAMI_LULE_NORWAY = @as(u32, 4); pub const SUBLANG_SAMI_LULE_SWEDEN = @as(u32, 5); pub const SUBLANG_SAMI_SOUTHERN_NORWAY = @as(u32, 6); pub const SUBLANG_SAMI_SOUTHERN_SWEDEN = @as(u32, 7); pub const SUBLANG_SAMI_SKOLT_FINLAND = @as(u32, 8); pub const SUBLANG_SAMI_INARI_FINLAND = @as(u32, 9); pub const SUBLANG_SANSKRIT_INDIA = @as(u32, 1); pub const SUBLANG_SCOTTISH_GAELIC = @as(u32, 1); pub const SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_LATIN = @as(u32, 6); pub const SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC = @as(u32, 7); pub const SUBLANG_SERBIAN_MONTENEGRO_LATIN = @as(u32, 11); pub const SUBLANG_SERBIAN_MONTENEGRO_CYRILLIC = @as(u32, 12); pub const SUBLANG_SERBIAN_SERBIA_LATIN = @as(u32, 9); pub const SUBLANG_SERBIAN_SERBIA_CYRILLIC = @as(u32, 10); pub const SUBLANG_SERBIAN_CROATIA = @as(u32, 1); pub const SUBLANG_SERBIAN_LATIN = @as(u32, 2); pub const SUBLANG_SERBIAN_CYRILLIC = @as(u32, 3); pub const SUBLANG_SINDHI_INDIA = @as(u32, 1); pub const SUBLANG_SINDHI_PAKISTAN = @as(u32, 2); pub const SUBLANG_SINDHI_AFGHANISTAN = @as(u32, 2); pub const SUBLANG_SINHALESE_SRI_LANKA = @as(u32, 1); pub const SUBLANG_SOTHO_NORTHERN_SOUTH_AFRICA = @as(u32, 1); pub const SUBLANG_SLOVAK_SLOVAKIA = @as(u32, 1); pub const SUBLANG_SLOVENIAN_SLOVENIA = @as(u32, 1); pub const SUBLANG_SPANISH = @as(u32, 1); pub const SUBLANG_SPANISH_MEXICAN = @as(u32, 2); pub const SUBLANG_SPANISH_MODERN = @as(u32, 3); pub const SUBLANG_SPANISH_GUATEMALA = @as(u32, 4); pub const SUBLANG_SPANISH_COSTA_RICA = @as(u32, 5); pub const SUBLANG_SPANISH_PANAMA = @as(u32, 6); pub const SUBLANG_SPANISH_DOMINICAN_REPUBLIC = @as(u32, 7); pub const SUBLANG_SPANISH_VENEZUELA = @as(u32, 8); pub const SUBLANG_SPANISH_COLOMBIA = @as(u32, 9); pub const SUBLANG_SPANISH_PERU = @as(u32, 10); pub const SUBLANG_SPANISH_ARGENTINA = @as(u32, 11); pub const SUBLANG_SPANISH_ECUADOR = @as(u32, 12); pub const SUBLANG_SPANISH_CHILE = @as(u32, 13); pub const SUBLANG_SPANISH_URUGUAY = @as(u32, 14); pub const SUBLANG_SPANISH_PARAGUAY = @as(u32, 15); pub const SUBLANG_SPANISH_BOLIVIA = @as(u32, 16); pub const SUBLANG_SPANISH_EL_SALVADOR = @as(u32, 17); pub const SUBLANG_SPANISH_HONDURAS = @as(u32, 18); pub const SUBLANG_SPANISH_NICARAGUA = @as(u32, 19); pub const SUBLANG_SPANISH_PUERTO_RICO = @as(u32, 20); pub const SUBLANG_SPANISH_US = @as(u32, 21); pub const SUBLANG_SWAHILI_KENYA = @as(u32, 1); pub const SUBLANG_SWEDISH = @as(u32, 1); pub const SUBLANG_SWEDISH_FINLAND = @as(u32, 2); pub const SUBLANG_SYRIAC_SYRIA = @as(u32, 1); pub const SUBLANG_TAJIK_TAJIKISTAN = @as(u32, 1); pub const SUBLANG_TAMAZIGHT_ALGERIA_LATIN = @as(u32, 2); pub const SUBLANG_TAMAZIGHT_MOROCCO_TIFINAGH = @as(u32, 4); pub const SUBLANG_TAMIL_INDIA = @as(u32, 1); pub const SUBLANG_TAMIL_SRI_LANKA = @as(u32, 2); pub const SUBLANG_TATAR_RUSSIA = @as(u32, 1); pub const SUBLANG_TELUGU_INDIA = @as(u32, 1); pub const SUBLANG_THAI_THAILAND = @as(u32, 1); pub const SUBLANG_TIBETAN_PRC = @as(u32, 1); pub const SUBLANG_TIGRIGNA_ERITREA = @as(u32, 2); pub const SUBLANG_TIGRINYA_ERITREA = @as(u32, 2); pub const SUBLANG_TIGRINYA_ETHIOPIA = @as(u32, 1); pub const SUBLANG_TSWANA_BOTSWANA = @as(u32, 2); pub const SUBLANG_TSWANA_SOUTH_AFRICA = @as(u32, 1); pub const SUBLANG_TURKISH_TURKEY = @as(u32, 1); pub const SUBLANG_TURKMEN_TURKMENISTAN = @as(u32, 1); pub const SUBLANG_UIGHUR_PRC = @as(u32, 1); pub const SUBLANG_UKRAINIAN_UKRAINE = @as(u32, 1); pub const SUBLANG_UPPER_SORBIAN_GERMANY = @as(u32, 1); pub const SUBLANG_URDU_PAKISTAN = @as(u32, 1); pub const SUBLANG_URDU_INDIA = @as(u32, 2); pub const SUBLANG_UZBEK_LATIN = @as(u32, 1); pub const SUBLANG_UZBEK_CYRILLIC = @as(u32, 2); pub const SUBLANG_VALENCIAN_VALENCIA = @as(u32, 2); pub const SUBLANG_VIETNAMESE_VIETNAM = @as(u32, 1); pub const SUBLANG_WELSH_UNITED_KINGDOM = @as(u32, 1); pub const SUBLANG_WOLOF_SENEGAL = @as(u32, 1); pub const SUBLANG_XHOSA_SOUTH_AFRICA = @as(u32, 1); pub const SUBLANG_YAKUT_RUSSIA = @as(u32, 1); pub const SUBLANG_YI_PRC = @as(u32, 1); pub const SUBLANG_YORUBA_NIGERIA = @as(u32, 1); pub const SUBLANG_ZULU_SOUTH_AFRICA = @as(u32, 1); pub const SORT_DEFAULT = @as(u32, 0); pub const SORT_INVARIANT_MATH = @as(u32, 1); pub const SORT_JAPANESE_XJIS = @as(u32, 0); pub const SORT_JAPANESE_UNICODE = @as(u32, 1); pub const SORT_JAPANESE_RADICALSTROKE = @as(u32, 4); pub const SORT_CHINESE_BIG5 = @as(u32, 0); pub const SORT_CHINESE_PRCP = @as(u32, 0); pub const SORT_CHINESE_UNICODE = @as(u32, 1); pub const SORT_CHINESE_PRC = @as(u32, 2); pub const SORT_CHINESE_BOPOMOFO = @as(u32, 3); pub const SORT_CHINESE_RADICALSTROKE = @as(u32, 4); pub const SORT_KOREAN_KSC = @as(u32, 0); pub const SORT_KOREAN_UNICODE = @as(u32, 1); pub const SORT_GERMAN_PHONE_BOOK = @as(u32, 1); pub const SORT_HUNGARIAN_DEFAULT = @as(u32, 0); pub const SORT_HUNGARIAN_TECHNICAL = @as(u32, 1); pub const SORT_GEORGIAN_TRADITIONAL = @as(u32, 0); pub const SORT_GEORGIAN_MODERN = @as(u32, 1); pub const NLS_VALID_LOCALE_MASK = @as(u32, 1048575); pub const LOCALE_NAME_MAX_LENGTH = @as(u32, 85); pub const LOCALE_TRANSIENT_KEYBOARD1 = @as(u32, 8192); pub const LOCALE_TRANSIENT_KEYBOARD2 = @as(u32, 9216); pub const LOCALE_TRANSIENT_KEYBOARD3 = @as(u32, 10240); pub const LOCALE_TRANSIENT_KEYBOARD4 = @as(u32, 11264); pub const MAXIMUM_WAIT_OBJECTS = @as(u32, 64); pub const MAXIMUM_SUSPEND_COUNT = @as(u32, 127); pub const PF_TEMPORAL_LEVEL_1 = @as(u32, 1); pub const PF_TEMPORAL_LEVEL_2 = @as(u32, 2); pub const PF_TEMPORAL_LEVEL_3 = @as(u32, 3); pub const PF_NON_TEMPORAL_LEVEL_ALL = @as(u32, 0); pub const EXCEPTION_READ_FAULT = @as(u32, 0); pub const EXCEPTION_WRITE_FAULT = @as(u32, 1); pub const EXCEPTION_EXECUTE_FAULT = @as(u32, 8); pub const CONTEXT_AMD64 = @as(i32, 1048576); pub const CONTEXT_KERNEL_DEBUGGER = @as(i32, 67108864); pub const CONTEXT_EXCEPTION_ACTIVE = @as(i32, 134217728); pub const CONTEXT_SERVICE_ACTIVE = @as(i32, 268435456); pub const CONTEXT_EXCEPTION_REQUEST = @as(i32, 1073741824); pub const CONTEXT_EXCEPTION_REPORTING = @as(i32, -2147483648); pub const CONTEXT_UNWOUND_TO_CALL = @as(u32, 536870912); pub const INITIAL_MXCSR = @as(u32, 8064); pub const INITIAL_FPCSR = @as(u32, 639); pub const RUNTIME_FUNCTION_INDIRECT = @as(u32, 1); pub const UNW_FLAG_NO_EPILOGUE = @as(u32, 2147483648); pub const UNWIND_CHAIN_LIMIT = @as(u32, 32); pub const CONTEXT_ARM = @as(i32, 2097152); pub const INITIAL_CPSR = @as(u32, 16); pub const INITIAL_FPSCR = @as(u32, 0); pub const ARM_MAX_BREAKPOINTS = @as(u32, 8); pub const ARM_MAX_WATCHPOINTS = @as(u32, 1); pub const ARM64_PREFETCH_PLD = @as(u32, 0); pub const ARM64_PREFETCH_PLI = @as(u32, 8); pub const ARM64_PREFETCH_PST = @as(u32, 16); pub const ARM64_PREFETCH_L1 = @as(u32, 0); pub const ARM64_PREFETCH_L2 = @as(u32, 2); pub const ARM64_PREFETCH_L3 = @as(u32, 4); pub const ARM64_PREFETCH_KEEP = @as(u32, 0); pub const ARM64_PREFETCH_STRM = @as(u32, 1); pub const ARM64_MULT_INTRINSICS_SUPPORTED = @as(u32, 1); pub const CONTEXT_ARM64 = @as(i32, 4194304); pub const CONTEXT_ARM64_UNWOUND_TO_CALL = @as(u32, 536870912); pub const CONTEXT_ARM64_RET_TO_GUEST = @as(u32, 67108864); pub const CONTEXT_RET_TO_GUEST = @as(u32, 67108864); pub const ARM64_MAX_BREAKPOINTS = @as(u32, 8); pub const ARM64_MAX_WATCHPOINTS = @as(u32, 2); pub const NONVOL_INT_NUMREG_ARM64 = @as(u32, 11); pub const NONVOL_FP_NUMREG_ARM64 = @as(u32, 8); pub const BREAK_DEBUG_BASE = @as(u32, 524288); pub const ASSERT_BREAKPOINT = @as(u32, 524291); pub const SIZE_OF_80387_REGISTERS = @as(u32, 80); pub const CONTEXT_i386 = @as(i32, 65536); pub const CONTEXT_i486 = @as(i32, 65536); pub const MAXIMUM_SUPPORTED_EXTENSION = @as(u32, 512); pub const EXCEPTION_NONCONTINUABLE = @as(u32, 1); pub const EXCEPTION_UNWINDING = @as(u32, 2); pub const EXCEPTION_EXIT_UNWIND = @as(u32, 4); pub const EXCEPTION_STACK_INVALID = @as(u32, 8); pub const EXCEPTION_NESTED_CALL = @as(u32, 16); pub const EXCEPTION_TARGET_UNWIND = @as(u32, 32); pub const EXCEPTION_COLLIDED_UNWIND = @as(u32, 64); pub const EXCEPTION_SOFTWARE_ORIGINATE = @as(u32, 128); pub const EXCEPTION_MAXIMUM_PARAMETERS = @as(u32, 15); pub const DELETE = @as(u32, 65536); pub const WRITE_DAC = @as(u32, 262144); pub const WRITE_OWNER = @as(u32, 524288); pub const ACCESS_SYSTEM_SECURITY = @as(u32, 16777216); pub const MAXIMUM_ALLOWED = @as(u32, 33554432); pub const GENERIC_READ = @as(u32, 2147483648); pub const GENERIC_WRITE = @as(u32, 1073741824); pub const GENERIC_EXECUTE = @as(u32, 536870912); pub const GENERIC_ALL = @as(u32, 268435456); pub const SID_REVISION = @as(u32, 1); pub const SID_MAX_SUB_AUTHORITIES = @as(u32, 15); pub const SID_RECOMMENDED_SUB_AUTHORITIES = @as(u32, 1); pub const SID_HASH_SIZE = @as(u32, 32); pub const SECURITY_NULL_RID = @as(i32, 0); pub const SECURITY_WORLD_RID = @as(i32, 0); pub const SECURITY_LOCAL_RID = @as(i32, 0); pub const SECURITY_LOCAL_LOGON_RID = @as(i32, 1); pub const SECURITY_CREATOR_OWNER_RID = @as(i32, 0); pub const SECURITY_CREATOR_GROUP_RID = @as(i32, 1); pub const SECURITY_CREATOR_OWNER_SERVER_RID = @as(i32, 2); pub const SECURITY_CREATOR_GROUP_SERVER_RID = @as(i32, 3); pub const SECURITY_CREATOR_OWNER_RIGHTS_RID = @as(i32, 4); pub const SECURITY_DIALUP_RID = @as(i32, 1); pub const SECURITY_NETWORK_RID = @as(i32, 2); pub const SECURITY_BATCH_RID = @as(i32, 3); pub const SECURITY_INTERACTIVE_RID = @as(i32, 4); pub const SECURITY_LOGON_IDS_RID = @as(i32, 5); pub const SECURITY_LOGON_IDS_RID_COUNT = @as(i32, 3); pub const SECURITY_SERVICE_RID = @as(i32, 6); pub const SECURITY_ANONYMOUS_LOGON_RID = @as(i32, 7); pub const SECURITY_PROXY_RID = @as(i32, 8); pub const SECURITY_ENTERPRISE_CONTROLLERS_RID = @as(i32, 9); pub const SECURITY_SERVER_LOGON_RID = @as(i32, 9); pub const SECURITY_PRINCIPAL_SELF_RID = @as(i32, 10); pub const SECURITY_AUTHENTICATED_USER_RID = @as(i32, 11); pub const SECURITY_RESTRICTED_CODE_RID = @as(i32, 12); pub const SECURITY_TERMINAL_SERVER_RID = @as(i32, 13); pub const SECURITY_REMOTE_LOGON_RID = @as(i32, 14); pub const SECURITY_THIS_ORGANIZATION_RID = @as(i32, 15); pub const SECURITY_IUSER_RID = @as(i32, 17); pub const SECURITY_LOCAL_SYSTEM_RID = @as(i32, 18); pub const SECURITY_LOCAL_SERVICE_RID = @as(i32, 19); pub const SECURITY_NETWORK_SERVICE_RID = @as(i32, 20); pub const SECURITY_NT_NON_UNIQUE = @as(i32, 21); pub const SECURITY_NT_NON_UNIQUE_SUB_AUTH_COUNT = @as(i32, 3); pub const SECURITY_ENTERPRISE_READONLY_CONTROLLERS_RID = @as(i32, 22); pub const SECURITY_BUILTIN_DOMAIN_RID = @as(i32, 32); pub const SECURITY_WRITE_RESTRICTED_CODE_RID = @as(i32, 33); pub const SECURITY_PACKAGE_BASE_RID = @as(i32, 64); pub const SECURITY_PACKAGE_RID_COUNT = @as(i32, 2); pub const SECURITY_PACKAGE_NTLM_RID = @as(i32, 10); pub const SECURITY_PACKAGE_SCHANNEL_RID = @as(i32, 14); pub const SECURITY_PACKAGE_DIGEST_RID = @as(i32, 21); pub const SECURITY_CRED_TYPE_BASE_RID = @as(i32, 65); pub const SECURITY_CRED_TYPE_RID_COUNT = @as(i32, 2); pub const SECURITY_CRED_TYPE_THIS_ORG_CERT_RID = @as(i32, 1); pub const SECURITY_MIN_BASE_RID = @as(i32, 80); pub const SECURITY_SERVICE_ID_BASE_RID = @as(i32, 80); pub const SECURITY_SERVICE_ID_RID_COUNT = @as(i32, 6); pub const SECURITY_RESERVED_ID_BASE_RID = @as(i32, 81); pub const SECURITY_APPPOOL_ID_BASE_RID = @as(i32, 82); pub const SECURITY_APPPOOL_ID_RID_COUNT = @as(i32, 6); pub const SECURITY_VIRTUALSERVER_ID_BASE_RID = @as(i32, 83); pub const SECURITY_VIRTUALSERVER_ID_RID_COUNT = @as(i32, 6); pub const SECURITY_USERMODEDRIVERHOST_ID_BASE_RID = @as(i32, 84); pub const SECURITY_USERMODEDRIVERHOST_ID_RID_COUNT = @as(i32, 6); pub const SECURITY_CLOUD_INFRASTRUCTURE_SERVICES_ID_BASE_RID = @as(i32, 85); pub const SECURITY_CLOUD_INFRASTRUCTURE_SERVICES_ID_RID_COUNT = @as(i32, 6); pub const SECURITY_WMIHOST_ID_BASE_RID = @as(i32, 86); pub const SECURITY_WMIHOST_ID_RID_COUNT = @as(i32, 6); pub const SECURITY_TASK_ID_BASE_RID = @as(i32, 87); pub const SECURITY_NFS_ID_BASE_RID = @as(i32, 88); pub const SECURITY_COM_ID_BASE_RID = @as(i32, 89); pub const SECURITY_WINDOW_MANAGER_BASE_RID = @as(i32, 90); pub const SECURITY_RDV_GFX_BASE_RID = @as(i32, 91); pub const SECURITY_DASHOST_ID_BASE_RID = @as(i32, 92); pub const SECURITY_DASHOST_ID_RID_COUNT = @as(i32, 6); pub const SECURITY_USERMANAGER_ID_BASE_RID = @as(i32, 93); pub const SECURITY_USERMANAGER_ID_RID_COUNT = @as(i32, 6); pub const SECURITY_WINRM_ID_BASE_RID = @as(i32, 94); pub const SECURITY_WINRM_ID_RID_COUNT = @as(i32, 6); pub const SECURITY_CCG_ID_BASE_RID = @as(i32, 95); pub const SECURITY_UMFD_BASE_RID = @as(i32, 96); pub const SECURITY_VIRTUALACCOUNT_ID_RID_COUNT = @as(i32, 6); pub const SECURITY_MAX_BASE_RID = @as(i32, 111); pub const SECURITY_MAX_ALWAYS_FILTERED = @as(i32, 999); pub const SECURITY_MIN_NEVER_FILTERED = @as(i32, 1000); pub const SECURITY_OTHER_ORGANIZATION_RID = @as(i32, 1000); pub const SECURITY_WINDOWSMOBILE_ID_BASE_RID = @as(i32, 112); pub const SECURITY_INSTALLER_GROUP_CAPABILITY_BASE = @as(u32, 32); pub const SECURITY_INSTALLER_GROUP_CAPABILITY_RID_COUNT = @as(u32, 9); pub const SECURITY_INSTALLER_CAPABILITY_RID_COUNT = @as(u32, 10); pub const SECURITY_LOCAL_ACCOUNT_RID = @as(i32, 113); pub const SECURITY_LOCAL_ACCOUNT_AND_ADMIN_RID = @as(i32, 114); pub const DOMAIN_GROUP_RID_AUTHORIZATION_DATA_IS_COMPOUNDED = @as(i32, 496); pub const DOMAIN_GROUP_RID_AUTHORIZATION_DATA_CONTAINS_CLAIMS = @as(i32, 497); pub const DOMAIN_GROUP_RID_ENTERPRISE_READONLY_DOMAIN_CONTROLLERS = @as(i32, 498); pub const FOREST_USER_RID_MAX = @as(i32, 499); pub const DOMAIN_USER_RID_ADMIN = @as(i32, 500); pub const DOMAIN_USER_RID_GUEST = @as(i32, 501); pub const DOMAIN_USER_RID_KRBTGT = @as(i32, 502); pub const DOMAIN_USER_RID_DEFAULT_ACCOUNT = @as(i32, 503); pub const DOMAIN_USER_RID_WDAG_ACCOUNT = @as(i32, 504); pub const DOMAIN_USER_RID_MAX = @as(i32, 999); pub const DOMAIN_GROUP_RID_ADMINS = @as(i32, 512); pub const DOMAIN_GROUP_RID_USERS = @as(i32, 513); pub const DOMAIN_GROUP_RID_GUESTS = @as(i32, 514); pub const DOMAIN_GROUP_RID_COMPUTERS = @as(i32, 515); pub const DOMAIN_GROUP_RID_CONTROLLERS = @as(i32, 516); pub const DOMAIN_GROUP_RID_CERT_ADMINS = @as(i32, 517); pub const DOMAIN_GROUP_RID_SCHEMA_ADMINS = @as(i32, 518); pub const DOMAIN_GROUP_RID_ENTERPRISE_ADMINS = @as(i32, 519); pub const DOMAIN_GROUP_RID_POLICY_ADMINS = @as(i32, 520); pub const DOMAIN_GROUP_RID_READONLY_CONTROLLERS = @as(i32, 521); pub const DOMAIN_GROUP_RID_CLONEABLE_CONTROLLERS = @as(i32, 522); pub const DOMAIN_GROUP_RID_CDC_RESERVED = @as(i32, 524); pub const DOMAIN_GROUP_RID_PROTECTED_USERS = @as(i32, 525); pub const DOMAIN_GROUP_RID_KEY_ADMINS = @as(i32, 526); pub const DOMAIN_GROUP_RID_ENTERPRISE_KEY_ADMINS = @as(i32, 527); pub const DOMAIN_ALIAS_RID_ADMINS = @as(i32, 544); pub const DOMAIN_ALIAS_RID_USERS = @as(i32, 545); pub const DOMAIN_ALIAS_RID_GUESTS = @as(i32, 546); pub const DOMAIN_ALIAS_RID_POWER_USERS = @as(i32, 547); pub const DOMAIN_ALIAS_RID_ACCOUNT_OPS = @as(i32, 548); pub const DOMAIN_ALIAS_RID_SYSTEM_OPS = @as(i32, 549); pub const DOMAIN_ALIAS_RID_PRINT_OPS = @as(i32, 550); pub const DOMAIN_ALIAS_RID_BACKUP_OPS = @as(i32, 551); pub const DOMAIN_ALIAS_RID_REPLICATOR = @as(i32, 552); pub const DOMAIN_ALIAS_RID_RAS_SERVERS = @as(i32, 553); pub const DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = @as(i32, 554); pub const DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS = @as(i32, 555); pub const DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS = @as(i32, 556); pub const DOMAIN_ALIAS_RID_INCOMING_FOREST_TRUST_BUILDERS = @as(i32, 557); pub const DOMAIN_ALIAS_RID_MONITORING_USERS = @as(i32, 558); pub const DOMAIN_ALIAS_RID_LOGGING_USERS = @as(i32, 559); pub const DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS = @as(i32, 560); pub const DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS = @as(i32, 561); pub const DOMAIN_ALIAS_RID_DCOM_USERS = @as(i32, 562); pub const DOMAIN_ALIAS_RID_IUSERS = @as(i32, 568); pub const DOMAIN_ALIAS_RID_CRYPTO_OPERATORS = @as(i32, 569); pub const DOMAIN_ALIAS_RID_CACHEABLE_PRINCIPALS_GROUP = @as(i32, 571); pub const DOMAIN_ALIAS_RID_NON_CACHEABLE_PRINCIPALS_GROUP = @as(i32, 572); pub const DOMAIN_ALIAS_RID_EVENT_LOG_READERS_GROUP = @as(i32, 573); pub const DOMAIN_ALIAS_RID_CERTSVC_DCOM_ACCESS_GROUP = @as(i32, 574); pub const DOMAIN_ALIAS_RID_RDS_REMOTE_ACCESS_SERVERS = @as(i32, 575); pub const DOMAIN_ALIAS_RID_RDS_ENDPOINT_SERVERS = @as(i32, 576); pub const DOMAIN_ALIAS_RID_RDS_MANAGEMENT_SERVERS = @as(i32, 577); pub const DOMAIN_ALIAS_RID_HYPER_V_ADMINS = @as(i32, 578); pub const DOMAIN_ALIAS_RID_ACCESS_CONTROL_ASSISTANCE_OPS = @as(i32, 579); pub const DOMAIN_ALIAS_RID_REMOTE_MANAGEMENT_USERS = @as(i32, 580); pub const DOMAIN_ALIAS_RID_DEFAULT_ACCOUNT = @as(i32, 581); pub const DOMAIN_ALIAS_RID_STORAGE_REPLICA_ADMINS = @as(i32, 582); pub const DOMAIN_ALIAS_RID_DEVICE_OWNERS = @as(i32, 583); pub const SECURITY_APP_PACKAGE_BASE_RID = @as(i32, 2); pub const SECURITY_BUILTIN_APP_PACKAGE_RID_COUNT = @as(i32, 2); pub const SECURITY_APP_PACKAGE_RID_COUNT = @as(i32, 8); pub const SECURITY_CAPABILITY_BASE_RID = @as(i32, 3); pub const SECURITY_CAPABILITY_APP_RID = @as(u64, 1024); pub const SECURITY_BUILTIN_CAPABILITY_RID_COUNT = @as(i32, 2); pub const SECURITY_CAPABILITY_RID_COUNT = @as(i32, 5); pub const SECURITY_PARENT_PACKAGE_RID_COUNT = @as(i32, 8); pub const SECURITY_CHILD_PACKAGE_RID_COUNT = @as(i32, 12); pub const SECURITY_BUILTIN_PACKAGE_ANY_PACKAGE = @as(i32, 1); pub const SECURITY_BUILTIN_PACKAGE_ANY_RESTRICTED_PACKAGE = @as(i32, 2); pub const SECURITY_CAPABILITY_INTERNET_CLIENT = @as(i32, 1); pub const SECURITY_CAPABILITY_INTERNET_CLIENT_SERVER = @as(i32, 2); pub const SECURITY_CAPABILITY_PRIVATE_NETWORK_CLIENT_SERVER = @as(i32, 3); pub const SECURITY_CAPABILITY_PICTURES_LIBRARY = @as(i32, 4); pub const SECURITY_CAPABILITY_VIDEOS_LIBRARY = @as(i32, 5); pub const SECURITY_CAPABILITY_MUSIC_LIBRARY = @as(i32, 6); pub const SECURITY_CAPABILITY_DOCUMENTS_LIBRARY = @as(i32, 7); pub const SECURITY_CAPABILITY_ENTERPRISE_AUTHENTICATION = @as(i32, 8); pub const SECURITY_CAPABILITY_SHARED_USER_CERTIFICATES = @as(i32, 9); pub const SECURITY_CAPABILITY_REMOVABLE_STORAGE = @as(i32, 10); pub const SECURITY_CAPABILITY_APPOINTMENTS = @as(i32, 11); pub const SECURITY_CAPABILITY_CONTACTS = @as(i32, 12); pub const SECURITY_CAPABILITY_INTERNET_EXPLORER = @as(i32, 4096); pub const SECURITY_MANDATORY_UNTRUSTED_RID = @as(i32, 0); pub const SECURITY_MANDATORY_LOW_RID = @as(i32, 4096); pub const SECURITY_MANDATORY_MEDIUM_RID = @as(i32, 8192); pub const SECURITY_MANDATORY_MEDIUM_PLUS_RID = @as(u32, 8448); pub const SECURITY_MANDATORY_HIGH_RID = @as(i32, 12288); pub const SECURITY_MANDATORY_SYSTEM_RID = @as(i32, 16384); pub const SECURITY_MANDATORY_PROTECTED_PROCESS_RID = @as(i32, 20480); pub const SECURITY_MANDATORY_MAXIMUM_USER_RID = @as(i32, 16384); pub const SECURITY_AUTHENTICATION_AUTHORITY_RID_COUNT = @as(i32, 1); pub const SECURITY_AUTHENTICATION_AUTHORITY_ASSERTED_RID = @as(i32, 1); pub const SECURITY_AUTHENTICATION_SERVICE_ASSERTED_RID = @as(i32, 2); pub const SECURITY_AUTHENTICATION_FRESH_KEY_AUTH_RID = @as(i32, 3); pub const SECURITY_AUTHENTICATION_KEY_TRUST_RID = @as(i32, 4); pub const SECURITY_AUTHENTICATION_KEY_PROPERTY_MFA_RID = @as(i32, 5); pub const SECURITY_AUTHENTICATION_KEY_PROPERTY_ATTESTATION_RID = @as(i32, 6); pub const SECURITY_PROCESS_TRUST_AUTHORITY_RID_COUNT = @as(i32, 2); pub const SECURITY_PROCESS_PROTECTION_TYPE_FULL_RID = @as(i32, 1024); pub const SECURITY_PROCESS_PROTECTION_TYPE_LITE_RID = @as(i32, 512); pub const SECURITY_PROCESS_PROTECTION_TYPE_NONE_RID = @as(i32, 0); pub const SECURITY_PROCESS_PROTECTION_LEVEL_WINTCB_RID = @as(i32, 8192); pub const SECURITY_PROCESS_PROTECTION_LEVEL_WINDOWS_RID = @as(i32, 4096); pub const SECURITY_PROCESS_PROTECTION_LEVEL_APP_RID = @as(i32, 2048); pub const SECURITY_PROCESS_PROTECTION_LEVEL_ANTIMALWARE_RID = @as(i32, 1536); pub const SECURITY_PROCESS_PROTECTION_LEVEL_AUTHENTICODE_RID = @as(i32, 1024); pub const SECURITY_PROCESS_PROTECTION_LEVEL_NONE_RID = @as(i32, 0); pub const SECURITY_TRUSTED_INSTALLER_RID1 = @as(u32, 956008885); pub const SECURITY_TRUSTED_INSTALLER_RID2 = @as(u32, 3418522649); pub const SECURITY_TRUSTED_INSTALLER_RID3 = @as(u32, 1831038044); pub const SECURITY_TRUSTED_INSTALLER_RID4 = @as(u32, 1853292631); pub const SECURITY_TRUSTED_INSTALLER_RID5 = @as(u32, 2271478464); pub const SE_GROUP_MANDATORY = @as(i32, 1); pub const SE_GROUP_ENABLED_BY_DEFAULT = @as(i32, 2); pub const SE_GROUP_ENABLED = @as(i32, 4); pub const SE_GROUP_OWNER = @as(i32, 8); pub const SE_GROUP_USE_FOR_DENY_ONLY = @as(i32, 16); pub const SE_GROUP_INTEGRITY = @as(i32, 32); pub const SE_GROUP_INTEGRITY_ENABLED = @as(i32, 64); pub const SE_GROUP_LOGON_ID = @as(i32, -1073741824); pub const SE_GROUP_RESOURCE = @as(i32, 536870912); pub const ACL_REVISION1 = @as(u32, 1); pub const ACL_REVISION2 = @as(u32, 2); pub const ACL_REVISION3 = @as(u32, 3); pub const ACL_REVISION4 = @as(u32, 4); pub const MAX_ACL_REVISION = @as(u32, 4); pub const ACCESS_MIN_MS_ACE_TYPE = @as(u32, 0); pub const ACCESS_ALLOWED_ACE_TYPE = @as(u32, 0); pub const ACCESS_DENIED_ACE_TYPE = @as(u32, 1); pub const SYSTEM_AUDIT_ACE_TYPE = @as(u32, 2); pub const SYSTEM_ALARM_ACE_TYPE = @as(u32, 3); pub const ACCESS_MAX_MS_V2_ACE_TYPE = @as(u32, 3); pub const ACCESS_ALLOWED_COMPOUND_ACE_TYPE = @as(u32, 4); pub const ACCESS_MAX_MS_V3_ACE_TYPE = @as(u32, 4); pub const ACCESS_MIN_MS_OBJECT_ACE_TYPE = @as(u32, 5); pub const ACCESS_ALLOWED_OBJECT_ACE_TYPE = @as(u32, 5); pub const ACCESS_DENIED_OBJECT_ACE_TYPE = @as(u32, 6); pub const SYSTEM_AUDIT_OBJECT_ACE_TYPE = @as(u32, 7); pub const SYSTEM_ALARM_OBJECT_ACE_TYPE = @as(u32, 8); pub const ACCESS_MAX_MS_OBJECT_ACE_TYPE = @as(u32, 8); pub const ACCESS_MAX_MS_V4_ACE_TYPE = @as(u32, 8); pub const ACCESS_MAX_MS_ACE_TYPE = @as(u32, 8); pub const ACCESS_ALLOWED_CALLBACK_ACE_TYPE = @as(u32, 9); pub const ACCESS_DENIED_CALLBACK_ACE_TYPE = @as(u32, 10); pub const ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE = @as(u32, 11); pub const ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE = @as(u32, 12); pub const SYSTEM_AUDIT_CALLBACK_ACE_TYPE = @as(u32, 13); pub const SYSTEM_ALARM_CALLBACK_ACE_TYPE = @as(u32, 14); pub const SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE = @as(u32, 15); pub const SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE = @as(u32, 16); pub const SYSTEM_MANDATORY_LABEL_ACE_TYPE = @as(u32, 17); pub const SYSTEM_RESOURCE_ATTRIBUTE_ACE_TYPE = @as(u32, 18); pub const SYSTEM_SCOPED_POLICY_ID_ACE_TYPE = @as(u32, 19); pub const SYSTEM_PROCESS_TRUST_LABEL_ACE_TYPE = @as(u32, 20); pub const SYSTEM_ACCESS_FILTER_ACE_TYPE = @as(u32, 21); pub const ACCESS_MAX_MS_V5_ACE_TYPE = @as(u32, 21); pub const VALID_INHERIT_FLAGS = @as(u32, 31); pub const CRITICAL_ACE_FLAG = @as(u32, 32); pub const TRUST_PROTECTED_FILTER_ACE_FLAG = @as(u32, 64); pub const SYSTEM_MANDATORY_LABEL_NO_WRITE_UP = @as(u32, 1); pub const SYSTEM_MANDATORY_LABEL_NO_READ_UP = @as(u32, 2); pub const SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP = @as(u32, 4); pub const SYSTEM_PROCESS_TRUST_LABEL_VALID_MASK = @as(u32, 16777215); pub const SYSTEM_PROCESS_TRUST_NOCONSTRAINT_MASK = @as(u32, 4294967295); pub const SYSTEM_ACCESS_FILTER_VALID_MASK = @as(u32, 16777215); pub const SYSTEM_ACCESS_FILTER_NOCONSTRAINT_MASK = @as(u32, 4294967295); pub const SECURITY_DESCRIPTOR_REVISION = @as(u32, 1); pub const SECURITY_DESCRIPTOR_REVISION1 = @as(u32, 1); pub const SE_OWNER_DEFAULTED = @as(u32, 1); pub const SE_GROUP_DEFAULTED = @as(u32, 2); pub const SE_DACL_PRESENT = @as(u32, 4); pub const SE_DACL_DEFAULTED = @as(u32, 8); pub const SE_SACL_PRESENT = @as(u32, 16); pub const SE_SACL_DEFAULTED = @as(u32, 32); pub const SE_DACL_AUTO_INHERIT_REQ = @as(u32, 256); pub const SE_SACL_AUTO_INHERIT_REQ = @as(u32, 512); pub const SE_DACL_AUTO_INHERITED = @as(u32, 1024); pub const SE_SACL_AUTO_INHERITED = @as(u32, 2048); pub const SE_DACL_PROTECTED = @as(u32, 4096); pub const SE_SACL_PROTECTED = @as(u32, 8192); pub const SE_RM_CONTROL_VALID = @as(u32, 16384); pub const SE_SELF_RELATIVE = @as(u32, 32768); pub const ACCESS_OBJECT_GUID = @as(u32, 0); pub const ACCESS_PROPERTY_SET_GUID = @as(u32, 1); pub const ACCESS_PROPERTY_GUID = @as(u32, 2); pub const ACCESS_MAX_LEVEL = @as(u32, 4); pub const AUDIT_ALLOW_NO_PRIVILEGE = @as(u32, 1); pub const PRIVILEGE_SET_ALL_NECESSARY = @as(u32, 1); pub const ACCESS_REASON_TYPE_MASK = @as(u32, 16711680); pub const ACCESS_REASON_DATA_MASK = @as(u32, 65535); pub const ACCESS_REASON_STAGING_MASK = @as(u32, 2147483648); pub const ACCESS_REASON_EXDATA_MASK = @as(u32, 2130706432); pub const SE_SECURITY_DESCRIPTOR_FLAG_NO_OWNER_ACE = @as(u32, 1); pub const SE_SECURITY_DESCRIPTOR_FLAG_NO_LABEL_ACE = @as(u32, 2); pub const SE_SECURITY_DESCRIPTOR_FLAG_NO_ACCESS_FILTER_ACE = @as(u32, 4); pub const SE_SECURITY_DESCRIPTOR_VALID_FLAGS = @as(u32, 7); pub const SE_ACCESS_CHECK_FLAG_NO_LEARNING_MODE_LOGGING = @as(u32, 8); pub const SE_ACCESS_CHECK_VALID_FLAGS = @as(u32, 8); pub const POLICY_AUDIT_SUBCATEGORY_COUNT = @as(u32, 59); pub const TOKEN_SOURCE_LENGTH = @as(u32, 8); pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_INVALID = @as(u32, 0); pub const CLAIM_SECURITY_ATTRIBUTE_CUSTOM_FLAGS = @as(u32, 4294901760); pub const CLAIM_SECURITY_ATTRIBUTES_INFORMATION_VERSION_V1 = @as(u32, 1); pub const CLAIM_SECURITY_ATTRIBUTES_INFORMATION_VERSION = @as(u32, 1); pub const PROCESS_TRUST_LABEL_SECURITY_INFORMATION = @as(i32, 128); pub const ACCESS_FILTER_SECURITY_INFORMATION = @as(i32, 256); pub const SE_SIGNING_LEVEL_UNCHECKED = @as(u32, 0); pub const SE_SIGNING_LEVEL_UNSIGNED = @as(u32, 1); pub const SE_SIGNING_LEVEL_ENTERPRISE = @as(u32, 2); pub const SE_SIGNING_LEVEL_CUSTOM_1 = @as(u32, 3); pub const SE_SIGNING_LEVEL_DEVELOPER = @as(u32, 3); pub const SE_SIGNING_LEVEL_AUTHENTICODE = @as(u32, 4); pub const SE_SIGNING_LEVEL_CUSTOM_2 = @as(u32, 5); pub const SE_SIGNING_LEVEL_STORE = @as(u32, 6); pub const SE_SIGNING_LEVEL_CUSTOM_3 = @as(u32, 7); pub const SE_SIGNING_LEVEL_ANTIMALWARE = @as(u32, 7); pub const SE_SIGNING_LEVEL_MICROSOFT = @as(u32, 8); pub const SE_SIGNING_LEVEL_CUSTOM_4 = @as(u32, 9); pub const SE_SIGNING_LEVEL_CUSTOM_5 = @as(u32, 10); pub const SE_SIGNING_LEVEL_DYNAMIC_CODEGEN = @as(u32, 11); pub const SE_SIGNING_LEVEL_WINDOWS = @as(u32, 12); pub const SE_SIGNING_LEVEL_CUSTOM_7 = @as(u32, 13); pub const SE_SIGNING_LEVEL_WINDOWS_TCB = @as(u32, 14); pub const SE_SIGNING_LEVEL_CUSTOM_6 = @as(u32, 15); pub const SE_LEARNING_MODE_FLAG_PERMISSIVE = @as(u32, 1); pub const JOB_OBJECT_ASSIGN_PROCESS = @as(u32, 1); pub const JOB_OBJECT_SET_ATTRIBUTES = @as(u32, 2); pub const JOB_OBJECT_QUERY = @as(u32, 4); pub const JOB_OBJECT_TERMINATE = @as(u32, 8); pub const JOB_OBJECT_SET_SECURITY_ATTRIBUTES = @as(u32, 16); pub const JOB_OBJECT_IMPERSONATE = @as(u32, 32); pub const FLS_MAXIMUM_AVAILABLE = @as(u32, 4080); pub const TLS_MINIMUM_AVAILABLE = @as(u32, 64); pub const THREAD_DYNAMIC_CODE_ALLOW = @as(u32, 1); pub const THREAD_BASE_PRIORITY_LOWRT = @as(u32, 15); pub const THREAD_BASE_PRIORITY_MAX = @as(u32, 2); pub const THREAD_BASE_PRIORITY_MIN = @as(i32, -2); pub const THREAD_BASE_PRIORITY_IDLE = @as(i32, -15); pub const COMPONENT_KTM = @as(u32, 1); pub const COMPONENT_VALID_FLAGS = @as(u32, 1); pub const MEMORY_PRIORITY_LOWEST = @as(u32, 0); pub const DYNAMIC_EH_CONTINUATION_TARGET_ADD = @as(u32, 1); pub const DYNAMIC_EH_CONTINUATION_TARGET_PROCESSED = @as(u32, 2); pub const DYNAMIC_ENFORCED_ADDRESS_RANGE_ADD = @as(u32, 1); pub const DYNAMIC_ENFORCED_ADDRESS_RANGE_PROCESSED = @as(u32, 2); pub const QUOTA_LIMITS_HARDWS_MIN_ENABLE = @as(u32, 1); pub const QUOTA_LIMITS_HARDWS_MIN_DISABLE = @as(u32, 2); pub const QUOTA_LIMITS_HARDWS_MAX_ENABLE = @as(u32, 4); pub const QUOTA_LIMITS_HARDWS_MAX_DISABLE = @as(u32, 8); pub const QUOTA_LIMITS_USE_DEFAULT_LIMITS = @as(u32, 16); pub const MAX_HW_COUNTERS = @as(u32, 16); pub const THREAD_PROFILING_FLAG_DISPATCH = @as(u32, 1); pub const JOB_OBJECT_NET_RATE_CONTROL_MAX_DSCP_TAG = @as(u32, 64); pub const JOB_OBJECT_MSG_END_OF_JOB_TIME = @as(u32, 1); pub const JOB_OBJECT_MSG_END_OF_PROCESS_TIME = @as(u32, 2); pub const JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT = @as(u32, 3); pub const JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO = @as(u32, 4); pub const JOB_OBJECT_MSG_NEW_PROCESS = @as(u32, 6); pub const JOB_OBJECT_MSG_EXIT_PROCESS = @as(u32, 7); pub const JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS = @as(u32, 8); pub const JOB_OBJECT_MSG_PROCESS_MEMORY_LIMIT = @as(u32, 9); pub const JOB_OBJECT_MSG_JOB_MEMORY_LIMIT = @as(u32, 10); pub const JOB_OBJECT_MSG_NOTIFICATION_LIMIT = @as(u32, 11); pub const JOB_OBJECT_MSG_JOB_CYCLE_TIME_LIMIT = @as(u32, 12); pub const JOB_OBJECT_MSG_SILO_TERMINATED = @as(u32, 13); pub const JOB_OBJECT_MSG_MINIMUM = @as(u32, 1); pub const JOB_OBJECT_MSG_MAXIMUM = @as(u32, 13); pub const JOB_OBJECT_UILIMIT_ALL = @as(u32, 255); pub const JOB_OBJECT_UI_VALID_FLAGS = @as(u32, 255); pub const JOB_OBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE = @as(u32, 16); pub const JOB_OBJECT_CPU_RATE_CONTROL_VALID_FLAGS = @as(u32, 31); pub const MEMORY_PARTITION_QUERY_ACCESS = @as(u32, 1); pub const MEMORY_PARTITION_MODIFY_ACCESS = @as(u32, 2); pub const EVENT_MODIFY_STATE = @as(u32, 2); pub const MUTANT_QUERY_STATE = @as(u32, 1); pub const SEMAPHORE_MODIFY_STATE = @as(u32, 2); pub const TIMER_QUERY_STATE = @as(u32, 1); pub const TIMER_MODIFY_STATE = @as(u32, 2); pub const TIME_ZONE_ID_UNKNOWN = @as(u32, 0); pub const TIME_ZONE_ID_STANDARD = @as(u32, 1); pub const TIME_ZONE_ID_DAYLIGHT = @as(u32, 2); pub const LTP_PC_SMT = @as(u32, 1); pub const CACHE_FULLY_ASSOCIATIVE = @as(u32, 255); pub const PROCESSOR_INTEL_386 = @as(u32, 386); pub const PROCESSOR_INTEL_486 = @as(u32, 486); pub const PROCESSOR_INTEL_PENTIUM = @as(u32, 586); pub const PROCESSOR_INTEL_IA64 = @as(u32, 2200); pub const PROCESSOR_AMD_X8664 = @as(u32, 8664); pub const PROCESSOR_MIPS_R4000 = @as(u32, 4000); pub const PROCESSOR_ALPHA_21064 = @as(u32, 21064); pub const PROCESSOR_PPC_601 = @as(u32, 601); pub const PROCESSOR_PPC_603 = @as(u32, 603); pub const PROCESSOR_PPC_604 = @as(u32, 604); pub const PROCESSOR_PPC_620 = @as(u32, 620); pub const PROCESSOR_HITACHI_SH3 = @as(u32, 10003); pub const PROCESSOR_HITACHI_SH3E = @as(u32, 10004); pub const PROCESSOR_HITACHI_SH4 = @as(u32, 10005); pub const PROCESSOR_MOTOROLA_821 = @as(u32, 821); pub const PROCESSOR_SHx_SH3 = @as(u32, 103); pub const PROCESSOR_SHx_SH4 = @as(u32, 104); pub const PROCESSOR_STRONGARM = @as(u32, 2577); pub const PROCESSOR_ARM720 = @as(u32, 1824); pub const PROCESSOR_ARM820 = @as(u32, 2080); pub const PROCESSOR_ARM920 = @as(u32, 2336); pub const PROCESSOR_ARM_7TDMI = @as(u32, 70001); pub const PROCESSOR_OPTIL = @as(u32, 18767); pub const PROCESSOR_ARCHITECTURE_MIPS = @as(u32, 1); pub const PROCESSOR_ARCHITECTURE_ALPHA = @as(u32, 2); pub const PROCESSOR_ARCHITECTURE_PPC = @as(u32, 3); pub const PROCESSOR_ARCHITECTURE_SHX = @as(u32, 4); pub const PROCESSOR_ARCHITECTURE_ALPHA64 = @as(u32, 7); pub const PROCESSOR_ARCHITECTURE_MSIL = @as(u32, 8); pub const PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 = @as(u32, 10); pub const PROCESSOR_ARCHITECTURE_NEUTRAL = @as(u32, 11); pub const PROCESSOR_ARCHITECTURE_ARM64 = @as(u32, 12); pub const PROCESSOR_ARCHITECTURE_ARM32_ON_WIN64 = @as(u32, 13); pub const PROCESSOR_ARCHITECTURE_IA32_ON_ARM64 = @as(u32, 14); pub const PF_PPC_MOVEMEM_64BIT_OK = @as(u32, 4); pub const PF_ALPHA_BYTE_INSTRUCTIONS = @as(u32, 5); pub const PF_SSE_DAZ_MODE_AVAILABLE = @as(u32, 11); pub const PF_ARM_NEON_INSTRUCTIONS_AVAILABLE = @as(u32, 19); pub const PF_RDRAND_INSTRUCTION_AVAILABLE = @as(u32, 28); pub const PF_RDTSCP_INSTRUCTION_AVAILABLE = @as(u32, 32); pub const PF_RDPID_INSTRUCTION_AVAILABLE = @as(u32, 33); pub const PF_MONITORX_INSTRUCTION_AVAILABLE = @as(u32, 35); pub const PF_SSSE3_INSTRUCTIONS_AVAILABLE = @as(u32, 36); pub const PF_SSE4_1_INSTRUCTIONS_AVAILABLE = @as(u32, 37); pub const PF_SSE4_2_INSTRUCTIONS_AVAILABLE = @as(u32, 38); pub const PF_AVX_INSTRUCTIONS_AVAILABLE = @as(u32, 39); pub const PF_AVX2_INSTRUCTIONS_AVAILABLE = @as(u32, 40); pub const PF_AVX512F_INSTRUCTIONS_AVAILABLE = @as(u32, 41); pub const PF_ERMS_AVAILABLE = @as(u32, 42); pub const PF_ARM_V82_DP_INSTRUCTIONS_AVAILABLE = @as(u32, 43); pub const PF_ARM_V83_JSCVT_INSTRUCTIONS_AVAILABLE = @as(u32, 44); pub const XSTATE_LEGACY_FLOATING_POINT = @as(u32, 0); pub const XSTATE_LEGACY_SSE = @as(u32, 1); pub const XSTATE_GSSE = @as(u32, 2); pub const XSTATE_AVX = @as(u32, 2); pub const XSTATE_MPX_BNDREGS = @as(u32, 3); pub const XSTATE_MPX_BNDCSR = @as(u32, 4); pub const XSTATE_AVX512_KMASK = @as(u32, 5); pub const XSTATE_AVX512_ZMM_H = @as(u32, 6); pub const XSTATE_AVX512_ZMM = @as(u32, 7); pub const XSTATE_IPT = @as(u32, 8); pub const XSTATE_PASID = @as(u32, 10); pub const XSTATE_CET_U = @as(u32, 11); pub const XSTATE_CET_S = @as(u32, 12); pub const XSTATE_AMX_TILE_CONFIG = @as(u32, 17); pub const XSTATE_AMX_TILE_DATA = @as(u32, 18); pub const XSTATE_LWP = @as(u32, 62); pub const MAXIMUM_XSTATE_FEATURES = @as(u32, 64); pub const XSTATE_COMPACTION_ENABLE = @as(u32, 63); pub const XSTATE_ALIGN_BIT = @as(u32, 1); pub const XSTATE_XFD_BIT = @as(u32, 2); pub const XSTATE_CONTROLFLAG_XSAVEOPT_MASK = @as(u32, 1); pub const XSTATE_CONTROLFLAG_XSAVEC_MASK = @as(u32, 2); pub const XSTATE_CONTROLFLAG_XFD_MASK = @as(u32, 4); pub const CFG_CALL_TARGET_VALID = @as(u32, 1); pub const CFG_CALL_TARGET_PROCESSED = @as(u32, 2); pub const CFG_CALL_TARGET_CONVERT_EXPORT_SUPPRESSED_TO_VALID = @as(u32, 4); pub const CFG_CALL_TARGET_VALID_XFG = @as(u32, 8); pub const CFG_CALL_TARGET_CONVERT_XFG_TO_CFG = @as(u32, 16); pub const SESSION_QUERY_ACCESS = @as(u32, 1); pub const SESSION_MODIFY_ACCESS = @as(u32, 2); pub const MEM_TOP_DOWN = @as(u32, 1048576); pub const MEM_WRITE_WATCH = @as(u32, 2097152); pub const MEM_PHYSICAL = @as(u32, 4194304); pub const MEM_ROTATE = @as(u32, 8388608); pub const MEM_DIFFERENT_IMAGE_BASE_OK = @as(u32, 8388608); pub const MEM_4MB_PAGES = @as(u32, 2147483648); pub const MEM_COALESCE_PLACEHOLDERS = @as(u32, 1); pub const MEM_EXTENDED_PARAMETER_GRAPHICS = @as(u32, 1); pub const MEM_EXTENDED_PARAMETER_NONPAGED = @as(u32, 2); pub const MEM_EXTENDED_PARAMETER_ZERO_PAGES_OPTIONAL = @as(u32, 4); pub const MEM_EXTENDED_PARAMETER_NONPAGED_LARGE = @as(u32, 8); pub const MEM_EXTENDED_PARAMETER_NONPAGED_HUGE = @as(u32, 16); pub const MEM_EXTENDED_PARAMETER_SOFT_FAULT_PAGES = @as(u32, 32); pub const MEM_EXTENDED_PARAMETER_EC_CODE = @as(u32, 64); pub const MEM_EXTENDED_PARAMETER_TYPE_BITS = @as(u32, 8); pub const SEC_HUGE_PAGES = @as(u32, 131072); pub const WRITE_WATCH_FLAG_RESET = @as(u32, 1); pub const ENCLAVE_TYPE_SGX = @as(u32, 1); pub const ENCLAVE_TYPE_SGX2 = @as(u32, 2); pub const ENCLAVE_TYPE_VBS = @as(u32, 16); pub const ENCLAVE_VBS_FLAG_DEBUG = @as(u32, 1); pub const ENCLAVE_TYPE_VBS_BASIC = @as(u32, 17); pub const VBS_BASIC_PAGE_MEASURED_DATA = @as(u32, 1); pub const VBS_BASIC_PAGE_UNMEASURED_DATA = @as(u32, 2); pub const VBS_BASIC_PAGE_ZERO_FILL = @as(u32, 3); pub const VBS_BASIC_PAGE_THREAD_DESCRIPTOR = @as(u32, 4); pub const VBS_BASIC_PAGE_SYSTEM_CALL = @as(u32, 5); pub const DEDICATED_MEMORY_CACHE_ELIGIBLE = @as(u32, 1); pub const TREE_CONNECT_ATTRIBUTE_PRIVACY = @as(u32, 16384); pub const TREE_CONNECT_ATTRIBUTE_INTEGRITY = @as(u32, 32768); pub const TREE_CONNECT_ATTRIBUTE_GLOBAL = @as(u32, 4); pub const TREE_CONNECT_ATTRIBUTE_PINNED = @as(u32, 2); pub const FILE_ATTRIBUTE_STRICTLY_SEQUENTIAL = @as(u32, 536870912); pub const MAILSLOT_NO_MESSAGE = @as(u32, 4294967295); pub const MAILSLOT_WAIT_FOREVER = @as(u32, 4294967295); pub const FILE_CASE_SENSITIVE_SEARCH = @as(u32, 1); pub const FILE_CASE_PRESERVED_NAMES = @as(u32, 2); pub const FILE_UNICODE_ON_DISK = @as(u32, 4); pub const FILE_PERSISTENT_ACLS = @as(u32, 8); pub const FILE_FILE_COMPRESSION = @as(u32, 16); pub const FILE_VOLUME_QUOTAS = @as(u32, 32); pub const FILE_SUPPORTS_SPARSE_FILES = @as(u32, 64); pub const FILE_SUPPORTS_REPARSE_POINTS = @as(u32, 128); pub const FILE_SUPPORTS_REMOTE_STORAGE = @as(u32, 256); pub const FILE_RETURNS_CLEANUP_RESULT_INFO = @as(u32, 512); pub const FILE_SUPPORTS_POSIX_UNLINK_RENAME = @as(u32, 1024); pub const FILE_SUPPORTS_BYPASS_IO = @as(u32, 2048); pub const FILE_VOLUME_IS_COMPRESSED = @as(u32, 32768); pub const FILE_SUPPORTS_OBJECT_IDS = @as(u32, 65536); pub const FILE_SUPPORTS_ENCRYPTION = @as(u32, 131072); pub const FILE_NAMED_STREAMS = @as(u32, 262144); pub const FILE_READ_ONLY_VOLUME = @as(u32, 524288); pub const FILE_SEQUENTIAL_WRITE_ONCE = @as(u32, 1048576); pub const FILE_SUPPORTS_TRANSACTIONS = @as(u32, 2097152); pub const FILE_SUPPORTS_HARD_LINKS = @as(u32, 4194304); pub const FILE_SUPPORTS_EXTENDED_ATTRIBUTES = @as(u32, 8388608); pub const FILE_SUPPORTS_OPEN_BY_FILE_ID = @as(u32, 16777216); pub const FILE_SUPPORTS_USN_JOURNAL = @as(u32, 33554432); pub const FILE_SUPPORTS_INTEGRITY_STREAMS = @as(u32, 67108864); pub const FILE_SUPPORTS_BLOCK_REFCOUNTING = @as(u32, 134217728); pub const FILE_SUPPORTS_SPARSE_VDL = @as(u32, 268435456); pub const FILE_DAX_VOLUME = @as(u32, 536870912); pub const FILE_SUPPORTS_GHOSTING = @as(u32, 1073741824); pub const FILE_CS_FLAG_CASE_SENSITIVE_DIR = @as(u32, 1); pub const FLUSH_FLAGS_FILE_DATA_ONLY = @as(u32, 1); pub const FLUSH_FLAGS_NO_SYNC = @as(u32, 2); pub const FLUSH_FLAGS_FILE_DATA_SYNC_ONLY = @as(u32, 4); pub const IO_REPARSE_TAG_RESERVED_ZERO = @as(u32, 0); pub const IO_REPARSE_TAG_RESERVED_ONE = @as(u32, 1); pub const IO_REPARSE_TAG_RESERVED_TWO = @as(u32, 2); pub const IO_REPARSE_TAG_RESERVED_RANGE = @as(u32, 2); pub const IO_REPARSE_TAG_MOUNT_POINT = @as(i32, -1610612733); pub const IO_REPARSE_TAG_HSM = @as(i32, -1073741820); pub const IO_REPARSE_TAG_HSM2 = @as(i32, -2147483642); pub const IO_REPARSE_TAG_SIS = @as(i32, -2147483641); pub const IO_REPARSE_TAG_WIM = @as(i32, -2147483640); pub const IO_REPARSE_TAG_CSV = @as(i32, -2147483639); pub const IO_REPARSE_TAG_DFS = @as(i32, -2147483638); pub const IO_REPARSE_TAG_SYMLINK = @as(i32, -1610612724); pub const IO_REPARSE_TAG_DFSR = @as(i32, -2147483630); pub const IO_REPARSE_TAG_DEDUP = @as(i32, -2147483629); pub const IO_REPARSE_TAG_NFS = @as(i32, -2147483628); pub const IO_REPARSE_TAG_FILE_PLACEHOLDER = @as(i32, -2147483627); pub const IO_REPARSE_TAG_WOF = @as(i32, -2147483625); pub const IO_REPARSE_TAG_WCI = @as(i32, -2147483624); pub const IO_REPARSE_TAG_WCI_1 = @as(i32, -1879044072); pub const IO_REPARSE_TAG_GLOBAL_REPARSE = @as(i32, -1610612711); pub const IO_REPARSE_TAG_CLOUD = @as(i32, -1879048166); pub const IO_REPARSE_TAG_CLOUD_1 = @as(i32, -1879044070); pub const IO_REPARSE_TAG_CLOUD_2 = @as(i32, -1879039974); pub const IO_REPARSE_TAG_CLOUD_3 = @as(i32, -1879035878); pub const IO_REPARSE_TAG_CLOUD_4 = @as(i32, -1879031782); pub const IO_REPARSE_TAG_CLOUD_5 = @as(i32, -1879027686); pub const IO_REPARSE_TAG_CLOUD_6 = @as(i32, -1879023590); pub const IO_REPARSE_TAG_CLOUD_7 = @as(i32, -1879019494); pub const IO_REPARSE_TAG_CLOUD_8 = @as(i32, -1879015398); pub const IO_REPARSE_TAG_CLOUD_9 = @as(i32, -1879011302); pub const IO_REPARSE_TAG_CLOUD_A = @as(i32, -1879007206); pub const IO_REPARSE_TAG_CLOUD_B = @as(i32, -1879003110); pub const IO_REPARSE_TAG_CLOUD_C = @as(i32, -1878999014); pub const IO_REPARSE_TAG_CLOUD_D = @as(i32, -1878994918); pub const IO_REPARSE_TAG_CLOUD_E = @as(i32, -1878990822); pub const IO_REPARSE_TAG_CLOUD_F = @as(i32, -1878986726); pub const IO_REPARSE_TAG_CLOUD_MASK = @as(i32, 61440); pub const IO_REPARSE_TAG_APPEXECLINK = @as(i32, -2147483621); pub const IO_REPARSE_TAG_PROJFS = @as(i32, -1879048164); pub const IO_REPARSE_TAG_STORAGE_SYNC = @as(i32, -2147483618); pub const IO_REPARSE_TAG_WCI_TOMBSTONE = @as(i32, -1610612705); pub const IO_REPARSE_TAG_UNHANDLED = @as(i32, -2147483616); pub const IO_REPARSE_TAG_ONEDRIVE = @as(i32, -2147483615); pub const IO_REPARSE_TAG_PROJFS_TOMBSTONE = @as(i32, -1610612702); pub const IO_REPARSE_TAG_AF_UNIX = @as(i32, -2147483613); pub const IO_REPARSE_TAG_WCI_LINK = @as(i32, -1610612697); pub const IO_REPARSE_TAG_WCI_LINK_1 = @as(i32, -1610608601); pub const IO_REPARSE_TAG_DATALESS_CIM = @as(i32, -1610612696); pub const SCRUB_DATA_INPUT_FLAG_RESUME = @as(u32, 1); pub const SCRUB_DATA_INPUT_FLAG_SKIP_IN_SYNC = @as(u32, 2); pub const SCRUB_DATA_INPUT_FLAG_SKIP_NON_INTEGRITY_DATA = @as(u32, 4); pub const SCRUB_DATA_INPUT_FLAG_IGNORE_REDUNDANCY = @as(u32, 8); pub const SCRUB_DATA_INPUT_FLAG_SKIP_DATA = @as(u32, 16); pub const SCRUB_DATA_INPUT_FLAG_SCRUB_BY_OBJECT_ID = @as(u32, 32); pub const SCRUB_DATA_INPUT_FLAG_OPLOCK_NOT_ACQUIRED = @as(u32, 64); pub const SCRUB_DATA_OUTPUT_FLAG_INCOMPLETE = @as(u32, 1); pub const SCRUB_DATA_OUTPUT_FLAG_NON_USER_DATA_RANGE = @as(u32, 65536); pub const SCRUB_DATA_OUTPUT_FLAG_PARITY_EXTENT_DATA_RETURNED = @as(u32, 131072); pub const SCRUB_DATA_OUTPUT_FLAG_RESUME_CONTEXT_LENGTH_SPECIFIED = @as(u32, 262144); pub const SHUFFLE_FILE_FLAG_SKIP_INITIALIZING_NEW_CLUSTERS = @as(u32, 1); pub const IO_COMPLETION_MODIFY_STATE = @as(u32, 2); pub const NETWORK_APP_INSTANCE_CSV_FLAGS_VALID_ONLY_IF_CSV_COORDINATOR = @as(u32, 1); pub const GUID_MAX_POWER_SAVINGS = Guid.initString("a1841308-3541-4fab-bc81-f71556f20b4a"); pub const GUID_MIN_POWER_SAVINGS = Guid.initString("8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c"); pub const GUID_TYPICAL_POWER_SAVINGS = Guid.initString("381b4222-f694-41f0-9685-ff5bb260df2e"); pub const NO_SUBGROUP_GUID = Guid.initString("fea3413e-7e05-4911-9a71-700331f1c294"); pub const ALL_POWERSCHEMES_GUID = Guid.initString("68a1e95e-13ea-41e1-8011-0c496ca490b0"); pub const GUID_POWERSCHEME_PERSONALITY = Guid.initString("245d8541-3943-4422-b025-13a784f679b7"); pub const GUID_ACTIVE_POWERSCHEME = Guid.initString("31f9f286-5084-42fe-b720-2b0264993763"); pub const GUID_IDLE_RESILIENCY_SUBGROUP = Guid.initString("2e601130-5351-4d9d-8e04-252966bad054"); pub const GUID_IDLE_RESILIENCY_PERIOD = Guid.initString("c42b79aa-aa3a-484b-a98f-2cf32aa90a28"); pub const GUID_DEEP_SLEEP_ENABLED = Guid.initString("d502f7ee-1dc7-4efd-a55d-f04b6f5c0545"); pub const GUID_DEEP_SLEEP_PLATFORM_STATE = Guid.initString("d23f2fb8-9536-4038-9c94-1ce02e5c2152"); pub const GUID_DISK_COALESCING_POWERDOWN_TIMEOUT = Guid.initString("c36f0eb4-2988-4a70-8eee-0884fc2c2433"); pub const GUID_EXECUTION_REQUIRED_REQUEST_TIMEOUT = Guid.initString("3166bc41-7e98-4e03-b34e-ec0f5f2b218e"); pub const GUID_VIDEO_SUBGROUP = Guid.initString("7516b95f-f776-4464-8c53-06167f40cc99"); pub const GUID_VIDEO_POWERDOWN_TIMEOUT = Guid.initString("3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e"); pub const GUID_VIDEO_ANNOYANCE_TIMEOUT = Guid.initString("82dbcf2d-cd67-40c5-bfdc-9f1a5ccd4663"); pub const GUID_VIDEO_ADAPTIVE_PERCENT_INCREASE = Guid.initString("eed904df-b142-4183-b10b-5a1197a37864"); pub const GUID_VIDEO_DIM_TIMEOUT = Guid.initString("17aaa29b-8b43-4b94-aafe-35f64daaf1ee"); pub const GUID_VIDEO_ADAPTIVE_POWERDOWN = Guid.initString("90959d22-d6a1-49b9-af93-bce885ad335b"); pub const GUID_MONITOR_POWER_ON = Guid.initString("02731015-4510-4526-99e6-e5a17ebd1aea"); pub const GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS = Guid.initString("aded5e82-b909-4619-9949-f5d71dac0bcb"); pub const GUID_DEVICE_POWER_POLICY_VIDEO_DIM_BRIGHTNESS = Guid.initString("f1fbfde2-a960-4165-9f88-50667911ce96"); pub const GUID_VIDEO_CURRENT_MONITOR_BRIGHTNESS = Guid.initString("8ffee2c6-2d01-46be-adb9-398addc5b4ff"); pub const GUID_VIDEO_ADAPTIVE_DISPLAY_BRIGHTNESS = Guid.initString("fbd9aa66-9553-4097-ba44-ed6e9d65eab8"); pub const GUID_CONSOLE_DISPLAY_STATE = Guid.initString("6fe69556-704a-47a0-8f24-c28d936fda47"); pub const GUID_ALLOW_DISPLAY_REQUIRED = Guid.initString("a9ceb8da-cd46-44fb-a98b-02af69de4623"); pub const GUID_VIDEO_CONSOLE_LOCK_TIMEOUT = Guid.initString("8ec4b3a5-6868-48c2-be75-4f3044be88a7"); pub const GUID_ADVANCED_COLOR_QUALITY_BIAS = Guid.initString("684c3e69-a4f7-4014-8754-d45179a56167"); pub const GUID_ADAPTIVE_POWER_BEHAVIOR_SUBGROUP = Guid.initString("8619b916-e004-4dd8-9b66-dae86f806698"); pub const GUID_NON_ADAPTIVE_INPUT_TIMEOUT = Guid.initString("5adbbfbc-074e-4da1-ba38-db8b36b2c8f3"); pub const GUID_ADAPTIVE_INPUT_CONTROLLER_STATE = Guid.initString("0e98fae9-f45a-4de1-a757-6031f197f6ea"); pub const GUID_DISK_SUBGROUP = Guid.initString("0012ee47-9041-4b5d-9b77-535fba8b1442"); pub const GUID_DISK_MAX_POWER = Guid.initString("51dea550-bb38-4bc4-991b-eacf37be5ec8"); pub const GUID_DISK_POWERDOWN_TIMEOUT = Guid.initString("6738e2c4-e8a5-4a42-b16a-e040e769756e"); pub const GUID_DISK_IDLE_TIMEOUT = Guid.initString("58e39ba8-b8e6-4ef6-90d0-89ae32b258d6"); pub const GUID_DISK_BURST_IGNORE_THRESHOLD = Guid.initString("80e3c60e-bb94-4ad8-bbe0-0d3195efc663"); pub const GUID_DISK_ADAPTIVE_POWERDOWN = Guid.initString("396a32e1-499a-40b2-9124-a96afe707667"); pub const GUID_DISK_NVME_NOPPME = Guid.initString("fc7372b6-ab2d-43ee-8797-15e9841f2cca"); pub const GUID_SLEEP_SUBGROUP = Guid.initString("238c9fa8-0aad-41ed-83f4-97be242c8f20"); pub const GUID_SLEEP_IDLE_THRESHOLD = Guid.initString("81cd32e0-7833-44f3-8737-7081f38d1f70"); pub const GUID_STANDBY_TIMEOUT = Guid.initString("29f6c1db-86da-48c5-9fdb-f2b67b1f44da"); pub const GUID_UNATTEND_SLEEP_TIMEOUT = Guid.initString("7bc4a2f9-d8fc-4469-b07b-33eb785aaca0"); pub const GUID_HIBERNATE_TIMEOUT = Guid.initString("9d7815a6-7ee4-497e-8888-515a05f02364"); pub const GUID_HIBERNATE_FASTS4_POLICY = Guid.initString("94ac6d29-73ce-41a6-809f-6363ba21b47e"); pub const GUID_CRITICAL_POWER_TRANSITION = Guid.initString("b7a27025-e569-46c2-a504-2b96cad225a1"); pub const GUID_SYSTEM_AWAYMODE = Guid.initString("98a7f580-01f7-48aa-9c0f-44352c29e5c0"); pub const GUID_ALLOW_AWAYMODE = Guid.initString("25dfa149-5dd1-4736-b5ab-e8a37b5b8187"); pub const GUID_USER_PRESENCE_PREDICTION = Guid.initString("82011705-fb95-4d46-8d35-4042b1d20def"); pub const GUID_STANDBY_BUDGET_GRACE_PERIOD = Guid.initString("60c07fe1-0556-45cf-9903-d56e32210242"); pub const GUID_STANDBY_BUDGET_PERCENT = Guid.initString("9fe527be-1b70-48da-930d-7bcf17b44990"); pub const GUID_STANDBY_RESERVE_GRACE_PERIOD = Guid.initString("c763ee92-71e8-4127-84eb-f6ed043a3e3d"); pub const GUID_STANDBY_RESERVE_TIME = Guid.initString("468fe7e5-1158-46ec-88bc-5b96c9e44fd0"); pub const GUID_STANDBY_RESET_PERCENT = Guid.initString("49cb11a5-56e2-4afb-9d38-3df47872e21b"); pub const GUID_HUPR_ADAPTIVE_DISPLAY_TIMEOUT = Guid.initString("0a7d6ab6-ac83-4ad1-8282-eca5b58308f3"); pub const GUID_ALLOW_STANDBY_STATES = Guid.initString("abfc2519-3608-4c2a-94ea-171b0ed546ab"); pub const GUID_ALLOW_RTC_WAKE = Guid.initString("bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d"); pub const GUID_LEGACY_RTC_MITIGATION = Guid.initString("1a34bdc3-7e6b-442e-a9d0-64b6ef378e84"); pub const GUID_ALLOW_SYSTEM_REQUIRED = Guid.initString("a4b195f5-8225-47d8-8012-9d41369786e2"); pub const GUID_POWER_SAVING_STATUS = Guid.initString("e00958c0-c213-4ace-ac77-fecced2eeea5"); pub const GUID_ENERGY_SAVER_SUBGROUP = Guid.initString("de830923-a562-41af-a086-e3a2c6bad2da"); pub const GUID_ENERGY_SAVER_BATTERY_THRESHOLD = Guid.initString("e69653ca-cf7f-4f05-aa73-cb833fa90ad4"); pub const GUID_ENERGY_SAVER_BRIGHTNESS = Guid.initString("13d09884-f74e-474a-a852-b6bde8ad03a8"); pub const GUID_ENERGY_SAVER_POLICY = Guid.initString("5c5bb349-ad29-4ee2-9d0b-2b25270f7a81"); pub const GUID_SYSTEM_BUTTON_SUBGROUP = Guid.initString("4f971e89-eebd-4455-a8de-9e59040e7347"); pub const POWERBUTTON_ACTION_INDEX_NOTHING = @as(u32, 0); pub const POWERBUTTON_ACTION_INDEX_SLEEP = @as(u32, 1); pub const POWERBUTTON_ACTION_INDEX_HIBERNATE = @as(u32, 2); pub const POWERBUTTON_ACTION_INDEX_SHUTDOWN = @as(u32, 3); pub const POWERBUTTON_ACTION_INDEX_TURN_OFF_THE_DISPLAY = @as(u32, 4); pub const POWERBUTTON_ACTION_VALUE_NOTHING = @as(u32, 0); pub const POWERBUTTON_ACTION_VALUE_SLEEP = @as(u32, 2); pub const POWERBUTTON_ACTION_VALUE_HIBERNATE = @as(u32, 3); pub const POWERBUTTON_ACTION_VALUE_SHUTDOWN = @as(u32, 6); pub const POWERBUTTON_ACTION_VALUE_TURN_OFF_THE_DISPLAY = @as(u32, 8); pub const GUID_POWERBUTTON_ACTION = Guid.initString("7648efa3-dd9c-4e3e-b566-50f929386280"); pub const GUID_SLEEPBUTTON_ACTION = Guid.initString("96996bc0-ad50-47ec-923b-6f41874dd9eb"); pub const GUID_USERINTERFACEBUTTON_ACTION = Guid.initString("a7066653-8d6c-40a8-910e-a1f54b84c7e5"); pub const GUID_LIDCLOSE_ACTION = Guid.initString("5ca83367-6e45-459f-a27b-476b1d01c936"); pub const GUID_LIDOPEN_POWERSTATE = Guid.initString("99ff10e7-23b1-4c07-a9d1-5c3206d741b4"); pub const GUID_BATTERY_SUBGROUP = Guid.initString("e73a048d-bf27-4f12-9731-8b2076e8891f"); pub const GUID_BATTERY_DISCHARGE_ACTION_0 = Guid.initString("637ea02f-bbcb-4015-8e2c-a1c7b9c0b546"); pub const GUID_BATTERY_DISCHARGE_LEVEL_0 = Guid.initString("9a66d8d7-4ff7-4ef9-b5a2-5a326ca2a469"); pub const GUID_BATTERY_DISCHARGE_FLAGS_0 = Guid.initString("5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f"); pub const GUID_BATTERY_DISCHARGE_ACTION_1 = Guid.initString("d8742dcb-3e6a-4b3c-b3fe-374623cdcf06"); pub const GUID_BATTERY_DISCHARGE_LEVEL_1 = Guid.initString("8183ba9a-e910-48da-8769-14ae6dc1170a"); pub const GUID_BATTERY_DISCHARGE_FLAGS_1 = Guid.initString("bcded951-187b-4d05-bccc-f7e51960c258"); pub const GUID_BATTERY_DISCHARGE_ACTION_2 = Guid.initString("421cba38-1a8e-4881-ac89-e33a8b04ece4"); pub const GUID_BATTERY_DISCHARGE_LEVEL_2 = Guid.initString("07a07ca2-adaf-40d7-b077-533aaded1bfa"); pub const GUID_BATTERY_DISCHARGE_FLAGS_2 = Guid.initString("7fd2f0c4-feb7-4da3-8117-e3fbedc46582"); pub const GUID_BATTERY_DISCHARGE_ACTION_3 = Guid.initString("80472613-9780-455e-b308-72d3003cf2f8"); pub const GUID_BATTERY_DISCHARGE_LEVEL_3 = Guid.initString("58afd5a6-c2dd-47d2-9fbf-ef70cc5c5965"); pub const GUID_BATTERY_DISCHARGE_FLAGS_3 = Guid.initString("73613ccf-dbfa-4279-8356-4935f6bf62f3"); pub const GUID_PROCESSOR_SETTINGS_SUBGROUP = Guid.initString("54533251-82be-4824-96c1-47b60b740d00"); pub const GUID_PROCESSOR_THROTTLE_POLICY = Guid.initString("57027304-4af6-4104-9260-e3d95248fc36"); pub const PERFSTATE_POLICY_CHANGE_IDEAL = @as(u32, 0); pub const PERFSTATE_POLICY_CHANGE_SINGLE = @as(u32, 1); pub const PERFSTATE_POLICY_CHANGE_ROCKET = @as(u32, 2); pub const PERFSTATE_POLICY_CHANGE_IDEAL_AGGRESSIVE = @as(u32, 3); pub const PERFSTATE_POLICY_CHANGE_DECREASE_MAX = @as(u32, 2); pub const PERFSTATE_POLICY_CHANGE_INCREASE_MAX = @as(u32, 3); pub const GUID_PROCESSOR_THROTTLE_MAXIMUM = Guid.initString("bc5038f7-23e0-4960-96da-33abaf5935ec"); pub const GUID_PROCESSOR_THROTTLE_MAXIMUM_1 = Guid.initString("bc5038f7-23e0-4960-96da-33abaf5935ed"); pub const GUID_PROCESSOR_THROTTLE_MINIMUM = Guid.initString("893dee8e-2bef-41e0-89c6-b55d0929964c"); pub const GUID_PROCESSOR_THROTTLE_MINIMUM_1 = Guid.initString("893dee8e-2bef-41e0-89c6-b55d0929964d"); pub const GUID_PROCESSOR_FREQUENCY_LIMIT = Guid.initString("75b0ae3f-bce0-45a7-8c89-c9611c25e100"); pub const GUID_PROCESSOR_FREQUENCY_LIMIT_1 = Guid.initString("75b0ae3f-bce0-45a7-8c89-c9611c25e101"); pub const GUID_PROCESSOR_ALLOW_THROTTLING = Guid.initString("3b04d4fd-1cc7-4f23-ab1c-d1337819c4bb"); pub const PROCESSOR_THROTTLE_DISABLED = @as(u32, 0); pub const PROCESSOR_THROTTLE_ENABLED = @as(u32, 1); pub const PROCESSOR_THROTTLE_AUTOMATIC = @as(u32, 2); pub const GUID_PROCESSOR_IDLESTATE_POLICY = Guid.initString("68f262a7-f621-4069-b9a5-4874169be23c"); pub const GUID_PROCESSOR_PERFSTATE_POLICY = Guid.initString("bbdc3814-18e9-4463-8a55-d197327c45c0"); pub const GUID_PROCESSOR_PERF_INCREASE_THRESHOLD = Guid.initString("06cadf0e-64ed-448a-8927-ce7bf90eb35d"); pub const GUID_PROCESSOR_PERF_INCREASE_THRESHOLD_1 = Guid.initString("06cadf0e-64ed-448a-8927-ce7bf90eb35e"); pub const GUID_PROCESSOR_PERF_DECREASE_THRESHOLD = Guid.initString("12a0ab44-fe28-4fa9-b3bd-4b64f44960a6"); pub const GUID_PROCESSOR_PERF_DECREASE_THRESHOLD_1 = Guid.initString("12a0ab44-fe28-4fa9-b3bd-4b64f44960a7"); pub const GUID_PROCESSOR_PERF_INCREASE_POLICY = Guid.initString("465e1f50-b610-473a-ab58-00d1077dc418"); pub const GUID_PROCESSOR_PERF_INCREASE_POLICY_1 = Guid.initString("465e1f50-b610-473a-ab58-00d1077dc419"); pub const GUID_PROCESSOR_PERF_DECREASE_POLICY = Guid.initString("40fbefc7-2e9d-4d25-a185-0cfd8574bac6"); pub const GUID_PROCESSOR_PERF_DECREASE_POLICY_1 = Guid.initString("40fbefc7-2e9d-4d25-a185-0cfd8574bac7"); pub const GUID_PROCESSOR_PERF_INCREASE_TIME = Guid.initString("984cf492-3bed-4488-a8f9-4286c97bf5aa"); pub const GUID_PROCESSOR_PERF_INCREASE_TIME_1 = Guid.initString("984cf492-3bed-4488-a8f9-4286c97bf5ab"); pub const GUID_PROCESSOR_PERF_DECREASE_TIME = Guid.initString("d8edeb9b-95cf-4f95-a73c-b061973693c8"); pub const GUID_PROCESSOR_PERF_DECREASE_TIME_1 = Guid.initString("d8edeb9b-95cf-4f95-a73c-b061973693c9"); pub const GUID_PROCESSOR_PERF_TIME_CHECK = Guid.initString("4d2b0152-7d5c-498b-88e2-34345392a2c5"); pub const GUID_PROCESSOR_PERF_BOOST_POLICY = Guid.initString("45bcc044-d885-43e2-8605-ee0ec6e96b59"); pub const PROCESSOR_PERF_BOOST_POLICY_DISABLED = @as(u32, 0); pub const PROCESSOR_PERF_BOOST_POLICY_MAX = @as(u32, 100); pub const GUID_PROCESSOR_PERF_BOOST_MODE = Guid.initString("be337238-0d82-4146-a960-4f3749d470c7"); pub const PROCESSOR_PERF_BOOST_MODE_DISABLED = @as(u32, 0); pub const PROCESSOR_PERF_BOOST_MODE_ENABLED = @as(u32, 1); pub const PROCESSOR_PERF_BOOST_MODE_AGGRESSIVE = @as(u32, 2); pub const PROCESSOR_PERF_BOOST_MODE_EFFICIENT_ENABLED = @as(u32, 3); pub const PROCESSOR_PERF_BOOST_MODE_EFFICIENT_AGGRESSIVE = @as(u32, 4); pub const PROCESSOR_PERF_BOOST_MODE_AGGRESSIVE_AT_GUARANTEED = @as(u32, 5); pub const PROCESSOR_PERF_BOOST_MODE_EFFICIENT_AGGRESSIVE_AT_GUARANTEED = @as(u32, 6); pub const PROCESSOR_PERF_BOOST_MODE_MAX = @as(u32, 6); pub const GUID_PROCESSOR_PERF_AUTONOMOUS_MODE = Guid.initString("8baa4a8a-14c6-4451-8e8b-14bdbd197537"); pub const PROCESSOR_PERF_AUTONOMOUS_MODE_DISABLED = @as(u32, 0); pub const PROCESSOR_PERF_AUTONOMOUS_MODE_ENABLED = @as(u32, 1); pub const GUID_PROCESSOR_PERF_ENERGY_PERFORMANCE_PREFERENCE = Guid.initString("36687f9e-e3a5-4dbf-b1dc-15eb381c6863"); pub const GUID_PROCESSOR_PERF_ENERGY_PERFORMANCE_PREFERENCE_1 = Guid.initString("36687f9e-e3a5-4dbf-b1dc-15eb381c6864"); pub const PROCESSOR_PERF_PERFORMANCE_PREFERENCE = @as(u32, 255); pub const PROCESSOR_PERF_ENERGY_PREFERENCE = @as(u32, 0); pub const GUID_PROCESSOR_PERF_AUTONOMOUS_ACTIVITY_WINDOW = Guid.initString("cfeda3d0-7697-4566-a922-a9086cd49dfa"); pub const PROCESSOR_PERF_MINIMUM_ACTIVITY_WINDOW = @as(u32, 0); pub const PROCESSOR_PERF_MAXIMUM_ACTIVITY_WINDOW = @as(u32, 1270000000); pub const GUID_PROCESSOR_DUTY_CYCLING = Guid.initString("4e4450b3-6179-4e91-b8f1-5bb9938f81a1"); pub const PROCESSOR_DUTY_CYCLING_DISABLED = @as(u32, 0); pub const PROCESSOR_DUTY_CYCLING_ENABLED = @as(u32, 1); pub const GUID_PROCESSOR_IDLE_ALLOW_SCALING = Guid.initString("6c2993b0-8f48-481f-bcc6-00dd2742aa06"); pub const GUID_PROCESSOR_IDLE_DISABLE = Guid.initString("5d76a2ca-e8c0-402f-a133-2158492d58ad"); pub const GUID_PROCESSOR_IDLE_STATE_MAXIMUM = Guid.initString("9943e905-9a30-4ec1-9b99-44dd3b76f7a2"); pub const GUID_PROCESSOR_IDLE_TIME_CHECK = Guid.initString("c4581c31-89ab-4597-8e2b-9c9cab440e6b"); pub const GUID_PROCESSOR_IDLE_DEMOTE_THRESHOLD = Guid.initString("4b92d758-5a24-4851-a470-815d78aee119"); pub const GUID_PROCESSOR_IDLE_PROMOTE_THRESHOLD = Guid.initString("7b224883-b3cc-4d79-819f-8374152cbe7c"); pub const GUID_PROCESSOR_CORE_PARKING_INCREASE_THRESHOLD = Guid.initString("df142941-20f3-4edf-9a4a-9c83d3d717d1"); pub const GUID_PROCESSOR_CORE_PARKING_DECREASE_THRESHOLD = Guid.initString("68dd2f27-a4ce-4e11-8487-3794e4135dfa"); pub const GUID_PROCESSOR_CORE_PARKING_INCREASE_POLICY = Guid.initString("c7be0679-2817-4d69-9d02-519a537ed0c6"); pub const CORE_PARKING_POLICY_CHANGE_IDEAL = @as(u32, 0); pub const CORE_PARKING_POLICY_CHANGE_SINGLE = @as(u32, 1); pub const CORE_PARKING_POLICY_CHANGE_ROCKET = @as(u32, 2); pub const CORE_PARKING_POLICY_CHANGE_MULTISTEP = @as(u32, 3); pub const CORE_PARKING_POLICY_CHANGE_MAX = @as(u32, 3); pub const GUID_PROCESSOR_CORE_PARKING_DECREASE_POLICY = Guid.initString("71021b41-c749-4d21-be74-a00f335d582b"); pub const GUID_PROCESSOR_CORE_PARKING_MAX_CORES = Guid.initString("ea062031-0e34-4ff1-9b6d-eb1059334028"); pub const GUID_PROCESSOR_CORE_PARKING_MAX_CORES_1 = Guid.initString("ea062031-0e34-4ff1-9b6d-eb1059334029"); pub const GUID_PROCESSOR_CORE_PARKING_MIN_CORES = Guid.initString("0cc5b647-c1df-4637-891a-dec35c318583"); pub const GUID_PROCESSOR_CORE_PARKING_MIN_CORES_1 = Guid.initString("0cc5b647-c1df-4637-891a-dec35c318584"); pub const GUID_PROCESSOR_CORE_PARKING_INCREASE_TIME = Guid.initString("2ddd5a84-5a71-437e-912a-db0b8c788732"); pub const GUID_PROCESSOR_CORE_PARKING_DECREASE_TIME = Guid.initString("dfd10d17-d5eb-45dd-877a-9a34ddd15c82"); pub const GUID_PROCESSOR_CORE_PARKING_AFFINITY_HISTORY_DECREASE_FACTOR = Guid.initString("8f7b45e3-c393-480a-878c-f67ac3d07082"); pub const GUID_PROCESSOR_CORE_PARKING_AFFINITY_HISTORY_THRESHOLD = Guid.initString("5b33697b-e89d-4d38-aa46-9e7dfb7cd2f9"); pub const GUID_PROCESSOR_CORE_PARKING_AFFINITY_WEIGHTING = Guid.initString("e70867f1-fa2f-4f4e-aea1-4d8a0ba23b20"); pub const GUID_PROCESSOR_CORE_PARKING_OVER_UTILIZATION_HISTORY_DECREASE_FACTOR = Guid.initString("1299023c-bc28-4f0a-81ec-d3295a8d815d"); pub const GUID_PROCESSOR_CORE_PARKING_OVER_UTILIZATION_HISTORY_THRESHOLD = Guid.initString("9ac18e92-aa3c-4e27-b307-01ae37307129"); pub const GUID_PROCESSOR_CORE_PARKING_OVER_UTILIZATION_WEIGHTING = Guid.initString("8809c2d8-b155-42d4-bcda-0d345651b1db"); pub const GUID_PROCESSOR_CORE_PARKING_OVER_UTILIZATION_THRESHOLD = Guid.initString("943c8cb6-6f93-4227-ad87-e9a3feec08d1"); pub const GUID_PROCESSOR_PARKING_CORE_OVERRIDE = Guid.initString("a55612aa-f624-42c6-a443-7397d064c04f"); pub const GUID_PROCESSOR_PARKING_PERF_STATE = Guid.initString("447235c7-6a8d-4cc0-8e24-9eaf70b96e2b"); pub const GUID_PROCESSOR_PARKING_PERF_STATE_1 = Guid.initString("447235c7-6a8d-4cc0-8e24-9eaf70b96e2c"); pub const GUID_PROCESSOR_PARKING_CONCURRENCY_THRESHOLD = Guid.initString("2430ab6f-a520-44a2-9601-f7f23b5134b1"); pub const GUID_PROCESSOR_PARKING_HEADROOM_THRESHOLD = Guid.initString("f735a673-2066-4f80-a0c5-ddee0cf1bf5d"); pub const GUID_PROCESSOR_PARKING_DISTRIBUTION_THRESHOLD = Guid.initString("4bdaf4e9-d103-46d7-a5f0-6280121616ef"); pub const GUID_PROCESSOR_SOFT_PARKING_LATENCY = Guid.initString("97cfac41-2217-47eb-992d-618b1977c907"); pub const GUID_PROCESSOR_PERF_HISTORY = Guid.initString("7d24baa7-0b84-480f-840c-1b0743c00f5f"); pub const GUID_PROCESSOR_PERF_HISTORY_1 = Guid.initString("7d24baa7-0b84-480f-840c-1b0743c00f60"); pub const GUID_PROCESSOR_PERF_INCREASE_HISTORY = Guid.initString("99b3ef01-752f-46a1-80fb-7730011f2354"); pub const GUID_PROCESSOR_PERF_DECREASE_HISTORY = Guid.initString("0300f6f8-abd6-45a9-b74f-4908691a40b5"); pub const GUID_PROCESSOR_PERF_CORE_PARKING_HISTORY = Guid.initString("77d7f282-8f1a-42cd-8537-45450a839be8"); pub const GUID_PROCESSOR_PERF_LATENCY_HINT = Guid.initString("0822df31-9c83-441c-a079-0de4cf009c7b"); pub const GUID_PROCESSOR_PERF_LATENCY_HINT_PERF = Guid.initString("619b7505-003b-4e82-b7a6-4dd29c300971"); pub const GUID_PROCESSOR_PERF_LATENCY_HINT_PERF_1 = Guid.initString("619b7505-003b-4e82-b7a6-4dd29c300972"); pub const GUID_PROCESSOR_LATENCY_HINT_MIN_UNPARK = Guid.initString("616cdaa5-695e-4545-97ad-97dc2d1bdd88"); pub const GUID_PROCESSOR_LATENCY_HINT_MIN_UNPARK_1 = Guid.initString("616cdaa5-695e-4545-97ad-97dc2d1bdd89"); pub const GUID_PROCESSOR_DISTRIBUTE_UTILITY = Guid.initString("e0007330-f589-42ed-a401-5ddb10e785d3"); pub const GUID_PROCESSOR_HETEROGENEOUS_POLICY = Guid.initString("7f2f5cfa-f10c-4823-b5e1-e93ae85f46b5"); pub const GUID_PROCESSOR_HETERO_DECREASE_TIME = Guid.initString("7f2492b6-60b1-45e5-ae55-773f8cd5caec"); pub const GUID_PROCESSOR_HETERO_INCREASE_TIME = Guid.initString("4009efa7-e72d-4cba-9edf-91084ea8cbc3"); pub const GUID_PROCESSOR_HETERO_DECREASE_THRESHOLD = Guid.initString("f8861c27-95e7-475c-865b-13c0cb3f9d6b"); pub const GUID_PROCESSOR_HETERO_INCREASE_THRESHOLD = Guid.initString("b000397d-9b0b-483d-98c9-692a6060cfbf"); pub const GUID_PROCESSOR_CLASS0_FLOOR_PERF = Guid.initString("fddc842b-8364-4edc-94cf-c17f60de1c80"); pub const GUID_PROCESSOR_CLASS1_INITIAL_PERF = Guid.initString("1facfc65-a930-4bc5-9f38-504ec097bbc0"); pub const GUID_PROCESSOR_THREAD_SCHEDULING_POLICY = Guid.initString("93b8b6dc-0698-4d1c-9ee4-0644e900c85d"); pub const GUID_PROCESSOR_SHORT_THREAD_SCHEDULING_POLICY = Guid.initString("bae08b81-2d5e-4688-ad6a-13243356654b"); pub const GUID_PROCESSOR_SHORT_THREAD_RUNTIME_THRESHOLD = Guid.initString("d92998c2-6a48-49ca-85d4-8cceec294570"); pub const GUID_SYSTEM_COOLING_POLICY = Guid.initString("94d3a615-a899-4ac5-ae2b-e4d8f634367f"); pub const GUID_PROCESSOR_RESPONSIVENESS_DISABLE_THRESHOLD = Guid.initString("38b8383d-cce0-4c79-9e3e-56a4f17cc480"); pub const GUID_PROCESSOR_RESPONSIVENESS_DISABLE_THRESHOLD_1 = Guid.initString("38b8383d-cce0-4c79-9e3e-56a4f17cc481"); pub const GUID_PROCESSOR_RESPONSIVENESS_ENABLE_THRESHOLD = Guid.initString("3d44e256-7222-4415-a9ed-9c45fa3dd830"); pub const GUID_PROCESSOR_RESPONSIVENESS_ENABLE_THRESHOLD_1 = Guid.initString("3d44e256-7222-4415-a9ed-9c45fa3dd831"); pub const GUID_PROCESSOR_RESPONSIVENESS_DISABLE_TIME = Guid.initString("f565999f-3fb0-411a-a226-3f0198dec130"); pub const GUID_PROCESSOR_RESPONSIVENESS_DISABLE_TIME_1 = Guid.initString("f565999f-3fb0-411a-a226-3f0198dec131"); pub const GUID_PROCESSOR_RESPONSIVENESS_ENABLE_TIME = Guid.initString("3d915188-7830-49ae-a79a-0fb0a1e5a200"); pub const GUID_PROCESSOR_RESPONSIVENESS_ENABLE_TIME_1 = Guid.initString("3d915188-7830-49ae-a79a-0fb0a1e5a201"); pub const GUID_PROCESSOR_RESPONSIVENESS_EPP_CEILING = Guid.initString("4427c73b-9756-4a5c-b84b-c7bda79c7320"); pub const GUID_PROCESSOR_RESPONSIVENESS_EPP_CEILING_1 = Guid.initString("4427c73b-9756-4a5c-b84b-c7bda79c7321"); pub const GUID_PROCESSOR_RESPONSIVENESS_PERF_FLOOR = Guid.initString("ce8e92ee-6a86-4572-bfe0-20c21d03cd40"); pub const GUID_PROCESSOR_RESPONSIVENESS_PERF_FLOOR_1 = Guid.initString("ce8e92ee-6a86-4572-bfe0-20c21d03cd41"); pub const GUID_LOCK_CONSOLE_ON_WAKE = Guid.initString("0e796bdb-100d-47d6-a2d5-f7d2daa51f51"); pub const GUID_DEVICE_IDLE_POLICY = Guid.initString("4faab71a-92e5-4726-b531-224559672d19"); pub const POWER_DEVICE_IDLE_POLICY_PERFORMANCE = @as(u32, 0); pub const POWER_DEVICE_IDLE_POLICY_CONSERVATIVE = @as(u32, 1); pub const GUID_CONNECTIVITY_IN_STANDBY = Guid.initString("f15576e8-98b7-4186-b944-eafa664402d9"); pub const POWER_CONNECTIVITY_IN_STANDBY_DISABLED = @as(u32, 0); pub const POWER_CONNECTIVITY_IN_STANDBY_ENABLED = @as(u32, 1); pub const POWER_CONNECTIVITY_IN_STANDBY_SYSTEM_MANAGED = @as(u32, 2); pub const GUID_DISCONNECTED_STANDBY_MODE = Guid.initString("68afb2d9-ee95-47a8-8f50-4115088073b1"); pub const POWER_DISCONNECTED_STANDBY_MODE_NORMAL = @as(u32, 0); pub const POWER_DISCONNECTED_STANDBY_MODE_AGGRESSIVE = @as(u32, 1); pub const GUID_ACDC_POWER_SOURCE = Guid.initString("5d3e9a59-e9d5-4b00-a6bd-ff34ff516548"); pub const GUID_LIDSWITCH_STATE_CHANGE = Guid.initString("ba3e0f4d-b817-4094-a2d1-d56379e6a0f3"); pub const GUID_LIDSWITCH_STATE_RELIABILITY = Guid.initString("ae4c4ff1-d361-43f4-80aa-bbb6eb03de94"); pub const GUID_BATTERY_PERCENTAGE_REMAINING = Guid.initString("a7ad8041-b45a-4cae-87a3-eecbb468a9e1"); pub const GUID_BATTERY_COUNT = Guid.initString("7d263f15-fca4-49e5-854b-a9f2bfbd5c24"); pub const GUID_GLOBAL_USER_PRESENCE = Guid.initString("786e8a1d-b427-4344-9207-09e70bdcbea9"); pub const GUID_SESSION_DISPLAY_STATUS = Guid.initString("2b84c20e-ad23-4ddf-93db-05ffbd7efca5"); pub const GUID_SESSION_USER_PRESENCE = Guid.initString("3c0f4548-c03f-4c4d-b9f2-237ede686376"); pub const GUID_IDLE_BACKGROUND_TASK = Guid.initString("515c31d8-f734-163d-a0fd-11a08c91e8f1"); pub const GUID_BACKGROUND_TASK_NOTIFICATION = Guid.initString("cf23f240-2a54-48d8-b114-de1518ff052e"); pub const GUID_APPLAUNCH_BUTTON = Guid.initString("1a689231-7399-4e9a-8f99-b71f999db3fa"); pub const GUID_PCIEXPRESS_SETTINGS_SUBGROUP = Guid.initString("501a4d13-42af-4429-9fd1-a8218c268e20"); pub const GUID_PCIEXPRESS_ASPM_POLICY = Guid.initString("ee12f906-d277-404b-b6da-e5fa1a576df5"); pub const GUID_ENABLE_SWITCH_FORCED_SHUTDOWN = Guid.initString("833a6b62-dfa4-46d1-82f8-e09e34d029d6"); pub const GUID_INTSTEER_SUBGROUP = Guid.initString("48672f38-7a9a-4bb2-8bf8-3d85be19de4e"); pub const GUID_INTSTEER_MODE = Guid.initString("2bfc24f9-5ea2-4801-8213-3dbae01aa39d"); pub const GUID_INTSTEER_LOAD_PER_PROC_TRIGGER = Guid.initString("73cde64d-d720-4bb2-a860-c755afe77ef2"); pub const GUID_INTSTEER_TIME_UNPARK_TRIGGER = Guid.initString("d6ba4903-386f-4c2c-8adb-5c21b3328d25"); pub const GUID_GRAPHICS_SUBGROUP = Guid.initString("5fb4938d-1ee8-4b0f-9a3c-5036b0ab995c"); pub const GUID_GPU_PREFERENCE_POLICY = Guid.initString("dd848b2a-8a5d-4451-9ae2-39cd41658f6c"); pub const GUID_MIXED_REALITY_MODE = Guid.initString("1e626b4e-cf04-4f8d-9cc7-c97c5b0f2391"); pub const GUID_SPR_ACTIVE_SESSION_CHANGE = Guid.initString("0e24ce38-c393-4742-bdb1-744f4b9ee08e"); pub const POWER_SYSTEM_MAXIMUM = @as(u32, 7); pub const DIAGNOSTIC_REASON_VERSION = @as(u32, 0); pub const DIAGNOSTIC_REASON_SIMPLE_STRING = @as(u32, 1); pub const DIAGNOSTIC_REASON_DETAILED_STRING = @as(u32, 2); pub const DIAGNOSTIC_REASON_NOT_SPECIFIED = @as(u32, 2147483648); pub const POWER_REQUEST_CONTEXT_VERSION = @as(u32, 0); pub const PDCAP_D0_SUPPORTED = @as(u32, 1); pub const PDCAP_D1_SUPPORTED = @as(u32, 2); pub const PDCAP_D2_SUPPORTED = @as(u32, 4); pub const PDCAP_D3_SUPPORTED = @as(u32, 8); pub const PDCAP_WAKE_FROM_D0_SUPPORTED = @as(u32, 16); pub const PDCAP_WAKE_FROM_D1_SUPPORTED = @as(u32, 32); pub const PDCAP_WAKE_FROM_D2_SUPPORTED = @as(u32, 64); pub const PDCAP_WAKE_FROM_D3_SUPPORTED = @as(u32, 128); pub const PDCAP_WARM_EJECT_SUPPORTED = @as(u32, 256); pub const POWER_SETTING_VALUE_VERSION = @as(u32, 1); pub const PROC_IDLE_BUCKET_COUNT = @as(u32, 6); pub const PROC_IDLE_BUCKET_COUNT_EX = @as(u32, 16); pub const ACPI_PPM_SOFTWARE_ALL = @as(u32, 252); pub const ACPI_PPM_SOFTWARE_ANY = @as(u32, 253); pub const ACPI_PPM_HARDWARE_ALL = @as(u32, 254); pub const MS_PPM_SOFTWARE_ALL = @as(u32, 1); pub const PPM_FIRMWARE_ACPI1C2 = @as(u32, 1); pub const PPM_FIRMWARE_ACPI1C3 = @as(u32, 2); pub const PPM_FIRMWARE_ACPI1TSTATES = @as(u32, 4); pub const PPM_FIRMWARE_CST = @as(u32, 8); pub const PPM_FIRMWARE_CSD = @as(u32, 16); pub const PPM_FIRMWARE_PCT = @as(u32, 32); pub const PPM_FIRMWARE_PSS = @as(u32, 64); pub const PPM_FIRMWARE_XPSS = @as(u32, 128); pub const PPM_FIRMWARE_PPC = @as(u32, 256); pub const PPM_FIRMWARE_PSD = @as(u32, 512); pub const PPM_FIRMWARE_PTC = @as(u32, 1024); pub const PPM_FIRMWARE_TSS = @as(u32, 2048); pub const PPM_FIRMWARE_TPC = @as(u32, 4096); pub const PPM_FIRMWARE_TSD = @as(u32, 8192); pub const PPM_FIRMWARE_PCCH = @as(u32, 16384); pub const PPM_FIRMWARE_PCCP = @as(u32, 32768); pub const PPM_FIRMWARE_OSC = @as(u32, 65536); pub const PPM_FIRMWARE_PDC = @as(u32, 131072); pub const PPM_FIRMWARE_CPC = @as(u32, 262144); pub const PPM_FIRMWARE_LPI = @as(u32, 524288); pub const PPM_PERFORMANCE_IMPLEMENTATION_NONE = @as(u32, 0); pub const PPM_PERFORMANCE_IMPLEMENTATION_PSTATES = @as(u32, 1); pub const PPM_PERFORMANCE_IMPLEMENTATION_PCCV1 = @as(u32, 2); pub const PPM_PERFORMANCE_IMPLEMENTATION_CPPC = @as(u32, 3); pub const PPM_PERFORMANCE_IMPLEMENTATION_PEP = @as(u32, 4); pub const PPM_IDLE_IMPLEMENTATION_NONE = @as(u32, 0); pub const PPM_IDLE_IMPLEMENTATION_CSTATES = @as(u32, 1); pub const PPM_IDLE_IMPLEMENTATION_PEP = @as(u32, 2); pub const PPM_IDLE_IMPLEMENTATION_MICROPEP = @as(u32, 3); pub const PPM_IDLE_IMPLEMENTATION_LPISTATES = @as(u32, 4); pub const PPM_PERFSTATE_CHANGE_GUID = Guid.initString("a5b32ddd-7f39-4abc-b892-900e43b59ebb"); pub const PPM_PERFSTATE_DOMAIN_CHANGE_GUID = Guid.initString("995e6b7f-d653-497a-b978-36a30c29bf01"); pub const PPM_IDLESTATE_CHANGE_GUID = Guid.initString("4838fe4f-f71c-4e51-9ecc-8430a7ac4c6c"); pub const PPM_PERFSTATES_DATA_GUID = Guid.initString("5708cc20-7d40-4bf4-b4aa-2b01338d0126"); pub const PPM_IDLESTATES_DATA_GUID = Guid.initString("ba138e10-e250-4ad7-8616-cf1a7ad410e7"); pub const PPM_IDLE_ACCOUNTING_GUID = Guid.initString("e2a26f78-ae07-4ee0-a30f-ce54f55a94cd"); pub const PPM_IDLE_ACCOUNTING_EX_GUID = Guid.initString("d67abd39-81f8-4a5e-8152-72e31ec912ee"); pub const PPM_THERMALCONSTRAINT_GUID = Guid.initString("a852c2c8-1a4c-423b-8c2c-f30d82931a88"); pub const PPM_PERFMON_PERFSTATE_GUID = Guid.initString("7fd18652-0cfe-40d2-b0a1-0b066a87759e"); pub const PPM_THERMAL_POLICY_CHANGE_GUID = Guid.initString("48f377b8-6880-4c7b-8bdc-380176c6654d"); pub const POWER_ACTION_QUERY_ALLOWED = @as(u32, 1); pub const POWER_ACTION_UI_ALLOWED = @as(u32, 2); pub const POWER_ACTION_OVERRIDE_APPS = @as(u32, 4); pub const POWER_ACTION_HIBERBOOT = @as(u32, 8); pub const POWER_ACTION_USER_NOTIFY = @as(u32, 16); pub const POWER_ACTION_DOZE_TO_HIBERNATE = @as(u32, 32); pub const POWER_ACTION_ACPI_CRITICAL = @as(u32, 16777216); pub const POWER_ACTION_ACPI_USER_NOTIFY = @as(u32, 33554432); pub const POWER_ACTION_DIRECTED_DRIPS = @as(u32, 67108864); pub const POWER_ACTION_PSEUDO_TRANSITION = @as(u32, 134217728); pub const POWER_ACTION_LIGHTEST_FIRST = @as(u32, 268435456); pub const POWER_ACTION_LOCK_CONSOLE = @as(u32, 536870912); pub const POWER_ACTION_DISABLE_WAKES = @as(u32, 1073741824); pub const POWER_ACTION_CRITICAL = @as(u32, 2147483648); pub const POWER_USER_NOTIFY_FORCED_SHUTDOWN = @as(u32, 32); pub const BATTERY_DISCHARGE_FLAGS_EVENTCODE_MASK = @as(u32, 7); pub const BATTERY_DISCHARGE_FLAGS_ENABLE = @as(u32, 2147483648); pub const NUM_DISCHARGE_POLICIES = @as(u32, 4); pub const DISCHARGE_POLICY_CRITICAL = @as(u32, 0); pub const DISCHARGE_POLICY_LOW = @as(u32, 1); pub const PROCESSOR_IDLESTATE_POLICY_COUNT = @as(u32, 3); pub const PO_THROTTLE_NONE = @as(u32, 0); pub const PO_THROTTLE_CONSTANT = @as(u32, 1); pub const PO_THROTTLE_DEGRADE = @as(u32, 2); pub const PO_THROTTLE_ADAPTIVE = @as(u32, 3); pub const PO_THROTTLE_MAXIMUM = @as(u32, 4); pub const HIBERFILE_TYPE_NONE = @as(u32, 0); pub const HIBERFILE_TYPE_REDUCED = @as(u32, 1); pub const HIBERFILE_TYPE_FULL = @as(u32, 2); pub const HIBERFILE_TYPE_MAX = @as(u32, 3); pub const IMAGE_DOS_SIGNATURE = @as(u32, 23117); pub const IMAGE_OS2_SIGNATURE = @as(u32, 17742); pub const IMAGE_OS2_SIGNATURE_LE = @as(u32, 17740); pub const IMAGE_VXD_SIGNATURE = @as(u32, 17740); pub const IMAGE_NT_SIGNATURE = @as(u32, 17744); pub const IMAGE_SIZEOF_FILE_HEADER = @as(u32, 20); pub const IMAGE_NUMBEROF_DIRECTORY_ENTRIES = @as(u32, 16); pub const IMAGE_SIZEOF_SHORT_NAME = @as(u32, 8); pub const IMAGE_SIZEOF_SECTION_HEADER = @as(u32, 40); pub const IMAGE_SIZEOF_SYMBOL = @as(u32, 18); pub const IMAGE_SYM_SECTION_MAX = @as(u32, 65279); pub const IMAGE_SYM_SECTION_MAX_EX = @as(u32, 2147483647); pub const IMAGE_SYM_TYPE_NULL = @as(u32, 0); pub const IMAGE_SYM_TYPE_VOID = @as(u32, 1); pub const IMAGE_SYM_TYPE_CHAR = @as(u32, 2); pub const IMAGE_SYM_TYPE_SHORT = @as(u32, 3); pub const IMAGE_SYM_TYPE_INT = @as(u32, 4); pub const IMAGE_SYM_TYPE_LONG = @as(u32, 5); pub const IMAGE_SYM_TYPE_FLOAT = @as(u32, 6); pub const IMAGE_SYM_TYPE_DOUBLE = @as(u32, 7); pub const IMAGE_SYM_TYPE_STRUCT = @as(u32, 8); pub const IMAGE_SYM_TYPE_UNION = @as(u32, 9); pub const IMAGE_SYM_TYPE_ENUM = @as(u32, 10); pub const IMAGE_SYM_TYPE_MOE = @as(u32, 11); pub const IMAGE_SYM_TYPE_BYTE = @as(u32, 12); pub const IMAGE_SYM_TYPE_WORD = @as(u32, 13); pub const IMAGE_SYM_TYPE_UINT = @as(u32, 14); pub const IMAGE_SYM_TYPE_DWORD = @as(u32, 15); pub const IMAGE_SYM_TYPE_PCODE = @as(u32, 32768); pub const IMAGE_SYM_DTYPE_NULL = @as(u32, 0); pub const IMAGE_SYM_DTYPE_POINTER = @as(u32, 1); pub const IMAGE_SYM_DTYPE_FUNCTION = @as(u32, 2); pub const IMAGE_SYM_DTYPE_ARRAY = @as(u32, 3); pub const IMAGE_SYM_CLASS_NULL = @as(u32, 0); pub const IMAGE_SYM_CLASS_AUTOMATIC = @as(u32, 1); pub const IMAGE_SYM_CLASS_EXTERNAL = @as(u32, 2); pub const IMAGE_SYM_CLASS_STATIC = @as(u32, 3); pub const IMAGE_SYM_CLASS_REGISTER = @as(u32, 4); pub const IMAGE_SYM_CLASS_EXTERNAL_DEF = @as(u32, 5); pub const IMAGE_SYM_CLASS_LABEL = @as(u32, 6); pub const IMAGE_SYM_CLASS_UNDEFINED_LABEL = @as(u32, 7); pub const IMAGE_SYM_CLASS_MEMBER_OF_STRUCT = @as(u32, 8); pub const IMAGE_SYM_CLASS_ARGUMENT = @as(u32, 9); pub const IMAGE_SYM_CLASS_STRUCT_TAG = @as(u32, 10); pub const IMAGE_SYM_CLASS_MEMBER_OF_UNION = @as(u32, 11); pub const IMAGE_SYM_CLASS_UNION_TAG = @as(u32, 12); pub const IMAGE_SYM_CLASS_TYPE_DEFINITION = @as(u32, 13); pub const IMAGE_SYM_CLASS_UNDEFINED_STATIC = @as(u32, 14); pub const IMAGE_SYM_CLASS_ENUM_TAG = @as(u32, 15); pub const IMAGE_SYM_CLASS_MEMBER_OF_ENUM = @as(u32, 16); pub const IMAGE_SYM_CLASS_REGISTER_PARAM = @as(u32, 17); pub const IMAGE_SYM_CLASS_BIT_FIELD = @as(u32, 18); pub const IMAGE_SYM_CLASS_FAR_EXTERNAL = @as(u32, 68); pub const IMAGE_SYM_CLASS_BLOCK = @as(u32, 100); pub const IMAGE_SYM_CLASS_FUNCTION = @as(u32, 101); pub const IMAGE_SYM_CLASS_END_OF_STRUCT = @as(u32, 102); pub const IMAGE_SYM_CLASS_FILE = @as(u32, 103); pub const IMAGE_SYM_CLASS_SECTION = @as(u32, 104); pub const IMAGE_SYM_CLASS_WEAK_EXTERNAL = @as(u32, 105); pub const IMAGE_SYM_CLASS_CLR_TOKEN = @as(u32, 107); pub const N_BTMASK = @as(u32, 15); pub const N_TMASK = @as(u32, 48); pub const N_TMASK1 = @as(u32, 192); pub const N_TMASK2 = @as(u32, 240); pub const N_BTSHFT = @as(u32, 4); pub const N_TSHIFT = @as(u32, 2); pub const IMAGE_COMDAT_SELECT_NODUPLICATES = @as(u32, 1); pub const IMAGE_COMDAT_SELECT_ANY = @as(u32, 2); pub const IMAGE_COMDAT_SELECT_SAME_SIZE = @as(u32, 3); pub const IMAGE_COMDAT_SELECT_EXACT_MATCH = @as(u32, 4); pub const IMAGE_COMDAT_SELECT_ASSOCIATIVE = @as(u32, 5); pub const IMAGE_COMDAT_SELECT_LARGEST = @as(u32, 6); pub const IMAGE_COMDAT_SELECT_NEWEST = @as(u32, 7); pub const IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY = @as(u32, 1); pub const IMAGE_WEAK_EXTERN_SEARCH_LIBRARY = @as(u32, 2); pub const IMAGE_WEAK_EXTERN_SEARCH_ALIAS = @as(u32, 3); pub const IMAGE_WEAK_EXTERN_ANTI_DEPENDENCY = @as(u32, 4); pub const IMAGE_REL_I386_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_I386_DIR16 = @as(u32, 1); pub const IMAGE_REL_I386_REL16 = @as(u32, 2); pub const IMAGE_REL_I386_DIR32 = @as(u32, 6); pub const IMAGE_REL_I386_DIR32NB = @as(u32, 7); pub const IMAGE_REL_I386_SEG12 = @as(u32, 9); pub const IMAGE_REL_I386_SECTION = @as(u32, 10); pub const IMAGE_REL_I386_SECREL = @as(u32, 11); pub const IMAGE_REL_I386_TOKEN = @as(u32, 12); pub const IMAGE_REL_I386_SECREL7 = @as(u32, 13); pub const IMAGE_REL_I386_REL32 = @as(u32, 20); pub const IMAGE_REL_MIPS_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_MIPS_REFHALF = @as(u32, 1); pub const IMAGE_REL_MIPS_REFWORD = @as(u32, 2); pub const IMAGE_REL_MIPS_JMPADDR = @as(u32, 3); pub const IMAGE_REL_MIPS_REFHI = @as(u32, 4); pub const IMAGE_REL_MIPS_REFLO = @as(u32, 5); pub const IMAGE_REL_MIPS_GPREL = @as(u32, 6); pub const IMAGE_REL_MIPS_LITERAL = @as(u32, 7); pub const IMAGE_REL_MIPS_SECTION = @as(u32, 10); pub const IMAGE_REL_MIPS_SECREL = @as(u32, 11); pub const IMAGE_REL_MIPS_SECRELLO = @as(u32, 12); pub const IMAGE_REL_MIPS_SECRELHI = @as(u32, 13); pub const IMAGE_REL_MIPS_TOKEN = @as(u32, 14); pub const IMAGE_REL_MIPS_JMPADDR16 = @as(u32, 16); pub const IMAGE_REL_MIPS_REFWORDNB = @as(u32, 34); pub const IMAGE_REL_MIPS_PAIR = @as(u32, 37); pub const IMAGE_REL_ALPHA_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_ALPHA_REFLONG = @as(u32, 1); pub const IMAGE_REL_ALPHA_REFQUAD = @as(u32, 2); pub const IMAGE_REL_ALPHA_GPREL32 = @as(u32, 3); pub const IMAGE_REL_ALPHA_LITERAL = @as(u32, 4); pub const IMAGE_REL_ALPHA_LITUSE = @as(u32, 5); pub const IMAGE_REL_ALPHA_GPDISP = @as(u32, 6); pub const IMAGE_REL_ALPHA_BRADDR = @as(u32, 7); pub const IMAGE_REL_ALPHA_HINT = @as(u32, 8); pub const IMAGE_REL_ALPHA_INLINE_REFLONG = @as(u32, 9); pub const IMAGE_REL_ALPHA_REFHI = @as(u32, 10); pub const IMAGE_REL_ALPHA_REFLO = @as(u32, 11); pub const IMAGE_REL_ALPHA_PAIR = @as(u32, 12); pub const IMAGE_REL_ALPHA_MATCH = @as(u32, 13); pub const IMAGE_REL_ALPHA_SECTION = @as(u32, 14); pub const IMAGE_REL_ALPHA_SECREL = @as(u32, 15); pub const IMAGE_REL_ALPHA_REFLONGNB = @as(u32, 16); pub const IMAGE_REL_ALPHA_SECRELLO = @as(u32, 17); pub const IMAGE_REL_ALPHA_SECRELHI = @as(u32, 18); pub const IMAGE_REL_ALPHA_REFQ3 = @as(u32, 19); pub const IMAGE_REL_ALPHA_REFQ2 = @as(u32, 20); pub const IMAGE_REL_ALPHA_REFQ1 = @as(u32, 21); pub const IMAGE_REL_ALPHA_GPRELLO = @as(u32, 22); pub const IMAGE_REL_ALPHA_GPRELHI = @as(u32, 23); pub const IMAGE_REL_PPC_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_PPC_ADDR64 = @as(u32, 1); pub const IMAGE_REL_PPC_ADDR32 = @as(u32, 2); pub const IMAGE_REL_PPC_ADDR24 = @as(u32, 3); pub const IMAGE_REL_PPC_ADDR16 = @as(u32, 4); pub const IMAGE_REL_PPC_ADDR14 = @as(u32, 5); pub const IMAGE_REL_PPC_REL24 = @as(u32, 6); pub const IMAGE_REL_PPC_REL14 = @as(u32, 7); pub const IMAGE_REL_PPC_TOCREL16 = @as(u32, 8); pub const IMAGE_REL_PPC_TOCREL14 = @as(u32, 9); pub const IMAGE_REL_PPC_ADDR32NB = @as(u32, 10); pub const IMAGE_REL_PPC_SECREL = @as(u32, 11); pub const IMAGE_REL_PPC_SECTION = @as(u32, 12); pub const IMAGE_REL_PPC_IFGLUE = @as(u32, 13); pub const IMAGE_REL_PPC_IMGLUE = @as(u32, 14); pub const IMAGE_REL_PPC_SECREL16 = @as(u32, 15); pub const IMAGE_REL_PPC_REFHI = @as(u32, 16); pub const IMAGE_REL_PPC_REFLO = @as(u32, 17); pub const IMAGE_REL_PPC_PAIR = @as(u32, 18); pub const IMAGE_REL_PPC_SECRELLO = @as(u32, 19); pub const IMAGE_REL_PPC_SECRELHI = @as(u32, 20); pub const IMAGE_REL_PPC_GPREL = @as(u32, 21); pub const IMAGE_REL_PPC_TOKEN = @as(u32, 22); pub const IMAGE_REL_PPC_TYPEMASK = @as(u32, 255); pub const IMAGE_REL_PPC_NEG = @as(u32, 256); pub const IMAGE_REL_PPC_BRTAKEN = @as(u32, 512); pub const IMAGE_REL_PPC_BRNTAKEN = @as(u32, 1024); pub const IMAGE_REL_PPC_TOCDEFN = @as(u32, 2048); pub const IMAGE_REL_SH3_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_SH3_DIRECT16 = @as(u32, 1); pub const IMAGE_REL_SH3_DIRECT32 = @as(u32, 2); pub const IMAGE_REL_SH3_DIRECT8 = @as(u32, 3); pub const IMAGE_REL_SH3_DIRECT8_WORD = @as(u32, 4); pub const IMAGE_REL_SH3_DIRECT8_LONG = @as(u32, 5); pub const IMAGE_REL_SH3_DIRECT4 = @as(u32, 6); pub const IMAGE_REL_SH3_DIRECT4_WORD = @as(u32, 7); pub const IMAGE_REL_SH3_DIRECT4_LONG = @as(u32, 8); pub const IMAGE_REL_SH3_PCREL8_WORD = @as(u32, 9); pub const IMAGE_REL_SH3_PCREL8_LONG = @as(u32, 10); pub const IMAGE_REL_SH3_PCREL12_WORD = @as(u32, 11); pub const IMAGE_REL_SH3_STARTOF_SECTION = @as(u32, 12); pub const IMAGE_REL_SH3_SIZEOF_SECTION = @as(u32, 13); pub const IMAGE_REL_SH3_SECTION = @as(u32, 14); pub const IMAGE_REL_SH3_SECREL = @as(u32, 15); pub const IMAGE_REL_SH3_DIRECT32_NB = @as(u32, 16); pub const IMAGE_REL_SH3_GPREL4_LONG = @as(u32, 17); pub const IMAGE_REL_SH3_TOKEN = @as(u32, 18); pub const IMAGE_REL_SHM_PCRELPT = @as(u32, 19); pub const IMAGE_REL_SHM_REFLO = @as(u32, 20); pub const IMAGE_REL_SHM_REFHALF = @as(u32, 21); pub const IMAGE_REL_SHM_RELLO = @as(u32, 22); pub const IMAGE_REL_SHM_RELHALF = @as(u32, 23); pub const IMAGE_REL_SHM_PAIR = @as(u32, 24); pub const IMAGE_REL_SH_NOMODE = @as(u32, 32768); pub const IMAGE_REL_ARM_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_ARM_ADDR32 = @as(u32, 1); pub const IMAGE_REL_ARM_ADDR32NB = @as(u32, 2); pub const IMAGE_REL_ARM_BRANCH24 = @as(u32, 3); pub const IMAGE_REL_ARM_BRANCH11 = @as(u32, 4); pub const IMAGE_REL_ARM_TOKEN = @as(u32, 5); pub const IMAGE_REL_ARM_GPREL12 = @as(u32, 6); pub const IMAGE_REL_ARM_GPREL7 = @as(u32, 7); pub const IMAGE_REL_ARM_BLX24 = @as(u32, 8); pub const IMAGE_REL_ARM_BLX11 = @as(u32, 9); pub const IMAGE_REL_ARM_SECTION = @as(u32, 14); pub const IMAGE_REL_ARM_SECREL = @as(u32, 15); pub const IMAGE_REL_ARM_MOV32A = @as(u32, 16); pub const IMAGE_REL_ARM_MOV32 = @as(u32, 16); pub const IMAGE_REL_ARM_MOV32T = @as(u32, 17); pub const IMAGE_REL_THUMB_MOV32 = @as(u32, 17); pub const IMAGE_REL_ARM_BRANCH20T = @as(u32, 18); pub const IMAGE_REL_THUMB_BRANCH20 = @as(u32, 18); pub const IMAGE_REL_ARM_BRANCH24T = @as(u32, 20); pub const IMAGE_REL_THUMB_BRANCH24 = @as(u32, 20); pub const IMAGE_REL_ARM_BLX23T = @as(u32, 21); pub const IMAGE_REL_THUMB_BLX23 = @as(u32, 21); pub const IMAGE_REL_AM_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_AM_ADDR32 = @as(u32, 1); pub const IMAGE_REL_AM_ADDR32NB = @as(u32, 2); pub const IMAGE_REL_AM_CALL32 = @as(u32, 3); pub const IMAGE_REL_AM_FUNCINFO = @as(u32, 4); pub const IMAGE_REL_AM_REL32_1 = @as(u32, 5); pub const IMAGE_REL_AM_REL32_2 = @as(u32, 6); pub const IMAGE_REL_AM_SECREL = @as(u32, 7); pub const IMAGE_REL_AM_SECTION = @as(u32, 8); pub const IMAGE_REL_AM_TOKEN = @as(u32, 9); pub const IMAGE_REL_ARM64_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_ARM64_ADDR32 = @as(u32, 1); pub const IMAGE_REL_ARM64_ADDR32NB = @as(u32, 2); pub const IMAGE_REL_ARM64_BRANCH26 = @as(u32, 3); pub const IMAGE_REL_ARM64_PAGEBASE_REL21 = @as(u32, 4); pub const IMAGE_REL_ARM64_REL21 = @as(u32, 5); pub const IMAGE_REL_ARM64_PAGEOFFSET_12A = @as(u32, 6); pub const IMAGE_REL_ARM64_PAGEOFFSET_12L = @as(u32, 7); pub const IMAGE_REL_ARM64_SECREL = @as(u32, 8); pub const IMAGE_REL_ARM64_SECREL_LOW12A = @as(u32, 9); pub const IMAGE_REL_ARM64_SECREL_HIGH12A = @as(u32, 10); pub const IMAGE_REL_ARM64_SECREL_LOW12L = @as(u32, 11); pub const IMAGE_REL_ARM64_TOKEN = @as(u32, 12); pub const IMAGE_REL_ARM64_SECTION = @as(u32, 13); pub const IMAGE_REL_ARM64_ADDR64 = @as(u32, 14); pub const IMAGE_REL_ARM64_BRANCH19 = @as(u32, 15); pub const IMAGE_REL_AMD64_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_AMD64_ADDR64 = @as(u32, 1); pub const IMAGE_REL_AMD64_ADDR32 = @as(u32, 2); pub const IMAGE_REL_AMD64_ADDR32NB = @as(u32, 3); pub const IMAGE_REL_AMD64_REL32 = @as(u32, 4); pub const IMAGE_REL_AMD64_REL32_1 = @as(u32, 5); pub const IMAGE_REL_AMD64_REL32_2 = @as(u32, 6); pub const IMAGE_REL_AMD64_REL32_3 = @as(u32, 7); pub const IMAGE_REL_AMD64_REL32_4 = @as(u32, 8); pub const IMAGE_REL_AMD64_REL32_5 = @as(u32, 9); pub const IMAGE_REL_AMD64_SECTION = @as(u32, 10); pub const IMAGE_REL_AMD64_SECREL = @as(u32, 11); pub const IMAGE_REL_AMD64_SECREL7 = @as(u32, 12); pub const IMAGE_REL_AMD64_TOKEN = @as(u32, 13); pub const IMAGE_REL_AMD64_SREL32 = @as(u32, 14); pub const IMAGE_REL_AMD64_PAIR = @as(u32, 15); pub const IMAGE_REL_AMD64_SSPAN32 = @as(u32, 16); pub const IMAGE_REL_AMD64_EHANDLER = @as(u32, 17); pub const IMAGE_REL_AMD64_IMPORT_BR = @as(u32, 18); pub const IMAGE_REL_AMD64_IMPORT_CALL = @as(u32, 19); pub const IMAGE_REL_AMD64_CFG_BR = @as(u32, 20); pub const IMAGE_REL_AMD64_CFG_BR_REX = @as(u32, 21); pub const IMAGE_REL_AMD64_CFG_CALL = @as(u32, 22); pub const IMAGE_REL_AMD64_INDIR_BR = @as(u32, 23); pub const IMAGE_REL_AMD64_INDIR_BR_REX = @as(u32, 24); pub const IMAGE_REL_AMD64_INDIR_CALL = @as(u32, 25); pub const IMAGE_REL_AMD64_INDIR_BR_SWITCHTABLE_FIRST = @as(u32, 32); pub const IMAGE_REL_AMD64_INDIR_BR_SWITCHTABLE_LAST = @as(u32, 47); pub const IMAGE_REL_IA64_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_IA64_IMM14 = @as(u32, 1); pub const IMAGE_REL_IA64_IMM22 = @as(u32, 2); pub const IMAGE_REL_IA64_IMM64 = @as(u32, 3); pub const IMAGE_REL_IA64_DIR32 = @as(u32, 4); pub const IMAGE_REL_IA64_DIR64 = @as(u32, 5); pub const IMAGE_REL_IA64_PCREL21B = @as(u32, 6); pub const IMAGE_REL_IA64_PCREL21M = @as(u32, 7); pub const IMAGE_REL_IA64_PCREL21F = @as(u32, 8); pub const IMAGE_REL_IA64_GPREL22 = @as(u32, 9); pub const IMAGE_REL_IA64_LTOFF22 = @as(u32, 10); pub const IMAGE_REL_IA64_SECTION = @as(u32, 11); pub const IMAGE_REL_IA64_SECREL22 = @as(u32, 12); pub const IMAGE_REL_IA64_SECREL64I = @as(u32, 13); pub const IMAGE_REL_IA64_SECREL32 = @as(u32, 14); pub const IMAGE_REL_IA64_DIR32NB = @as(u32, 16); pub const IMAGE_REL_IA64_SREL14 = @as(u32, 17); pub const IMAGE_REL_IA64_SREL22 = @as(u32, 18); pub const IMAGE_REL_IA64_SREL32 = @as(u32, 19); pub const IMAGE_REL_IA64_UREL32 = @as(u32, 20); pub const IMAGE_REL_IA64_PCREL60X = @as(u32, 21); pub const IMAGE_REL_IA64_PCREL60B = @as(u32, 22); pub const IMAGE_REL_IA64_PCREL60F = @as(u32, 23); pub const IMAGE_REL_IA64_PCREL60I = @as(u32, 24); pub const IMAGE_REL_IA64_PCREL60M = @as(u32, 25); pub const IMAGE_REL_IA64_IMMGPREL64 = @as(u32, 26); pub const IMAGE_REL_IA64_TOKEN = @as(u32, 27); pub const IMAGE_REL_IA64_GPREL32 = @as(u32, 28); pub const IMAGE_REL_IA64_ADDEND = @as(u32, 31); pub const IMAGE_REL_CEF_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_CEF_ADDR32 = @as(u32, 1); pub const IMAGE_REL_CEF_ADDR64 = @as(u32, 2); pub const IMAGE_REL_CEF_ADDR32NB = @as(u32, 3); pub const IMAGE_REL_CEF_SECTION = @as(u32, 4); pub const IMAGE_REL_CEF_SECREL = @as(u32, 5); pub const IMAGE_REL_CEF_TOKEN = @as(u32, 6); pub const IMAGE_REL_CEE_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_CEE_ADDR32 = @as(u32, 1); pub const IMAGE_REL_CEE_ADDR64 = @as(u32, 2); pub const IMAGE_REL_CEE_ADDR32NB = @as(u32, 3); pub const IMAGE_REL_CEE_SECTION = @as(u32, 4); pub const IMAGE_REL_CEE_SECREL = @as(u32, 5); pub const IMAGE_REL_CEE_TOKEN = @as(u32, 6); pub const IMAGE_REL_M32R_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_M32R_ADDR32 = @as(u32, 1); pub const IMAGE_REL_M32R_ADDR32NB = @as(u32, 2); pub const IMAGE_REL_M32R_ADDR24 = @as(u32, 3); pub const IMAGE_REL_M32R_GPREL16 = @as(u32, 4); pub const IMAGE_REL_M32R_PCREL24 = @as(u32, 5); pub const IMAGE_REL_M32R_PCREL16 = @as(u32, 6); pub const IMAGE_REL_M32R_PCREL8 = @as(u32, 7); pub const IMAGE_REL_M32R_REFHALF = @as(u32, 8); pub const IMAGE_REL_M32R_REFHI = @as(u32, 9); pub const IMAGE_REL_M32R_REFLO = @as(u32, 10); pub const IMAGE_REL_M32R_PAIR = @as(u32, 11); pub const IMAGE_REL_M32R_SECTION = @as(u32, 12); pub const IMAGE_REL_M32R_SECREL32 = @as(u32, 13); pub const IMAGE_REL_M32R_TOKEN = @as(u32, 14); pub const IMAGE_REL_EBC_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_EBC_ADDR32NB = @as(u32, 1); pub const IMAGE_REL_EBC_REL32 = @as(u32, 2); pub const IMAGE_REL_EBC_SECTION = @as(u32, 3); pub const IMAGE_REL_EBC_SECREL = @as(u32, 4); pub const EMARCH_ENC_I17_IMM7B_INST_WORD_X = @as(u32, 3); pub const EMARCH_ENC_I17_IMM7B_SIZE_X = @as(u32, 7); pub const EMARCH_ENC_I17_IMM7B_INST_WORD_POS_X = @as(u32, 4); pub const EMARCH_ENC_I17_IMM7B_VAL_POS_X = @as(u32, 0); pub const EMARCH_ENC_I17_IMM9D_INST_WORD_X = @as(u32, 3); pub const EMARCH_ENC_I17_IMM9D_SIZE_X = @as(u32, 9); pub const EMARCH_ENC_I17_IMM9D_INST_WORD_POS_X = @as(u32, 18); pub const EMARCH_ENC_I17_IMM9D_VAL_POS_X = @as(u32, 7); pub const EMARCH_ENC_I17_IMM5C_INST_WORD_X = @as(u32, 3); pub const EMARCH_ENC_I17_IMM5C_SIZE_X = @as(u32, 5); pub const EMARCH_ENC_I17_IMM5C_INST_WORD_POS_X = @as(u32, 13); pub const EMARCH_ENC_I17_IMM5C_VAL_POS_X = @as(u32, 16); pub const EMARCH_ENC_I17_IC_INST_WORD_X = @as(u32, 3); pub const EMARCH_ENC_I17_IC_SIZE_X = @as(u32, 1); pub const EMARCH_ENC_I17_IC_INST_WORD_POS_X = @as(u32, 12); pub const EMARCH_ENC_I17_IC_VAL_POS_X = @as(u32, 21); pub const EMARCH_ENC_I17_IMM41a_INST_WORD_X = @as(u32, 1); pub const EMARCH_ENC_I17_IMM41a_SIZE_X = @as(u32, 10); pub const EMARCH_ENC_I17_IMM41a_INST_WORD_POS_X = @as(u32, 14); pub const EMARCH_ENC_I17_IMM41a_VAL_POS_X = @as(u32, 22); pub const EMARCH_ENC_I17_IMM41b_INST_WORD_X = @as(u32, 1); pub const EMARCH_ENC_I17_IMM41b_SIZE_X = @as(u32, 8); pub const EMARCH_ENC_I17_IMM41b_INST_WORD_POS_X = @as(u32, 24); pub const EMARCH_ENC_I17_IMM41b_VAL_POS_X = @as(u32, 32); pub const EMARCH_ENC_I17_IMM41c_INST_WORD_X = @as(u32, 2); pub const EMARCH_ENC_I17_IMM41c_SIZE_X = @as(u32, 23); pub const EMARCH_ENC_I17_IMM41c_INST_WORD_POS_X = @as(u32, 0); pub const EMARCH_ENC_I17_IMM41c_VAL_POS_X = @as(u32, 40); pub const EMARCH_ENC_I17_SIGN_INST_WORD_X = @as(u32, 3); pub const EMARCH_ENC_I17_SIGN_SIZE_X = @as(u32, 1); pub const EMARCH_ENC_I17_SIGN_INST_WORD_POS_X = @as(u32, 27); pub const EMARCH_ENC_I17_SIGN_VAL_POS_X = @as(u32, 63); pub const X3_OPCODE_INST_WORD_X = @as(u32, 3); pub const X3_OPCODE_SIZE_X = @as(u32, 4); pub const X3_OPCODE_INST_WORD_POS_X = @as(u32, 28); pub const X3_OPCODE_SIGN_VAL_POS_X = @as(u32, 0); pub const X3_I_INST_WORD_X = @as(u32, 3); pub const X3_I_SIZE_X = @as(u32, 1); pub const X3_I_INST_WORD_POS_X = @as(u32, 27); pub const X3_I_SIGN_VAL_POS_X = @as(u32, 59); pub const X3_D_WH_INST_WORD_X = @as(u32, 3); pub const X3_D_WH_SIZE_X = @as(u32, 3); pub const X3_D_WH_INST_WORD_POS_X = @as(u32, 24); pub const X3_D_WH_SIGN_VAL_POS_X = @as(u32, 0); pub const X3_IMM20_INST_WORD_X = @as(u32, 3); pub const X3_IMM20_SIZE_X = @as(u32, 20); pub const X3_IMM20_INST_WORD_POS_X = @as(u32, 4); pub const X3_IMM20_SIGN_VAL_POS_X = @as(u32, 0); pub const X3_IMM39_1_INST_WORD_X = @as(u32, 2); pub const X3_IMM39_1_SIZE_X = @as(u32, 23); pub const X3_IMM39_1_INST_WORD_POS_X = @as(u32, 0); pub const X3_IMM39_1_SIGN_VAL_POS_X = @as(u32, 36); pub const X3_IMM39_2_INST_WORD_X = @as(u32, 1); pub const X3_IMM39_2_SIZE_X = @as(u32, 16); pub const X3_IMM39_2_INST_WORD_POS_X = @as(u32, 16); pub const X3_IMM39_2_SIGN_VAL_POS_X = @as(u32, 20); pub const X3_P_INST_WORD_X = @as(u32, 3); pub const X3_P_SIZE_X = @as(u32, 4); pub const X3_P_INST_WORD_POS_X = @as(u32, 0); pub const X3_P_SIGN_VAL_POS_X = @as(u32, 0); pub const X3_TMPLT_INST_WORD_X = @as(u32, 0); pub const X3_TMPLT_SIZE_X = @as(u32, 4); pub const X3_TMPLT_INST_WORD_POS_X = @as(u32, 0); pub const X3_TMPLT_SIGN_VAL_POS_X = @as(u32, 0); pub const X3_BTYPE_QP_INST_WORD_X = @as(u32, 2); pub const X3_BTYPE_QP_SIZE_X = @as(u32, 9); pub const X3_BTYPE_QP_INST_WORD_POS_X = @as(u32, 23); pub const X3_BTYPE_QP_INST_VAL_POS_X = @as(u32, 0); pub const X3_EMPTY_INST_WORD_X = @as(u32, 1); pub const X3_EMPTY_SIZE_X = @as(u32, 2); pub const X3_EMPTY_INST_WORD_POS_X = @as(u32, 14); pub const X3_EMPTY_INST_VAL_POS_X = @as(u32, 0); pub const IMAGE_REL_BASED_ABSOLUTE = @as(u32, 0); pub const IMAGE_REL_BASED_HIGH = @as(u32, 1); pub const IMAGE_REL_BASED_LOW = @as(u32, 2); pub const IMAGE_REL_BASED_HIGHLOW = @as(u32, 3); pub const IMAGE_REL_BASED_HIGHADJ = @as(u32, 4); pub const IMAGE_REL_BASED_MACHINE_SPECIFIC_5 = @as(u32, 5); pub const IMAGE_REL_BASED_RESERVED = @as(u32, 6); pub const IMAGE_REL_BASED_MACHINE_SPECIFIC_7 = @as(u32, 7); pub const IMAGE_REL_BASED_MACHINE_SPECIFIC_8 = @as(u32, 8); pub const IMAGE_REL_BASED_MACHINE_SPECIFIC_9 = @as(u32, 9); pub const IMAGE_REL_BASED_DIR64 = @as(u32, 10); pub const IMAGE_REL_BASED_IA64_IMM64 = @as(u32, 9); pub const IMAGE_REL_BASED_MIPS_JMPADDR = @as(u32, 5); pub const IMAGE_REL_BASED_MIPS_JMPADDR16 = @as(u32, 9); pub const IMAGE_REL_BASED_ARM_MOV32 = @as(u32, 5); pub const IMAGE_REL_BASED_THUMB_MOV32 = @as(u32, 7); pub const IMAGE_ARCHIVE_START_SIZE = @as(u32, 8); pub const IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR = @as(u32, 60); pub const IMAGE_ORDINAL_FLAG64 = @as(u64, 9223372036854775808); pub const IMAGE_ORDINAL_FLAG32 = @as(u32, 2147483648); pub const IMAGE_ORDINAL_FLAG = @as(u64, 9223372036854775808); pub const IMAGE_RESOURCE_NAME_IS_STRING = @as(u32, 2147483648); pub const IMAGE_RESOURCE_DATA_IS_DIRECTORY = @as(u32, 2147483648); pub const IMAGE_DYNAMIC_RELOCATION_GUARD_RF_PROLOGUE = @as(u32, 1); pub const IMAGE_DYNAMIC_RELOCATION_GUARD_RF_EPILOGUE = @as(u32, 2); pub const IMAGE_DYNAMIC_RELOCATION_GUARD_IMPORT_CONTROL_TRANSFER = @as(u32, 3); pub const IMAGE_DYNAMIC_RELOCATION_GUARD_INDIR_CONTROL_TRANSFER = @as(u32, 4); pub const IMAGE_DYNAMIC_RELOCATION_GUARD_SWITCHTABLE_BRANCH = @as(u32, 5); pub const IMAGE_HOT_PATCH_BASE_OBLIGATORY = @as(u32, 1); pub const IMAGE_HOT_PATCH_BASE_CAN_ROLL_BACK = @as(u32, 2); pub const IMAGE_HOT_PATCH_CHUNK_INVERSE = @as(u32, 2147483648); pub const IMAGE_HOT_PATCH_CHUNK_OBLIGATORY = @as(u32, 1073741824); pub const IMAGE_HOT_PATCH_CHUNK_RESERVED = @as(u32, 1072705536); pub const IMAGE_HOT_PATCH_CHUNK_TYPE = @as(u32, 1032192); pub const IMAGE_HOT_PATCH_CHUNK_SOURCE_RVA = @as(u32, 32768); pub const IMAGE_HOT_PATCH_CHUNK_TARGET_RVA = @as(u32, 16384); pub const IMAGE_HOT_PATCH_CHUNK_SIZE = @as(u32, 4095); pub const IMAGE_HOT_PATCH_NONE = @as(u32, 0); pub const IMAGE_HOT_PATCH_FUNCTION = @as(u32, 114688); pub const IMAGE_HOT_PATCH_ABSOLUTE = @as(u32, 180224); pub const IMAGE_HOT_PATCH_REL32 = @as(u32, 245760); pub const IMAGE_HOT_PATCH_CALL_TARGET = @as(u32, 278528); pub const IMAGE_HOT_PATCH_INDIRECT = @as(u32, 376832); pub const IMAGE_HOT_PATCH_NO_CALL_TARGET = @as(u32, 409600); pub const IMAGE_HOT_PATCH_DYNAMIC_VALUE = @as(u32, 491520); pub const IMAGE_GUARD_CF_INSTRUMENTED = @as(u32, 256); pub const IMAGE_GUARD_CFW_INSTRUMENTED = @as(u32, 512); pub const IMAGE_GUARD_CF_FUNCTION_TABLE_PRESENT = @as(u32, 1024); pub const IMAGE_GUARD_SECURITY_COOKIE_UNUSED = @as(u32, 2048); pub const IMAGE_GUARD_PROTECT_DELAYLOAD_IAT = @as(u32, 4096); pub const IMAGE_GUARD_DELAYLOAD_IAT_IN_ITS_OWN_SECTION = @as(u32, 8192); pub const IMAGE_GUARD_CF_EXPORT_SUPPRESSION_INFO_PRESENT = @as(u32, 16384); pub const IMAGE_GUARD_CF_ENABLE_EXPORT_SUPPRESSION = @as(u32, 32768); pub const IMAGE_GUARD_CF_LONGJUMP_TABLE_PRESENT = @as(u32, 65536); pub const IMAGE_GUARD_RF_INSTRUMENTED = @as(u32, 131072); pub const IMAGE_GUARD_RF_ENABLE = @as(u32, 262144); pub const IMAGE_GUARD_RF_STRICT = @as(u32, 524288); pub const IMAGE_GUARD_RETPOLINE_PRESENT = @as(u32, 1048576); pub const IMAGE_GUARD_EH_CONTINUATION_TABLE_PRESENT = @as(u32, 4194304); pub const IMAGE_GUARD_XFG_ENABLED = @as(u32, 8388608); pub const IMAGE_GUARD_CF_FUNCTION_TABLE_SIZE_MASK = @as(u32, 4026531840); pub const IMAGE_GUARD_CF_FUNCTION_TABLE_SIZE_SHIFT = @as(u32, 28); pub const IMAGE_GUARD_FLAG_FID_SUPPRESSED = @as(u32, 1); pub const IMAGE_GUARD_FLAG_EXPORT_SUPPRESSED = @as(u32, 2); pub const IMAGE_GUARD_FLAG_FID_LANGEXCPTHANDLER = @as(u32, 4); pub const IMAGE_GUARD_FLAG_FID_XFG = @as(u32, 8); pub const IMAGE_ENCLAVE_LONG_ID_LENGTH = @as(u32, 32); pub const IMAGE_ENCLAVE_SHORT_ID_LENGTH = @as(u32, 16); pub const IMAGE_ENCLAVE_POLICY_DEBUGGABLE = @as(u32, 1); pub const IMAGE_ENCLAVE_FLAG_PRIMARY_IMAGE = @as(u32, 1); pub const IMAGE_ENCLAVE_IMPORT_MATCH_NONE = @as(u32, 0); pub const IMAGE_ENCLAVE_IMPORT_MATCH_UNIQUE_ID = @as(u32, 1); pub const IMAGE_ENCLAVE_IMPORT_MATCH_AUTHOR_ID = @as(u32, 2); pub const IMAGE_ENCLAVE_IMPORT_MATCH_FAMILY_ID = @as(u32, 3); pub const IMAGE_ENCLAVE_IMPORT_MATCH_IMAGE_ID = @as(u32, 4); pub const IMAGE_DEBUG_TYPE_OMAP_TO_SRC = @as(u32, 7); pub const IMAGE_DEBUG_TYPE_OMAP_FROM_SRC = @as(u32, 8); pub const IMAGE_DEBUG_TYPE_RESERVED10 = @as(u32, 10); pub const IMAGE_DEBUG_TYPE_CLSID = @as(u32, 11); pub const IMAGE_DEBUG_TYPE_VC_FEATURE = @as(u32, 12); pub const IMAGE_DEBUG_TYPE_POGO = @as(u32, 13); pub const IMAGE_DEBUG_TYPE_ILTCG = @as(u32, 14); pub const IMAGE_DEBUG_TYPE_MPX = @as(u32, 15); pub const IMAGE_DEBUG_TYPE_REPRO = @as(u32, 16); pub const IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS = @as(u32, 20); pub const FRAME_FPO = @as(u32, 0); pub const FRAME_TRAP = @as(u32, 1); pub const FRAME_TSS = @as(u32, 2); pub const FRAME_NONFPO = @as(u32, 3); pub const SIZEOF_RFPO_DATA = @as(u32, 16); pub const IMAGE_DEBUG_MISC_EXENAME = @as(u32, 1); pub const IMAGE_SEPARATE_DEBUG_SIGNATURE = @as(u32, 18756); pub const NON_PAGED_DEBUG_SIGNATURE = @as(u32, 18766); pub const IMAGE_SEPARATE_DEBUG_FLAGS_MASK = @as(u32, 32768); pub const IMAGE_SEPARATE_DEBUG_MISMATCH = @as(u32, 32768); pub const IMPORT_OBJECT_HDR_SIG2 = @as(u32, 65535); pub const UNWIND_HISTORY_TABLE_SIZE = @as(u32, 12); pub const RTL_RUN_ONCE_CHECK_ONLY = @as(u32, 1); pub const RTL_RUN_ONCE_ASYNC = @as(u32, 2); pub const RTL_RUN_ONCE_INIT_FAILED = @as(u32, 4); pub const RTL_RUN_ONCE_CTX_RESERVED_BITS = @as(u32, 2); pub const FAST_FAIL_LEGACY_GS_VIOLATION = @as(u32, 0); pub const FAST_FAIL_VTGUARD_CHECK_FAILURE = @as(u32, 1); pub const FAST_FAIL_STACK_COOKIE_CHECK_FAILURE = @as(u32, 2); pub const FAST_FAIL_CORRUPT_LIST_ENTRY = @as(u32, 3); pub const FAST_FAIL_INCORRECT_STACK = @as(u32, 4); pub const FAST_FAIL_INVALID_ARG = @as(u32, 5); pub const FAST_FAIL_GS_COOKIE_INIT = @as(u32, 6); pub const FAST_FAIL_FATAL_APP_EXIT = @as(u32, 7); pub const FAST_FAIL_RANGE_CHECK_FAILURE = @as(u32, 8); pub const FAST_FAIL_UNSAFE_REGISTRY_ACCESS = @as(u32, 9); pub const FAST_FAIL_GUARD_ICALL_CHECK_FAILURE = @as(u32, 10); pub const FAST_FAIL_GUARD_WRITE_CHECK_FAILURE = @as(u32, 11); pub const FAST_FAIL_INVALID_FIBER_SWITCH = @as(u32, 12); pub const FAST_FAIL_INVALID_SET_OF_CONTEXT = @as(u32, 13); pub const FAST_FAIL_INVALID_REFERENCE_COUNT = @as(u32, 14); pub const FAST_FAIL_INVALID_JUMP_BUFFER = @as(u32, 18); pub const FAST_FAIL_MRDATA_MODIFIED = @as(u32, 19); pub const FAST_FAIL_CERTIFICATION_FAILURE = @as(u32, 20); pub const FAST_FAIL_INVALID_EXCEPTION_CHAIN = @as(u32, 21); pub const FAST_FAIL_CRYPTO_LIBRARY = @as(u32, 22); pub const FAST_FAIL_INVALID_CALL_IN_DLL_CALLOUT = @as(u32, 23); pub const FAST_FAIL_INVALID_IMAGE_BASE = @as(u32, 24); pub const FAST_FAIL_DLOAD_PROTECTION_FAILURE = @as(u32, 25); pub const FAST_FAIL_UNSAFE_EXTENSION_CALL = @as(u32, 26); pub const FAST_FAIL_DEPRECATED_SERVICE_INVOKED = @as(u32, 27); pub const FAST_FAIL_INVALID_BUFFER_ACCESS = @as(u32, 28); pub const FAST_FAIL_INVALID_BALANCED_TREE = @as(u32, 29); pub const FAST_FAIL_INVALID_NEXT_THREAD = @as(u32, 30); pub const FAST_FAIL_GUARD_ICALL_CHECK_SUPPRESSED = @as(u32, 31); pub const FAST_FAIL_APCS_DISABLED = @as(u32, 32); pub const FAST_FAIL_INVALID_IDLE_STATE = @as(u32, 33); pub const FAST_FAIL_MRDATA_PROTECTION_FAILURE = @as(u32, 34); pub const FAST_FAIL_UNEXPECTED_HEAP_EXCEPTION = @as(u32, 35); pub const FAST_FAIL_INVALID_LOCK_STATE = @as(u32, 36); pub const FAST_FAIL_GUARD_JUMPTABLE = @as(u32, 37); pub const FAST_FAIL_INVALID_LONGJUMP_TARGET = @as(u32, 38); pub const FAST_FAIL_INVALID_DISPATCH_CONTEXT = @as(u32, 39); pub const FAST_FAIL_INVALID_THREAD = @as(u32, 40); pub const FAST_FAIL_INVALID_SYSCALL_NUMBER = @as(u32, 41); pub const FAST_FAIL_INVALID_FILE_OPERATION = @as(u32, 42); pub const FAST_FAIL_LPAC_ACCESS_DENIED = @as(u32, 43); pub const FAST_FAIL_GUARD_SS_FAILURE = @as(u32, 44); pub const FAST_FAIL_LOADER_CONTINUITY_FAILURE = @as(u32, 45); pub const FAST_FAIL_GUARD_EXPORT_SUPPRESSION_FAILURE = @as(u32, 46); pub const FAST_FAIL_INVALID_CONTROL_STACK = @as(u32, 47); pub const FAST_FAIL_SET_CONTEXT_DENIED = @as(u32, 48); pub const FAST_FAIL_INVALID_IAT = @as(u32, 49); pub const FAST_FAIL_HEAP_METADATA_CORRUPTION = @as(u32, 50); pub const FAST_FAIL_PAYLOAD_RESTRICTION_VIOLATION = @as(u32, 51); pub const FAST_FAIL_LOW_LABEL_ACCESS_DENIED = @as(u32, 52); pub const FAST_FAIL_ENCLAVE_CALL_FAILURE = @as(u32, 53); pub const FAST_FAIL_UNHANDLED_LSS_EXCEPTON = @as(u32, 54); pub const FAST_FAIL_ADMINLESS_ACCESS_DENIED = @as(u32, 55); pub const FAST_FAIL_UNEXPECTED_CALL = @as(u32, 56); pub const FAST_FAIL_CONTROL_INVALID_RETURN_ADDRESS = @as(u32, 57); pub const FAST_FAIL_UNEXPECTED_HOST_BEHAVIOR = @as(u32, 58); pub const FAST_FAIL_FLAGS_CORRUPTION = @as(u32, 59); pub const FAST_FAIL_VEH_CORRUPTION = @as(u32, 60); pub const FAST_FAIL_ETW_CORRUPTION = @as(u32, 61); pub const FAST_FAIL_RIO_ABORT = @as(u32, 62); pub const FAST_FAIL_INVALID_PFN = @as(u32, 63); pub const FAST_FAIL_GUARD_ICALL_CHECK_FAILURE_XFG = @as(u32, 64); pub const FAST_FAIL_CAST_GUARD = @as(u32, 65); pub const FAST_FAIL_HOST_VISIBILITY_CHANGE = @as(u32, 66); pub const FAST_FAIL_KERNEL_CET_SHADOW_STACK_ASSIST = @as(u32, 67); pub const FAST_FAIL_PATCH_CALLBACK_FAILED = @as(u32, 68); pub const FAST_FAIL_NTDLL_PATCH_FAILED = @as(u32, 69); pub const FAST_FAIL_INVALID_FLS_DATA = @as(u32, 70); pub const FAST_FAIL_INVALID_FAST_FAIL_CODE = @as(u32, 4294967295); pub const IS_TEXT_UNICODE_DBCS_LEADBYTE = @as(u32, 1024); pub const IS_TEXT_UNICODE_UTF8 = @as(u32, 2048); pub const COMPRESSION_FORMAT_NONE = @as(u32, 0); pub const COMPRESSION_FORMAT_DEFAULT = @as(u32, 1); pub const COMPRESSION_FORMAT_LZNT1 = @as(u32, 2); pub const COMPRESSION_FORMAT_XPRESS = @as(u32, 3); pub const COMPRESSION_FORMAT_XPRESS_HUFF = @as(u32, 4); pub const COMPRESSION_FORMAT_XP10 = @as(u32, 5); pub const COMPRESSION_ENGINE_STANDARD = @as(u32, 0); pub const COMPRESSION_ENGINE_MAXIMUM = @as(u32, 256); pub const COMPRESSION_ENGINE_HIBER = @as(u32, 512); pub const SEF_AI_USE_EXTRA_PARAMS = @as(u32, 2048); pub const SEF_FORCE_USER_MODE = @as(u32, 8192); pub const MESSAGE_RESOURCE_UNICODE = @as(u32, 1); pub const MESSAGE_RESOURCE_UTF8 = @as(u32, 2); pub const VER_EQUAL = @as(u32, 1); pub const VER_GREATER = @as(u32, 2); pub const VER_GREATER_EQUAL = @as(u32, 3); pub const VER_LESS = @as(u32, 4); pub const VER_LESS_EQUAL = @as(u32, 5); pub const VER_AND = @as(u32, 6); pub const VER_OR = @as(u32, 7); pub const VER_CONDITION_MASK = @as(u32, 7); pub const VER_NUM_BITS_PER_CONDITION_MASK = @as(u32, 3); pub const VER_NT_WORKSTATION = @as(u32, 1); pub const VER_NT_DOMAIN_CONTROLLER = @as(u32, 2); pub const VER_NT_SERVER = @as(u32, 3); pub const RTL_UMS_VERSION = @as(u32, 256); pub const VRL_PREDEFINED_CLASS_BEGIN = @as(u32, 1); pub const VRL_CUSTOM_CLASS_BEGIN = @as(u32, 256); pub const VRL_ENABLE_KERNEL_BREAKS = @as(u32, 2147483648); pub const CTMF_INCLUDE_APPCONTAINER = @as(u32, 1); pub const CTMF_INCLUDE_LPAC = @as(u32, 2); pub const FLUSH_NV_MEMORY_IN_FLAG_NO_DRAIN = @as(u32, 1); pub const WRITE_NV_MEMORY_FLAG_FLUSH = @as(u32, 1); pub const WRITE_NV_MEMORY_FLAG_NON_TEMPORAL = @as(u32, 2); pub const WRITE_NV_MEMORY_FLAG_NO_DRAIN = @as(u32, 256); pub const FILL_NV_MEMORY_FLAG_FLUSH = @as(u32, 1); pub const FILL_NV_MEMORY_FLAG_NON_TEMPORAL = @as(u32, 2); pub const FILL_NV_MEMORY_FLAG_NO_DRAIN = @as(u32, 256); pub const IMAGE_POLICY_METADATA_VERSION = @as(u32, 1); pub const RTL_VIRTUAL_UNWIND2_VALIDATE_PAC = @as(u32, 1); pub const RTL_CRITICAL_SECTION_FLAG_NO_DEBUG_INFO = @as(u32, 16777216); pub const RTL_CRITICAL_SECTION_FLAG_DYNAMIC_SPIN = @as(u32, 33554432); pub const RTL_CRITICAL_SECTION_FLAG_STATIC_INIT = @as(u32, 67108864); pub const RTL_CRITICAL_SECTION_FLAG_RESOURCE_TYPE = @as(u32, 134217728); pub const RTL_CRITICAL_SECTION_FLAG_FORCE_DEBUG_INFO = @as(u32, 268435456); pub const RTL_CRITICAL_SECTION_ALL_FLAG_BITS = @as(u32, 4278190080); pub const RTL_CRITICAL_SECTION_DEBUG_FLAG_STATIC_INIT = @as(u32, 1); pub const RTL_CONDITION_VARIABLE_LOCKMODE_SHARED = @as(u32, 1); pub const HEAP_OPTIMIZE_RESOURCES_CURRENT_VERSION = @as(u32, 1); pub const WT_EXECUTEINUITHREAD = @as(u32, 2); pub const WT_EXECUTEINPERSISTENTIOTHREAD = @as(u32, 64); pub const WT_EXECUTEINLONGTHREAD = @as(u32, 16); pub const WT_EXECUTEDELETEWAIT = @as(u32, 8); pub const ACTIVATION_CONTEXT_PATH_TYPE_NONE = @as(u32, 1); pub const ACTIVATION_CONTEXT_PATH_TYPE_WIN32_FILE = @as(u32, 2); pub const ACTIVATION_CONTEXT_PATH_TYPE_URL = @as(u32, 3); pub const ACTIVATION_CONTEXT_PATH_TYPE_ASSEMBLYREF = @as(u32, 4); pub const CREATE_BOUNDARY_DESCRIPTOR_ADD_APPCONTAINER_SID = @as(u32, 1); pub const PERFORMANCE_DATA_VERSION = @as(u32, 1); pub const READ_THREAD_PROFILING_FLAG_DISPATCHING = @as(u32, 1); pub const READ_THREAD_PROFILING_FLAG_HARDWARE_COUNTERS = @as(u32, 2); pub const UNIFIEDBUILDREVISION_MIN = @as(u32, 0); pub const DLL_PROCESS_ATTACH = @as(u32, 1); pub const DLL_THREAD_ATTACH = @as(u32, 2); pub const DLL_THREAD_DETACH = @as(u32, 3); pub const DLL_PROCESS_DETACH = @as(u32, 0); pub const EVENTLOG_FORWARDS_READ = @as(u32, 4); pub const EVENTLOG_BACKWARDS_READ = @as(u32, 8); pub const EVENTLOG_START_PAIRED_EVENT = @as(u32, 1); pub const EVENTLOG_END_PAIRED_EVENT = @as(u32, 2); pub const EVENTLOG_END_ALL_PAIRED_EVENTS = @as(u32, 4); pub const EVENTLOG_PAIRED_EVENT_ACTIVE = @as(u32, 8); pub const EVENTLOG_PAIRED_EVENT_INACTIVE = @as(u32, 16); pub const MAXLOGICALLOGNAMESIZE = @as(u32, 256); pub const REG_REFRESH_HIVE = @as(i32, 2); pub const REG_NO_LAZY_FLUSH = @as(i32, 4); pub const REG_APP_HIVE = @as(i32, 16); pub const REG_PROCESS_PRIVATE = @as(i32, 32); pub const REG_START_JOURNAL = @as(i32, 64); pub const REG_HIVE_EXACT_FILE_GROWTH = @as(i32, 128); pub const REG_HIVE_NO_RM = @as(i32, 256); pub const REG_HIVE_SINGLE_LOG = @as(i32, 512); pub const REG_BOOT_HIVE = @as(i32, 1024); pub const REG_LOAD_HIVE_OPEN_HANDLE = @as(i32, 2048); pub const REG_FLUSH_HIVE_FILE_GROWTH = @as(i32, 4096); pub const REG_OPEN_READ_ONLY = @as(i32, 8192); pub const REG_IMMUTABLE = @as(i32, 16384); pub const REG_NO_IMPERSONATION_FALLBACK = @as(i32, 32768); pub const REG_APP_HIVE_OPEN_READ_ONLY = @as(i32, 8192); pub const REG_FORCE_UNLOAD = @as(u32, 1); pub const REG_UNLOAD_LEGAL_FLAGS = @as(u32, 1); pub const SERVICE_USER_SERVICE = @as(u32, 64); pub const SERVICE_USERSERVICE_INSTANCE = @as(u32, 128); pub const SERVICE_INTERACTIVE_PROCESS = @as(u32, 256); pub const SERVICE_PKG_SERVICE = @as(u32, 512); pub const CM_SERVICE_NETWORK_BOOT_LOAD = @as(u32, 1); pub const CM_SERVICE_VIRTUAL_DISK_BOOT_LOAD = @as(u32, 2); pub const CM_SERVICE_USB_DISK_BOOT_LOAD = @as(u32, 4); pub const CM_SERVICE_SD_DISK_BOOT_LOAD = @as(u32, 8); pub const CM_SERVICE_USB3_DISK_BOOT_LOAD = @as(u32, 16); pub const CM_SERVICE_MEASURED_BOOT_LOAD = @as(u32, 32); pub const CM_SERVICE_VERIFIER_BOOT_LOAD = @as(u32, 64); pub const CM_SERVICE_WINPE_BOOT_LOAD = @as(u32, 128); pub const CM_SERVICE_RAM_DISK_BOOT_LOAD = @as(u32, 256); pub const TAPE_PSEUDO_LOGICAL_POSITION = @as(i32, 2); pub const TAPE_PSEUDO_LOGICAL_BLOCK = @as(i32, 3); pub const TAPE_DRIVE_FIXED = @as(u32, 1); pub const TAPE_DRIVE_SELECT = @as(u32, 2); pub const TAPE_DRIVE_INITIATOR = @as(u32, 4); pub const TAPE_DRIVE_ERASE_SHORT = @as(u32, 16); pub const TAPE_DRIVE_ERASE_LONG = @as(u32, 32); pub const TAPE_DRIVE_ERASE_BOP_ONLY = @as(u32, 64); pub const TAPE_DRIVE_ERASE_IMMEDIATE = @as(u32, 128); pub const TAPE_DRIVE_TAPE_CAPACITY = @as(u32, 256); pub const TAPE_DRIVE_TAPE_REMAINING = @as(u32, 512); pub const TAPE_DRIVE_FIXED_BLOCK = @as(u32, 1024); pub const TAPE_DRIVE_VARIABLE_BLOCK = @as(u32, 2048); pub const TAPE_DRIVE_WRITE_PROTECT = @as(u32, 4096); pub const TAPE_DRIVE_EOT_WZ_SIZE = @as(u32, 8192); pub const TAPE_DRIVE_ECC = @as(u32, 65536); pub const TAPE_DRIVE_COMPRESSION = @as(u32, 131072); pub const TAPE_DRIVE_PADDING = @as(u32, 262144); pub const TAPE_DRIVE_REPORT_SMKS = @as(u32, 524288); pub const TAPE_DRIVE_GET_ABSOLUTE_BLK = @as(u32, 1048576); pub const TAPE_DRIVE_GET_LOGICAL_BLK = @as(u32, 2097152); pub const TAPE_DRIVE_SET_EOT_WZ_SIZE = @as(u32, 4194304); pub const TAPE_DRIVE_EJECT_MEDIA = @as(u32, 16777216); pub const TAPE_DRIVE_CLEAN_REQUESTS = @as(u32, 33554432); pub const TAPE_DRIVE_SET_CMP_BOP_ONLY = @as(u32, 67108864); pub const TAPE_DRIVE_RESERVED_BIT = @as(u32, 2147483648); pub const TAPE_DRIVE_FORMAT = @as(u32, 2684354560); pub const TAPE_DRIVE_FORMAT_IMMEDIATE = @as(u32, 3221225472); pub const TAPE_DRIVE_HIGH_FEATURES = @as(u32, 2147483648); pub const TAPE_QUERY_DRIVE_PARAMETERS = @as(i32, 0); pub const TAPE_QUERY_MEDIA_CAPACITY = @as(i32, 1); pub const TAPE_CHECK_FOR_DRIVE_PROBLEM = @as(i32, 2); pub const TAPE_QUERY_IO_ERROR_DATA = @as(i32, 3); pub const TAPE_QUERY_DEVICE_ERROR_DATA = @as(i32, 4); pub const TRANSACTIONMANAGER_QUERY_INFORMATION = @as(u32, 1); pub const TRANSACTIONMANAGER_SET_INFORMATION = @as(u32, 2); pub const TRANSACTIONMANAGER_RECOVER = @as(u32, 4); pub const TRANSACTIONMANAGER_RENAME = @as(u32, 8); pub const TRANSACTIONMANAGER_CREATE_RM = @as(u32, 16); pub const TRANSACTIONMANAGER_BIND_TRANSACTION = @as(u32, 32); pub const TRANSACTION_QUERY_INFORMATION = @as(u32, 1); pub const TRANSACTION_SET_INFORMATION = @as(u32, 2); pub const TRANSACTION_ENLIST = @as(u32, 4); pub const TRANSACTION_COMMIT = @as(u32, 8); pub const TRANSACTION_ROLLBACK = @as(u32, 16); pub const TRANSACTION_PROPAGATE = @as(u32, 32); pub const TRANSACTION_RIGHT_RESERVED1 = @as(u32, 64); pub const RESOURCEMANAGER_QUERY_INFORMATION = @as(u32, 1); pub const RESOURCEMANAGER_SET_INFORMATION = @as(u32, 2); pub const RESOURCEMANAGER_RECOVER = @as(u32, 4); pub const RESOURCEMANAGER_ENLIST = @as(u32, 8); pub const RESOURCEMANAGER_GET_NOTIFICATION = @as(u32, 16); pub const RESOURCEMANAGER_REGISTER_PROTOCOL = @as(u32, 32); pub const RESOURCEMANAGER_COMPLETE_PROPAGATION = @as(u32, 64); pub const ENLISTMENT_QUERY_INFORMATION = @as(u32, 1); pub const ENLISTMENT_SET_INFORMATION = @as(u32, 2); pub const ENLISTMENT_RECOVER = @as(u32, 4); pub const ENLISTMENT_SUBORDINATE_RIGHTS = @as(u32, 8); pub const ENLISTMENT_SUPERIOR_RIGHTS = @as(u32, 16); pub const PcTeb = @as(u32, 24); pub const ACTIVATION_CONTEXT_SECTION_ASSEMBLY_INFORMATION = @as(u32, 1); pub const ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION = @as(u32, 2); pub const ACTIVATION_CONTEXT_SECTION_WINDOW_CLASS_REDIRECTION = @as(u32, 3); pub const ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION = @as(u32, 4); pub const ACTIVATION_CONTEXT_SECTION_COM_INTERFACE_REDIRECTION = @as(u32, 5); pub const ACTIVATION_CONTEXT_SECTION_COM_TYPE_LIBRARY_REDIRECTION = @as(u32, 6); pub const ACTIVATION_CONTEXT_SECTION_COM_PROGID_REDIRECTION = @as(u32, 7); pub const ACTIVATION_CONTEXT_SECTION_GLOBAL_OBJECT_RENAME_TABLE = @as(u32, 8); pub const ACTIVATION_CONTEXT_SECTION_CLR_SURROGATES = @as(u32, 9); pub const ACTIVATION_CONTEXT_SECTION_APPLICATION_SETTINGS = @as(u32, 10); pub const ACTIVATION_CONTEXT_SECTION_COMPATIBILITY_INFO = @as(u32, 11); pub const ACTIVATION_CONTEXT_SECTION_WINRT_ACTIVATABLE_CLASSES = @as(u32, 12); pub const BSF_MSGSRV32ISOK = @as(u32, 2147483648); pub const BSF_MSGSRV32ISOK_BIT = @as(u32, 31); pub const DBT_APPYBEGIN = @as(u32, 0); pub const DBT_APPYEND = @as(u32, 1); pub const DBT_DEVNODES_CHANGED = @as(u32, 7); pub const DBT_QUERYCHANGECONFIG = @as(u32, 23); pub const DBT_CONFIGCHANGED = @as(u32, 24); pub const DBT_CONFIGCHANGECANCELED = @as(u32, 25); pub const DBT_MONITORCHANGE = @as(u32, 27); pub const DBT_SHELLLOGGEDON = @as(u32, 32); pub const DBT_CONFIGMGAPI32 = @as(u32, 34); pub const DBT_VXDINITCOMPLETE = @as(u32, 35); pub const DBT_VOLLOCKQUERYLOCK = @as(u32, 32833); pub const DBT_VOLLOCKLOCKTAKEN = @as(u32, 32834); pub const DBT_VOLLOCKLOCKFAILED = @as(u32, 32835); pub const DBT_VOLLOCKQUERYUNLOCK = @as(u32, 32836); pub const DBT_VOLLOCKLOCKRELEASED = @as(u32, 32837); pub const DBT_VOLLOCKUNLOCKFAILED = @as(u32, 32838); pub const LOCKP_ALLOW_WRITES = @as(u32, 1); pub const LOCKP_FAIL_WRITES = @as(u32, 0); pub const LOCKP_FAIL_MEM_MAPPING = @as(u32, 2); pub const LOCKP_ALLOW_MEM_MAPPING = @as(u32, 0); pub const LOCKP_USER_MASK = @as(u32, 3); pub const LOCKP_LOCK_FOR_FORMAT = @as(u32, 4); pub const LOCKF_LOGICAL_LOCK = @as(u32, 0); pub const LOCKF_PHYSICAL_LOCK = @as(u32, 1); pub const DBT_NO_DISK_SPACE = @as(u32, 71); pub const DBT_LOW_DISK_SPACE = @as(u32, 72); pub const DBT_CONFIGMGPRIVATE = @as(u32, 32767); pub const DBT_DEVICEARRIVAL = @as(u32, 32768); pub const DBT_DEVICEQUERYREMOVE = @as(u32, 32769); pub const DBT_DEVICEQUERYREMOVEFAILED = @as(u32, 32770); pub const DBT_DEVICEREMOVEPENDING = @as(u32, 32771); pub const DBT_DEVICEREMOVECOMPLETE = @as(u32, 32772); pub const DBT_DEVICETYPESPECIFIC = @as(u32, 32773); pub const DBT_CUSTOMEVENT = @as(u32, 32774); pub const DBT_DEVTYP_DEVNODE = @as(u32, 1); pub const DBT_DEVTYP_NET = @as(u32, 4); pub const DBTF_RESOURCE = @as(u32, 1); pub const DBTF_XPORT = @as(u32, 2); pub const DBTF_SLOWNET = @as(u32, 4); pub const DBT_VPOWERDAPI = @as(u32, 33024); pub const DBT_USERDEFINED = @as(u32, 65535); pub const GUID_IO_VOLUME_CHANGE = Guid.initString("7373654a-812a-11d0-bec7-08002be2092f"); pub const GUID_IO_VOLUME_DISMOUNT = Guid.initString("d16a55e8-1059-11d2-8ffd-00a0c9a06d32"); pub const GUID_IO_VOLUME_DISMOUNT_FAILED = Guid.initString("e3c5b178-105d-11d2-8ffd-00a0c9a06d32"); pub const GUID_IO_VOLUME_MOUNT = Guid.initString("b5804878-1a96-11d2-8ffd-00a0c9a06d32"); pub const GUID_IO_VOLUME_LOCK = Guid.initString("50708874-c9af-11d1-8fef-00a0c9a06d32"); pub const GUID_IO_VOLUME_LOCK_FAILED = Guid.initString("ae2eed10-0ba8-11d2-8ffb-00a0c9a06d32"); pub const GUID_IO_VOLUME_UNLOCK = Guid.initString("9a8c3d68-d0cb-11d1-8fef-00a0c9a06d32"); pub const GUID_IO_VOLUME_NAME_CHANGE = Guid.initString("2de97f83-4c06-11d2-a532-00609713055a"); pub const GUID_IO_VOLUME_NEED_CHKDSK = Guid.initString("799a0960-0a0b-4e03-ad88-2fa7c6ce748a"); pub const GUID_IO_VOLUME_WORM_NEAR_FULL = Guid.initString("f3bfff82-f3de-48d2-af95-457f80b763f2"); pub const GUID_IO_VOLUME_WEARING_OUT = Guid.initString("873113ca-1486-4508-82ac-c3b2e5297aaa"); pub const GUID_IO_VOLUME_FORCE_CLOSED = Guid.initString("411ad84f-433e-4dc2-a5ae-4a2d1a2de654"); pub const GUID_IO_VOLUME_INFO_MAKE_COMPAT = Guid.initString("3ab9a0d2-ef80-45cf-8cdc-cbe02a212906"); pub const GUID_IO_VOLUME_PREPARING_EJECT = Guid.initString("c79eb16e-0dac-4e7a-a86c-b25ceeaa88f6"); pub const GUID_IO_VOLUME_BACKGROUND_FORMAT = Guid.initString("a2e5fc86-d5cd-4038-b2e3-4445065c2377"); pub const GUID_IO_VOLUME_PHYSICAL_CONFIGURATION_CHANGE = Guid.initString("2de97f84-4c06-11d2-a532-00609713055a"); pub const GUID_IO_VOLUME_UNIQUE_ID_CHANGE = Guid.initString("af39da42-6622-41f5-970b-139d092fa3d9"); pub const GUID_IO_VOLUME_FVE_STATUS_CHANGE = Guid.initString("062998b2-ee1f-4b6a-b857-e76cbbe9a6da"); pub const GUID_IO_VOLUME_DEVICE_INTERFACE = Guid.initString("53f5630d-b6bf-11d0-94f2-00a0c91efb8b"); pub const GUID_IO_VOLUME_CHANGE_SIZE = Guid.initString("3a1625be-ad03-49f1-8ef8-6bbac182d1fd"); pub const GUID_IO_MEDIA_ARRIVAL = Guid.initString("d07433c0-a98e-11d2-917a-00a0c9068ff3"); pub const GUID_IO_MEDIA_REMOVAL = Guid.initString("d07433c1-a98e-11d2-917a-00a0c9068ff3"); pub const GUID_IO_CDROM_EXCLUSIVE_LOCK = Guid.initString("bc56c139-7a10-47ee-a294-4c6a38f0149a"); pub const GUID_IO_CDROM_EXCLUSIVE_UNLOCK = Guid.initString("a3b6d27d-5e35-4885-81e5-ee18c00ed779"); pub const GUID_IO_DEVICE_BECOMING_READY = Guid.initString("d07433f0-a98e-11d2-917a-00a0c9068ff3"); pub const GUID_IO_DEVICE_EXTERNAL_REQUEST = Guid.initString("d07433d0-a98e-11d2-917a-00a0c9068ff3"); pub const GUID_IO_MEDIA_EJECT_REQUEST = Guid.initString("d07433d1-a98e-11d2-917a-00a0c9068ff3"); pub const GUID_IO_DRIVE_REQUIRES_CLEANING = Guid.initString("7207877c-90ed-44e5-a000-81428d4c79bb"); pub const GUID_IO_TAPE_ERASE = Guid.initString("852d11eb-4bb8-4507-9d9b-417cc2b1b438"); pub const GUID_DEVICE_EVENT_RBC = Guid.initString("d0744792-a98e-11d2-917a-00a0c9068ff3"); pub const GUID_IO_DISK_CLONE_ARRIVAL = Guid.initString("6a61885b-7c39-43dd-9b56-b8ac22a549aa"); pub const GUID_IO_DISK_LAYOUT_CHANGE = Guid.initString("11dff54c-8469-41f9-b3de-ef836487c54a"); pub const GUID_IO_DISK_HEALTH_NOTIFICATION = Guid.initString("0f1bd644-3916-49c5-b063-991940118fb2"); pub const D3DNTHAL_NUMCLIPVERTICES = @as(u32, 20); pub const D3DNTHAL_SCENE_CAPTURE_START = @as(i32, 0); pub const D3DNTHAL_SCENE_CAPTURE_END = @as(i32, 1); pub const D3DNTHAL_CONTEXT_BAD = @as(i64, 512); pub const D3DNTHAL_OUTOFCONTEXTS = @as(i64, 513); pub const D3DNTHAL2_CB32_SETRENDERTARGET = @as(i32, 1); pub const D3DHAL_STATESETBEGIN = @as(u32, 0); pub const D3DHAL_STATESETEND = @as(u32, 1); pub const D3DHAL_STATESETDELETE = @as(u32, 2); pub const D3DHAL_STATESETEXECUTE = @as(u32, 3); pub const D3DHAL_STATESETCAPTURE = @as(u32, 4); pub const D3DNTHALDP2_USERMEMVERTICES = @as(i32, 1); pub const D3DNTHALDP2_EXECUTEBUFFER = @as(i32, 2); pub const D3DNTHALDP2_SWAPVERTEXBUFFER = @as(i32, 4); pub const D3DNTHALDP2_SWAPCOMMANDBUFFER = @as(i32, 8); pub const D3DNTHALDP2_REQVERTEXBUFSIZE = @as(i32, 16); pub const D3DNTHALDP2_REQCOMMANDBUFSIZE = @as(i32, 32); pub const D3DNTHALDP2_VIDMEMVERTEXBUF = @as(i32, 64); pub const D3DNTHALDP2_VIDMEMCOMMANDBUF = @as(i32, 128); pub const D3DNTHAL3_CB32_CLEAR2 = @as(i32, 1); pub const D3DNTHAL3_CB32_RESERVED = @as(i32, 2); pub const D3DNTHAL3_CB32_VALIDATETEXTURESTAGESTATE = @as(i32, 4); pub const D3DNTHAL3_CB32_DRAWPRIMITIVES2 = @as(i32, 8); pub const D3DNTHAL_TSS_RENDERSTATEBASE = @as(u32, 256); pub const D3DNTHAL_TSS_MAXSTAGES = @as(u32, 8); pub const D3DNTHAL_TSS_STATESPERSTAGE = @as(u32, 64); pub const D3DTSS_TEXTUREMAP = @as(u32, 0); pub const D3DHAL_SAMPLER_MAXSAMP = @as(u32, 16); pub const D3DHAL_SAMPLER_MAXVERTEXSAMP = @as(u32, 4); pub const D3DPMISCCAPS_LINEPATTERNREP = @as(i32, 4); pub const D3DRS_MAXVERTEXSHADERINST = @as(u32, 196); pub const D3DRS_MAXPIXELSHADERINST = @as(u32, 197); pub const D3DRENDERSTATE_EVICTMANAGEDTEXTURES = @as(u32, 61); pub const D3DRENDERSTATE_SCENECAPTURE = @as(u32, 62); pub const _NT_D3DRS_DELETERTPATCH = @as(u32, 169); pub const D3DINFINITEINSTRUCTIONS = @as(u32, 4294967295); pub const D3DNTHAL_STATESETCREATE = @as(u32, 5); pub const D3DNTCLEAR_COMPUTERECTS = @as(i32, 8); pub const _NT_RTPATCHFLAG_HASSEGS = @as(i32, 1); pub const _NT_RTPATCHFLAG_HASINFO = @as(i32, 2); pub const D3DNTHAL_ROW_WEIGHTS = @as(u32, 1); pub const D3DNTHAL_COL_WEIGHTS = @as(u32, 2); pub const DP2BLT_POINT = @as(i32, 1); pub const DP2BLT_LINEAR = @as(i32, 2); pub const DDBLT_EXTENDED_PRESENTATION_STRETCHFACTOR = @as(i32, 16); pub const _NT_D3DGDI2_MAGIC = @as(u32, 4294967295); pub const _NT_D3DGDI2_TYPE_GETD3DCAPS8 = @as(u32, 1); pub const _NT_D3DGDI2_TYPE_GETFORMATCOUNT = @as(u32, 2); pub const _NT_D3DGDI2_TYPE_GETFORMAT = @as(u32, 3); pub const _NT_D3DGDI2_TYPE_DXVERSION = @as(u32, 4); pub const _NT_D3DGDI2_TYPE_DEFERRED_AGP_AWARE = @as(u32, 24); pub const _NT_D3DGDI2_TYPE_FREE_DEFERRED_AGP = @as(u32, 25); pub const _NT_D3DGDI2_TYPE_DEFER_AGP_FREES = @as(u32, 32); pub const _NT_D3DGDI2_TYPE_GETD3DCAPS9 = @as(u32, 16); pub const _NT_D3DGDI2_TYPE_GETEXTENDEDMODECOUNT = @as(u32, 17); pub const _NT_D3DGDI2_TYPE_GETEXTENDEDMODE = @as(u32, 18); pub const _NT_D3DGDI2_TYPE_GETADAPTERGROUP = @as(u32, 19); pub const _NT_D3DGDI2_TYPE_GETMULTISAMPLEQUALITYLEVELS = @as(u32, 22); pub const _NT_D3DGDI2_TYPE_GETD3DQUERYCOUNT = @as(u32, 33); pub const _NT_D3DGDI2_TYPE_GETD3DQUERY = @as(u32, 34); pub const _NT_D3DGDI2_TYPE_GETDDIVERSION = @as(u32, 35); pub const DX9_DDI_VERSION = @as(u32, 4); pub const _NT_D3DDEVCAPS_HWVERTEXBUFFER = @as(i32, 33554432); pub const _NT_D3DDEVCAPS_HWINDEXBUFFER = @as(i32, 67108864); pub const _NT_D3DDEVCAPS_SUBVOLUMELOCK = @as(i32, 134217728); pub const _NT_D3DPMISCCAPS_FOGINFVF = @as(i32, 8192); pub const _NT_D3DFVF_FOG = @as(i32, 8192); pub const D3DPRASTERCAPS_STRETCHBLTMULTISAMPLE = @as(i32, 8388608); pub const _NT_D3DVS_MAXINSTRUCTIONCOUNT_V1_1 = @as(u32, 128); pub const _NT_D3DVS_LABEL_MAX_V3_0 = @as(u32, 2048); pub const _NT_D3DVS_TCRDOUTREG_MAX_V1_1 = @as(u32, 8); pub const _NT_D3DVS_TCRDOUTREG_MAX_V2_0 = @as(u32, 8); pub const _NT_D3DVS_TCRDOUTREG_MAX_V2_1 = @as(u32, 8); pub const _NT_D3DVS_OUTPUTREG_MAX_V3_0 = @as(u32, 12); pub const _NT_D3DVS_OUTPUTREG_MAX_SW_DX9 = @as(u32, 16); pub const _NT_D3DVS_ATTROUTREG_MAX_V1_1 = @as(u32, 2); pub const _NT_D3DVS_ATTROUTREG_MAX_V2_0 = @as(u32, 2); pub const _NT_D3DVS_ATTROUTREG_MAX_V2_1 = @as(u32, 2); pub const _NT_D3DVS_INPUTREG_MAX_V1_1 = @as(u32, 16); pub const _NT_D3DVS_INPUTREG_MAX_V2_0 = @as(u32, 16); pub const _NT_D3DVS_INPUTREG_MAX_V2_1 = @as(u32, 16); pub const _NT_D3DVS_INPUTREG_MAX_V3_0 = @as(u32, 16); pub const _NT_D3DVS_TEMPREG_MAX_V1_1 = @as(u32, 12); pub const _NT_D3DVS_TEMPREG_MAX_V2_0 = @as(u32, 12); pub const _NT_D3DVS_TEMPREG_MAX_V2_1 = @as(u32, 32); pub const _NT_D3DVS_TEMPREG_MAX_V3_0 = @as(u32, 32); pub const _NT_D3DVS_CONSTREG_MAX_V1_1 = @as(u32, 96); pub const _NT_D3DVS_CONSTREG_MAX_V2_0 = @as(u32, 8192); pub const _NT_D3DVS_CONSTREG_MAX_V2_1 = @as(u32, 8192); pub const _NT_D3DVS_CONSTREG_MAX_V3_0 = @as(u32, 8192); pub const _NT_D3DVS_CONSTINTREG_MAX_SW_DX9 = @as(u32, 2048); pub const _NT_D3DVS_CONSTINTREG_MAX_V2_0 = @as(u32, 16); pub const _NT_D3DVS_CONSTINTREG_MAX_V2_1 = @as(u32, 16); pub const _NT_D3DVS_CONSTINTREG_MAX_V3_0 = @as(u32, 16); pub const _NT_D3DVS_CONSTBOOLREG_MAX_SW_DX9 = @as(u32, 2048); pub const _NT_D3DVS_CONSTBOOLREG_MAX_V2_0 = @as(u32, 16); pub const _NT_D3DVS_CONSTBOOLREG_MAX_V2_1 = @as(u32, 16); pub const _NT_D3DVS_CONSTBOOLREG_MAX_V3_0 = @as(u32, 16); pub const _NT_D3DVS_ADDRREG_MAX_V1_1 = @as(u32, 1); pub const _NT_D3DVS_ADDRREG_MAX_V2_0 = @as(u32, 1); pub const _NT_D3DVS_ADDRREG_MAX_V2_1 = @as(u32, 1); pub const _NT_D3DVS_ADDRREG_MAX_V3_0 = @as(u32, 1); pub const _NT_D3DVS_MAXLOOPSTEP_V2_0 = @as(u32, 128); pub const _NT_D3DVS_MAXLOOPSTEP_V2_1 = @as(u32, 128); pub const _NT_D3DVS_MAXLOOPSTEP_V3_0 = @as(u32, 128); pub const _NT_D3DVS_MAXLOOPINITVALUE_V2_0 = @as(u32, 255); pub const _NT_D3DVS_MAXLOOPINITVALUE_V2_1 = @as(u32, 255); pub const _NT_D3DVS_MAXLOOPINITVALUE_V3_0 = @as(u32, 255); pub const _NT_D3DVS_MAXLOOPITERATIONCOUNT_V2_0 = @as(u32, 255); pub const _NT_D3DVS_MAXLOOPITERATIONCOUNT_V2_1 = @as(u32, 255); pub const _NT_D3DVS_MAXLOOPITERATIONCOUNT_V3_0 = @as(u32, 255); pub const _NT_D3DVS_PREDICATE_MAX_V2_1 = @as(u32, 1); pub const _NT_D3DVS_PREDICATE_MAX_V3_0 = @as(u32, 1); pub const _NT_D3DPS_INPUTREG_MAX_V1_1 = @as(u32, 2); pub const _NT_D3DPS_INPUTREG_MAX_V1_2 = @as(u32, 2); pub const _NT_D3DPS_INPUTREG_MAX_V1_3 = @as(u32, 2); pub const _NT_D3DPS_INPUTREG_MAX_V1_4 = @as(u32, 2); pub const _NT_D3DPS_INPUTREG_MAX_V2_0 = @as(u32, 2); pub const _NT_D3DPS_INPUTREG_MAX_V2_1 = @as(u32, 2); pub const _NT_D3DPS_INPUTREG_MAX_V3_0 = @as(u32, 12); pub const _NT_D3DPS_TEMPREG_MAX_V1_1 = @as(u32, 2); pub const _NT_D3DPS_TEMPREG_MAX_V1_2 = @as(u32, 2); pub const _NT_D3DPS_TEMPREG_MAX_V1_3 = @as(u32, 2); pub const _NT_D3DPS_TEMPREG_MAX_V1_4 = @as(u32, 6); pub const _NT_D3DPS_TEMPREG_MAX_V2_0 = @as(u32, 12); pub const _NT_D3DPS_TEMPREG_MAX_V2_1 = @as(u32, 32); pub const _NT_D3DPS_TEMPREG_MAX_V3_0 = @as(u32, 32); pub const _NT_D3DPS_TEXTUREREG_MAX_V1_1 = @as(u32, 4); pub const _NT_D3DPS_TEXTUREREG_MAX_V1_2 = @as(u32, 4); pub const _NT_D3DPS_TEXTUREREG_MAX_V1_3 = @as(u32, 4); pub const _NT_D3DPS_TEXTUREREG_MAX_V1_4 = @as(u32, 6); pub const _NT_D3DPS_TEXTUREREG_MAX_V2_0 = @as(u32, 8); pub const _NT_D3DPS_TEXTUREREG_MAX_V2_1 = @as(u32, 8); pub const _NT_D3DPS_TEXTUREREG_MAX_V3_0 = @as(u32, 0); pub const _NT_D3DPS_COLOROUT_MAX_V2_0 = @as(u32, 4); pub const _NT_D3DPS_COLOROUT_MAX_V2_1 = @as(u32, 4); pub const _NT_D3DPS_COLOROUT_MAX_V3_0 = @as(u32, 4); pub const _NT_D3DPS_PREDICATE_MAX_V2_1 = @as(u32, 1); pub const _NT_D3DPS_PREDICATE_MAX_V3_0 = @as(u32, 1); pub const _NT_D3DPS_CONSTREG_MAX_SW_DX9 = @as(u32, 8192); pub const _NT_D3DPS_CONSTREG_MAX_V1_1 = @as(u32, 8); pub const _NT_D3DPS_CONSTREG_MAX_V1_2 = @as(u32, 8); pub const _NT_D3DPS_CONSTREG_MAX_V1_3 = @as(u32, 8); pub const _NT_D3DPS_CONSTREG_MAX_V1_4 = @as(u32, 8); pub const _NT_D3DPS_CONSTREG_MAX_V2_0 = @as(u32, 32); pub const _NT_D3DPS_CONSTREG_MAX_V2_1 = @as(u32, 32); pub const _NT_D3DPS_CONSTREG_MAX_V3_0 = @as(u32, 224); pub const _NT_D3DPS_CONSTBOOLREG_MAX_SW_DX9 = @as(u32, 2048); pub const _NT_D3DPS_CONSTBOOLREG_MAX_V2_1 = @as(u32, 16); pub const _NT_D3DPS_CONSTBOOLREG_MAX_V3_0 = @as(u32, 16); pub const _NT_D3DPS_CONSTINTREG_MAX_SW_DX9 = @as(u32, 2048); pub const _NT_D3DPS_CONSTINTREG_MAX_V2_1 = @as(u32, 16); pub const _NT_D3DPS_CONSTINTREG_MAX_V3_0 = @as(u32, 16); pub const _NT_D3DPS_MAXLOOPSTEP_V2_1 = @as(u32, 128); pub const _NT_D3DPS_MAXLOOPSTEP_V3_0 = @as(u32, 128); pub const _NT_D3DPS_MAXLOOPINITVALUE_V2_1 = @as(u32, 255); pub const _NT_D3DPS_MAXLOOPINITVALUE_V3_0 = @as(u32, 255); pub const _NT_D3DPS_MAXLOOPITERATIONCOUNT_V2_1 = @as(u32, 255); pub const _NT_D3DPS_MAXLOOPITERATIONCOUNT_V3_0 = @as(u32, 255); pub const _NT_D3DPS_INPUTREG_MAX_DX8 = @as(u32, 8); pub const _NT_D3DPS_TEMPREG_MAX_DX8 = @as(u32, 8); pub const _NT_D3DPS_CONSTREG_MAX_DX8 = @as(u32, 8); pub const _NT_D3DPS_TEXTUREREG_MAX_DX8 = @as(u32, 8); pub const D3DVSDT_FLOAT1 = @as(u32, 0); pub const D3DVSDT_FLOAT2 = @as(u32, 1); pub const D3DVSDT_FLOAT3 = @as(u32, 2); pub const D3DVSDT_FLOAT4 = @as(u32, 3); pub const D3DVSDT_D3DCOLOR = @as(u32, 4); pub const D3DVSDT_UBYTE4 = @as(u32, 5); pub const D3DVSDT_SHORT2 = @as(u32, 6); pub const D3DVSDT_SHORT4 = @as(u32, 7); pub const D3DVSDE_POSITION = @as(u32, 0); pub const D3DVSDE_BLENDWEIGHT = @as(u32, 1); pub const D3DVSDE_BLENDINDICES = @as(u32, 2); pub const D3DVSDE_NORMAL = @as(u32, 3); pub const D3DVSDE_PSIZE = @as(u32, 4); pub const D3DVSDE_DIFFUSE = @as(u32, 5); pub const D3DVSDE_SPECULAR = @as(u32, 6); pub const D3DVSDE_TEXCOORD0 = @as(u32, 7); pub const D3DVSDE_TEXCOORD1 = @as(u32, 8); pub const D3DVSDE_TEXCOORD2 = @as(u32, 9); pub const D3DVSDE_TEXCOORD3 = @as(u32, 10); pub const D3DVSDE_TEXCOORD4 = @as(u32, 11); pub const D3DVSDE_TEXCOORD5 = @as(u32, 12); pub const D3DVSDE_TEXCOORD6 = @as(u32, 13); pub const D3DVSDE_TEXCOORD7 = @as(u32, 14); pub const D3DVSDE_POSITION2 = @as(u32, 15); pub const D3DVSDE_NORMAL2 = @as(u32, 16); pub const D3DVSD_TOKENTYPESHIFT = @as(u32, 29); pub const D3DVSD_STREAMNUMBERSHIFT = @as(u32, 0); pub const D3DVSD_DATALOADTYPESHIFT = @as(u32, 28); pub const D3DVSD_DATATYPESHIFT = @as(u32, 16); pub const D3DVSD_SKIPCOUNTSHIFT = @as(u32, 16); pub const D3DVSD_VERTEXREGSHIFT = @as(u32, 0); pub const D3DVSD_VERTEXREGINSHIFT = @as(u32, 20); pub const D3DVSD_CONSTCOUNTSHIFT = @as(u32, 25); pub const D3DVSD_CONSTADDRESSSHIFT = @as(u32, 0); pub const D3DVSD_CONSTRSSHIFT = @as(u32, 16); pub const D3DVSD_EXTCOUNTSHIFT = @as(u32, 24); pub const D3DVSD_EXTINFOSHIFT = @as(u32, 0); pub const D3DVSD_STREAMTESSSHIFT = @as(u32, 28); pub const DIRECT3D_VERSION = @as(u32, 1792); pub const D3DTRANSFORMCAPS_CLIP = @as(i32, 1); pub const D3DLIGHTINGMODEL_RGB = @as(i32, 1); pub const D3DLIGHTINGMODEL_MONO = @as(i32, 2); pub const D3DLIGHTCAPS_POINT = @as(i32, 1); pub const D3DLIGHTCAPS_SPOT = @as(i32, 2); pub const D3DLIGHTCAPS_DIRECTIONAL = @as(i32, 4); pub const D3DLIGHTCAPS_PARALLELPOINT = @as(i32, 8); pub const D3DLIGHTCAPS_GLSPOT = @as(i32, 16); pub const D3DPMISCCAPS_MASKPLANES = @as(i32, 1); pub const D3DPMISCCAPS_MASKZ = @as(i32, 2); pub const D3DPMISCCAPS_CONFORMANT = @as(i32, 8); pub const D3DPMISCCAPS_CULLNONE = @as(i32, 16); pub const D3DPMISCCAPS_CULLCW = @as(i32, 32); pub const D3DPMISCCAPS_CULLCCW = @as(i32, 64); pub const D3DPRASTERCAPS_DITHER = @as(i32, 1); pub const D3DPRASTERCAPS_ROP2 = @as(i32, 2); pub const D3DPRASTERCAPS_XOR = @as(i32, 4); pub const D3DPRASTERCAPS_PAT = @as(i32, 8); pub const D3DPRASTERCAPS_ZTEST = @as(i32, 16); pub const D3DPRASTERCAPS_SUBPIXEL = @as(i32, 32); pub const D3DPRASTERCAPS_SUBPIXELX = @as(i32, 64); pub const D3DPRASTERCAPS_FOGVERTEX = @as(i32, 128); pub const D3DPRASTERCAPS_FOGTABLE = @as(i32, 256); pub const D3DPRASTERCAPS_STIPPLE = @as(i32, 512); pub const D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT = @as(i32, 1024); pub const D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT = @as(i32, 2048); pub const D3DPRASTERCAPS_ANTIALIASEDGES = @as(i32, 4096); pub const D3DPRASTERCAPS_MIPMAPLODBIAS = @as(i32, 8192); pub const D3DPRASTERCAPS_ZBIAS = @as(i32, 16384); pub const D3DPRASTERCAPS_ZBUFFERLESSHSR = @as(i32, 32768); pub const D3DPRASTERCAPS_FOGRANGE = @as(i32, 65536); pub const D3DPRASTERCAPS_ANISOTROPY = @as(i32, 131072); pub const D3DPRASTERCAPS_WBUFFER = @as(i32, 262144); pub const D3DPRASTERCAPS_TRANSLUCENTSORTINDEPENDENT = @as(i32, 524288); pub const D3DPRASTERCAPS_WFOG = @as(i32, 1048576); pub const D3DPRASTERCAPS_ZFOG = @as(i32, 2097152); pub const D3DPCMPCAPS_NEVER = @as(i32, 1); pub const D3DPCMPCAPS_LESS = @as(i32, 2); pub const D3DPCMPCAPS_EQUAL = @as(i32, 4); pub const D3DPCMPCAPS_LESSEQUAL = @as(i32, 8); pub const D3DPCMPCAPS_GREATER = @as(i32, 16); pub const D3DPCMPCAPS_NOTEQUAL = @as(i32, 32); pub const D3DPCMPCAPS_GREATEREQUAL = @as(i32, 64); pub const D3DPCMPCAPS_ALWAYS = @as(i32, 128); pub const D3DPBLENDCAPS_ZERO = @as(i32, 1); pub const D3DPBLENDCAPS_ONE = @as(i32, 2); pub const D3DPBLENDCAPS_SRCCOLOR = @as(i32, 4); pub const D3DPBLENDCAPS_INVSRCCOLOR = @as(i32, 8); pub const D3DPBLENDCAPS_SRCALPHA = @as(i32, 16); pub const D3DPBLENDCAPS_INVSRCALPHA = @as(i32, 32); pub const D3DPBLENDCAPS_DESTALPHA = @as(i32, 64); pub const D3DPBLENDCAPS_INVDESTALPHA = @as(i32, 128); pub const D3DPBLENDCAPS_DESTCOLOR = @as(i32, 256); pub const D3DPBLENDCAPS_INVDESTCOLOR = @as(i32, 512); pub const D3DPBLENDCAPS_SRCALPHASAT = @as(i32, 1024); pub const D3DPBLENDCAPS_BOTHSRCALPHA = @as(i32, 2048); pub const D3DPBLENDCAPS_BOTHINVSRCALPHA = @as(i32, 4096); pub const D3DPSHADECAPS_COLORFLATMONO = @as(i32, 1); pub const D3DPSHADECAPS_COLORFLATRGB = @as(i32, 2); pub const D3DPSHADECAPS_COLORGOURAUDMONO = @as(i32, 4); pub const D3DPSHADECAPS_COLORGOURAUDRGB = @as(i32, 8); pub const D3DPSHADECAPS_COLORPHONGMONO = @as(i32, 16); pub const D3DPSHADECAPS_COLORPHONGRGB = @as(i32, 32); pub const D3DPSHADECAPS_SPECULARFLATMONO = @as(i32, 64); pub const D3DPSHADECAPS_SPECULARFLATRGB = @as(i32, 128); pub const D3DPSHADECAPS_SPECULARGOURAUDMONO = @as(i32, 256); pub const D3DPSHADECAPS_SPECULARGOURAUDRGB = @as(i32, 512); pub const D3DPSHADECAPS_SPECULARPHONGMONO = @as(i32, 1024); pub const D3DPSHADECAPS_SPECULARPHONGRGB = @as(i32, 2048); pub const D3DPSHADECAPS_ALPHAFLATBLEND = @as(i32, 4096); pub const D3DPSHADECAPS_ALPHAFLATSTIPPLED = @as(i32, 8192); pub const D3DPSHADECAPS_ALPHAGOURAUDBLEND = @as(i32, 16384); pub const D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED = @as(i32, 32768); pub const D3DPSHADECAPS_ALPHAPHONGBLEND = @as(i32, 65536); pub const D3DPSHADECAPS_ALPHAPHONGSTIPPLED = @as(i32, 131072); pub const D3DPSHADECAPS_FOGFLAT = @as(i32, 262144); pub const D3DPSHADECAPS_FOGGOURAUD = @as(i32, 524288); pub const D3DPSHADECAPS_FOGPHONG = @as(i32, 1048576); pub const D3DPTEXTURECAPS_PERSPECTIVE = @as(i32, 1); pub const D3DPTEXTURECAPS_POW2 = @as(i32, 2); pub const D3DPTEXTURECAPS_ALPHA = @as(i32, 4); pub const D3DPTEXTURECAPS_TRANSPARENCY = @as(i32, 8); pub const D3DPTEXTURECAPS_BORDER = @as(i32, 16); pub const D3DPTEXTURECAPS_SQUAREONLY = @as(i32, 32); pub const D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE = @as(i32, 64); pub const D3DPTEXTURECAPS_ALPHAPALETTE = @as(i32, 128); pub const D3DPTEXTURECAPS_NONPOW2CONDITIONAL = @as(i32, 256); pub const D3DPTEXTURECAPS_PROJECTED = @as(i32, 1024); pub const D3DPTEXTURECAPS_CUBEMAP = @as(i32, 2048); pub const D3DPTEXTURECAPS_COLORKEYBLEND = @as(i32, 4096); pub const D3DPTFILTERCAPS_NEAREST = @as(i32, 1); pub const D3DPTFILTERCAPS_LINEAR = @as(i32, 2); pub const D3DPTFILTERCAPS_MIPNEAREST = @as(i32, 4); pub const D3DPTFILTERCAPS_MIPLINEAR = @as(i32, 8); pub const D3DPTFILTERCAPS_LINEARMIPNEAREST = @as(i32, 16); pub const D3DPTFILTERCAPS_LINEARMIPLINEAR = @as(i32, 32); pub const D3DPTFILTERCAPS_MINFPOINT = @as(i32, 256); pub const D3DPTFILTERCAPS_MINFLINEAR = @as(i32, 512); pub const D3DPTFILTERCAPS_MINFANISOTROPIC = @as(i32, 1024); pub const D3DPTFILTERCAPS_MIPFPOINT = @as(i32, 65536); pub const D3DPTFILTERCAPS_MIPFLINEAR = @as(i32, 131072); pub const D3DPTFILTERCAPS_MAGFPOINT = @as(i32, 16777216); pub const D3DPTFILTERCAPS_MAGFLINEAR = @as(i32, 33554432); pub const D3DPTFILTERCAPS_MAGFANISOTROPIC = @as(i32, 67108864); pub const D3DPTFILTERCAPS_MAGFAFLATCUBIC = @as(i32, 134217728); pub const D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC = @as(i32, 268435456); pub const D3DPTBLENDCAPS_DECAL = @as(i32, 1); pub const D3DPTBLENDCAPS_MODULATE = @as(i32, 2); pub const D3DPTBLENDCAPS_DECALALPHA = @as(i32, 4); pub const D3DPTBLENDCAPS_MODULATEALPHA = @as(i32, 8); pub const D3DPTBLENDCAPS_DECALMASK = @as(i32, 16); pub const D3DPTBLENDCAPS_MODULATEMASK = @as(i32, 32); pub const D3DPTBLENDCAPS_COPY = @as(i32, 64); pub const D3DPTBLENDCAPS_ADD = @as(i32, 128); pub const D3DPTADDRESSCAPS_WRAP = @as(i32, 1); pub const D3DPTADDRESSCAPS_MIRROR = @as(i32, 2); pub const D3DPTADDRESSCAPS_CLAMP = @as(i32, 4); pub const D3DPTADDRESSCAPS_BORDER = @as(i32, 8); pub const D3DPTADDRESSCAPS_INDEPENDENTUV = @as(i32, 16); pub const D3DSTENCILCAPS_KEEP = @as(i32, 1); pub const D3DSTENCILCAPS_ZERO = @as(i32, 2); pub const D3DSTENCILCAPS_REPLACE = @as(i32, 4); pub const D3DSTENCILCAPS_INCRSAT = @as(i32, 8); pub const D3DSTENCILCAPS_DECRSAT = @as(i32, 16); pub const D3DSTENCILCAPS_INVERT = @as(i32, 32); pub const D3DSTENCILCAPS_INCR = @as(i32, 64); pub const D3DSTENCILCAPS_DECR = @as(i32, 128); pub const D3DTEXOPCAPS_DISABLE = @as(i32, 1); pub const D3DTEXOPCAPS_SELECTARG1 = @as(i32, 2); pub const D3DTEXOPCAPS_SELECTARG2 = @as(i32, 4); pub const D3DTEXOPCAPS_MODULATE = @as(i32, 8); pub const D3DTEXOPCAPS_MODULATE2X = @as(i32, 16); pub const D3DTEXOPCAPS_MODULATE4X = @as(i32, 32); pub const D3DTEXOPCAPS_ADD = @as(i32, 64); pub const D3DTEXOPCAPS_ADDSIGNED = @as(i32, 128); pub const D3DTEXOPCAPS_ADDSIGNED2X = @as(i32, 256); pub const D3DTEXOPCAPS_SUBTRACT = @as(i32, 512); pub const D3DTEXOPCAPS_ADDSMOOTH = @as(i32, 1024); pub const D3DTEXOPCAPS_BLENDDIFFUSEALPHA = @as(i32, 2048); pub const D3DTEXOPCAPS_BLENDTEXTUREALPHA = @as(i32, 4096); pub const D3DTEXOPCAPS_BLENDFACTORALPHA = @as(i32, 8192); pub const D3DTEXOPCAPS_BLENDTEXTUREALPHAPM = @as(i32, 16384); pub const D3DTEXOPCAPS_BLENDCURRENTALPHA = @as(i32, 32768); pub const D3DTEXOPCAPS_PREMODULATE = @as(i32, 65536); pub const D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR = @as(i32, 131072); pub const D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA = @as(i32, 262144); pub const D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR = @as(i32, 524288); pub const D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA = @as(i32, 1048576); pub const D3DTEXOPCAPS_BUMPENVMAP = @as(i32, 2097152); pub const D3DTEXOPCAPS_BUMPENVMAPLUMINANCE = @as(i32, 4194304); pub const D3DTEXOPCAPS_DOTPRODUCT3 = @as(i32, 8388608); pub const D3DFVFCAPS_TEXCOORDCOUNTMASK = @as(i32, 65535); pub const D3DFVFCAPS_DONOTSTRIPELEMENTS = @as(i32, 524288); pub const D3DDD_COLORMODEL = @as(i32, 1); pub const D3DDD_DEVCAPS = @as(i32, 2); pub const D3DDD_TRANSFORMCAPS = @as(i32, 4); pub const D3DDD_LIGHTINGCAPS = @as(i32, 8); pub const D3DDD_BCLIPPING = @as(i32, 16); pub const D3DDD_LINECAPS = @as(i32, 32); pub const D3DDD_TRICAPS = @as(i32, 64); pub const D3DDD_DEVICERENDERBITDEPTH = @as(i32, 128); pub const D3DDD_DEVICEZBUFFERBITDEPTH = @as(i32, 256); pub const D3DDD_MAXBUFFERSIZE = @as(i32, 512); pub const D3DDD_MAXVERTEXCOUNT = @as(i32, 1024); pub const D3DDEVCAPS_FLOATTLVERTEX = @as(i32, 1); pub const D3DDEVCAPS_SORTINCREASINGZ = @as(i32, 2); pub const D3DDEVCAPS_SORTDECREASINGZ = @as(i32, 4); pub const D3DDEVCAPS_SORTEXACT = @as(i32, 8); pub const D3DDEVCAPS_EXECUTESYSTEMMEMORY = @as(i32, 16); pub const D3DDEVCAPS_EXECUTEVIDEOMEMORY = @as(i32, 32); pub const D3DDEVCAPS_TLVERTEXSYSTEMMEMORY = @as(i32, 64); pub const D3DDEVCAPS_TLVERTEXVIDEOMEMORY = @as(i32, 128); pub const D3DDEVCAPS_TEXTURESYSTEMMEMORY = @as(i32, 256); pub const D3DDEVCAPS_TEXTUREVIDEOMEMORY = @as(i32, 512); pub const D3DDEVCAPS_DRAWPRIMTLVERTEX = @as(i32, 1024); pub const D3DDEVCAPS_CANRENDERAFTERFLIP = @as(i32, 2048); pub const D3DDEVCAPS_TEXTURENONLOCALVIDMEM = @as(i32, 4096); pub const D3DDEVCAPS_DRAWPRIMITIVES2 = @as(i32, 8192); pub const D3DDEVCAPS_SEPARATETEXTUREMEMORIES = @as(i32, 16384); pub const D3DDEVCAPS_DRAWPRIMITIVES2EX = @as(i32, 32768); pub const D3DDEVCAPS_HWTRANSFORMANDLIGHT = @as(i32, 65536); pub const D3DDEVCAPS_CANBLTSYSTONONLOCAL = @as(i32, 131072); pub const D3DDEVCAPS_HWRASTERIZATION = @as(i32, 524288); pub const D3DVTXPCAPS_TEXGEN = @as(i32, 1); pub const D3DVTXPCAPS_MATERIALSOURCE7 = @as(i32, 2); pub const D3DVTXPCAPS_VERTEXFOG = @as(i32, 4); pub const D3DVTXPCAPS_DIRECTIONALLIGHTS = @as(i32, 8); pub const D3DVTXPCAPS_POSITIONALLIGHTS = @as(i32, 16); pub const D3DVTXPCAPS_LOCALVIEWER = @as(i32, 32); pub const D3DFDS_COLORMODEL = @as(i32, 1); pub const D3DFDS_GUID = @as(i32, 2); pub const D3DFDS_HARDWARE = @as(i32, 4); pub const D3DFDS_TRIANGLES = @as(i32, 8); pub const D3DFDS_LINES = @as(i32, 16); pub const D3DFDS_MISCCAPS = @as(i32, 32); pub const D3DFDS_RASTERCAPS = @as(i32, 64); pub const D3DFDS_ZCMPCAPS = @as(i32, 128); pub const D3DFDS_ALPHACMPCAPS = @as(i32, 256); pub const D3DFDS_SRCBLENDCAPS = @as(i32, 512); pub const D3DFDS_DSTBLENDCAPS = @as(i32, 1024); pub const D3DFDS_SHADECAPS = @as(i32, 2048); pub const D3DFDS_TEXTURECAPS = @as(i32, 4096); pub const D3DFDS_TEXTUREFILTERCAPS = @as(i32, 8192); pub const D3DFDS_TEXTUREBLENDCAPS = @as(i32, 16384); pub const D3DFDS_TEXTUREADDRESSCAPS = @as(i32, 32768); pub const D3DDEB_BUFSIZE = @as(i32, 1); pub const D3DDEB_CAPS = @as(i32, 2); pub const D3DDEB_LPDATA = @as(i32, 4); pub const D3DDEBCAPS_SYSTEMMEMORY = @as(i32, 1); pub const D3DDEBCAPS_VIDEOMEMORY = @as(i32, 2); pub const D3DMAXUSERCLIPPLANES = @as(u32, 32); pub const D3DCLIPPLANE0 = @as(u32, 1); pub const D3DCLIPPLANE1 = @as(u32, 2); pub const D3DCLIPPLANE2 = @as(u32, 4); pub const D3DCLIPPLANE3 = @as(u32, 8); pub const D3DCLIPPLANE4 = @as(u32, 16); pub const D3DCLIPPLANE5 = @as(u32, 32); pub const D3DCLIP_LEFT = @as(i32, 1); pub const D3DCLIP_RIGHT = @as(i32, 2); pub const D3DCLIP_TOP = @as(i32, 4); pub const D3DCLIP_BOTTOM = @as(i32, 8); pub const D3DCLIP_FRONT = @as(i32, 16); pub const D3DCLIP_BACK = @as(i32, 32); pub const D3DCLIP_GEN0 = @as(i32, 64); pub const D3DCLIP_GEN1 = @as(i32, 128); pub const D3DCLIP_GEN2 = @as(i32, 256); pub const D3DCLIP_GEN3 = @as(i32, 512); pub const D3DCLIP_GEN4 = @as(i32, 1024); pub const D3DCLIP_GEN5 = @as(i32, 2048); pub const D3DSTATUS_CLIPUNIONLEFT = @as(i32, 1); pub const D3DSTATUS_CLIPUNIONRIGHT = @as(i32, 2); pub const D3DSTATUS_CLIPUNIONTOP = @as(i32, 4); pub const D3DSTATUS_CLIPUNIONBOTTOM = @as(i32, 8); pub const D3DSTATUS_CLIPUNIONFRONT = @as(i32, 16); pub const D3DSTATUS_CLIPUNIONBACK = @as(i32, 32); pub const D3DSTATUS_CLIPUNIONGEN0 = @as(i32, 64); pub const D3DSTATUS_CLIPUNIONGEN1 = @as(i32, 128); pub const D3DSTATUS_CLIPUNIONGEN2 = @as(i32, 256); pub const D3DSTATUS_CLIPUNIONGEN3 = @as(i32, 512); pub const D3DSTATUS_CLIPUNIONGEN4 = @as(i32, 1024); pub const D3DSTATUS_CLIPUNIONGEN5 = @as(i32, 2048); pub const D3DSTATUS_CLIPINTERSECTIONLEFT = @as(i32, 4096); pub const D3DSTATUS_CLIPINTERSECTIONRIGHT = @as(i32, 8192); pub const D3DSTATUS_CLIPINTERSECTIONTOP = @as(i32, 16384); pub const D3DSTATUS_CLIPINTERSECTIONBOTTOM = @as(i32, 32768); pub const D3DSTATUS_CLIPINTERSECTIONFRONT = @as(i32, 65536); pub const D3DSTATUS_CLIPINTERSECTIONBACK = @as(i32, 131072); pub const D3DSTATUS_CLIPINTERSECTIONGEN0 = @as(i32, 262144); pub const D3DSTATUS_CLIPINTERSECTIONGEN1 = @as(i32, 524288); pub const D3DSTATUS_CLIPINTERSECTIONGEN2 = @as(i32, 1048576); pub const D3DSTATUS_CLIPINTERSECTIONGEN3 = @as(i32, 2097152); pub const D3DSTATUS_CLIPINTERSECTIONGEN4 = @as(i32, 4194304); pub const D3DSTATUS_CLIPINTERSECTIONGEN5 = @as(i32, 8388608); pub const D3DSTATUS_ZNOTVISIBLE = @as(i32, 16777216); pub const D3DTRANSFORM_CLIPPED = @as(i32, 1); pub const D3DTRANSFORM_UNCLIPPED = @as(i32, 2); pub const D3DLIGHT_ACTIVE = @as(u32, 1); pub const D3DLIGHT_NO_SPECULAR = @as(u32, 2); pub const D3DCOLOR_MONO = @as(u32, 1); pub const D3DCOLOR_RGB = @as(u32, 2); pub const D3DCLEAR_TARGET = @as(i32, 1); pub const D3DCLEAR_ZBUFFER = @as(i32, 2); pub const D3DCLEAR_STENCIL = @as(i32, 4); pub const D3DSTATE_OVERRIDE_BIAS = @as(u32, 256); pub const D3DRENDERSTATE_WRAPBIAS = @as(u32, 128); pub const D3DWRAP_U = @as(i32, 1); pub const D3DWRAP_V = @as(i32, 2); pub const D3DWRAPCOORD_0 = @as(i32, 1); pub const D3DWRAPCOORD_1 = @as(i32, 2); pub const D3DWRAPCOORD_2 = @as(i32, 4); pub const D3DWRAPCOORD_3 = @as(i32, 8); pub const D3DPROCESSVERTICES_TRANSFORMLIGHT = @as(i32, 0); pub const D3DPROCESSVERTICES_TRANSFORM = @as(i32, 1); pub const D3DPROCESSVERTICES_COPY = @as(i32, 2); pub const D3DPROCESSVERTICES_OPMASK = @as(i32, 7); pub const D3DPROCESSVERTICES_UPDATEEXTENTS = @as(i32, 8); pub const D3DPROCESSVERTICES_NOCOLOR = @as(i32, 16); pub const D3DTSS_TCI_PASSTHRU = @as(u32, 0); pub const D3DTSS_TCI_CAMERASPACENORMAL = @as(u32, 65536); pub const D3DTSS_TCI_CAMERASPACEPOSITION = @as(u32, 131072); pub const D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR = @as(u32, 196608); pub const D3DTA_SELECTMASK = @as(u32, 15); pub const D3DTA_DIFFUSE = @as(u32, 0); pub const D3DTA_CURRENT = @as(u32, 1); pub const D3DTA_TEXTURE = @as(u32, 2); pub const D3DTA_TFACTOR = @as(u32, 3); pub const D3DTA_SPECULAR = @as(u32, 4); pub const D3DTA_COMPLEMENT = @as(u32, 16); pub const D3DTA_ALPHAREPLICATE = @as(u32, 32); pub const D3DTRIFLAG_START = @as(i32, 0); pub const D3DTRIFLAG_ODD = @as(i32, 30); pub const D3DTRIFLAG_EVEN = @as(i32, 31); pub const D3DTRIFLAG_EDGEENABLE1 = @as(i32, 256); pub const D3DTRIFLAG_EDGEENABLE2 = @as(i32, 512); pub const D3DTRIFLAG_EDGEENABLE3 = @as(i32, 1024); pub const D3DSETSTATUS_STATUS = @as(i32, 1); pub const D3DSETSTATUS_EXTENTS = @as(i32, 2); pub const D3DCLIPSTATUS_STATUS = @as(i32, 1); pub const D3DCLIPSTATUS_EXTENTS2 = @as(i32, 2); pub const D3DCLIPSTATUS_EXTENTS3 = @as(i32, 4); pub const D3DEXECUTE_CLIPPED = @as(i32, 1); pub const D3DEXECUTE_UNCLIPPED = @as(i32, 2); pub const D3DPAL_FREE = @as(u32, 0); pub const D3DPAL_READONLY = @as(u32, 64); pub const D3DPAL_RESERVED = @as(u32, 128); pub const D3DVBCAPS_SYSTEMMEMORY = @as(i32, 2048); pub const D3DVBCAPS_WRITEONLY = @as(i32, 65536); pub const D3DVBCAPS_OPTIMIZED = @as(i32, -2147483648); pub const D3DVBCAPS_DONOTCLIP = @as(i32, 1); pub const D3DVOP_LIGHT = @as(u32, 1024); pub const D3DVOP_TRANSFORM = @as(u32, 1); pub const D3DVOP_CLIP = @as(u32, 4); pub const D3DVOP_EXTENTS = @as(u32, 8); pub const D3DPV_DONOTCOPYDATA = @as(u32, 1); pub const D3DFVF_RESERVED0 = @as(u32, 1); pub const D3DFVF_POSITION_MASK = @as(u32, 14); pub const D3DFVF_XYZ = @as(u32, 2); pub const D3DFVF_XYZRHW = @as(u32, 4); pub const D3DFVF_XYZB1 = @as(u32, 6); pub const D3DFVF_XYZB2 = @as(u32, 8); pub const D3DFVF_XYZB3 = @as(u32, 10); pub const D3DFVF_XYZB4 = @as(u32, 12); pub const D3DFVF_XYZB5 = @as(u32, 14); pub const D3DFVF_NORMAL = @as(u32, 16); pub const D3DFVF_RESERVED1 = @as(u32, 32); pub const D3DFVF_DIFFUSE = @as(u32, 64); pub const D3DFVF_SPECULAR = @as(u32, 128); pub const D3DFVF_TEXCOUNT_MASK = @as(u32, 3840); pub const D3DFVF_TEXCOUNT_SHIFT = @as(u32, 8); pub const D3DFVF_TEX0 = @as(u32, 0); pub const D3DFVF_TEX1 = @as(u32, 256); pub const D3DFVF_TEX2 = @as(u32, 512); pub const D3DFVF_TEX3 = @as(u32, 768); pub const D3DFVF_TEX4 = @as(u32, 1024); pub const D3DFVF_TEX5 = @as(u32, 1280); pub const D3DFVF_TEX6 = @as(u32, 1536); pub const D3DFVF_TEX7 = @as(u32, 1792); pub const D3DFVF_TEX8 = @as(u32, 2048); pub const D3DFVF_RESERVED2 = @as(u32, 61440); pub const D3DDP_MAXTEXCOORD = @as(u32, 8); pub const D3DVIS_INSIDE_FRUSTUM = @as(u32, 0); pub const D3DVIS_INTERSECT_FRUSTUM = @as(u32, 1); pub const D3DVIS_OUTSIDE_FRUSTUM = @as(u32, 2); pub const D3DVIS_INSIDE_LEFT = @as(u32, 0); pub const D3DVIS_INTERSECT_LEFT = @as(u32, 4); pub const D3DVIS_OUTSIDE_LEFT = @as(u32, 8); pub const D3DVIS_INSIDE_RIGHT = @as(u32, 0); pub const D3DVIS_INTERSECT_RIGHT = @as(u32, 16); pub const D3DVIS_OUTSIDE_RIGHT = @as(u32, 32); pub const D3DVIS_INSIDE_TOP = @as(u32, 0); pub const D3DVIS_INTERSECT_TOP = @as(u32, 64); pub const D3DVIS_OUTSIDE_TOP = @as(u32, 128); pub const D3DVIS_INSIDE_BOTTOM = @as(u32, 0); pub const D3DVIS_INTERSECT_BOTTOM = @as(u32, 256); pub const D3DVIS_OUTSIDE_BOTTOM = @as(u32, 512); pub const D3DVIS_INSIDE_NEAR = @as(u32, 0); pub const D3DVIS_INTERSECT_NEAR = @as(u32, 1024); pub const D3DVIS_OUTSIDE_NEAR = @as(u32, 2048); pub const D3DVIS_INSIDE_FAR = @as(u32, 0); pub const D3DVIS_INTERSECT_FAR = @as(u32, 4096); pub const D3DVIS_OUTSIDE_FAR = @as(u32, 8192); pub const D3DVIS_MASK_FRUSTUM = @as(u32, 3); pub const D3DVIS_MASK_LEFT = @as(u32, 12); pub const D3DVIS_MASK_RIGHT = @as(u32, 48); pub const D3DVIS_MASK_TOP = @as(u32, 192); pub const D3DVIS_MASK_BOTTOM = @as(u32, 768); pub const D3DVIS_MASK_NEAR = @as(u32, 3072); pub const D3DVIS_MASK_FAR = @as(u32, 12288); pub const D3DDEVINFOID_TEXTUREMANAGER = @as(u32, 1); pub const D3DDEVINFOID_D3DTEXTUREMANAGER = @as(u32, 2); pub const D3DDEVINFOID_TEXTURING = @as(u32, 3); pub const D3DFVF_TEXTUREFORMAT2 = @as(u32, 0); pub const D3DFVF_TEXTUREFORMAT1 = @as(u32, 3); pub const D3DFVF_TEXTUREFORMAT3 = @as(u32, 1); pub const D3DFVF_TEXTUREFORMAT4 = @as(u32, 2); pub const ROTFLAGS_REGISTRATIONKEEPSALIVE = @as(u32, 1); pub const ROTFLAGS_ALLOWANYCLIENT = @as(u32, 2); pub const ROT_COMPARE_MAX = @as(u32, 2048); pub const WDT_INPROC_CALL = @as(u32, 1215587415); pub const WDT_REMOTE_CALL = @as(u32, 1383359575); pub const WDT_INPROC64_CALL = @as(u32, 1349805143); pub const PROCESS_HEAP_REGION = @as(u32, 1); pub const PROCESS_HEAP_UNCOMMITTED_RANGE = @as(u32, 2); pub const PROCESS_HEAP_ENTRY_BUSY = @as(u32, 4); pub const PROCESS_HEAP_SEG_ALLOC = @as(u32, 8); pub const PROCESS_HEAP_ENTRY_MOVEABLE = @as(u32, 16); pub const PROCESS_HEAP_ENTRY_DDESHARE = @as(u32, 32); pub const LMEM_NOCOMPACT = @as(u32, 16); pub const LMEM_NODISCARD = @as(u32, 32); pub const LMEM_MODIFY = @as(u32, 128); pub const LMEM_DISCARDABLE = @as(u32, 3840); pub const LMEM_VALID_FLAGS = @as(u32, 3954); pub const LMEM_INVALID_HANDLE = @as(u32, 32768); pub const LMEM_DISCARDED = @as(u32, 16384); pub const LMEM_LOCKCOUNT = @as(u32, 255); pub const NUMA_NO_PREFERRED_NODE = @as(u32, 4294967295); pub const REDBOOK_DIGITAL_AUDIO_EXTRACTION_INFO_VERSION = @as(u32, 1); pub const FACILITY_MCA_ERROR_CODE = @as(u32, 5); pub const IO_ERR_INSUFFICIENT_RESOURCES = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479678)); pub const IO_ERR_DRIVER_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479676)); pub const IO_ERR_SEEK_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479674)); pub const IO_ERR_BAD_BLOCK = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479673)); pub const IO_ERR_TIMEOUT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479671)); pub const IO_ERR_CONTROLLER_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479669)); pub const IO_ERR_NOT_READY = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479665)); pub const IO_ERR_INVALID_REQUEST = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479664)); pub const IO_ERR_RESET = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479661)); pub const IO_ERR_BAD_FIRMWARE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479655)); pub const IO_WRN_BAD_FIRMWARE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221478)); pub const IO_WRITE_CACHE_ENABLED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221472)); pub const IO_RECOVERED_VIA_ECC = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221471)); pub const IO_WRITE_CACHE_DISABLED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221470)); pub const IO_WARNING_PAGING_FAILURE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221453)); pub const IO_WRN_FAILURE_PREDICTED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221452)); pub const IO_WARNING_ALLOCATION_FAILED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221448)); pub const IO_WARNING_DUPLICATE_SIGNATURE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221446)); pub const IO_WARNING_DUPLICATE_PATH = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221445)); pub const IO_WARNING_WRITE_FUA_PROBLEM = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221372)); pub const IO_WARNING_VOLUME_LOST_DISK_EXTENT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221362)); pub const IO_WARNING_DEVICE_HAS_INTERNAL_DUMP = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221361)); pub const IO_WARNING_SOFT_THRESHOLD_REACHED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221360)); pub const IO_WARNING_SOFT_THRESHOLD_REACHED_EX = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221359)); pub const IO_WARNING_SOFT_THRESHOLD_REACHED_EX_LUN_LUN = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221358)); pub const IO_WARNING_SOFT_THRESHOLD_REACHED_EX_LUN_POOL = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221357)); pub const IO_WARNING_SOFT_THRESHOLD_REACHED_EX_POOL_LUN = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221356)); pub const IO_WARNING_SOFT_THRESHOLD_REACHED_EX_POOL_POOL = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221355)); pub const IO_ERROR_DISK_RESOURCES_EXHAUSTED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479530)); pub const IO_WARNING_DISK_CAPACITY_CHANGED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221353)); pub const IO_WARNING_DISK_PROVISIONING_TYPE_CHANGED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221352)); pub const IO_WARNING_IO_OPERATION_RETRIED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221351)); pub const IO_ERROR_IO_HARDWARE_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479526)); pub const IO_WARNING_COMPLETION_TIME = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221349)); pub const IO_WARNING_DISK_SURPRISE_REMOVED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221347)); pub const IO_WARNING_REPEATED_DISK_GUID = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221346)); pub const IO_WARNING_DISK_FIRMWARE_UPDATED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, 1074004127)); pub const IO_ERR_RETRY_SUCCEEDED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, 262145)); pub const IO_DUMP_CREATION_SUCCESS = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, 262306)); pub const IO_FILE_QUOTA_THRESHOLD = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, 1074004004)); pub const IO_FILE_QUOTA_LIMIT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, 1074004005)); pub const IO_FILE_QUOTA_STARTED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, 1074004006)); pub const IO_FILE_QUOTA_SUCCEEDED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, 1074004007)); pub const IO_INFO_THROTTLE_COMPLETE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, 1074004087)); pub const IO_CDROM_EXCLUSIVE_LOCK = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, 1074004101)); pub const IO_WARNING_ADAPTER_FIRMWARE_UPDATED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, 1074004128)); pub const IO_FILE_QUOTA_FAILED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221464)); pub const IO_LOST_DELAYED_WRITE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221454)); pub const IO_WARNING_INTERRUPT_STILL_PENDING = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221451)); pub const IO_DRIVER_CANCEL_TIMEOUT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221450)); pub const IO_WARNING_LOG_FLUSH_FAILED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221447)); pub const IO_WARNING_BUS_RESET = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221386)); pub const IO_WARNING_RESET = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221375)); pub const IO_LOST_DELAYED_WRITE_NETWORK_DISCONNECTED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221365)); pub const IO_LOST_DELAYED_WRITE_NETWORK_SERVER_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221364)); pub const IO_LOST_DELAYED_WRITE_NETWORK_LOCAL_DISK_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221363)); pub const IO_WARNING_DUMP_DISABLED_DEVICE_GONE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147221348)); pub const IO_ERR_CONFIGURATION_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479677)); pub const IO_ERR_PARITY = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479675)); pub const IO_ERR_OVERRUN_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479672)); pub const IO_ERR_SEQUENCE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479670)); pub const IO_ERR_INTERNAL_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479668)); pub const IO_ERR_INCORRECT_IRQL = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479667)); pub const IO_ERR_INVALID_IOBASE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479666)); pub const IO_ERR_VERSION = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479663)); pub const IO_ERR_LAYERED_FAILURE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479662)); pub const IO_ERR_PROTOCOL = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479660)); pub const IO_ERR_MEMORY_CONFLICT_DETECTED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479659)); pub const IO_ERR_PORT_CONFLICT_DETECTED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479658)); pub const IO_ERR_DMA_CONFLICT_DETECTED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479657)); pub const IO_ERR_IRQ_CONFLICT_DETECTED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479656)); pub const IO_ERR_DMA_RESOURCE_CONFLICT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479653)); pub const IO_ERR_INTERRUPT_RESOURCE_CONFLICT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479652)); pub const IO_ERR_MEMORY_RESOURCE_CONFLICT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479651)); pub const IO_ERR_PORT_RESOURCE_CONFLICT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479650)); pub const IO_BAD_BLOCK_WITH_NAME = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479649)); pub const IO_FILE_SYSTEM_CORRUPT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479639)); pub const IO_FILE_QUOTA_CORRUPT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479638)); pub const IO_SYSTEM_SLEEP_FAILED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479637)); pub const IO_DUMP_POINTER_FAILURE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479636)); pub const IO_DUMP_DRIVER_LOAD_FAILURE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479635)); pub const IO_DUMP_INITIALIZATION_FAILURE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479634)); pub const IO_DUMP_DUMPFILE_CONFLICT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479633)); pub const IO_DUMP_DIRECT_CONFIG_FAILED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479632)); pub const IO_DUMP_PAGE_CONFIG_FAILED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479631)); pub const IO_FILE_SYSTEM_CORRUPT_WITH_NAME = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479625)); pub const IO_ERR_THREAD_STUCK_IN_DEVICE_DRIVER = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479572)); pub const IO_ERR_PORT_TIMEOUT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479563)); pub const IO_ERROR_DUMP_CREATION_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479519)); pub const IO_DUMP_CALLBACK_EXCEPTION = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073479517)); pub const MCA_INFO_CPU_THERMAL_THROTTLING_REMOVED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, 1074069616)); pub const MCA_INFO_NO_MORE_CORRECTED_ERROR_LOGS = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, 1074069619)); pub const MCA_INFO_MEMORY_PAGE_MARKED_BAD = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, 1074069620)); pub const MCA_WARNING_CACHE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155908)); pub const MCA_WARNING_TLB = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155906)); pub const MCA_WARNING_CPU_BUS = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155904)); pub const MCA_WARNING_REGISTER_FILE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155902)); pub const MCA_WARNING_MAS = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155900)); pub const MCA_WARNING_MEM_UNKNOWN = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155898)); pub const MCA_WARNING_MEM_1_2 = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155896)); pub const MCA_WARNING_MEM_1_2_5 = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155894)); pub const MCA_WARNING_MEM_1_2_5_4 = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155892)); pub const MCA_WARNING_SYSTEM_EVENT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155890)); pub const MCA_WARNING_PCI_BUS_PARITY = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155888)); pub const MCA_WARNING_PCI_BUS_PARITY_NO_INFO = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155886)); pub const MCA_WARNING_PCI_BUS_SERR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155884)); pub const MCA_WARNING_PCI_BUS_SERR_NO_INFO = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155882)); pub const MCA_WARNING_PCI_BUS_MASTER_ABORT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155880)); pub const MCA_WARNING_PCI_BUS_MASTER_ABORT_NO_INFO = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155878)); pub const MCA_WARNING_PCI_BUS_TIMEOUT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155876)); pub const MCA_WARNING_PCI_BUS_TIMEOUT_NO_INFO = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155874)); pub const MCA_WARNING_PCI_BUS_UNKNOWN = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155872)); pub const MCA_WARNING_PCI_DEVICE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155870)); pub const MCA_WARNING_SMBIOS = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155868)); pub const MCA_WARNING_PLATFORM_SPECIFIC = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155866)); pub const MCA_WARNING_UNKNOWN = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155864)); pub const MCA_WARNING_UNKNOWN_NO_CPU = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155862)); pub const MCA_WARNING_CMC_THRESHOLD_EXCEEDED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155859)); pub const MCA_WARNING_CPE_THRESHOLD_EXCEEDED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155858)); pub const MCA_WARNING_CPU_THERMAL_THROTTLED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155857)); pub const MCA_WARNING_CPU = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2147155855)); pub const MCA_ERROR_CACHE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414083)); pub const MCA_ERROR_TLB = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414081)); pub const MCA_ERROR_CPU_BUS = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414079)); pub const MCA_ERROR_REGISTER_FILE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414077)); pub const MCA_ERROR_MAS = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414075)); pub const MCA_ERROR_MEM_UNKNOWN = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414073)); pub const MCA_ERROR_MEM_1_2 = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414071)); pub const MCA_ERROR_MEM_1_2_5 = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414069)); pub const MCA_ERROR_MEM_1_2_5_4 = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414067)); pub const MCA_ERROR_SYSTEM_EVENT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414065)); pub const MCA_ERROR_PCI_BUS_PARITY = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414063)); pub const MCA_ERROR_PCI_BUS_PARITY_NO_INFO = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414061)); pub const MCA_ERROR_PCI_BUS_SERR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414059)); pub const MCA_ERROR_PCI_BUS_SERR_NO_INFO = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414057)); pub const MCA_ERROR_PCI_BUS_MASTER_ABORT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414055)); pub const MCA_ERROR_PCI_BUS_MASTER_ABORT_NO_INFO = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414053)); pub const MCA_ERROR_PCI_BUS_TIMEOUT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414051)); pub const MCA_ERROR_PCI_BUS_TIMEOUT_NO_INFO = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414049)); pub const MCA_ERROR_PCI_BUS_UNKNOWN = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414047)); pub const MCA_ERROR_PCI_DEVICE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414045)); pub const MCA_ERROR_SMBIOS = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414043)); pub const MCA_ERROR_PLATFORM_SPECIFIC = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414041)); pub const MCA_ERROR_UNKNOWN = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414039)); pub const MCA_ERROR_UNKNOWN_NO_CPU = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414037)); pub const MCA_ERROR_CPU = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414030)); pub const MCA_MEMORYHIERARCHY_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414024)); pub const MCA_TLB_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414023)); pub const MCA_BUS_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414022)); pub const MCA_BUS_TIMEOUT_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414021)); pub const MCA_INTERNALTIMER_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414020)); pub const MCA_MICROCODE_ROM_PARITY_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414018)); pub const MCA_EXTERNAL_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414017)); pub const MCA_FRC_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073414016)); pub const VOLMGR_KSR_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2143813631)); pub const VOLMGR_KSR_READ_ERROR = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2143813630)); pub const VOLMGR_KSR_BYPASS = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -2143813629)); pub const GUID_DEVINTERFACE_DMR = Guid.initString("d0875fb4-2196-4c7a-a63d-e416addd60a1"); pub const GUID_DEVINTERFACE_DMP = Guid.initString("25b4e268-2a05-496e-803b-266837fbda4b"); pub const GUID_DEVINTERFACE_DMS = Guid.initString("c96037ae-a558-4470-b432-115a31b85553"); //-------------------------------------------------------------------------------- // Section: Types (261) //-------------------------------------------------------------------------------- pub const ALERT_SYSTEM_SEV = enum(u32) { INFORMATIONAL = 1, WARNING = 2, ERROR = 3, QUERY = 4, CRITICAL = 5, }; pub const ALERT_SYSTEM_INFORMATIONAL = ALERT_SYSTEM_SEV.INFORMATIONAL; pub const ALERT_SYSTEM_WARNING = ALERT_SYSTEM_SEV.WARNING; pub const ALERT_SYSTEM_ERROR = ALERT_SYSTEM_SEV.ERROR; pub const ALERT_SYSTEM_QUERY = ALERT_SYSTEM_SEV.QUERY; pub const ALERT_SYSTEM_CRITICAL = ALERT_SYSTEM_SEV.CRITICAL; pub const APPCOMMAND_ID = enum(u32) { BROWSER_BACKWARD = 1, BROWSER_FORWARD = 2, BROWSER_REFRESH = 3, BROWSER_STOP = 4, BROWSER_SEARCH = 5, BROWSER_FAVORITES = 6, BROWSER_HOME = 7, VOLUME_MUTE = 8, VOLUME_DOWN = 9, VOLUME_UP = 10, MEDIA_NEXTTRACK = 11, MEDIA_PREVIOUSTRACK = 12, MEDIA_STOP = 13, MEDIA_PLAY_PAUSE = 14, LAUNCH_MAIL = 15, LAUNCH_MEDIA_SELECT = 16, LAUNCH_APP1 = 17, LAUNCH_APP2 = 18, BASS_DOWN = 19, BASS_BOOST = 20, BASS_UP = 21, TREBLE_DOWN = 22, TREBLE_UP = 23, MICROPHONE_VOLUME_MUTE = 24, MICROPHONE_VOLUME_DOWN = 25, MICROPHONE_VOLUME_UP = 26, HELP = 27, FIND = 28, NEW = 29, OPEN = 30, CLOSE = 31, SAVE = 32, PRINT = 33, UNDO = 34, REDO = 35, COPY = 36, CUT = 37, PASTE = 38, REPLY_TO_MAIL = 39, FORWARD_MAIL = 40, SEND_MAIL = 41, SPELL_CHECK = 42, DICTATE_OR_COMMAND_CONTROL_TOGGLE = 43, MIC_ON_OFF_TOGGLE = 44, CORRECTION_LIST = 45, MEDIA_PLAY = 46, MEDIA_PAUSE = 47, MEDIA_RECORD = 48, MEDIA_FAST_FORWARD = 49, MEDIA_REWIND = 50, MEDIA_CHANNEL_UP = 51, MEDIA_CHANNEL_DOWN = 52, DELETE = 53, DWM_FLIP3D = 54, }; pub const APPCOMMAND_BROWSER_BACKWARD = APPCOMMAND_ID.BROWSER_BACKWARD; pub const APPCOMMAND_BROWSER_FORWARD = APPCOMMAND_ID.BROWSER_FORWARD; pub const APPCOMMAND_BROWSER_REFRESH = APPCOMMAND_ID.BROWSER_REFRESH; pub const APPCOMMAND_BROWSER_STOP = APPCOMMAND_ID.BROWSER_STOP; pub const APPCOMMAND_BROWSER_SEARCH = APPCOMMAND_ID.BROWSER_SEARCH; pub const APPCOMMAND_BROWSER_FAVORITES = APPCOMMAND_ID.BROWSER_FAVORITES; pub const APPCOMMAND_BROWSER_HOME = APPCOMMAND_ID.BROWSER_HOME; pub const APPCOMMAND_VOLUME_MUTE = APPCOMMAND_ID.VOLUME_MUTE; pub const APPCOMMAND_VOLUME_DOWN = APPCOMMAND_ID.VOLUME_DOWN; pub const APPCOMMAND_VOLUME_UP = APPCOMMAND_ID.VOLUME_UP; pub const APPCOMMAND_MEDIA_NEXTTRACK = APPCOMMAND_ID.MEDIA_NEXTTRACK; pub const APPCOMMAND_MEDIA_PREVIOUSTRACK = APPCOMMAND_ID.MEDIA_PREVIOUSTRACK; pub const APPCOMMAND_MEDIA_STOP = APPCOMMAND_ID.MEDIA_STOP; pub const APPCOMMAND_MEDIA_PLAY_PAUSE = APPCOMMAND_ID.MEDIA_PLAY_PAUSE; pub const APPCOMMAND_LAUNCH_MAIL = APPCOMMAND_ID.LAUNCH_MAIL; pub const APPCOMMAND_LAUNCH_MEDIA_SELECT = APPCOMMAND_ID.LAUNCH_MEDIA_SELECT; pub const APPCOMMAND_LAUNCH_APP1 = APPCOMMAND_ID.LAUNCH_APP1; pub const APPCOMMAND_LAUNCH_APP2 = APPCOMMAND_ID.LAUNCH_APP2; pub const APPCOMMAND_BASS_DOWN = APPCOMMAND_ID.BASS_DOWN; pub const APPCOMMAND_BASS_BOOST = APPCOMMAND_ID.BASS_BOOST; pub const APPCOMMAND_BASS_UP = APPCOMMAND_ID.BASS_UP; pub const APPCOMMAND_TREBLE_DOWN = APPCOMMAND_ID.TREBLE_DOWN; pub const APPCOMMAND_TREBLE_UP = APPCOMMAND_ID.TREBLE_UP; pub const APPCOMMAND_MICROPHONE_VOLUME_MUTE = APPCOMMAND_ID.MICROPHONE_VOLUME_MUTE; pub const APPCOMMAND_MICROPHONE_VOLUME_DOWN = APPCOMMAND_ID.MICROPHONE_VOLUME_DOWN; pub const APPCOMMAND_MICROPHONE_VOLUME_UP = APPCOMMAND_ID.MICROPHONE_VOLUME_UP; pub const APPCOMMAND_HELP = APPCOMMAND_ID.HELP; pub const APPCOMMAND_FIND = APPCOMMAND_ID.FIND; pub const APPCOMMAND_NEW = APPCOMMAND_ID.NEW; pub const APPCOMMAND_OPEN = APPCOMMAND_ID.OPEN; pub const APPCOMMAND_CLOSE = APPCOMMAND_ID.CLOSE; pub const APPCOMMAND_SAVE = APPCOMMAND_ID.SAVE; pub const APPCOMMAND_PRINT = APPCOMMAND_ID.PRINT; pub const APPCOMMAND_UNDO = APPCOMMAND_ID.UNDO; pub const APPCOMMAND_REDO = APPCOMMAND_ID.REDO; pub const APPCOMMAND_COPY = APPCOMMAND_ID.COPY; pub const APPCOMMAND_CUT = APPCOMMAND_ID.CUT; pub const APPCOMMAND_PASTE = APPCOMMAND_ID.PASTE; pub const APPCOMMAND_REPLY_TO_MAIL = APPCOMMAND_ID.REPLY_TO_MAIL; pub const APPCOMMAND_FORWARD_MAIL = APPCOMMAND_ID.FORWARD_MAIL; pub const APPCOMMAND_SEND_MAIL = APPCOMMAND_ID.SEND_MAIL; pub const APPCOMMAND_SPELL_CHECK = APPCOMMAND_ID.SPELL_CHECK; pub const APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE = APPCOMMAND_ID.DICTATE_OR_COMMAND_CONTROL_TOGGLE; pub const APPCOMMAND_MIC_ON_OFF_TOGGLE = APPCOMMAND_ID.MIC_ON_OFF_TOGGLE; pub const APPCOMMAND_CORRECTION_LIST = APPCOMMAND_ID.CORRECTION_LIST; pub const APPCOMMAND_MEDIA_PLAY = APPCOMMAND_ID.MEDIA_PLAY; pub const APPCOMMAND_MEDIA_PAUSE = APPCOMMAND_ID.MEDIA_PAUSE; pub const APPCOMMAND_MEDIA_RECORD = APPCOMMAND_ID.MEDIA_RECORD; pub const APPCOMMAND_MEDIA_FAST_FORWARD = APPCOMMAND_ID.MEDIA_FAST_FORWARD; pub const APPCOMMAND_MEDIA_REWIND = APPCOMMAND_ID.MEDIA_REWIND; pub const APPCOMMAND_MEDIA_CHANNEL_UP = APPCOMMAND_ID.MEDIA_CHANNEL_UP; pub const APPCOMMAND_MEDIA_CHANNEL_DOWN = APPCOMMAND_ID.MEDIA_CHANNEL_DOWN; pub const APPCOMMAND_DELETE = APPCOMMAND_ID.DELETE; pub const APPCOMMAND_DWM_FLIP3D = APPCOMMAND_ID.DWM_FLIP3D; pub const ATF_FLAGS = enum(u32) { TIMEOUTON = 1, ONOFFFEEDBACK = 2, _, pub fn initFlags(o: struct { TIMEOUTON: u1 = 0, ONOFFFEEDBACK: u1 = 0, }) ATF_FLAGS { return @intToEnum(ATF_FLAGS, (if (o.TIMEOUTON == 1) @enumToInt(ATF_FLAGS.TIMEOUTON) else 0) | (if (o.ONOFFFEEDBACK == 1) @enumToInt(ATF_FLAGS.ONOFFFEEDBACK) else 0) ); } }; pub const ATF_TIMEOUTON = ATF_FLAGS.TIMEOUTON; pub const ATF_ONOFFFEEDBACK = ATF_FLAGS.ONOFFFEEDBACK; pub const CHOOSECOLOR_FLAGS = enum(u32) { RGBINIT = 1, FULLOPEN = 2, PREVENTFULLOPEN = 4, SHOWHELP = 8, ENABLEHOOK = 16, ENABLETEMPLATE = 32, ENABLETEMPLATEHANDLE = 64, SOLIDCOLOR = 128, ANYCOLOR = 256, _, pub fn initFlags(o: struct { RGBINIT: u1 = 0, FULLOPEN: u1 = 0, PREVENTFULLOPEN: u1 = 0, SHOWHELP: u1 = 0, ENABLEHOOK: u1 = 0, ENABLETEMPLATE: u1 = 0, ENABLETEMPLATEHANDLE: u1 = 0, SOLIDCOLOR: u1 = 0, ANYCOLOR: u1 = 0, }) CHOOSECOLOR_FLAGS { return @intToEnum(CHOOSECOLOR_FLAGS, (if (o.RGBINIT == 1) @enumToInt(CHOOSECOLOR_FLAGS.RGBINIT) else 0) | (if (o.FULLOPEN == 1) @enumToInt(CHOOSECOLOR_FLAGS.FULLOPEN) else 0) | (if (o.PREVENTFULLOPEN == 1) @enumToInt(CHOOSECOLOR_FLAGS.PREVENTFULLOPEN) else 0) | (if (o.SHOWHELP == 1) @enumToInt(CHOOSECOLOR_FLAGS.SHOWHELP) else 0) | (if (o.ENABLEHOOK == 1) @enumToInt(CHOOSECOLOR_FLAGS.ENABLEHOOK) else 0) | (if (o.ENABLETEMPLATE == 1) @enumToInt(CHOOSECOLOR_FLAGS.ENABLETEMPLATE) else 0) | (if (o.ENABLETEMPLATEHANDLE == 1) @enumToInt(CHOOSECOLOR_FLAGS.ENABLETEMPLATEHANDLE) else 0) | (if (o.SOLIDCOLOR == 1) @enumToInt(CHOOSECOLOR_FLAGS.SOLIDCOLOR) else 0) | (if (o.ANYCOLOR == 1) @enumToInt(CHOOSECOLOR_FLAGS.ANYCOLOR) else 0) ); } }; pub const CC_RGBINIT = CHOOSECOLOR_FLAGS.RGBINIT; pub const CC_FULLOPEN = CHOOSECOLOR_FLAGS.FULLOPEN; pub const CC_PREVENTFULLOPEN = CHOOSECOLOR_FLAGS.PREVENTFULLOPEN; pub const CC_SHOWHELP = CHOOSECOLOR_FLAGS.SHOWHELP; pub const CC_ENABLEHOOK = CHOOSECOLOR_FLAGS.ENABLEHOOK; pub const CC_ENABLETEMPLATE = CHOOSECOLOR_FLAGS.ENABLETEMPLATE; pub const CC_ENABLETEMPLATEHANDLE = CHOOSECOLOR_FLAGS.ENABLETEMPLATEHANDLE; pub const CC_SOLIDCOLOR = CHOOSECOLOR_FLAGS.SOLIDCOLOR; pub const CC_ANYCOLOR = CHOOSECOLOR_FLAGS.ANYCOLOR; pub const CLIPBOARD_FORMATS = enum(u32) { TEXT = 1, BITMAP = 2, METAFILEPICT = 3, SYLK = 4, DIF = 5, TIFF = 6, OEMTEXT = 7, DIB = 8, PALETTE = 9, PENDATA = 10, RIFF = 11, WAVE = 12, UNICODETEXT = 13, ENHMETAFILE = 14, HDROP = 15, LOCALE = 16, DIBV5 = 17, MAX = 18, OWNERDISPLAY = 128, DSPTEXT = 129, DSPBITMAP = 130, DSPMETAFILEPICT = 131, DSPENHMETAFILE = 142, PRIVATEFIRST = 512, PRIVATELAST = 767, GDIOBJFIRST = 768, GDIOBJLAST = 1023, }; pub const CF_TEXT = CLIPBOARD_FORMATS.TEXT; pub const CF_BITMAP = CLIPBOARD_FORMATS.BITMAP; pub const CF_METAFILEPICT = CLIPBOARD_FORMATS.METAFILEPICT; pub const CF_SYLK = CLIPBOARD_FORMATS.SYLK; pub const CF_DIF = CLIPBOARD_FORMATS.DIF; pub const CF_TIFF = CLIPBOARD_FORMATS.TIFF; pub const CF_OEMTEXT = CLIPBOARD_FORMATS.OEMTEXT; pub const CF_DIB = CLIPBOARD_FORMATS.DIB; pub const CF_PALETTE = CLIPBOARD_FORMATS.PALETTE; pub const CF_PENDATA = CLIPBOARD_FORMATS.PENDATA; pub const CF_RIFF = CLIPBOARD_FORMATS.RIFF; pub const CF_WAVE = CLIPBOARD_FORMATS.WAVE; pub const CF_UNICODETEXT = CLIPBOARD_FORMATS.UNICODETEXT; pub const CF_ENHMETAFILE = CLIPBOARD_FORMATS.ENHMETAFILE; pub const CF_HDROP = CLIPBOARD_FORMATS.HDROP; pub const CF_LOCALE = CLIPBOARD_FORMATS.LOCALE; pub const CF_DIBV5 = CLIPBOARD_FORMATS.DIBV5; pub const CF_MAX = CLIPBOARD_FORMATS.MAX; pub const CF_OWNERDISPLAY = CLIPBOARD_FORMATS.OWNERDISPLAY; pub const CF_DSPTEXT = CLIPBOARD_FORMATS.DSPTEXT; pub const CF_DSPBITMAP = CLIPBOARD_FORMATS.DSPBITMAP; pub const CF_DSPMETAFILEPICT = CLIPBOARD_FORMATS.DSPMETAFILEPICT; pub const CF_DSPENHMETAFILE = CLIPBOARD_FORMATS.DSPENHMETAFILE; pub const CF_PRIVATEFIRST = CLIPBOARD_FORMATS.PRIVATEFIRST; pub const CF_PRIVATELAST = CLIPBOARD_FORMATS.PRIVATELAST; pub const CF_GDIOBJFIRST = CLIPBOARD_FORMATS.GDIOBJFIRST; pub const CF_GDIOBJLAST = CLIPBOARD_FORMATS.GDIOBJLAST; pub const GESTURECONFIG_FLAGS = enum(u32) { ALLGESTURES = 1, // ZOOM = 1, this enum value conflicts with ALLGESTURES // PAN = 1, this enum value conflicts with ALLGESTURES PAN_WITH_SINGLE_FINGER_VERTICALLY = 2, PAN_WITH_SINGLE_FINGER_HORIZONTALLY = 4, PAN_WITH_GUTTER = 8, PAN_WITH_INERTIA = 16, // ROTATE = 1, this enum value conflicts with ALLGESTURES // TWOFINGERTAP = 1, this enum value conflicts with ALLGESTURES // PRESSANDTAP = 1, this enum value conflicts with ALLGESTURES // ROLLOVER = 1, this enum value conflicts with ALLGESTURES _, pub fn initFlags(o: struct { ALLGESTURES: u1 = 0, PAN_WITH_SINGLE_FINGER_VERTICALLY: u1 = 0, PAN_WITH_SINGLE_FINGER_HORIZONTALLY: u1 = 0, PAN_WITH_GUTTER: u1 = 0, PAN_WITH_INERTIA: u1 = 0, }) GESTURECONFIG_FLAGS { return @intToEnum(GESTURECONFIG_FLAGS, (if (o.ALLGESTURES == 1) @enumToInt(GESTURECONFIG_FLAGS.ALLGESTURES) else 0) | (if (o.PAN_WITH_SINGLE_FINGER_VERTICALLY == 1) @enumToInt(GESTURECONFIG_FLAGS.PAN_WITH_SINGLE_FINGER_VERTICALLY) else 0) | (if (o.PAN_WITH_SINGLE_FINGER_HORIZONTALLY == 1) @enumToInt(GESTURECONFIG_FLAGS.PAN_WITH_SINGLE_FINGER_HORIZONTALLY) else 0) | (if (o.PAN_WITH_GUTTER == 1) @enumToInt(GESTURECONFIG_FLAGS.PAN_WITH_GUTTER) else 0) | (if (o.PAN_WITH_INERTIA == 1) @enumToInt(GESTURECONFIG_FLAGS.PAN_WITH_INERTIA) else 0) ); } }; pub const GC_ALLGESTURES = GESTURECONFIG_FLAGS.ALLGESTURES; pub const GC_ZOOM = GESTURECONFIG_FLAGS.ALLGESTURES; pub const GC_PAN = GESTURECONFIG_FLAGS.ALLGESTURES; pub const GC_PAN_WITH_SINGLE_FINGER_VERTICALLY = GESTURECONFIG_FLAGS.PAN_WITH_SINGLE_FINGER_VERTICALLY; pub const GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY = GESTURECONFIG_FLAGS.PAN_WITH_SINGLE_FINGER_HORIZONTALLY; pub const GC_PAN_WITH_GUTTER = GESTURECONFIG_FLAGS.PAN_WITH_GUTTER; pub const GC_PAN_WITH_INERTIA = GESTURECONFIG_FLAGS.PAN_WITH_INERTIA; pub const GC_ROTATE = GESTURECONFIG_FLAGS.ALLGESTURES; pub const GC_TWOFINGERTAP = GESTURECONFIG_FLAGS.ALLGESTURES; pub const GC_PRESSANDTAP = GESTURECONFIG_FLAGS.ALLGESTURES; pub const GC_ROLLOVER = GESTURECONFIG_FLAGS.ALLGESTURES; pub const CFE_UNDERLINE = enum(u32) { CF1UNDERLINE = 255, INVERT = 254, UNDERLINETHICKLONGDASH = 18, UNDERLINETHICKDOTTED = 17, UNDERLINETHICKDASHDOTDOT = 16, UNDERLINETHICKDASHDOT = 15, UNDERLINETHICKDASH = 14, UNDERLINELONGDASH = 13, UNDERLINEHEAVYWAVE = 12, UNDERLINEDOUBLEWAVE = 11, UNDERLINEHAIRLINE = 10, UNDERLINETHICK = 9, UNDERLINEWAVE = 8, UNDERLINEDASHDOTDOT = 7, UNDERLINEDASHDOT = 6, UNDERLINEDASH = 5, UNDERLINEDOTTED = 4, UNDERLINEDOUBLE = 3, UNDERLINEWORD = 2, UNDERLINE = 1, UNDERLINENONE = 0, _, pub fn initFlags(o: struct { CF1UNDERLINE: u1 = 0, INVERT: u1 = 0, UNDERLINETHICKLONGDASH: u1 = 0, UNDERLINETHICKDOTTED: u1 = 0, UNDERLINETHICKDASHDOTDOT: u1 = 0, UNDERLINETHICKDASHDOT: u1 = 0, UNDERLINETHICKDASH: u1 = 0, UNDERLINELONGDASH: u1 = 0, UNDERLINEHEAVYWAVE: u1 = 0, UNDERLINEDOUBLEWAVE: u1 = 0, UNDERLINEHAIRLINE: u1 = 0, UNDERLINETHICK: u1 = 0, UNDERLINEWAVE: u1 = 0, UNDERLINEDASHDOTDOT: u1 = 0, UNDERLINEDASHDOT: u1 = 0, UNDERLINEDASH: u1 = 0, UNDERLINEDOTTED: u1 = 0, UNDERLINEDOUBLE: u1 = 0, UNDERLINEWORD: u1 = 0, UNDERLINE: u1 = 0, UNDERLINENONE: u1 = 0, }) CFE_UNDERLINE { return @intToEnum(CFE_UNDERLINE, (if (o.CF1UNDERLINE == 1) @enumToInt(CFE_UNDERLINE.CF1UNDERLINE) else 0) | (if (o.INVERT == 1) @enumToInt(CFE_UNDERLINE.INVERT) else 0) | (if (o.UNDERLINETHICKLONGDASH == 1) @enumToInt(CFE_UNDERLINE.UNDERLINETHICKLONGDASH) else 0) | (if (o.UNDERLINETHICKDOTTED == 1) @enumToInt(CFE_UNDERLINE.UNDERLINETHICKDOTTED) else 0) | (if (o.UNDERLINETHICKDASHDOTDOT == 1) @enumToInt(CFE_UNDERLINE.UNDERLINETHICKDASHDOTDOT) else 0) | (if (o.UNDERLINETHICKDASHDOT == 1) @enumToInt(CFE_UNDERLINE.UNDERLINETHICKDASHDOT) else 0) | (if (o.UNDERLINETHICKDASH == 1) @enumToInt(CFE_UNDERLINE.UNDERLINETHICKDASH) else 0) | (if (o.UNDERLINELONGDASH == 1) @enumToInt(CFE_UNDERLINE.UNDERLINELONGDASH) else 0) | (if (o.UNDERLINEHEAVYWAVE == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEHEAVYWAVE) else 0) | (if (o.UNDERLINEDOUBLEWAVE == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEDOUBLEWAVE) else 0) | (if (o.UNDERLINEHAIRLINE == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEHAIRLINE) else 0) | (if (o.UNDERLINETHICK == 1) @enumToInt(CFE_UNDERLINE.UNDERLINETHICK) else 0) | (if (o.UNDERLINEWAVE == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEWAVE) else 0) | (if (o.UNDERLINEDASHDOTDOT == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEDASHDOTDOT) else 0) | (if (o.UNDERLINEDASHDOT == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEDASHDOT) else 0) | (if (o.UNDERLINEDASH == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEDASH) else 0) | (if (o.UNDERLINEDOTTED == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEDOTTED) else 0) | (if (o.UNDERLINEDOUBLE == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEDOUBLE) else 0) | (if (o.UNDERLINEWORD == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEWORD) else 0) | (if (o.UNDERLINE == 1) @enumToInt(CFE_UNDERLINE.UNDERLINE) else 0) | (if (o.UNDERLINENONE == 1) @enumToInt(CFE_UNDERLINE.UNDERLINENONE) else 0) ); } }; pub const CFU_CF1UNDERLINE = CFE_UNDERLINE.CF1UNDERLINE; pub const CFU_INVERT = CFE_UNDERLINE.INVERT; pub const CFU_UNDERLINETHICKLONGDASH = CFE_UNDERLINE.UNDERLINETHICKLONGDASH; pub const CFU_UNDERLINETHICKDOTTED = CFE_UNDERLINE.UNDERLINETHICKDOTTED; pub const CFU_UNDERLINETHICKDASHDOTDOT = CFE_UNDERLINE.UNDERLINETHICKDASHDOTDOT; pub const CFU_UNDERLINETHICKDASHDOT = CFE_UNDERLINE.UNDERLINETHICKDASHDOT; pub const CFU_UNDERLINETHICKDASH = CFE_UNDERLINE.UNDERLINETHICKDASH; pub const CFU_UNDERLINELONGDASH = CFE_UNDERLINE.UNDERLINELONGDASH; pub const CFU_UNDERLINEHEAVYWAVE = CFE_UNDERLINE.UNDERLINEHEAVYWAVE; pub const CFU_UNDERLINEDOUBLEWAVE = CFE_UNDERLINE.UNDERLINEDOUBLEWAVE; pub const CFU_UNDERLINEHAIRLINE = CFE_UNDERLINE.UNDERLINEHAIRLINE; pub const CFU_UNDERLINETHICK = CFE_UNDERLINE.UNDERLINETHICK; pub const CFU_UNDERLINEWAVE = CFE_UNDERLINE.UNDERLINEWAVE; pub const CFU_UNDERLINEDASHDOTDOT = CFE_UNDERLINE.UNDERLINEDASHDOTDOT; pub const CFU_UNDERLINEDASHDOT = CFE_UNDERLINE.UNDERLINEDASHDOT; pub const CFU_UNDERLINEDASH = CFE_UNDERLINE.UNDERLINEDASH; pub const CFU_UNDERLINEDOTTED = CFE_UNDERLINE.UNDERLINEDOTTED; pub const CFU_UNDERLINEDOUBLE = CFE_UNDERLINE.UNDERLINEDOUBLE; pub const CFU_UNDERLINEWORD = CFE_UNDERLINE.UNDERLINEWORD; pub const CFU_UNDERLINE = CFE_UNDERLINE.UNDERLINE; pub const CFU_UNDERLINENONE = CFE_UNDERLINE.UNDERLINENONE; pub const IGP_ID = enum(u32) { GETIMEVERSION = 4294967292, PROPERTY = 4, CONVERSION = 8, SENTENCE = 12, UI = 16, SETCOMPSTR = 20, SELECT = 24, }; pub const IGP_GETIMEVERSION = IGP_ID.GETIMEVERSION; pub const IGP_PROPERTY = IGP_ID.PROPERTY; pub const IGP_CONVERSION = IGP_ID.CONVERSION; pub const IGP_SENTENCE = IGP_ID.SENTENCE; pub const IGP_UI = IGP_ID.UI; pub const IGP_SETCOMPSTR = IGP_ID.SETCOMPSTR; pub const IGP_SELECT = IGP_ID.SELECT; pub const SECTION_FLAGS = enum(u32) { ALL_ACCESS = 983071, QUERY = 1, MAP_WRITE = 2, MAP_READ = 4, MAP_EXECUTE = 8, EXTEND_SIZE = 16, MAP_EXECUTE_EXPLICIT = 32, _, pub fn initFlags(o: struct { ALL_ACCESS: u1 = 0, QUERY: u1 = 0, MAP_WRITE: u1 = 0, MAP_READ: u1 = 0, MAP_EXECUTE: u1 = 0, EXTEND_SIZE: u1 = 0, MAP_EXECUTE_EXPLICIT: u1 = 0, }) SECTION_FLAGS { return @intToEnum(SECTION_FLAGS, (if (o.ALL_ACCESS == 1) @enumToInt(SECTION_FLAGS.ALL_ACCESS) else 0) | (if (o.QUERY == 1) @enumToInt(SECTION_FLAGS.QUERY) else 0) | (if (o.MAP_WRITE == 1) @enumToInt(SECTION_FLAGS.MAP_WRITE) else 0) | (if (o.MAP_READ == 1) @enumToInt(SECTION_FLAGS.MAP_READ) else 0) | (if (o.MAP_EXECUTE == 1) @enumToInt(SECTION_FLAGS.MAP_EXECUTE) else 0) | (if (o.EXTEND_SIZE == 1) @enumToInt(SECTION_FLAGS.EXTEND_SIZE) else 0) | (if (o.MAP_EXECUTE_EXPLICIT == 1) @enumToInt(SECTION_FLAGS.MAP_EXECUTE_EXPLICIT) else 0) ); } }; pub const SECTION_ALL_ACCESS = SECTION_FLAGS.ALL_ACCESS; pub const SECTION_QUERY = SECTION_FLAGS.QUERY; pub const SECTION_MAP_WRITE = SECTION_FLAGS.MAP_WRITE; pub const SECTION_MAP_READ = SECTION_FLAGS.MAP_READ; pub const SECTION_MAP_EXECUTE = SECTION_FLAGS.MAP_EXECUTE; pub const SECTION_EXTEND_SIZE = SECTION_FLAGS.EXTEND_SIZE; pub const SECTION_MAP_EXECUTE_EXPLICIT = SECTION_FLAGS.MAP_EXECUTE_EXPLICIT; pub const TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH = enum(u32) { ABS_BLK_IMMED = 2147491840, ABSOLUTE_BLK = 2147487744, END_OF_DATA = 2147549184, FILEMARKS = 2147745792, LOAD_UNLOAD = 2147483649, LOAD_UNLD_IMMED = 2147483680, LOCK_UNLOCK = 2147483652, LOCK_UNLK_IMMED = 2147483776, LOG_BLK_IMMED = 2147516416, LOGICAL_BLK = 2147500032, RELATIVE_BLKS = 2147614720, REVERSE_POSITION = 2151677952, REWIND_IMMEDIATE = 2147483656, SEQUENTIAL_FMKS = 2148007936, SEQUENTIAL_SMKS = 2149580800, SET_BLOCK_SIZE = 2147483664, SET_COMPRESSION = 2147484160, SET_ECC = 2147483904, SET_PADDING = 2147484672, SET_REPORT_SMKS = 2147485696, SETMARKS = 2148532224, SPACE_IMMEDIATE = 2155872256, TENSION = 2147483650, TENSION_IMMED = 2147483712, WRITE_FILEMARKS = 2181038080, WRITE_LONG_FMKS = 2281701376, WRITE_MARK_IMMED = 2415919104, WRITE_SETMARKS = 2164260864, WRITE_SHORT_FMKS = 2214592512, _, pub fn initFlags(o: struct { ABS_BLK_IMMED: u1 = 0, ABSOLUTE_BLK: u1 = 0, END_OF_DATA: u1 = 0, FILEMARKS: u1 = 0, LOAD_UNLOAD: u1 = 0, LOAD_UNLD_IMMED: u1 = 0, LOCK_UNLOCK: u1 = 0, LOCK_UNLK_IMMED: u1 = 0, LOG_BLK_IMMED: u1 = 0, LOGICAL_BLK: u1 = 0, RELATIVE_BLKS: u1 = 0, REVERSE_POSITION: u1 = 0, REWIND_IMMEDIATE: u1 = 0, SEQUENTIAL_FMKS: u1 = 0, SEQUENTIAL_SMKS: u1 = 0, SET_BLOCK_SIZE: u1 = 0, SET_COMPRESSION: u1 = 0, SET_ECC: u1 = 0, SET_PADDING: u1 = 0, SET_REPORT_SMKS: u1 = 0, SETMARKS: u1 = 0, SPACE_IMMEDIATE: u1 = 0, TENSION: u1 = 0, TENSION_IMMED: u1 = 0, WRITE_FILEMARKS: u1 = 0, WRITE_LONG_FMKS: u1 = 0, WRITE_MARK_IMMED: u1 = 0, WRITE_SETMARKS: u1 = 0, WRITE_SHORT_FMKS: u1 = 0, }) TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH { return @intToEnum(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH, (if (o.ABS_BLK_IMMED == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.ABS_BLK_IMMED) else 0) | (if (o.ABSOLUTE_BLK == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.ABSOLUTE_BLK) else 0) | (if (o.END_OF_DATA == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.END_OF_DATA) else 0) | (if (o.FILEMARKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.FILEMARKS) else 0) | (if (o.LOAD_UNLOAD == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOAD_UNLOAD) else 0) | (if (o.LOAD_UNLD_IMMED == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOAD_UNLD_IMMED) else 0) | (if (o.LOCK_UNLOCK == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOCK_UNLOCK) else 0) | (if (o.LOCK_UNLK_IMMED == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOCK_UNLK_IMMED) else 0) | (if (o.LOG_BLK_IMMED == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOG_BLK_IMMED) else 0) | (if (o.LOGICAL_BLK == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOGICAL_BLK) else 0) | (if (o.RELATIVE_BLKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.RELATIVE_BLKS) else 0) | (if (o.REVERSE_POSITION == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.REVERSE_POSITION) else 0) | (if (o.REWIND_IMMEDIATE == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.REWIND_IMMEDIATE) else 0) | (if (o.SEQUENTIAL_FMKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SEQUENTIAL_FMKS) else 0) | (if (o.SEQUENTIAL_SMKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SEQUENTIAL_SMKS) else 0) | (if (o.SET_BLOCK_SIZE == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_BLOCK_SIZE) else 0) | (if (o.SET_COMPRESSION == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_COMPRESSION) else 0) | (if (o.SET_ECC == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_ECC) else 0) | (if (o.SET_PADDING == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_PADDING) else 0) | (if (o.SET_REPORT_SMKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_REPORT_SMKS) else 0) | (if (o.SETMARKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SETMARKS) else 0) | (if (o.SPACE_IMMEDIATE == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SPACE_IMMEDIATE) else 0) | (if (o.TENSION == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.TENSION) else 0) | (if (o.TENSION_IMMED == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.TENSION_IMMED) else 0) | (if (o.WRITE_FILEMARKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_FILEMARKS) else 0) | (if (o.WRITE_LONG_FMKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_LONG_FMKS) else 0) | (if (o.WRITE_MARK_IMMED == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_MARK_IMMED) else 0) | (if (o.WRITE_SETMARKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_SETMARKS) else 0) | (if (o.WRITE_SHORT_FMKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_SHORT_FMKS) else 0) ); } }; pub const TAPE_DRIVE_ABS_BLK_IMMED = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.ABS_BLK_IMMED; pub const TAPE_DRIVE_ABSOLUTE_BLK = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.ABSOLUTE_BLK; pub const TAPE_DRIVE_END_OF_DATA = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.END_OF_DATA; pub const TAPE_DRIVE_FILEMARKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.FILEMARKS; pub const TAPE_DRIVE_LOAD_UNLOAD = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOAD_UNLOAD; pub const TAPE_DRIVE_LOAD_UNLD_IMMED = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOAD_UNLD_IMMED; pub const TAPE_DRIVE_LOCK_UNLOCK = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOCK_UNLOCK; pub const TAPE_DRIVE_LOCK_UNLK_IMMED = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOCK_UNLK_IMMED; pub const TAPE_DRIVE_LOG_BLK_IMMED = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOG_BLK_IMMED; pub const TAPE_DRIVE_LOGICAL_BLK = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOGICAL_BLK; pub const TAPE_DRIVE_RELATIVE_BLKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.RELATIVE_BLKS; pub const TAPE_DRIVE_REVERSE_POSITION = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.REVERSE_POSITION; pub const TAPE_DRIVE_REWIND_IMMEDIATE = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.REWIND_IMMEDIATE; pub const TAPE_DRIVE_SEQUENTIAL_FMKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SEQUENTIAL_FMKS; pub const TAPE_DRIVE_SEQUENTIAL_SMKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SEQUENTIAL_SMKS; pub const TAPE_DRIVE_SET_BLOCK_SIZE = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_BLOCK_SIZE; pub const TAPE_DRIVE_SET_COMPRESSION = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_COMPRESSION; pub const TAPE_DRIVE_SET_ECC = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_ECC; pub const TAPE_DRIVE_SET_PADDING = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_PADDING; pub const TAPE_DRIVE_SET_REPORT_SMKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_REPORT_SMKS; pub const TAPE_DRIVE_SETMARKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SETMARKS; pub const TAPE_DRIVE_SPACE_IMMEDIATE = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SPACE_IMMEDIATE; pub const TAPE_DRIVE_TENSION = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.TENSION; pub const TAPE_DRIVE_TENSION_IMMED = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.TENSION_IMMED; pub const TAPE_DRIVE_WRITE_FILEMARKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_FILEMARKS; pub const TAPE_DRIVE_WRITE_LONG_FMKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_LONG_FMKS; pub const TAPE_DRIVE_WRITE_MARK_IMMED = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_MARK_IMMED; pub const TAPE_DRIVE_WRITE_SETMARKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_SETMARKS; pub const TAPE_DRIVE_WRITE_SHORT_FMKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_SHORT_FMKS; pub const DEV_BROADCAST_HDR_DEVICE_TYPE = enum(u32) { DEVICEINTERFACE = 5, HANDLE = 6, OEM = 0, PORT = 3, VOLUME = 2, }; pub const DBT_DEVTYP_DEVICEINTERFACE = DEV_BROADCAST_HDR_DEVICE_TYPE.DEVICEINTERFACE; pub const DBT_DEVTYP_HANDLE = DEV_BROADCAST_HDR_DEVICE_TYPE.HANDLE; pub const DBT_DEVTYP_OEM = DEV_BROADCAST_HDR_DEVICE_TYPE.OEM; pub const DBT_DEVTYP_PORT = DEV_BROADCAST_HDR_DEVICE_TYPE.PORT; pub const DBT_DEVTYP_VOLUME = DEV_BROADCAST_HDR_DEVICE_TYPE.VOLUME; pub const DEV_BROADCAST_VOLUME_FLAGS = enum(u16) { MEDIA = 1, NET = 2, }; pub const DBTF_MEDIA = DEV_BROADCAST_VOLUME_FLAGS.MEDIA; pub const DBTF_NET = DEV_BROADCAST_VOLUME_FLAGS.NET; pub const PUMS_SCHEDULER_ENTRY_POINT = fn( Reason: RTL_UMS_SCHEDULER_REASON, ActivationPayload: usize, SchedulerParam: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const TP_POOL = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const TP_CLEANUP_GROUP = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const TEB = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const RemHGLOBAL = extern struct { fNullHGlobal: i32, cbData: u32, data: [1]u8, }; pub const RemHMETAFILEPICT = extern struct { mm: i32, xExt: i32, yExt: i32, cbData: u32, data: [1]u8, }; pub const RemHENHMETAFILE = extern struct { cbData: u32, data: [1]u8, }; pub const RemHBITMAP = extern struct { cbData: u32, data: [1]u8, }; pub const RemHPALETTE = extern struct { cbData: u32, data: [1]u8, }; pub const RemBRUSH = extern struct { cbData: u32, data: [1]u8, }; pub const userCLIPFORMAT = extern struct { fContext: i32, u: extern struct { dwValue: u32, pwszName: ?PWSTR, }, }; pub const GDI_NONREMOTE = extern struct { fContext: i32, u: extern struct { hInproc: i32, hRemote: ?*DWORD_BLOB, }, }; pub const userHGLOBAL = extern struct { fContext: i32, u: extern struct { hInproc: i32, hRemote: ?*FLAGGED_BYTE_BLOB, hInproc64: i64, }, }; pub const userHMETAFILE = extern struct { fContext: i32, u: extern struct { hInproc: i32, hRemote: ?*BYTE_BLOB, hInproc64: i64, }, }; pub const remoteMETAFILEPICT = extern struct { mm: i32, xExt: i32, yExt: i32, hMF: ?*userHMETAFILE, }; pub const userHMETAFILEPICT = extern struct { fContext: i32, u: extern struct { hInproc: i32, hRemote: ?*remoteMETAFILEPICT, hInproc64: i64, }, }; pub const userHENHMETAFILE = extern struct { fContext: i32, u: extern struct { hInproc: i32, hRemote: ?*BYTE_BLOB, hInproc64: i64, }, }; pub const userBITMAP = extern struct { bmType: i32, bmWidth: i32, bmHeight: i32, bmWidthBytes: i32, bmPlanes: u16, bmBitsPixel: u16, cbSize: u32, pBuffer: [1]u8, }; pub const userHBITMAP = extern struct { fContext: i32, u: extern struct { hInproc: i32, hRemote: ?*userBITMAP, hInproc64: i64, }, }; pub const userHPALETTE = extern struct { fContext: i32, u: extern struct { hInproc: i32, hRemote: ?*LOGPALETTE, hInproc64: i64, }, }; pub const RemotableHandle = extern struct { fContext: i32, u: extern struct { hInproc: i32, hRemote: i32, }, }; pub const DEVICE_EVENT_MOUNT = extern struct { Version: u32, Flags: u32, FileSystemNameLength: u32, FileSystemNameOffset: u32, }; pub const DEVICE_EVENT_BECOMING_READY = extern struct { Version: u32, Reason: u32, Estimated100msToReady: u32, }; pub const DEVICE_EVENT_EXTERNAL_REQUEST = extern struct { Version: u32, DeviceClass: u32, ButtonStatus: u16, Request: u16, SystemTime: LARGE_INTEGER, }; pub const DEVICE_EVENT_GENERIC_DATA = extern struct { EventNumber: u32, }; pub const DEVICE_EVENT_RBC_DATA = extern struct { EventNumber: u32, SenseQualifier: u8, SenseCode: u8, SenseKey: u8, Reserved: u8, Information: u32, }; pub const GUID_IO_DISK_CLONE_ARRIVAL_INFORMATION = extern struct { DiskNumber: u32, }; pub const DISK_HEALTH_NOTIFICATION_DATA = extern struct { DeviceGuid: Guid, }; pub const REDBOOK_DIGITAL_AUDIO_EXTRACTION_INFO = extern struct { Version: u32, Accurate: u32, Supported: u32, AccurateMask0: u32, }; pub const DEV_BROADCAST_HDR = extern struct { dbch_size: u32, dbch_devicetype: DEV_BROADCAST_HDR_DEVICE_TYPE, dbch_reserved: u32, }; pub const VolLockBroadcast = extern struct { vlb_dbh: DEV_BROADCAST_HDR, vlb_owner: u32, vlb_perms: u8, vlb_lockType: u8, vlb_drive: u8, vlb_flags: u8, }; pub const _DEV_BROADCAST_HEADER = extern struct { dbcd_size: u32, dbcd_devicetype: u32, dbcd_reserved: u32, }; pub const DEV_BROADCAST_OEM = extern struct { dbco_size: u32, dbco_devicetype: u32, dbco_reserved: u32, dbco_identifier: u32, dbco_suppfunc: u32, }; pub const DEV_BROADCAST_DEVNODE = extern struct { dbcd_size: u32, dbcd_devicetype: u32, dbcd_reserved: u32, dbcd_devnode: u32, }; pub const DEV_BROADCAST_VOLUME = extern struct { dbcv_size: u32, dbcv_devicetype: u32, dbcv_reserved: u32, dbcv_unitmask: u32, dbcv_flags: DEV_BROADCAST_VOLUME_FLAGS, }; pub const DEV_BROADCAST_PORT_A = extern struct { dbcp_size: u32, dbcp_devicetype: u32, dbcp_reserved: u32, dbcp_name: [1]CHAR, }; pub const DEV_BROADCAST_PORT_W = extern struct { dbcp_size: u32, dbcp_devicetype: u32, dbcp_reserved: u32, dbcp_name: [1]u16, }; pub const DEV_BROADCAST_NET = extern struct { dbcn_size: u32, dbcn_devicetype: u32, dbcn_reserved: u32, dbcn_resource: u32, dbcn_flags: u32, }; pub const DEV_BROADCAST_DEVICEINTERFACE_A = extern struct { dbcc_size: u32, dbcc_devicetype: u32, dbcc_reserved: u32, dbcc_classguid: Guid, dbcc_name: [1]CHAR, }; pub const DEV_BROADCAST_DEVICEINTERFACE_W = extern struct { dbcc_size: u32, dbcc_devicetype: u32, dbcc_reserved: u32, dbcc_classguid: Guid, dbcc_name: [1]u16, }; pub const DEV_BROADCAST_HANDLE = extern struct { dbch_size: u32, dbch_devicetype: u32, dbch_reserved: u32, dbch_handle: ?HANDLE, dbch_hdevnotify: ?*anyopaque, dbch_eventguid: Guid, dbch_nameoffset: i32, dbch_data: [1]u8, }; pub const DEV_BROADCAST_HANDLE32 = extern struct { dbch_size: u32, dbch_devicetype: u32, dbch_reserved: u32, dbch_handle: u32, dbch_hdevnotify: u32, dbch_eventguid: Guid, dbch_nameoffset: i32, dbch_data: [1]u8, }; pub const DEV_BROADCAST_HANDLE64 = extern struct { dbch_size: u32, dbch_devicetype: u32, dbch_reserved: u32, dbch_handle: u64, dbch_hdevnotify: u64, dbch_eventguid: Guid, dbch_nameoffset: i32, dbch_data: [1]u8, }; pub const _DEV_BROADCAST_USERDEFINED = extern struct { dbud_dbh: DEV_BROADCAST_HDR, dbud_szName: [1]CHAR, }; pub const AtlThunkData_t = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const XSAVE_CET_U_FORMAT = extern struct { Ia32CetUMsr: u64, Ia32Pl3SspMsr: u64, }; pub const KERNEL_CET_CONTEXT = extern struct { Ssp: u64, Rip: u64, SegCs: u16, Anonymous: extern union { AllFlags: u16, Anonymous: extern struct { _bitfield: u16, }, }, Fill: [2]u16, }; pub const SCOPE_TABLE_AMD64 = extern struct { Count: u32, ScopeRecord: [1]extern struct { BeginAddress: u32, EndAddress: u32, HandlerAddress: u32, JumpTarget: u32, }, }; pub const SCOPE_TABLE_ARM = extern struct { Count: u32, ScopeRecord: [1]extern struct { BeginAddress: u32, EndAddress: u32, HandlerAddress: u32, JumpTarget: u32, }, }; pub const SCOPE_TABLE_ARM64 = extern struct { Count: u32, ScopeRecord: [1]extern struct { BeginAddress: u32, EndAddress: u32, HandlerAddress: u32, JumpTarget: u32, }, }; pub const DISPATCHER_CONTEXT_NONVOLREG_ARM64 = extern union { Buffer: [152]u8, Anonymous: extern struct { GpNvRegs: [11]u64, FpNvRegs: [8]f64, }, }; pub const SECURITY_DESCRIPTOR_RELATIVE = extern struct { Revision: u8, Sbz1: u8, Control: u16, Owner: u32, Group: u32, Sacl: u32, Dacl: u32, }; pub const SECURITY_OBJECT_AI_PARAMS = extern struct { Size: u32, ConstraintMask: u32, }; pub const ACCESS_REASON_TYPE = enum(i32) { None = 0, AllowedAce = 65536, DeniedAce = 131072, AllowedParentAce = 196608, DeniedParentAce = 262144, NotGrantedByCape = 327680, NotGrantedByParentCape = 393216, NotGrantedToAppContainer = 458752, MissingPrivilege = 1048576, FromPrivilege = 2097152, IntegrityLevel = 3145728, Ownership = 4194304, NullDacl = 5242880, EmptyDacl = 6291456, NoSD = 7340032, NoGrant = 8388608, TrustLabel = 9437184, FilterAce = 10485760, }; pub const AccessReasonNone = ACCESS_REASON_TYPE.None; pub const AccessReasonAllowedAce = ACCESS_REASON_TYPE.AllowedAce; pub const AccessReasonDeniedAce = ACCESS_REASON_TYPE.DeniedAce; pub const AccessReasonAllowedParentAce = ACCESS_REASON_TYPE.AllowedParentAce; pub const AccessReasonDeniedParentAce = ACCESS_REASON_TYPE.DeniedParentAce; pub const AccessReasonNotGrantedByCape = ACCESS_REASON_TYPE.NotGrantedByCape; pub const AccessReasonNotGrantedByParentCape = ACCESS_REASON_TYPE.NotGrantedByParentCape; pub const AccessReasonNotGrantedToAppContainer = ACCESS_REASON_TYPE.NotGrantedToAppContainer; pub const AccessReasonMissingPrivilege = ACCESS_REASON_TYPE.MissingPrivilege; pub const AccessReasonFromPrivilege = ACCESS_REASON_TYPE.FromPrivilege; pub const AccessReasonIntegrityLevel = ACCESS_REASON_TYPE.IntegrityLevel; pub const AccessReasonOwnership = ACCESS_REASON_TYPE.Ownership; pub const AccessReasonNullDacl = ACCESS_REASON_TYPE.NullDacl; pub const AccessReasonEmptyDacl = ACCESS_REASON_TYPE.EmptyDacl; pub const AccessReasonNoSD = ACCESS_REASON_TYPE.NoSD; pub const AccessReasonNoGrant = ACCESS_REASON_TYPE.NoGrant; pub const AccessReasonTrustLabel = ACCESS_REASON_TYPE.TrustLabel; pub const AccessReasonFilterAce = ACCESS_REASON_TYPE.FilterAce; pub const SE_TOKEN_USER = extern struct { Anonymous1: extern union { TokenUser: TOKEN_USER, User: SID_AND_ATTRIBUTES, }, Anonymous2: extern union { Sid: SID, Buffer: [68]u8, }, }; pub const TOKEN_SID_INFORMATION = extern struct { Sid: ?PSID, }; pub const TOKEN_BNO_ISOLATION_INFORMATION = extern struct { IsolationPrefix: ?PWSTR, IsolationEnabled: BOOLEAN, }; pub const SE_IMAGE_SIGNATURE_TYPE = enum(i32) { None = 0, Embedded = 1, Cache = 2, CatalogCached = 3, CatalogNotCached = 4, CatalogHint = 5, PackageCatalog = 6, PplMitigated = 7, }; pub const SeImageSignatureNone = SE_IMAGE_SIGNATURE_TYPE.None; pub const SeImageSignatureEmbedded = SE_IMAGE_SIGNATURE_TYPE.Embedded; pub const SeImageSignatureCache = SE_IMAGE_SIGNATURE_TYPE.Cache; pub const SeImageSignatureCatalogCached = SE_IMAGE_SIGNATURE_TYPE.CatalogCached; pub const SeImageSignatureCatalogNotCached = SE_IMAGE_SIGNATURE_TYPE.CatalogNotCached; pub const SeImageSignatureCatalogHint = SE_IMAGE_SIGNATURE_TYPE.CatalogHint; pub const SeImageSignaturePackageCatalog = SE_IMAGE_SIGNATURE_TYPE.PackageCatalog; pub const SeImageSignaturePplMitigated = SE_IMAGE_SIGNATURE_TYPE.PplMitigated; pub const SE_LEARNING_MODE_DATA_TYPE = enum(i32) { InvalidType = 0, Settings = 1, Max = 2, }; pub const SeLearningModeInvalidType = SE_LEARNING_MODE_DATA_TYPE.InvalidType; pub const SeLearningModeSettings = SE_LEARNING_MODE_DATA_TYPE.Settings; pub const SeLearningModeMax = SE_LEARNING_MODE_DATA_TYPE.Max; pub const NT_TIB32 = extern struct { ExceptionList: u32, StackBase: u32, StackLimit: u32, SubSystemTib: u32, Anonymous: extern union { FiberData: u32, Version: u32, }, ArbitraryUserPointer: u32, Self: u32, }; pub const NT_TIB64 = extern struct { ExceptionList: u64, StackBase: u64, StackLimit: u64, SubSystemTib: u64, Anonymous: extern union { FiberData: u64, Version: u32, }, ArbitraryUserPointer: u64, Self: u64, }; pub const UMS_CREATE_THREAD_ATTRIBUTES = extern struct { UmsVersion: u32, UmsContext: ?*anyopaque, UmsCompletionList: ?*anyopaque, }; pub const COMPONENT_FILTER = extern struct { ComponentFlags: u32, }; pub const RATE_QUOTA_LIMIT = extern union { RateData: u32, Anonymous: extern struct { _bitfield: u32, }, }; pub const QUOTA_LIMITS_EX = extern struct { PagedPoolLimit: usize, NonPagedPoolLimit: usize, MinimumWorkingSetSize: usize, MaximumWorkingSetSize: usize, PagefileLimit: usize, TimeLimit: LARGE_INTEGER, WorkingSetLimit: usize, Reserved2: usize, Reserved3: usize, Reserved4: usize, Flags: u32, CpuRateLimit: RATE_QUOTA_LIMIT, }; pub const PROCESS_MITIGATION_ASLR_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const PROCESS_MITIGATION_DEP_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, Permanent: BOOLEAN, }; pub const PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const PROCESS_MITIGATION_DYNAMIC_CODE_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const PROCESS_MITIGATION_CONTROL_FLOW_GUARD_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const PROCESS_MITIGATION_FONT_DISABLE_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const PROCESS_MITIGATION_IMAGE_LOAD_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const PROCESS_MITIGATION_SYSTEM_CALL_FILTER_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const PROCESS_MITIGATION_PAYLOAD_RESTRICTION_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const PROCESS_MITIGATION_CHILD_PROCESS_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const PROCESS_MITIGATION_SIDE_CHANNEL_ISOLATION_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const PROCESS_MITIGATION_USER_SHADOW_STACK_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const PROCESS_MITIGATION_REDIRECTION_TRUST_POLICY = extern struct { Anonymous: extern union { Flags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const SILOOBJECT_BASIC_INFORMATION = extern struct { SiloId: u32, SiloParentId: u32, NumberOfProcesses: u32, IsInServerSilo: BOOLEAN, Reserved: [3]u8, }; pub const SERVERSILO_STATE = enum(i32) { INITING = 0, STARTED = 1, SHUTTING_DOWN = 2, TERMINATING = 3, TERMINATED = 4, }; pub const SERVERSILO_INITING = SERVERSILO_STATE.INITING; pub const SERVERSILO_STARTED = SERVERSILO_STATE.STARTED; pub const SERVERSILO_SHUTTING_DOWN = SERVERSILO_STATE.SHUTTING_DOWN; pub const SERVERSILO_TERMINATING = SERVERSILO_STATE.TERMINATING; pub const SERVERSILO_TERMINATED = SERVERSILO_STATE.TERMINATED; pub const SERVERSILO_BASIC_INFORMATION = extern struct { ServiceSessionId: u32, State: SERVERSILO_STATE, ExitStatus: u32, IsDownlevelContainer: BOOLEAN, ApiSetSchema: ?*anyopaque, HostApiSetSchema: ?*anyopaque, }; pub const MEM_ADDRESS_REQUIREMENTS = extern struct { LowestStartingAddress: ?*anyopaque, HighestEndingAddress: ?*anyopaque, Alignment: usize, }; pub const MEM_DEDICATED_ATTRIBUTE_TYPE = enum(i32) { ReadBandwidth = 0, ReadLatency = 1, WriteBandwidth = 2, WriteLatency = 3, Max = 4, }; pub const MemDedicatedAttributeReadBandwidth = MEM_DEDICATED_ATTRIBUTE_TYPE.ReadBandwidth; pub const MemDedicatedAttributeReadLatency = MEM_DEDICATED_ATTRIBUTE_TYPE.ReadLatency; pub const MemDedicatedAttributeWriteBandwidth = MEM_DEDICATED_ATTRIBUTE_TYPE.WriteBandwidth; pub const MemDedicatedAttributeWriteLatency = MEM_DEDICATED_ATTRIBUTE_TYPE.WriteLatency; pub const MemDedicatedAttributeMax = MEM_DEDICATED_ATTRIBUTE_TYPE.Max; pub const MEM_SECTION_EXTENDED_PARAMETER_TYPE = enum(i32) { InvalidType = 0, UserPhysicalFlags = 1, NumaNode = 2, SigningLevel = 3, Max = 4, }; pub const MemSectionExtendedParameterInvalidType = MEM_SECTION_EXTENDED_PARAMETER_TYPE.InvalidType; pub const MemSectionExtendedParameterUserPhysicalFlags = MEM_SECTION_EXTENDED_PARAMETER_TYPE.UserPhysicalFlags; pub const MemSectionExtendedParameterNumaNode = MEM_SECTION_EXTENDED_PARAMETER_TYPE.NumaNode; pub const MemSectionExtendedParameterSigningLevel = MEM_SECTION_EXTENDED_PARAMETER_TYPE.SigningLevel; pub const MemSectionExtendedParameterMax = MEM_SECTION_EXTENDED_PARAMETER_TYPE.Max; pub const MEMORY_PARTITION_DEDICATED_MEMORY_ATTRIBUTE = extern struct { Type: MEM_DEDICATED_ATTRIBUTE_TYPE, Reserved: u32, Value: u64, }; pub const MEMORY_PARTITION_DEDICATED_MEMORY_INFORMATION = extern struct { NextEntryOffset: u32, SizeOfInformation: u32, Flags: u32, AttributesOffset: u32, AttributeCount: u32, Reserved: u32, TypeId: u64, }; pub const SCRUB_DATA_INPUT = extern struct { Size: u32, Flags: u32, MaximumIos: u32, ObjectId: [4]u32, Reserved: [41]u32, ResumeContext: [1040]u8, }; pub const SCRUB_PARITY_EXTENT = extern struct { Offset: i64, Length: u64, }; pub const SCRUB_PARITY_EXTENT_DATA = extern struct { Size: u16, Flags: u16, NumberOfParityExtents: u16, MaximumNumberOfParityExtents: u16, ParityExtents: [1]SCRUB_PARITY_EXTENT, }; pub const SCRUB_DATA_OUTPUT = extern struct { Size: u32, Flags: u32, Status: u32, ErrorFileOffset: u64, ErrorLength: u64, NumberOfBytesRepaired: u64, NumberOfBytesFailed: u64, InternalFileReference: u64, ResumeContextLength: u16, ParityExtentDataOffset: u16, Reserved: [9]u32, NumberOfMetadataBytesProcessed: u64, NumberOfDataBytesProcessed: u64, TotalNumberOfMetadataBytesInUse: u64, TotalNumberOfDataBytesInUse: u64, DataBytesSkippedDueToNoAllocation: u64, DataBytesSkippedDueToInvalidRun: u64, DataBytesSkippedDueToIntegrityStream: u64, DataBytesSkippedDueToRegionBeingClean: u64, DataBytesSkippedDueToLockConflict: u64, DataBytesSkippedDueToNoScrubDataFlag: u64, DataBytesSkippedDueToNoScrubNonIntegrityStreamFlag: u64, DataBytesScrubbed: u64, ResumeContext: [1040]u8, }; pub const SharedVirtualDiskSupportType = enum(i32) { sUnsupported = 0, sSupported = 1, SnapshotsSupported = 3, CDPSnapshotsSupported = 7, }; pub const SharedVirtualDisksUnsupported = SharedVirtualDiskSupportType.sUnsupported; pub const SharedVirtualDisksSupported = SharedVirtualDiskSupportType.sSupported; pub const SharedVirtualDiskSnapshotsSupported = SharedVirtualDiskSupportType.SnapshotsSupported; pub const SharedVirtualDiskCDPSnapshotsSupported = SharedVirtualDiskSupportType.CDPSnapshotsSupported; pub const SharedVirtualDiskHandleState = enum(i32) { None = 0, FileShared = 1, HandleShared = 3, }; pub const SharedVirtualDiskHandleStateNone = SharedVirtualDiskHandleState.None; pub const SharedVirtualDiskHandleStateFileShared = SharedVirtualDiskHandleState.FileShared; pub const SharedVirtualDiskHandleStateHandleShared = SharedVirtualDiskHandleState.HandleShared; pub const SHARED_VIRTUAL_DISK_SUPPORT = extern struct { SharedVirtualDiskSupport: SharedVirtualDiskSupportType, HandleState: SharedVirtualDiskHandleState, }; pub const REARRANGE_FILE_DATA = extern struct { SourceStartingOffset: u64, TargetOffset: u64, SourceFileHandle: ?HANDLE, Length: u32, Flags: u32, }; pub const SHUFFLE_FILE_DATA = extern struct { StartingOffset: i64, Length: i64, Flags: u32, }; pub const NETWORK_APP_INSTANCE_EA = extern struct { AppInstanceID: Guid, CsvFlags: u32, }; pub const MONITOR_DISPLAY_STATE = enum(i32) { Off = 0, On = 1, Dim = 2, }; pub const PowerMonitorOff = MONITOR_DISPLAY_STATE.Off; pub const PowerMonitorOn = MONITOR_DISPLAY_STATE.On; pub const PowerMonitorDim = MONITOR_DISPLAY_STATE.Dim; pub const USER_ACTIVITY_PRESENCE = enum(i32) { Present = 0, NotPresent = 1, Inactive = 2, Maximum = 3, // Invalid = 3, this enum value conflicts with Maximum }; pub const PowerUserPresent = USER_ACTIVITY_PRESENCE.Present; pub const PowerUserNotPresent = USER_ACTIVITY_PRESENCE.NotPresent; pub const PowerUserInactive = USER_ACTIVITY_PRESENCE.Inactive; pub const PowerUserMaximum = USER_ACTIVITY_PRESENCE.Maximum; pub const PowerUserInvalid = USER_ACTIVITY_PRESENCE.Maximum; pub const POWER_USER_PRESENCE_TYPE = enum(i32) { NotPresent = 0, Present = 1, Unknown = 255, }; pub const UserNotPresent = POWER_USER_PRESENCE_TYPE.NotPresent; pub const UserPresent = POWER_USER_PRESENCE_TYPE.Present; pub const UserUnknown = POWER_USER_PRESENCE_TYPE.Unknown; pub const POWER_USER_PRESENCE = extern struct { UserPresence: POWER_USER_PRESENCE_TYPE, }; pub const POWER_SESSION_CONNECT = extern struct { Connected: BOOLEAN, Console: BOOLEAN, }; pub const POWER_SESSION_TIMEOUTS = extern struct { InputTimeout: u32, DisplayTimeout: u32, }; pub const POWER_SESSION_RIT_STATE = extern struct { Active: BOOLEAN, LastInputTime: u64, }; pub const POWER_SESSION_WINLOGON = extern struct { SessionId: u32, Console: BOOLEAN, Locked: BOOLEAN, }; pub const POWER_SESSION_ALLOW_EXTERNAL_DMA_DEVICES = extern struct { IsAllowed: BOOLEAN, }; pub const POWER_IDLE_RESILIENCY = extern struct { CoalescingTimeout: u32, IdleResiliencyPeriod: u32, }; pub const POWER_MONITOR_REQUEST_REASON = enum(i32) { Unknown = 0, PowerButton = 1, RemoteConnection = 2, ScMonitorpower = 3, UserInput = 4, AcDcDisplayBurst = 5, UserDisplayBurst = 6, PoSetSystemState = 7, SetThreadExecutionState = 8, FullWake = 9, SessionUnlock = 10, ScreenOffRequest = 11, IdleTimeout = 12, PolicyChange = 13, SleepButton = 14, Lid = 15, BatteryCountChange = 16, GracePeriod = 17, PnP = 18, DP = 19, SxTransition = 20, SystemIdle = 21, NearProximity = 22, ThermalStandby = 23, ResumePdc = 24, ResumeS4 = 25, Terminal = 26, PdcSignal = 27, AcDcDisplayBurstSuppressed = 28, SystemStateEntered = 29, Winrt = 30, UserInputKeyboard = 31, UserInputMouse = 32, UserInputTouchpad = 33, UserInputPen = 34, UserInputAccelerometer = 35, UserInputHid = 36, UserInputPoUserPresent = 37, UserInputSessionSwitch = 38, UserInputInitialization = 39, PdcSignalWindowsMobilePwrNotif = 40, PdcSignalWindowsMobileShell = 41, PdcSignalHeyCortana = 42, PdcSignalHolographicShell = 43, PdcSignalFingerprint = 44, DirectedDrips = 45, Dim = 46, BuiltinPanel = 47, DisplayRequiredUnDim = 48, BatteryCountChangeSuppressed = 49, ResumeModernStandby = 50, TerminalInit = 51, PdcSignalSensorsHumanPresence = 52, BatteryPreCritical = 53, UserInputTouch = 54, Max = 55, }; pub const MonitorRequestReasonUnknown = POWER_MONITOR_REQUEST_REASON.Unknown; pub const MonitorRequestReasonPowerButton = POWER_MONITOR_REQUEST_REASON.PowerButton; pub const MonitorRequestReasonRemoteConnection = POWER_MONITOR_REQUEST_REASON.RemoteConnection; pub const MonitorRequestReasonScMonitorpower = POWER_MONITOR_REQUEST_REASON.ScMonitorpower; pub const MonitorRequestReasonUserInput = POWER_MONITOR_REQUEST_REASON.UserInput; pub const MonitorRequestReasonAcDcDisplayBurst = POWER_MONITOR_REQUEST_REASON.AcDcDisplayBurst; pub const MonitorRequestReasonUserDisplayBurst = POWER_MONITOR_REQUEST_REASON.UserDisplayBurst; pub const MonitorRequestReasonPoSetSystemState = POWER_MONITOR_REQUEST_REASON.PoSetSystemState; pub const MonitorRequestReasonSetThreadExecutionState = POWER_MONITOR_REQUEST_REASON.SetThreadExecutionState; pub const MonitorRequestReasonFullWake = POWER_MONITOR_REQUEST_REASON.FullWake; pub const MonitorRequestReasonSessionUnlock = POWER_MONITOR_REQUEST_REASON.SessionUnlock; pub const MonitorRequestReasonScreenOffRequest = POWER_MONITOR_REQUEST_REASON.ScreenOffRequest; pub const MonitorRequestReasonIdleTimeout = POWER_MONITOR_REQUEST_REASON.IdleTimeout; pub const MonitorRequestReasonPolicyChange = POWER_MONITOR_REQUEST_REASON.PolicyChange; pub const MonitorRequestReasonSleepButton = POWER_MONITOR_REQUEST_REASON.SleepButton; pub const MonitorRequestReasonLid = POWER_MONITOR_REQUEST_REASON.Lid; pub const MonitorRequestReasonBatteryCountChange = POWER_MONITOR_REQUEST_REASON.BatteryCountChange; pub const MonitorRequestReasonGracePeriod = POWER_MONITOR_REQUEST_REASON.GracePeriod; pub const MonitorRequestReasonPnP = POWER_MONITOR_REQUEST_REASON.PnP; pub const MonitorRequestReasonDP = POWER_MONITOR_REQUEST_REASON.DP; pub const MonitorRequestReasonSxTransition = POWER_MONITOR_REQUEST_REASON.SxTransition; pub const MonitorRequestReasonSystemIdle = POWER_MONITOR_REQUEST_REASON.SystemIdle; pub const MonitorRequestReasonNearProximity = POWER_MONITOR_REQUEST_REASON.NearProximity; pub const MonitorRequestReasonThermalStandby = POWER_MONITOR_REQUEST_REASON.ThermalStandby; pub const MonitorRequestReasonResumePdc = POWER_MONITOR_REQUEST_REASON.ResumePdc; pub const MonitorRequestReasonResumeS4 = POWER_MONITOR_REQUEST_REASON.ResumeS4; pub const MonitorRequestReasonTerminal = POWER_MONITOR_REQUEST_REASON.Terminal; pub const MonitorRequestReasonPdcSignal = POWER_MONITOR_REQUEST_REASON.PdcSignal; pub const MonitorRequestReasonAcDcDisplayBurstSuppressed = POWER_MONITOR_REQUEST_REASON.AcDcDisplayBurstSuppressed; pub const MonitorRequestReasonSystemStateEntered = POWER_MONITOR_REQUEST_REASON.SystemStateEntered; pub const MonitorRequestReasonWinrt = POWER_MONITOR_REQUEST_REASON.Winrt; pub const MonitorRequestReasonUserInputKeyboard = POWER_MONITOR_REQUEST_REASON.UserInputKeyboard; pub const MonitorRequestReasonUserInputMouse = POWER_MONITOR_REQUEST_REASON.UserInputMouse; pub const MonitorRequestReasonUserInputTouchpad = POWER_MONITOR_REQUEST_REASON.UserInputTouchpad; pub const MonitorRequestReasonUserInputPen = POWER_MONITOR_REQUEST_REASON.UserInputPen; pub const MonitorRequestReasonUserInputAccelerometer = POWER_MONITOR_REQUEST_REASON.UserInputAccelerometer; pub const MonitorRequestReasonUserInputHid = POWER_MONITOR_REQUEST_REASON.UserInputHid; pub const MonitorRequestReasonUserInputPoUserPresent = POWER_MONITOR_REQUEST_REASON.UserInputPoUserPresent; pub const MonitorRequestReasonUserInputSessionSwitch = POWER_MONITOR_REQUEST_REASON.UserInputSessionSwitch; pub const MonitorRequestReasonUserInputInitialization = POWER_MONITOR_REQUEST_REASON.UserInputInitialization; pub const MonitorRequestReasonPdcSignalWindowsMobilePwrNotif = POWER_MONITOR_REQUEST_REASON.PdcSignalWindowsMobilePwrNotif; pub const MonitorRequestReasonPdcSignalWindowsMobileShell = POWER_MONITOR_REQUEST_REASON.PdcSignalWindowsMobileShell; pub const MonitorRequestReasonPdcSignalHeyCortana = POWER_MONITOR_REQUEST_REASON.PdcSignalHeyCortana; pub const MonitorRequestReasonPdcSignalHolographicShell = POWER_MONITOR_REQUEST_REASON.PdcSignalHolographicShell; pub const MonitorRequestReasonPdcSignalFingerprint = POWER_MONITOR_REQUEST_REASON.PdcSignalFingerprint; pub const MonitorRequestReasonDirectedDrips = POWER_MONITOR_REQUEST_REASON.DirectedDrips; pub const MonitorRequestReasonDim = POWER_MONITOR_REQUEST_REASON.Dim; pub const MonitorRequestReasonBuiltinPanel = POWER_MONITOR_REQUEST_REASON.BuiltinPanel; pub const MonitorRequestReasonDisplayRequiredUnDim = POWER_MONITOR_REQUEST_REASON.DisplayRequiredUnDim; pub const MonitorRequestReasonBatteryCountChangeSuppressed = POWER_MONITOR_REQUEST_REASON.BatteryCountChangeSuppressed; pub const MonitorRequestReasonResumeModernStandby = POWER_MONITOR_REQUEST_REASON.ResumeModernStandby; pub const MonitorRequestReasonTerminalInit = POWER_MONITOR_REQUEST_REASON.TerminalInit; pub const MonitorRequestReasonPdcSignalSensorsHumanPresence = POWER_MONITOR_REQUEST_REASON.PdcSignalSensorsHumanPresence; pub const MonitorRequestReasonBatteryPreCritical = POWER_MONITOR_REQUEST_REASON.BatteryPreCritical; pub const MonitorRequestReasonUserInputTouch = POWER_MONITOR_REQUEST_REASON.UserInputTouch; pub const MonitorRequestReasonMax = POWER_MONITOR_REQUEST_REASON.Max; pub const POWER_MONITOR_REQUEST_TYPE = enum(i32) { Off = 0, OnAndPresent = 1, ToggleOn = 2, }; pub const MonitorRequestTypeOff = POWER_MONITOR_REQUEST_TYPE.Off; pub const MonitorRequestTypeOnAndPresent = POWER_MONITOR_REQUEST_TYPE.OnAndPresent; pub const MonitorRequestTypeToggleOn = POWER_MONITOR_REQUEST_TYPE.ToggleOn; pub const POWER_MONITOR_INVOCATION = extern struct { Console: BOOLEAN, RequestReason: POWER_MONITOR_REQUEST_REASON, }; pub const RESUME_PERFORMANCE = extern struct { PostTimeMs: u32, TotalResumeTimeMs: u64, ResumeCompleteTimestamp: u64, }; pub const NOTIFY_USER_POWER_SETTING = extern struct { Guid: Guid, }; pub const APPLICATIONLAUNCH_SETTING_VALUE = extern struct { ActivationTime: LARGE_INTEGER, Flags: u32, ButtonInstanceID: u32, }; pub const POWER_PLATFORM_INFORMATION = extern struct { AoAc: BOOLEAN, }; pub const POWER_SETTING_ALTITUDE = enum(i32) { GROUP_POLICY = 0, USER = 1, RUNTIME_OVERRIDE = 2, PROVISIONING = 3, OEM_CUSTOMIZATION = 4, INTERNAL_OVERRIDE = 5, OS_DEFAULT = 6, }; pub const ALTITUDE_GROUP_POLICY = POWER_SETTING_ALTITUDE.GROUP_POLICY; pub const ALTITUDE_USER = POWER_SETTING_ALTITUDE.USER; pub const ALTITUDE_RUNTIME_OVERRIDE = POWER_SETTING_ALTITUDE.RUNTIME_OVERRIDE; pub const ALTITUDE_PROVISIONING = POWER_SETTING_ALTITUDE.PROVISIONING; pub const ALTITUDE_OEM_CUSTOMIZATION = POWER_SETTING_ALTITUDE.OEM_CUSTOMIZATION; pub const ALTITUDE_INTERNAL_OVERRIDE = POWER_SETTING_ALTITUDE.INTERNAL_OVERRIDE; pub const ALTITUDE_OS_DEFAULT = POWER_SETTING_ALTITUDE.OS_DEFAULT; pub const PPM_WMI_LEGACY_PERFSTATE = extern struct { Frequency: u32, Flags: u32, PercentFrequency: u32, }; pub const PPM_WMI_IDLE_STATE = extern struct { Latency: u32, Power: u32, TimeCheck: u32, PromotePercent: u8, DemotePercent: u8, StateType: u8, Reserved: u8, StateFlags: u32, Context: u32, IdleHandler: u32, Reserved1: u32, }; pub const PPM_WMI_IDLE_STATES = extern struct { Type: u32, Count: u32, TargetState: u32, OldState: u32, TargetProcessors: u64, State: [1]PPM_WMI_IDLE_STATE, }; pub const PPM_WMI_IDLE_STATES_EX = extern struct { Type: u32, Count: u32, TargetState: u32, OldState: u32, TargetProcessors: ?*anyopaque, State: [1]PPM_WMI_IDLE_STATE, }; pub const PPM_WMI_PERF_STATE = extern struct { Frequency: u32, Power: u32, PercentFrequency: u8, IncreaseLevel: u8, DecreaseLevel: u8, Type: u8, IncreaseTime: u32, DecreaseTime: u32, Control: u64, Status: u64, HitCount: u32, Reserved1: u32, Reserved2: u64, Reserved3: u64, }; pub const PPM_WMI_PERF_STATES = extern struct { Count: u32, MaxFrequency: u32, CurrentState: u32, MaxPerfState: u32, MinPerfState: u32, LowestPerfState: u32, ThermalConstraint: u32, BusyAdjThreshold: u8, PolicyType: u8, Type: u8, Reserved: u8, TimerInterval: u32, TargetProcessors: u64, PStateHandler: u32, PStateContext: u32, TStateHandler: u32, TStateContext: u32, FeedbackHandler: u32, Reserved1: u32, Reserved2: u64, State: [1]PPM_WMI_PERF_STATE, }; pub const PPM_WMI_PERF_STATES_EX = extern struct { Count: u32, MaxFrequency: u32, CurrentState: u32, MaxPerfState: u32, MinPerfState: u32, LowestPerfState: u32, ThermalConstraint: u32, BusyAdjThreshold: u8, PolicyType: u8, Type: u8, Reserved: u8, TimerInterval: u32, TargetProcessors: ?*anyopaque, PStateHandler: u32, PStateContext: u32, TStateHandler: u32, TStateContext: u32, FeedbackHandler: u32, Reserved1: u32, Reserved2: u64, State: [1]PPM_WMI_PERF_STATE, }; pub const PPM_IDLE_STATE_ACCOUNTING = extern struct { IdleTransitions: u32, FailedTransitions: u32, InvalidBucketIndex: u32, TotalTime: u64, IdleTimeBuckets: [6]u32, }; pub const PPM_IDLE_ACCOUNTING = extern struct { StateCount: u32, TotalTransitions: u32, ResetCount: u32, StartTime: u64, State: [1]PPM_IDLE_STATE_ACCOUNTING, }; pub const PPM_IDLE_STATE_BUCKET_EX = extern struct { TotalTimeUs: u64, MinTimeUs: u32, MaxTimeUs: u32, Count: u32, }; pub const PPM_IDLE_STATE_ACCOUNTING_EX = extern struct { TotalTime: u64, IdleTransitions: u32, FailedTransitions: u32, InvalidBucketIndex: u32, MinTimeUs: u32, MaxTimeUs: u32, CancelledTransitions: u32, IdleTimeBuckets: [16]PPM_IDLE_STATE_BUCKET_EX, }; pub const PPM_IDLE_ACCOUNTING_EX = extern struct { StateCount: u32, TotalTransitions: u32, ResetCount: u32, AbortCount: u32, StartTime: u64, State: [1]PPM_IDLE_STATE_ACCOUNTING_EX, }; pub const PPM_PERFSTATE_EVENT = extern struct { State: u32, Status: u32, Latency: u32, Speed: u32, Processor: u32, }; pub const PPM_PERFSTATE_DOMAIN_EVENT = extern struct { State: u32, Latency: u32, Speed: u32, Processors: u64, }; pub const PPM_IDLESTATE_EVENT = extern struct { NewState: u32, OldState: u32, Processors: u64, }; pub const PPM_THERMALCHANGE_EVENT = extern struct { ThermalConstraint: u32, Processors: u64, }; pub const PPM_THERMAL_POLICY_EVENT = extern struct { Mode: u8, Processors: u64, }; pub const PROCESSOR_IDLESTATE_INFO = extern struct { TimeCheck: u32, DemotePercent: u8, PromotePercent: u8, Spare: [2]u8, }; pub const PROCESSOR_IDLESTATE_POLICY = extern struct { Revision: u16, Flags: extern union { AsWORD: u16, Anonymous: extern struct { _bitfield: u16, }, }, PolicyCount: u32, Policy: [3]PROCESSOR_IDLESTATE_INFO, }; pub const PROCESSOR_PERFSTATE_POLICY = extern struct { Revision: u32, MaxThrottle: u8, MinThrottle: u8, BusyAdjThreshold: u8, Anonymous: extern union { Spare: u8, Flags: extern union { AsBYTE: u8, Anonymous: extern struct { _bitfield: u8, }, }, }, TimeCheck: u32, IncreaseTime: u32, DecreaseTime: u32, IncreasePercent: u32, DecreasePercent: u32, }; pub const HIBERFILE_BUCKET_SIZE = enum(i32) { @"1GB" = 0, @"2GB" = 1, @"4GB" = 2, @"8GB" = 3, @"16GB" = 4, @"32GB" = 5, Unlimited = 6, Max = 7, }; pub const HiberFileBucket1GB = HIBERFILE_BUCKET_SIZE.@"1GB"; pub const HiberFileBucket2GB = HIBERFILE_BUCKET_SIZE.@"2GB"; pub const HiberFileBucket4GB = HIBERFILE_BUCKET_SIZE.@"4GB"; pub const HiberFileBucket8GB = HIBERFILE_BUCKET_SIZE.@"8GB"; pub const HiberFileBucket16GB = HIBERFILE_BUCKET_SIZE.@"16GB"; pub const HiberFileBucket32GB = HIBERFILE_BUCKET_SIZE.@"32GB"; pub const HiberFileBucketUnlimited = HIBERFILE_BUCKET_SIZE.Unlimited; pub const HiberFileBucketMax = HIBERFILE_BUCKET_SIZE.Max; pub const HIBERFILE_BUCKET = extern struct { MaxPhysicalMemory: u64, PhysicalMemoryPercent: [3]u32, }; pub const IMAGE_DOS_HEADER = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug e_magic: u16, e_cblp: u16, e_cp: u16, e_crlc: u16, e_cparhdr: u16, e_minalloc: u16, e_maxalloc: u16, e_ss: u16, e_sp: u16, e_csum: u16, e_ip: u16, e_cs: u16, e_lfarlc: u16, e_ovno: u16, e_res: [4]u16, e_oemid: u16, e_oeminfo: u16, e_res2: [10]u16, e_lfanew: i32, }; pub const IMAGE_OS2_HEADER = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug ne_magic: u16, ne_ver: CHAR, ne_rev: CHAR, ne_enttab: u16, ne_cbenttab: u16, ne_crc: i32, ne_flags: u16, ne_autodata: u16, ne_heap: u16, ne_stack: u16, ne_csip: i32, ne_sssp: i32, ne_cseg: u16, ne_cmod: u16, ne_cbnrestab: u16, ne_segtab: u16, ne_rsrctab: u16, ne_restab: u16, ne_modtab: u16, ne_imptab: u16, ne_nrestab: i32, ne_cmovent: u16, ne_align: u16, ne_cres: u16, ne_exetyp: u8, ne_flagsothers: u8, ne_pretthunks: u16, ne_psegrefbytes: u16, ne_swaparea: u16, ne_expver: u16, }; pub const IMAGE_VXD_HEADER = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug e32_magic: u16, e32_border: u8, e32_worder: u8, e32_level: u32, e32_cpu: u16, e32_os: u16, e32_ver: u32, e32_mflags: u32, e32_mpages: u32, e32_startobj: u32, e32_eip: u32, e32_stackobj: u32, e32_esp: u32, e32_pagesize: u32, e32_lastpagesize: u32, e32_fixupsize: u32, e32_fixupsum: u32, e32_ldrsize: u32, e32_ldrsum: u32, e32_objtab: u32, e32_objcnt: u32, e32_objmap: u32, e32_itermap: u32, e32_rsrctab: u32, e32_rsrccnt: u32, e32_restab: u32, e32_enttab: u32, e32_dirtab: u32, e32_dircnt: u32, e32_fpagetab: u32, e32_frectab: u32, e32_impmod: u32, e32_impmodcnt: u32, e32_impproc: u32, e32_pagesum: u32, e32_datapage: u32, e32_preload: u32, e32_nrestab: u32, e32_cbnrestab: u32, e32_nressum: u32, e32_autodata: u32, e32_debuginfo: u32, e32_debuglen: u32, e32_instpreload: u32, e32_instdemand: u32, e32_heapsize: u32, e32_res3: [12]u8, e32_winresoff: u32, e32_winreslen: u32, e32_devid: u16, e32_ddkver: u16, }; pub const ANON_OBJECT_HEADER = extern struct { Sig1: u16, Sig2: u16, Version: u16, Machine: u16, TimeDateStamp: u32, ClassID: Guid, SizeOfData: u32, }; pub const ANON_OBJECT_HEADER_V2 = extern struct { Sig1: u16, Sig2: u16, Version: u16, Machine: u16, TimeDateStamp: u32, ClassID: Guid, SizeOfData: u32, Flags: u32, MetaDataSize: u32, MetaDataOffset: u32, }; pub const ANON_OBJECT_HEADER_BIGOBJ = extern struct { Sig1: u16, Sig2: u16, Version: u16, Machine: u16, TimeDateStamp: u32, ClassID: Guid, SizeOfData: u32, Flags: u32, MetaDataSize: u32, MetaDataOffset: u32, NumberOfSections: u32, PointerToSymbolTable: u32, NumberOfSymbols: u32, }; pub const IMAGE_SYMBOL = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug N: extern union { // WARNING: unable to add field alignment because it's not implemented for unions ShortName: [8]u8, Name: extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug Short: u32, Long: u32, }, LongName: [2]u32, }, Value: u32, SectionNumber: i16, Type: u16, StorageClass: u8, NumberOfAuxSymbols: u8, }; pub const IMAGE_SYMBOL_EX = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug N: extern union { // WARNING: unable to add field alignment because it's not implemented for unions ShortName: [8]u8, Name: extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug Short: u32, Long: u32, }, LongName: [2]u32, }, Value: u32, SectionNumber: i32, Type: u16, StorageClass: u8, NumberOfAuxSymbols: u8, }; pub const IMAGE_AUX_SYMBOL_TOKEN_DEF = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug bAuxType: u8, bReserved: u8, SymbolTableIndex: u32, rgbReserved: [12]u8, }; pub const IMAGE_AUX_SYMBOL = extern union { Sym: extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug TagIndex: u32, Misc: extern union { // WARNING: unable to add field alignment because it's not implemented for unions LnSz: extern struct { Linenumber: u16, Size: u16, }, TotalSize: u32, }, FcnAry: extern union { Function: extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug PointerToLinenumber: u32, PointerToNextFunction: u32, }, Array: extern struct { Dimension: [4]u16, }, }, TvIndex: u16, }, File: extern struct { Name: [18]u8, }, Section: extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug Length: u32, NumberOfRelocations: u16, NumberOfLinenumbers: u16, CheckSum: u32, Number: i16, Selection: u8, bReserved: u8, HighNumber: i16, }, TokenDef: IMAGE_AUX_SYMBOL_TOKEN_DEF, CRC: extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug crc: u32, rgbReserved: [14]u8, }, }; pub const IMAGE_AUX_SYMBOL_EX = extern union { Sym: extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug WeakDefaultSymIndex: u32, WeakSearchType: u32, rgbReserved: [12]u8, }, File: extern struct { Name: [20]u8, }, Section: extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug Length: u32, NumberOfRelocations: u16, NumberOfLinenumbers: u16, CheckSum: u32, Number: i16, Selection: u8, bReserved: u8, HighNumber: i16, rgbReserved: [2]u8, }, Anonymous: extern struct { TokenDef: IMAGE_AUX_SYMBOL_TOKEN_DEF, rgbReserved: [2]u8, }, CRC: extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug crc: u32, rgbReserved: [16]u8, }, }; pub const IMAGE_AUX_SYMBOL_TYPE = enum(i32) { F = 1, }; pub const IMAGE_AUX_SYMBOL_TYPE_TOKEN_DEF = IMAGE_AUX_SYMBOL_TYPE.F; pub const IMAGE_RELOCATION = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug Anonymous: extern union { // WARNING: unable to add field alignment because it's not implemented for unions VirtualAddress: u32, RelocCount: u32, }, SymbolTableIndex: u32, Type: u16, }; pub const IMAGE_LINENUMBER = extern struct { Type: extern union { // WARNING: unable to add field alignment because it's not implemented for unions SymbolTableIndex: u32, VirtualAddress: u32, }, Linenumber: u16, }; pub const IMAGE_BASE_RELOCATION = extern struct { VirtualAddress: u32, SizeOfBlock: u32, }; pub const IMAGE_ARCHIVE_MEMBER_HEADER = extern struct { Name: [16]u8, Date: [12]u8, UserID: [6]u8, GroupID: [6]u8, Mode: [8]u8, Size: [10]u8, EndHeader: [2]u8, }; pub const IMAGE_EXPORT_DIRECTORY = extern struct { Characteristics: u32, TimeDateStamp: u32, MajorVersion: u16, MinorVersion: u16, Name: u32, Base: u32, NumberOfFunctions: u32, NumberOfNames: u32, AddressOfFunctions: u32, AddressOfNames: u32, AddressOfNameOrdinals: u32, }; pub const IMAGE_IMPORT_BY_NAME = extern struct { Hint: u16, Name: [1]CHAR, }; pub const PIMAGE_TLS_CALLBACK = fn( DllHandle: ?*anyopaque, Reason: u32, Reserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const IMAGE_TLS_DIRECTORY64 = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug StartAddressOfRawData: u64, EndAddressOfRawData: u64, AddressOfIndex: u64, AddressOfCallBacks: u64, SizeOfZeroFill: u32, Anonymous: extern union { Characteristics: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const IMAGE_TLS_DIRECTORY32 = extern struct { StartAddressOfRawData: u32, EndAddressOfRawData: u32, AddressOfIndex: u32, AddressOfCallBacks: u32, SizeOfZeroFill: u32, Anonymous: extern union { Characteristics: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const IMAGE_IMPORT_DESCRIPTOR = extern struct { Anonymous: extern union { Characteristics: u32, OriginalFirstThunk: u32, }, TimeDateStamp: u32, ForwarderChain: u32, Name: u32, FirstThunk: u32, }; pub const IMAGE_BOUND_IMPORT_DESCRIPTOR = extern struct { TimeDateStamp: u32, OffsetModuleName: u16, NumberOfModuleForwarderRefs: u16, }; pub const IMAGE_BOUND_FORWARDER_REF = extern struct { TimeDateStamp: u32, OffsetModuleName: u16, Reserved: u16, }; pub const IMAGE_RESOURCE_DIRECTORY = extern struct { Characteristics: u32, TimeDateStamp: u32, MajorVersion: u16, MinorVersion: u16, NumberOfNamedEntries: u16, NumberOfIdEntries: u16, }; pub const IMAGE_RESOURCE_DIRECTORY_ENTRY = extern struct { Anonymous1: extern union { Anonymous: extern struct { _bitfield: u32, }, Name: u32, Id: u16, }, Anonymous2: extern union { OffsetToData: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const IMAGE_RESOURCE_DIRECTORY_STRING = extern struct { Length: u16, NameString: [1]CHAR, }; pub const IMAGE_RESOURCE_DIR_STRING_U = extern struct { Length: u16, NameString: [1]u16, }; pub const IMAGE_RESOURCE_DATA_ENTRY = extern struct { OffsetToData: u32, Size: u32, CodePage: u32, Reserved: u32, }; pub const IMAGE_DYNAMIC_RELOCATION_TABLE = extern struct { Version: u32, Size: u32, }; pub const IMAGE_DYNAMIC_RELOCATION32 = packed struct { Symbol: u32, BaseRelocSize: u32, }; pub const IMAGE_DYNAMIC_RELOCATION64 = packed struct { Symbol: u64, BaseRelocSize: u32, }; pub const IMAGE_DYNAMIC_RELOCATION32_V2 = packed struct { HeaderSize: u32, FixupInfoSize: u32, Symbol: u32, SymbolGroup: u32, Flags: u32, }; pub const IMAGE_DYNAMIC_RELOCATION64_V2 = packed struct { HeaderSize: u32, FixupInfoSize: u32, Symbol: u64, SymbolGroup: u32, Flags: u32, }; pub const IMAGE_PROLOGUE_DYNAMIC_RELOCATION_HEADER = extern struct { PrologueByteCount: u8, }; pub const IMAGE_EPILOGUE_DYNAMIC_RELOCATION_HEADER = packed struct { EpilogueCount: u32, EpilogueByteCount: u8, BranchDescriptorElementSize: u8, BranchDescriptorCount: u16, }; pub const IMAGE_IMPORT_CONTROL_TRANSFER_DYNAMIC_RELOCATION = packed struct { _bitfield: u32, }; pub const IMAGE_INDIR_CONTROL_TRANSFER_DYNAMIC_RELOCATION = packed struct { _bitfield: u16, }; pub const IMAGE_SWITCHTABLE_BRANCH_DYNAMIC_RELOCATION = packed struct { _bitfield: u16, }; pub const IMAGE_HOT_PATCH_INFO = extern struct { Version: u32, Size: u32, SequenceNumber: u32, BaseImageList: u32, BaseImageCount: u32, BufferOffset: u32, ExtraPatchSize: u32, }; pub const IMAGE_HOT_PATCH_BASE = extern struct { SequenceNumber: u32, Flags: u32, OriginalTimeDateStamp: u32, OriginalCheckSum: u32, CodeIntegrityInfo: u32, CodeIntegritySize: u32, PatchTable: u32, BufferOffset: u32, }; pub const IMAGE_HOT_PATCH_HASHES = extern struct { SHA256: [32]u8, SHA1: [20]u8, }; pub const IMAGE_CE_RUNTIME_FUNCTION_ENTRY = extern struct { FuncStart: u32, _bitfield: u32, }; pub const IMAGE_ARM_RUNTIME_FUNCTION_ENTRY = extern struct { BeginAddress: u32, Anonymous: extern union { UnwindData: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const ARM64_FNPDATA_FLAGS = enum(i32) { RefToFullXdata = 0, PackedUnwindFunction = 1, PackedUnwindFragment = 2, }; pub const PdataRefToFullXdata = ARM64_FNPDATA_FLAGS.RefToFullXdata; pub const PdataPackedUnwindFunction = ARM64_FNPDATA_FLAGS.PackedUnwindFunction; pub const PdataPackedUnwindFragment = ARM64_FNPDATA_FLAGS.PackedUnwindFragment; pub const ARM64_FNPDATA_CR = enum(i32) { Unchained = 0, UnchainedSavedLr = 1, ChainedWithPac = 2, Chained = 3, }; pub const PdataCrUnchained = ARM64_FNPDATA_CR.Unchained; pub const PdataCrUnchainedSavedLr = ARM64_FNPDATA_CR.UnchainedSavedLr; pub const PdataCrChainedWithPac = ARM64_FNPDATA_CR.ChainedWithPac; pub const PdataCrChained = ARM64_FNPDATA_CR.Chained; pub const IMAGE_ARM64_RUNTIME_FUNCTION_ENTRY_XDATA = extern union { HeaderData: u32, Anonymous: extern struct { _bitfield: u32, }, }; pub const IMAGE_ALPHA64_RUNTIME_FUNCTION_ENTRY = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug BeginAddress: u64, EndAddress: u64, ExceptionHandler: u64, HandlerData: u64, PrologEndAddress: u64, }; pub const IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY = extern struct { BeginAddress: u32, EndAddress: u32, ExceptionHandler: u32, HandlerData: u32, PrologEndAddress: u32, }; pub const IMAGE_DEBUG_MISC = extern struct { DataType: u32, Length: u32, Unicode: BOOLEAN, Reserved: [3]u8, Data: [1]u8, }; pub const IMAGE_SEPARATE_DEBUG_HEADER = extern struct { Signature: u16, Flags: u16, Machine: u16, Characteristics: u16, TimeDateStamp: u32, CheckSum: u32, ImageBase: u32, SizeOfImage: u32, NumberOfSections: u32, ExportedNamesSize: u32, DebugDirectorySize: u32, SectionAlignment: u32, Reserved: [2]u32, }; pub const NON_PAGED_DEBUG_INFO = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug Signature: u16, Flags: u16, Size: u32, Machine: u16, Characteristics: u16, TimeDateStamp: u32, CheckSum: u32, SizeOfImage: u32, ImageBase: u64, }; pub const IMAGE_ARCHITECTURE_HEADER = extern struct { _bitfield: u32, FirstEntryRVA: u32, }; pub const IMAGE_ARCHITECTURE_ENTRY = extern struct { FixupInstRVA: u32, NewInst: u32, }; pub const IMPORT_OBJECT_HEADER = extern struct { Sig1: u16, Sig2: u16, Version: u16, Machine: u16, TimeDateStamp: u32, SizeOfData: u32, Anonymous: extern union { Ordinal: u16, Hint: u16, }, _bitfield: u16, }; pub const IMPORT_OBJECT_TYPE = enum(i32) { CODE = 0, DATA = 1, CONST = 2, }; pub const IMPORT_OBJECT_CODE = IMPORT_OBJECT_TYPE.CODE; pub const IMPORT_OBJECT_DATA = IMPORT_OBJECT_TYPE.DATA; pub const IMPORT_OBJECT_CONST = IMPORT_OBJECT_TYPE.CONST; pub const IMPORT_OBJECT_NAME_TYPE = enum(i32) { ORDINAL = 0, NAME = 1, NAME_NO_PREFIX = 2, NAME_UNDECORATE = 3, NAME_EXPORTAS = 4, }; pub const IMPORT_OBJECT_ORDINAL = IMPORT_OBJECT_NAME_TYPE.ORDINAL; pub const IMPORT_OBJECT_NAME = IMPORT_OBJECT_NAME_TYPE.NAME; pub const IMPORT_OBJECT_NAME_NO_PREFIX = IMPORT_OBJECT_NAME_TYPE.NAME_NO_PREFIX; pub const IMPORT_OBJECT_NAME_UNDECORATE = IMPORT_OBJECT_NAME_TYPE.NAME_UNDECORATE; pub const IMPORT_OBJECT_NAME_EXPORTAS = IMPORT_OBJECT_NAME_TYPE.NAME_EXPORTAS; pub const ReplacesCorHdrNumericDefines = enum(i32) { COMIMAGE_FLAGS_ILONLY = 1, COMIMAGE_FLAGS_32BITREQUIRED = 2, COMIMAGE_FLAGS_IL_LIBRARY = 4, COMIMAGE_FLAGS_STRONGNAMESIGNED = 8, COMIMAGE_FLAGS_NATIVE_ENTRYPOINT = 16, COMIMAGE_FLAGS_TRACKDEBUGDATA = 65536, COMIMAGE_FLAGS_32BITPREFERRED = 131072, // COR_VERSION_MAJOR_V2 = 2, this enum value conflicts with COMIMAGE_FLAGS_32BITREQUIRED // COR_VERSION_MAJOR = 2, this enum value conflicts with COMIMAGE_FLAGS_32BITREQUIRED COR_VERSION_MINOR = 5, // COR_DELETED_NAME_LENGTH = 8, this enum value conflicts with COMIMAGE_FLAGS_STRONGNAMESIGNED // COR_VTABLEGAP_NAME_LENGTH = 8, this enum value conflicts with COMIMAGE_FLAGS_STRONGNAMESIGNED // NATIVE_TYPE_MAX_CB = 1, this enum value conflicts with COMIMAGE_FLAGS_ILONLY COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE = 255, // IMAGE_COR_MIH_METHODRVA = 1, this enum value conflicts with COMIMAGE_FLAGS_ILONLY // IMAGE_COR_MIH_EHRVA = 2, this enum value conflicts with COMIMAGE_FLAGS_32BITREQUIRED // IMAGE_COR_MIH_BASICBLOCK = 8, this enum value conflicts with COMIMAGE_FLAGS_STRONGNAMESIGNED // COR_VTABLE_32BIT = 1, this enum value conflicts with COMIMAGE_FLAGS_ILONLY // COR_VTABLE_64BIT = 2, this enum value conflicts with COMIMAGE_FLAGS_32BITREQUIRED // COR_VTABLE_FROM_UNMANAGED = 4, this enum value conflicts with COMIMAGE_FLAGS_IL_LIBRARY // COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN = 8, this enum value conflicts with COMIMAGE_FLAGS_STRONGNAMESIGNED // COR_VTABLE_CALL_MOST_DERIVED = 16, this enum value conflicts with COMIMAGE_FLAGS_NATIVE_ENTRYPOINT IMAGE_COR_EATJ_THUNK_SIZE = 32, MAX_CLASS_NAME = 1024, // MAX_PACKAGE_NAME = 1024, this enum value conflicts with MAX_CLASS_NAME }; pub const COMIMAGE_FLAGS_ILONLY = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_ILONLY; pub const COMIMAGE_FLAGS_32BITREQUIRED = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED; pub const COMIMAGE_FLAGS_IL_LIBRARY = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_IL_LIBRARY; pub const COMIMAGE_FLAGS_STRONGNAMESIGNED = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED; pub const COMIMAGE_FLAGS_NATIVE_ENTRYPOINT = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_NATIVE_ENTRYPOINT; pub const COMIMAGE_FLAGS_TRACKDEBUGDATA = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_TRACKDEBUGDATA; pub const COMIMAGE_FLAGS_32BITPREFERRED = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITPREFERRED; pub const COR_VERSION_MAJOR_V2 = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED; pub const COR_VERSION_MAJOR = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED; pub const COR_VERSION_MINOR = ReplacesCorHdrNumericDefines.COR_VERSION_MINOR; pub const COR_DELETED_NAME_LENGTH = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED; pub const COR_VTABLEGAP_NAME_LENGTH = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED; pub const NATIVE_TYPE_MAX_CB = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_ILONLY; pub const COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE = ReplacesCorHdrNumericDefines.COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE; pub const IMAGE_COR_MIH_METHODRVA = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_ILONLY; pub const IMAGE_COR_MIH_EHRVA = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED; pub const IMAGE_COR_MIH_BASICBLOCK = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED; pub const COR_VTABLE_32BIT = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_ILONLY; pub const COR_VTABLE_64BIT = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED; pub const COR_VTABLE_FROM_UNMANAGED = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_IL_LIBRARY; pub const COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED; pub const COR_VTABLE_CALL_MOST_DERIVED = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_NATIVE_ENTRYPOINT; pub const IMAGE_COR_EATJ_THUNK_SIZE = ReplacesCorHdrNumericDefines.IMAGE_COR_EATJ_THUNK_SIZE; pub const MAX_CLASS_NAME = ReplacesCorHdrNumericDefines.MAX_CLASS_NAME; pub const MAX_PACKAGE_NAME = ReplacesCorHdrNumericDefines.MAX_CLASS_NAME; pub const RTL_UMS_SCHEDULER_REASON = enum(i32) { Startup = 0, ThreadBlocked = 1, ThreadYield = 2, }; pub const UmsSchedulerStartup = RTL_UMS_SCHEDULER_REASON.Startup; pub const UmsSchedulerThreadBlocked = RTL_UMS_SCHEDULER_REASON.ThreadBlocked; pub const UmsSchedulerThreadYield = RTL_UMS_SCHEDULER_REASON.ThreadYield; pub const IMAGE_POLICY_ENTRY_TYPE = enum(i32) { None = 0, Bool = 1, Int8 = 2, UInt8 = 3, Int16 = 4, UInt16 = 5, Int32 = 6, UInt32 = 7, Int64 = 8, UInt64 = 9, AnsiString = 10, UnicodeString = 11, Override = 12, Maximum = 13, }; pub const ImagePolicyEntryTypeNone = IMAGE_POLICY_ENTRY_TYPE.None; pub const ImagePolicyEntryTypeBool = IMAGE_POLICY_ENTRY_TYPE.Bool; pub const ImagePolicyEntryTypeInt8 = IMAGE_POLICY_ENTRY_TYPE.Int8; pub const ImagePolicyEntryTypeUInt8 = IMAGE_POLICY_ENTRY_TYPE.UInt8; pub const ImagePolicyEntryTypeInt16 = IMAGE_POLICY_ENTRY_TYPE.Int16; pub const ImagePolicyEntryTypeUInt16 = IMAGE_POLICY_ENTRY_TYPE.UInt16; pub const ImagePolicyEntryTypeInt32 = IMAGE_POLICY_ENTRY_TYPE.Int32; pub const ImagePolicyEntryTypeUInt32 = IMAGE_POLICY_ENTRY_TYPE.UInt32; pub const ImagePolicyEntryTypeInt64 = IMAGE_POLICY_ENTRY_TYPE.Int64; pub const ImagePolicyEntryTypeUInt64 = IMAGE_POLICY_ENTRY_TYPE.UInt64; pub const ImagePolicyEntryTypeAnsiString = IMAGE_POLICY_ENTRY_TYPE.AnsiString; pub const ImagePolicyEntryTypeUnicodeString = IMAGE_POLICY_ENTRY_TYPE.UnicodeString; pub const ImagePolicyEntryTypeOverride = IMAGE_POLICY_ENTRY_TYPE.Override; pub const ImagePolicyEntryTypeMaximum = IMAGE_POLICY_ENTRY_TYPE.Maximum; pub const IMAGE_POLICY_ID = enum(i32) { None = 0, Etw = 1, Debug = 2, CrashDump = 3, CrashDumpKey = 4, CrashDumpKeyGuid = 5, ParentSd = 6, ParentSdRev = 7, Svn = 8, DeviceId = 9, Capability = 10, ScenarioId = 11, Maximum = 12, }; pub const ImagePolicyIdNone = IMAGE_POLICY_ID.None; pub const ImagePolicyIdEtw = IMAGE_POLICY_ID.Etw; pub const ImagePolicyIdDebug = IMAGE_POLICY_ID.Debug; pub const ImagePolicyIdCrashDump = IMAGE_POLICY_ID.CrashDump; pub const ImagePolicyIdCrashDumpKey = IMAGE_POLICY_ID.CrashDumpKey; pub const ImagePolicyIdCrashDumpKeyGuid = IMAGE_POLICY_ID.CrashDumpKeyGuid; pub const ImagePolicyIdParentSd = IMAGE_POLICY_ID.ParentSd; pub const ImagePolicyIdParentSdRev = IMAGE_POLICY_ID.ParentSdRev; pub const ImagePolicyIdSvn = IMAGE_POLICY_ID.Svn; pub const ImagePolicyIdDeviceId = IMAGE_POLICY_ID.DeviceId; pub const ImagePolicyIdCapability = IMAGE_POLICY_ID.Capability; pub const ImagePolicyIdScenarioId = IMAGE_POLICY_ID.ScenarioId; pub const ImagePolicyIdMaximum = IMAGE_POLICY_ID.Maximum; pub const IMAGE_POLICY_ENTRY = extern struct { Type: IMAGE_POLICY_ENTRY_TYPE, PolicyId: IMAGE_POLICY_ID, u: extern union { None: ?*const anyopaque, BoolValue: BOOLEAN, Int8Value: i8, UInt8Value: u8, Int16Value: i16, UInt16Value: u16, Int32Value: i32, UInt32Value: u32, Int64Value: i64, UInt64Value: u64, AnsiStringValue: ?[*:0]const u8, UnicodeStringValue: ?[*:0]const u16, }, }; pub const IMAGE_POLICY_METADATA = extern struct { Version: u8, Reserved0: [7]u8, ApplicationId: u64, Policies: [1]IMAGE_POLICY_ENTRY, }; pub const HEAP_OPTIMIZE_RESOURCES_INFORMATION = extern struct { Version: u32, Flags: u32, }; pub const WORKERCALLBACKFUNC = fn( param0: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const APC_CALLBACK_FUNCTION = fn( param0: u32, param1: ?*anyopaque, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const ACTIVATION_CONTEXT_INFO_CLASS = enum(i32) { ActivationContextBasicInformation = 1, ActivationContextDetailedInformation = 2, AssemblyDetailedInformationInActivationContext = 3, FileInformationInAssemblyOfAssemblyInActivationContext = 4, RunlevelInformationInActivationContext = 5, CompatibilityInformationInActivationContext = 6, ActivationContextManifestResourceName = 7, MaxActivationContextInfoClass = 8, // AssemblyDetailedInformationInActivationContxt = 3, this enum value conflicts with AssemblyDetailedInformationInActivationContext // FileInformationInAssemblyOfAssemblyInActivationContxt = 4, this enum value conflicts with FileInformationInAssemblyOfAssemblyInActivationContext }; pub const ActivationContextBasicInformation = ACTIVATION_CONTEXT_INFO_CLASS.ActivationContextBasicInformation; pub const ActivationContextDetailedInformation = ACTIVATION_CONTEXT_INFO_CLASS.ActivationContextDetailedInformation; pub const AssemblyDetailedInformationInActivationContext = ACTIVATION_CONTEXT_INFO_CLASS.AssemblyDetailedInformationInActivationContext; pub const FileInformationInAssemblyOfAssemblyInActivationContext = ACTIVATION_CONTEXT_INFO_CLASS.FileInformationInAssemblyOfAssemblyInActivationContext; pub const RunlevelInformationInActivationContext = ACTIVATION_CONTEXT_INFO_CLASS.RunlevelInformationInActivationContext; pub const CompatibilityInformationInActivationContext = ACTIVATION_CONTEXT_INFO_CLASS.CompatibilityInformationInActivationContext; pub const ActivationContextManifestResourceName = ACTIVATION_CONTEXT_INFO_CLASS.ActivationContextManifestResourceName; pub const MaxActivationContextInfoClass = ACTIVATION_CONTEXT_INFO_CLASS.MaxActivationContextInfoClass; pub const AssemblyDetailedInformationInActivationContxt = ACTIVATION_CONTEXT_INFO_CLASS.AssemblyDetailedInformationInActivationContext; pub const FileInformationInAssemblyOfAssemblyInActivationContxt = ACTIVATION_CONTEXT_INFO_CLASS.FileInformationInAssemblyOfAssemblyInActivationContext; pub const SUPPORTED_OS_INFO = extern struct { MajorVersion: u16, MinorVersion: u16, }; pub const MAXVERSIONTESTED_INFO = extern struct { MaxVersionTested: u64, }; pub const PACKEDEVENTINFO = extern struct { ulSize: u32, ulNumEventsForLogFile: u32, ulOffsets: [1]u32, }; pub const CM_SERVICE_NODE_TYPE = enum(i32) { DriverType = 1, FileSystemType = 2, Win32ServiceOwnProcess = 16, Win32ServiceShareProcess = 32, AdapterType = 4, RecognizerType = 8, }; pub const DriverType = CM_SERVICE_NODE_TYPE.DriverType; pub const FileSystemType = CM_SERVICE_NODE_TYPE.FileSystemType; pub const Win32ServiceOwnProcess = CM_SERVICE_NODE_TYPE.Win32ServiceOwnProcess; pub const Win32ServiceShareProcess = CM_SERVICE_NODE_TYPE.Win32ServiceShareProcess; pub const AdapterType = CM_SERVICE_NODE_TYPE.AdapterType; pub const RecognizerType = CM_SERVICE_NODE_TYPE.RecognizerType; pub const CM_SERVICE_LOAD_TYPE = enum(i32) { BootLoad = 0, SystemLoad = 1, AutoLoad = 2, DemandLoad = 3, DisableLoad = 4, }; pub const BootLoad = CM_SERVICE_LOAD_TYPE.BootLoad; pub const SystemLoad = CM_SERVICE_LOAD_TYPE.SystemLoad; pub const AutoLoad = CM_SERVICE_LOAD_TYPE.AutoLoad; pub const DemandLoad = CM_SERVICE_LOAD_TYPE.DemandLoad; pub const DisableLoad = CM_SERVICE_LOAD_TYPE.DisableLoad; pub const CM_ERROR_CONTROL_TYPE = enum(i32) { IgnoreError = 0, NormalError = 1, SevereError = 2, CriticalError = 3, }; pub const IgnoreError = CM_ERROR_CONTROL_TYPE.IgnoreError; pub const NormalError = CM_ERROR_CONTROL_TYPE.NormalError; pub const SevereError = CM_ERROR_CONTROL_TYPE.SevereError; pub const CriticalError = CM_ERROR_CONTROL_TYPE.CriticalError; pub const TAPE_GET_DRIVE_PARAMETERS = extern struct { ECC: BOOLEAN, Compression: BOOLEAN, DataPadding: BOOLEAN, ReportSetmarks: BOOLEAN, DefaultBlockSize: u32, MaximumBlockSize: u32, MinimumBlockSize: u32, MaximumPartitionCount: u32, FeaturesLow: u32, FeaturesHigh: TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH, EOTWarningZoneSize: u32, }; pub const TAPE_SET_DRIVE_PARAMETERS = extern struct { ECC: BOOLEAN, Compression: BOOLEAN, DataPadding: BOOLEAN, ReportSetmarks: BOOLEAN, EOTWarningZoneSize: u32, }; pub const TAPE_GET_MEDIA_PARAMETERS = extern struct { Capacity: LARGE_INTEGER, Remaining: LARGE_INTEGER, BlockSize: u32, PartitionCount: u32, WriteProtected: BOOLEAN, }; pub const TAPE_SET_MEDIA_PARAMETERS = extern struct { BlockSize: u32, }; pub const TAPE_CREATE_PARTITION = extern struct { Method: u32, Count: u32, Size: u32, }; pub const TAPE_WMI_OPERATIONS = extern struct { Method: u32, DataBufferSize: u32, DataBuffer: ?*anyopaque, }; pub const TAPE_DRIVE_PROBLEM_TYPE = enum(i32) { ProblemNone = 0, ReadWriteWarning = 1, ReadWriteError = 2, ReadWarning = 3, WriteWarning = 4, ReadError = 5, WriteError = 6, HardwareError = 7, UnsupportedMedia = 8, ScsiConnectionError = 9, TimetoClean = 10, CleanDriveNow = 11, MediaLifeExpired = 12, SnappedTape = 13, }; pub const TapeDriveProblemNone = TAPE_DRIVE_PROBLEM_TYPE.ProblemNone; pub const TapeDriveReadWriteWarning = TAPE_DRIVE_PROBLEM_TYPE.ReadWriteWarning; pub const TapeDriveReadWriteError = TAPE_DRIVE_PROBLEM_TYPE.ReadWriteError; pub const TapeDriveReadWarning = TAPE_DRIVE_PROBLEM_TYPE.ReadWarning; pub const TapeDriveWriteWarning = TAPE_DRIVE_PROBLEM_TYPE.WriteWarning; pub const TapeDriveReadError = TAPE_DRIVE_PROBLEM_TYPE.ReadError; pub const TapeDriveWriteError = TAPE_DRIVE_PROBLEM_TYPE.WriteError; pub const TapeDriveHardwareError = TAPE_DRIVE_PROBLEM_TYPE.HardwareError; pub const TapeDriveUnsupportedMedia = TAPE_DRIVE_PROBLEM_TYPE.UnsupportedMedia; pub const TapeDriveScsiConnectionError = TAPE_DRIVE_PROBLEM_TYPE.ScsiConnectionError; pub const TapeDriveTimetoClean = TAPE_DRIVE_PROBLEM_TYPE.TimetoClean; pub const TapeDriveCleanDriveNow = TAPE_DRIVE_PROBLEM_TYPE.CleanDriveNow; pub const TapeDriveMediaLifeExpired = TAPE_DRIVE_PROBLEM_TYPE.MediaLifeExpired; pub const TapeDriveSnappedTape = TAPE_DRIVE_PROBLEM_TYPE.SnappedTape; pub const TRANSACTION_STATE = enum(i32) { Normal = 1, Indoubt = 2, CommittedNotify = 3, }; pub const TransactionStateNormal = TRANSACTION_STATE.Normal; pub const TransactionStateIndoubt = TRANSACTION_STATE.Indoubt; pub const TransactionStateCommittedNotify = TRANSACTION_STATE.CommittedNotify; pub const TRANSACTION_BASIC_INFORMATION = extern struct { TransactionId: Guid, State: u32, Outcome: u32, }; pub const TRANSACTIONMANAGER_BASIC_INFORMATION = extern struct { TmIdentity: Guid, VirtualClock: LARGE_INTEGER, }; pub const TRANSACTIONMANAGER_LOG_INFORMATION = extern struct { LogIdentity: Guid, }; pub const TRANSACTIONMANAGER_LOGPATH_INFORMATION = extern struct { LogPathLength: u32, LogPath: [1]u16, }; pub const TRANSACTIONMANAGER_RECOVERY_INFORMATION = extern struct { LastRecoveredLsn: u64, }; pub const TRANSACTIONMANAGER_OLDEST_INFORMATION = extern struct { OldestTransactionGuid: Guid, }; pub const TRANSACTION_PROPERTIES_INFORMATION = extern struct { IsolationLevel: u32, IsolationFlags: u32, Timeout: LARGE_INTEGER, Outcome: u32, DescriptionLength: u32, Description: [1]u16, }; pub const TRANSACTION_BIND_INFORMATION = extern struct { TmHandle: ?HANDLE, }; pub const TRANSACTION_ENLISTMENT_PAIR = extern struct { EnlistmentId: Guid, ResourceManagerId: Guid, }; pub const TRANSACTION_ENLISTMENTS_INFORMATION = extern struct { NumberOfEnlistments: u32, EnlistmentPair: [1]TRANSACTION_ENLISTMENT_PAIR, }; pub const TRANSACTION_SUPERIOR_ENLISTMENT_INFORMATION = extern struct { SuperiorEnlistmentPair: TRANSACTION_ENLISTMENT_PAIR, }; pub const RESOURCEMANAGER_BASIC_INFORMATION = extern struct { ResourceManagerId: Guid, DescriptionLength: u32, Description: [1]u16, }; pub const RESOURCEMANAGER_COMPLETION_INFORMATION = extern struct { IoCompletionPortHandle: ?HANDLE, CompletionKey: usize, }; pub const TRANSACTION_INFORMATION_CLASS = enum(i32) { BasicInformation = 0, PropertiesInformation = 1, EnlistmentInformation = 2, SuperiorEnlistmentInformation = 3, BindInformation = 4, DTCPrivateInformation = 5, }; pub const TransactionBasicInformation = TRANSACTION_INFORMATION_CLASS.BasicInformation; pub const TransactionPropertiesInformation = TRANSACTION_INFORMATION_CLASS.PropertiesInformation; pub const TransactionEnlistmentInformation = TRANSACTION_INFORMATION_CLASS.EnlistmentInformation; pub const TransactionSuperiorEnlistmentInformation = TRANSACTION_INFORMATION_CLASS.SuperiorEnlistmentInformation; pub const TransactionBindInformation = TRANSACTION_INFORMATION_CLASS.BindInformation; pub const TransactionDTCPrivateInformation = TRANSACTION_INFORMATION_CLASS.DTCPrivateInformation; pub const TRANSACTIONMANAGER_INFORMATION_CLASS = enum(i32) { BasicInformation = 0, LogInformation = 1, LogPathInformation = 2, RecoveryInformation = 4, OnlineProbeInformation = 3, OldestTransactionInformation = 5, }; pub const TransactionManagerBasicInformation = TRANSACTIONMANAGER_INFORMATION_CLASS.BasicInformation; pub const TransactionManagerLogInformation = TRANSACTIONMANAGER_INFORMATION_CLASS.LogInformation; pub const TransactionManagerLogPathInformation = TRANSACTIONMANAGER_INFORMATION_CLASS.LogPathInformation; pub const TransactionManagerRecoveryInformation = TRANSACTIONMANAGER_INFORMATION_CLASS.RecoveryInformation; pub const TransactionManagerOnlineProbeInformation = TRANSACTIONMANAGER_INFORMATION_CLASS.OnlineProbeInformation; pub const TransactionManagerOldestTransactionInformation = TRANSACTIONMANAGER_INFORMATION_CLASS.OldestTransactionInformation; pub const RESOURCEMANAGER_INFORMATION_CLASS = enum(i32) { BasicInformation = 0, CompletionInformation = 1, }; pub const ResourceManagerBasicInformation = RESOURCEMANAGER_INFORMATION_CLASS.BasicInformation; pub const ResourceManagerCompletionInformation = RESOURCEMANAGER_INFORMATION_CLASS.CompletionInformation; pub const ENLISTMENT_BASIC_INFORMATION = extern struct { EnlistmentId: Guid, TransactionId: Guid, ResourceManagerId: Guid, }; pub const ENLISTMENT_CRM_INFORMATION = extern struct { CrmTransactionManagerId: Guid, CrmResourceManagerId: Guid, CrmEnlistmentId: Guid, }; pub const ENLISTMENT_INFORMATION_CLASS = enum(i32) { BasicInformation = 0, RecoveryInformation = 1, CrmInformation = 2, }; pub const EnlistmentBasicInformation = ENLISTMENT_INFORMATION_CLASS.BasicInformation; pub const EnlistmentRecoveryInformation = ENLISTMENT_INFORMATION_CLASS.RecoveryInformation; pub const EnlistmentCrmInformation = ENLISTMENT_INFORMATION_CLASS.CrmInformation; pub const TRANSACTION_LIST_ENTRY = extern struct { UOW: Guid, }; pub const TRANSACTION_LIST_INFORMATION = extern struct { NumberOfTransactions: u32, TransactionInformation: [1]TRANSACTION_LIST_ENTRY, }; pub const KTMOBJECT_TYPE = enum(i32) { TRANSACTION = 0, TRANSACTION_MANAGER = 1, RESOURCE_MANAGER = 2, ENLISTMENT = 3, INVALID = 4, }; pub const KTMOBJECT_TRANSACTION = KTMOBJECT_TYPE.TRANSACTION; pub const KTMOBJECT_TRANSACTION_MANAGER = KTMOBJECT_TYPE.TRANSACTION_MANAGER; pub const KTMOBJECT_RESOURCE_MANAGER = KTMOBJECT_TYPE.RESOURCE_MANAGER; pub const KTMOBJECT_ENLISTMENT = KTMOBJECT_TYPE.ENLISTMENT; pub const KTMOBJECT_INVALID = KTMOBJECT_TYPE.INVALID; pub const KTMOBJECT_CURSOR = extern struct { LastQuery: Guid, ObjectIdCount: u32, ObjectIds: [1]Guid, }; pub const PTERMINATION_HANDLER = switch(@import("../zig.zig").arch) { .Arm64 => fn( _abnormal_termination: BOOLEAN, EstablisherFrame: u64, ) callconv(@import("std").os.windows.WINAPI) void, .X64 => fn( _abnormal_termination: BOOLEAN, EstablisherFrame: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; pub const POUT_OF_PROCESS_FUNCTION_TABLE_CALLBACK = switch(@import("../zig.zig").arch) { .Arm64 => fn( Process: ?HANDLE, TableAddress: ?*anyopaque, Entries: ?*u32, Functions: ?*?*IMAGE_ARM64_RUNTIME_FUNCTION_ENTRY, ) callconv(@import("std").os.windows.WINAPI) u32, .X64 => fn( Process: ?HANDLE, TableAddress: ?*anyopaque, Entries: ?*u32, Functions: ?*?*IMAGE_RUNTIME_FUNCTION_ENTRY, ) callconv(@import("std").os.windows.WINAPI) u32, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; pub const PEXCEPTION_FILTER = switch(@import("../zig.zig").arch) { .X64, .Arm64 => fn( ExceptionPointers: ?*EXCEPTION_POINTERS, EstablisherFrame: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; pub const REARRANGE_FILE_DATA32 = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { SourceStartingOffset: u64, TargetOffset: u64, SourceFileHandle: u32, Length: u32, Flags: u32, }, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; //-------------------------------------------------------------------------------- // Section: Functions (1) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.1.2600' pub extern "USER32" fn UnregisterDeviceNotification( Handle: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (2) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const DEV_BROADCAST_PORT_ = thismodule.DEV_BROADCAST_PORT_A; pub const DEV_BROADCAST_DEVICEINTERFACE_ = thismodule.DEV_BROADCAST_DEVICEINTERFACE_A; }, .wide => struct { pub const DEV_BROADCAST_PORT_ = thismodule.DEV_BROADCAST_PORT_W; pub const DEV_BROADCAST_DEVICEINTERFACE_ = thismodule.DEV_BROADCAST_DEVICEINTERFACE_W; }, .unspecified => if (@import("builtin").is_test) struct { pub const DEV_BROADCAST_PORT_ = *opaque{}; pub const DEV_BROADCAST_DEVICEINTERFACE_ = *opaque{}; } else struct { pub const DEV_BROADCAST_PORT_ = @compileError("'DEV_BROADCAST_PORT_' requires that UNICODE be set to true or false in the root module"); pub const DEV_BROADCAST_DEVICEINTERFACE_ = @compileError("'DEV_BROADCAST_DEVICEINTERFACE_' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (20) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BOOLEAN = @import("../foundation.zig").BOOLEAN; const BYTE_BLOB = @import("../system/com.zig").BYTE_BLOB; const CHAR = @import("../foundation.zig").CHAR; const DWORD_BLOB = @import("../system/com.zig").DWORD_BLOB; const FLAGGED_BYTE_BLOB = @import("../system/com.zig").FLAGGED_BYTE_BLOB; const HANDLE = @import("../foundation.zig").HANDLE; const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER; const LOGPALETTE = @import("../graphics/gdi.zig").LOGPALETTE; const NTSTATUS = @import("../foundation.zig").NTSTATUS; const PSID = @import("../foundation.zig").PSID; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const SID = @import("../security.zig").SID; const SID_AND_ATTRIBUTES = @import("../security.zig").SID_AND_ATTRIBUTES; const TOKEN_USER = @import("../security.zig").TOKEN_USER; // 3 arch-specific imports const EXCEPTION_POINTERS = switch(@import("../zig.zig").arch) { .X64, .Arm64 => @import("../system/diagnostics/debug.zig").EXCEPTION_POINTERS, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; const IMAGE_ARM64_RUNTIME_FUNCTION_ENTRY = switch(@import("../zig.zig").arch) { .Arm64 => @import("../system/diagnostics/debug.zig").IMAGE_ARM64_RUNTIME_FUNCTION_ENTRY, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; const IMAGE_RUNTIME_FUNCTION_ENTRY = switch(@import("../zig.zig").arch) { .X64 => @import("../system/diagnostics/debug.zig").IMAGE_RUNTIME_FUNCTION_ENTRY, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PUMS_SCHEDULER_ENTRY_POINT")) { _ = PUMS_SCHEDULER_ENTRY_POINT; } if (@hasDecl(@This(), "PIMAGE_TLS_CALLBACK")) { _ = PIMAGE_TLS_CALLBACK; } if (@hasDecl(@This(), "WORKERCALLBACKFUNC")) { _ = WORKERCALLBACKFUNC; } if (@hasDecl(@This(), "APC_CALLBACK_FUNCTION")) { _ = APC_CALLBACK_FUNCTION; } if (@hasDecl(@This(), "PTERMINATION_HANDLER")) { _ = PTERMINATION_HANDLER; } if (@hasDecl(@This(), "PTERMINATION_HANDLER")) { _ = PTERMINATION_HANDLER; } if (@hasDecl(@This(), "POUT_OF_PROCESS_FUNCTION_TABLE_CALLBACK")) { _ = POUT_OF_PROCESS_FUNCTION_TABLE_CALLBACK; } if (@hasDecl(@This(), "POUT_OF_PROCESS_FUNCTION_TABLE_CALLBACK")) { _ = POUT_OF_PROCESS_FUNCTION_TABLE_CALLBACK; } if (@hasDecl(@This(), "PEXCEPTION_FILTER")) { _ = PEXCEPTION_FILTER; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/system/system_services.zig
const std = @import("std"); const ascii = std.ascii; const base32 = @import("base32.zig"); const crc16 = @import("crc16.zig"); const crypto = std.crypto; const Ed25519 = crypto.sign.Ed25519; const mem = std.mem; const testing = std.testing; pub const InvalidPrefixByteError = error{InvalidPrefixByte}; pub const InvalidEncodingError = error{InvalidEncoding}; pub const InvalidPrivateKeyError = error{InvalidPrivateKey}; pub const InvalidSeedError = error{InvalidSeed}; pub const InvalidSignatureError = error{InvalidSignature}; pub const NoNkeySeedFoundError = error{NoNkeySeedFound}; pub const NoNkeyUserSeedFoundError = error{NoNkeyUserSeedFound}; pub const DecodeError = InvalidPrefixByteError || base32.DecodeError || crc16.InvalidChecksumError; pub const SeedDecodeError = DecodeError || InvalidSeedError || crypto.errors.IdentityElementError; pub const PrivateKeyDecodeError = DecodeError || InvalidPrivateKeyError || crypto.errors.IdentityElementError; pub const SignError = crypto.errors.IdentityElementError || crypto.errors.WeakPublicKeyError || crypto.errors.KeyMismatchError; pub const prefix_byte_account = 0; // A pub const prefix_byte_cluster = 2 << 3; // C pub const prefix_byte_operator = 14 << 3; // O pub const prefix_byte_private = 15 << 3; // P pub const prefix_byte_seed = 18 << 3; // S pub const prefix_byte_server = 13 << 3; // N pub const prefix_byte_user = 20 << 3; // U pub fn prefixByteToLetter(prefix_byte: u8) ?u8 { return switch (prefix_byte) { prefix_byte_account => 'A', prefix_byte_cluster => 'C', prefix_byte_operator => 'O', prefix_byte_private => 'P', prefix_byte_seed => 'S', prefix_byte_server => 'N', prefix_byte_user => 'U', else => null, }; } pub fn prefixByteFromLetter(letter: u8) ?u8 { return switch (letter) { 'A' => prefix_byte_account, 'C' => prefix_byte_cluster, 'O' => prefix_byte_operator, 'P' => prefix_byte_private, 'S' => prefix_byte_seed, 'N' => prefix_byte_server, 'U' => prefix_byte_user, else => null, }; } pub const Role = enum(u8) { const Self = @This(); account, cluster, operator, server, user, pub fn fromPublicPrefixByte(b: u8) ?Self { return switch (b) { prefix_byte_account => .account, prefix_byte_cluster => .cluster, prefix_byte_operator => .operator, prefix_byte_server => .server, prefix_byte_user => .user, else => null, }; } pub fn publicPrefixByte(self: Self) u8 { return switch (self) { .account => prefix_byte_account, .cluster => prefix_byte_cluster, .operator => prefix_byte_operator, .server => prefix_byte_server, .user => prefix_byte_user, }; } pub fn letter(self: Self) u8 { return prefixByteToLetter(self.publicPrefixByte()) orelse unreachable; } }; // One prefix byte, two CRC bytes const binary_private_size = 1 + Ed25519.secret_length + 2; // One prefix byte, two CRC bytes const binary_public_size = 1 + Ed25519.public_length + 2; // Two prefix bytes, two CRC bytes const binary_seed_size = 2 + Ed25519.seed_length + 2; pub const text_private_len = base32.Encoder.calcSize(binary_private_size); pub const text_public_len = base32.Encoder.calcSize(binary_public_size); pub const text_seed_len = base32.Encoder.calcSize(binary_seed_size); pub const text_private = [text_private_len]u8; pub const text_public = [text_public_len]u8; pub const text_seed = [text_seed_len]u8; pub const SeedKeyPair = struct { const Self = @This(); role: Role, kp: Ed25519.KeyPair, pub fn generate(role: Role) crypto.errors.IdentityElementError!Self { var raw_seed: [Ed25519.seed_length]u8 = undefined; crypto.random.bytes(&raw_seed); defer wipeBytes(&raw_seed); return Self{ .role = role, .kp = try Ed25519.KeyPair.create(raw_seed) }; } pub fn generateWithCustomEntropy(role: Role, reader: anytype) !Self { var raw_seed: [Ed25519.seed_length]u8 = undefined; try reader.readNoEof(&raw_seed); defer wipeBytes(&raw_seed); return Self{ .role = role, .kp = try Ed25519.KeyPair.create(raw_seed) }; } pub fn fromTextSeed(text: *const text_seed) SeedDecodeError!Self { var decoded = try decode(2, Ed25519.seed_length, text); defer decoded.wipe(); // gets copied var key_ty_prefix = decoded.prefix[0] & 0b11111000; var role_prefix = (decoded.prefix[0] << 5) | (decoded.prefix[1] >> 3); if (key_ty_prefix != prefix_byte_seed) return error.InvalidSeed; return Self{ .role = Role.fromPublicPrefixByte(role_prefix) orelse return error.InvalidPrefixByte, .kp = try Ed25519.KeyPair.create(decoded.data), }; } pub fn fromRawSeed( role: Role, raw_seed: *const [Ed25519.seed_length]u8, ) crypto.errors.IdentityElementError!Self { return Self{ .role = role, .kp = try Ed25519.KeyPair.create(raw_seed.*) }; } pub fn sign(self: *const Self, msg: []const u8) SignError![Ed25519.signature_length]u8 { return Ed25519.sign(msg, self.kp, null); } pub fn verify(self: *const Self, msg: []const u8, sig: [Ed25519.signature_length]u8) InvalidSignatureError!void { Ed25519.verify(sig, msg, self.kp.public_key) catch return error.InvalidSignature; } pub fn seedText(self: *const Self) text_seed { const public_prefix = self.role.publicPrefixByte(); const full_prefix = &[_]u8{ prefix_byte_seed | (public_prefix >> 5), (public_prefix & 0b00011111) << 3, }; const seed = self.kp.secret_key[0..Ed25519.seed_length]; return encode(full_prefix.len, seed.len, full_prefix, seed); } pub fn privateKeyText(self: *const Self) text_private { return encode(1, self.kp.secret_key.len, &.{prefix_byte_private}, &self.kp.secret_key); } pub fn publicKeyText(self: *const Self) text_public { return encode(1, self.kp.public_key.len, &.{self.role.publicPrefixByte()}, &self.kp.public_key); } pub fn intoPublicKey(self: *const Self) PublicKey { return .{ .role = self.role, .key = self.kp.public_key, }; } pub fn intoPrivateKey(self: *const Self) PrivateKey { return .{ .kp = self.kp }; } pub fn wipe(self: *Self) void { self.role = .account; wipeKeyPair(&self.kp); } }; pub const PublicKey = struct { const Self = @This(); role: Role, key: [Ed25519.public_length]u8, pub fn fromTextPublicKey(text: *const text_public) DecodeError!Self { var decoded = try decode(1, Ed25519.public_length, text); defer decoded.wipe(); // gets copied return PublicKey{ .role = Role.fromPublicPrefixByte(decoded.prefix[0]) orelse return error.InvalidPrefixByte, .key = decoded.data, }; } pub fn fromRawPublicKey(role: Role, raw_key: *const [Ed25519.public_length]u8) Self { return .{ .role = role, .key = raw_key.* }; } pub fn publicKeyText(self: *const Self) text_public { return encode(1, self.key.len, &.{self.role.publicPrefixByte()}, &self.key); } pub fn verify(self: *const Self, msg: []const u8, sig: [Ed25519.signature_length]u8) InvalidSignatureError!void { Ed25519.verify(sig, msg, self.key) catch return error.InvalidSignature; } pub fn wipe(self: *Self) void { self.role = .account; wipeBytes(&self.key); } }; pub const PrivateKey = struct { const Self = @This(); kp: Ed25519.KeyPair, pub fn fromTextPrivateKey(text: *const text_private) PrivateKeyDecodeError!Self { var decoded = try decode(1, Ed25519.secret_length, text); defer decoded.wipe(); // gets copied if (decoded.prefix[0] != prefix_byte_private) return error.InvalidPrivateKey; return Self{ .kp = Ed25519.KeyPair.fromSecretKey(decoded.data) }; } pub fn fromRawPrivateKey(raw_key: *const [Ed25519.secret_length]u8) Self { return .{ .kp = Ed25519.KeyPair.fromSecretKey(raw_key.*) }; } pub fn intoSeedKeyPair(self: *const Self, role: Role) SeedKeyPair { return .{ .role = role, .kp = self.kp, }; } pub fn intoPublicKey(self: *const Self, role: Role) PublicKey { return .{ .role = role, .key = self.kp.public_key, }; } pub fn privateKeyText(self: *const Self) text_private { return encode(1, self.kp.secret_key.len, &.{prefix_byte_private}, &self.kp.secret_key); } pub fn sign(self: *const Self, msg: []const u8) SignError![Ed25519.signature_length]u8 { return Ed25519.sign(msg, self.kp, null); } pub fn verify(self: *const Self, msg: []const u8, sig: [Ed25519.signature_length]u8) InvalidSignatureError!void { Ed25519.verify(sig, msg, self.kp.public_key) catch return error.InvalidSignature; } pub fn wipe(self: *Self) void { wipeKeyPair(&self.kp); } }; fn encoded_key(comptime prefix_len: usize, comptime data_len: usize) type { return [base32.Encoder.calcSize(prefix_len + data_len + 2)]u8; } fn encode( comptime prefix_len: usize, comptime data_len: usize, prefix: *const [prefix_len]u8, data: *const [data_len]u8, ) encoded_key(prefix_len, data_len) { var buf: [prefix_len + data_len + 2]u8 = undefined; defer wipeBytes(&buf); mem.copy(u8, &buf, prefix[0..]); mem.copy(u8, buf[prefix_len..], data[0..]); var off = prefix_len + data_len; var checksum = crc16.make(buf[0..off]); mem.writeIntLittle(u16, buf[buf.len - 2 .. buf.len], checksum); var text: encoded_key(prefix_len, data_len) = undefined; std.debug.assert(base32.Encoder.encode(&text, &buf).len == text.len); return text; } fn DecodedNkey(comptime prefix_len: usize, comptime data_len: usize) type { return struct { const Self = @This(); prefix: [prefix_len]u8, data: [data_len]u8, pub fn wipe(self: *Self) void { self.prefix[0] = Role.account.publicPrefixByte(); wipeBytes(&self.data); } }; } fn decode( comptime prefix_len: usize, comptime data_len: usize, text: *const [base32.Encoder.calcSize(prefix_len + data_len + 2)]u8, ) (base32.DecodeError || crc16.InvalidChecksumError)!DecodedNkey(prefix_len, data_len) { var raw: [prefix_len + data_len + 2]u8 = undefined; defer wipeBytes(&raw); std.debug.assert((try base32.Decoder.decode(&raw, text[0..])).len == raw.len); var checksum = mem.readIntLittle(u16, raw[raw.len - 2 .. raw.len]); try crc16.validate(raw[0 .. raw.len - 2], checksum); return DecodedNkey(prefix_len, data_len){ .prefix = raw[0..prefix_len].*, .data = raw[prefix_len .. raw.len - 2].*, }; } pub fn isValidEncoding(text: []const u8) bool { if (text.len < 4) return false; var made_crc: u16 = 0; var dec = base32.Decoder.init(text); var crc_buf: [2]u8 = undefined; var crc_buf_len: u8 = 0; var expect_len: usize = base32.Decoder.calcSize(text.len); var wrote_n_total: usize = 0; while (dec.next() catch return false) |b| { wrote_n_total += 1; if (crc_buf_len == 2) made_crc = crc16.update(made_crc, &.{crc_buf[0]}); crc_buf[0] = crc_buf[1]; crc_buf[1] = b; if (crc_buf_len != 2) crc_buf_len += 1; } std.debug.assert(wrote_n_total == expect_len); if (crc_buf_len != 2) unreachable; var got_crc = mem.readIntLittle(u16, &crc_buf); return made_crc == got_crc; } pub fn isValidSeed(text: []const u8, with_role: ?Role) bool { if (text.len < text_seed_len) return false; var res = SeedKeyPair.fromTextSeed(text[0..text_seed_len]) catch return false; defer res.wipe(); return if (with_role) |role| res.role == role else true; } pub fn isValidPublicKey(text: []const u8, with_role: ?Role) bool { if (text.len < text_public_len) return false; var res = PublicKey.fromTextPublicKey(text[0..text_public_len]) catch return false; defer res.wipe(); return if (with_role) |role| res.role == role else true; } pub fn isValidPrivateKey(text: []const u8) bool { if (text.len < text_private_len) return false; var res = PrivateKey.fromTextPrivateKey(text[0..text_private_len]) catch return false; res.wipe(); return true; } // `line` must not contain CR or LF characters. pub fn isKeySectionBarrier(line: []const u8, opening: bool) bool { if (line.len < 6) return false; const start = mem.indexOf(u8, line, "---") orelse return false; if (!opening and start != 0) return false; if (line.len - start < 6) return false; return mem.endsWith(u8, line, "---"); } const allowed_creds_section_chars_table: [256]bool = allowed: { var table = [_]bool{false} ** 256; const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.="; for (chars) |char| table[char] = true; break :allowed table; }; pub fn areKeySectionContentsValid(contents: []const u8) bool { for (contents) |c| if (!allowed_creds_section_chars_table[c]) return false; return true; } pub fn findKeySection(line_it: *std.mem.SplitIterator(u8)) ?[]const u8 { while (true) { const opening_line = line_it.next() orelse return null; if (!isKeySectionBarrier(opening_line, true)) continue; const contents_line = line_it.next() orelse return null; if (!areKeySectionContentsValid(contents_line)) continue; const closing_line = line_it.next() orelse return null; if (!isKeySectionBarrier(closing_line, false)) continue; return contents_line; } } pub fn parseDecoratedJwt(contents: []const u8) []const u8 { var line_it = mem.split(u8, contents, "\n"); return findKeySection(&line_it) orelse return contents; } pub fn parseDecoratedNkey(contents: []const u8) NoNkeySeedFoundError!SeedKeyPair { var line_it = mem.split(u8, contents, "\n"); var seed: ?[]const u8 = null; if (findKeySection(&line_it) != null) seed = findKeySection(&line_it); if (seed == null) seed = findNkey(contents) orelse return error.NoNkeySeedFound; if (!isValidCredsNkey(seed.?)) return error.NoNkeySeedFound; return SeedKeyPair.fromTextSeed(seed.?[0..text_seed_len]) catch return error.NoNkeySeedFound; } pub fn parseDecoratedUserNkey(contents: []const u8) (NoNkeySeedFoundError || NoNkeyUserSeedFoundError)!SeedKeyPair { var key = try parseDecoratedNkey(contents); if (!mem.startsWith(u8, &key.seedText(), "SU")) return error.NoNkeyUserSeedFound; defer key.wipe(); return key; } fn isValidCredsNkey(text: []const u8) bool { const valid_prefix = mem.startsWith(u8, text, "SO") or mem.startsWith(u8, text, "SA") or mem.startsWith(u8, text, "SU"); const valid_len = text.len >= text_seed_len; return valid_prefix and valid_len; } fn findNkey(text: []const u8) ?[]const u8 { var line_it = std.mem.split(u8, text, "\n"); while (line_it.next()) |line| { for (line) |c, i| { if (!ascii.isSpace(c)) { if (isValidCredsNkey(line[i..])) return line[i..]; break; } } } return null; } fn wipeKeyPair(kp: *Ed25519.KeyPair) void { wipeBytes(&kp.public_key); wipeBytes(&kp.secret_key); } fn wipeBytes(bs: []u8) void { for (bs) |*b| b.* = 0; } test "reference all declarations" { testing.refAllDecls(@This()); testing.refAllDecls(Role); testing.refAllDecls(SeedKeyPair); testing.refAllDecls(PublicKey); testing.refAllDecls(PrivateKey); } test "key conversions" { var key_pair = try SeedKeyPair.generate(.server); var decoded_seed = try SeedKeyPair.fromTextSeed(&key_pair.seedText()); try testing.expect(isValidEncoding(&decoded_seed.seedText())); var pub_key_str_a = key_pair.publicKeyText(); var priv_key_str_a = key_pair.privateKeyText(); try testing.expect(pub_key_str_a.len != 0); try testing.expect(priv_key_str_a.len != 0); try testing.expect(isValidEncoding(&pub_key_str_a)); try testing.expect(isValidEncoding(&priv_key_str_a)); var pub_key = key_pair.intoPublicKey(); var pub_key_str_b = pub_key.publicKeyText(); try testing.expectEqualStrings(&pub_key_str_a, &pub_key_str_b); var priv_key = key_pair.intoPrivateKey(); var priv_key_str_b = priv_key.privateKeyText(); try testing.expectEqualStrings(&priv_key_str_a, &priv_key_str_b); } test "decode" { const kp = try SeedKeyPair.generate(.account); const seed_text = kp.seedText(); const pub_key_text = kp.publicKeyText(); const priv_key_text = kp.privateKeyText(); _ = try SeedKeyPair.fromTextSeed(&seed_text); _ = try PublicKey.fromTextPublicKey(&pub_key_text); _ = try PrivateKey.fromTextPrivateKey(&priv_key_text); try testing.expectError(error.InvalidChecksum, PublicKey.fromTextPublicKey(seed_text[0..text_public_len])); try testing.expectError(error.InvalidChecksum, SeedKeyPair.fromTextSeed(priv_key_text[0..text_seed_len])); } test "seed" { inline for (@typeInfo(Role).Enum.fields) |field| { const role = @field(Role, field.name); const kp = try SeedKeyPair.generate(role); const decoded = try SeedKeyPair.fromTextSeed(&kp.seedText()); if (decoded.role != role) { std.debug.print("expected role {}, found role {}\n", .{ role, decoded.role }); return error.TestUnexpectedError; } } } test "public key" { inline for (@typeInfo(Role).Enum.fields) |field| { const role = @field(Role, field.name); const kp = try SeedKeyPair.generate(role); const decoded_pub_key = try PublicKey.fromTextPublicKey(&kp.publicKeyText()); if (decoded_pub_key.role != role) { std.debug.print("expected role {}, found role {}\n", .{ role, decoded_pub_key.role }); return error.TestUnexpectedError; } } } test "different key types" { inline for (@typeInfo(Role).Enum.fields) |field| { const role = @field(Role, field.name); const kp = try SeedKeyPair.generate(role); _ = try SeedKeyPair.fromTextSeed(&kp.seedText()); const pub_key_str = kp.publicKeyText(); try testing.expect(pub_key_str[0] == role.letter()); try testing.expect(isValidPublicKey(&pub_key_str, role)); const priv_key_str = kp.privateKeyText(); try testing.expect(priv_key_str[0] == 'P'); try testing.expect(isValidPrivateKey(&priv_key_str)); const data = "Hello, world!"; const sig = try kp.sign(data); try testing.expect(sig.len == Ed25519.signature_length); try kp.verify(data, sig); } } test "validation" { const roles = @typeInfo(Role).Enum.fields; inline for (roles) |field, i| { const role = @field(Role, field.name); const next_role = next: { const next_field_i = if (i == roles.len - 1) 0 else i + 1; std.debug.assert(next_field_i != i); break :next @field(Role, roles[next_field_i].name); }; const kp = try SeedKeyPair.generate(role); const seed_str = kp.seedText(); const pub_key_str = kp.publicKeyText(); const priv_key_str = kp.privateKeyText(); try testing.expect(isValidSeed(&seed_str, role)); try testing.expect(isValidSeed(&seed_str, null)); try testing.expect(isValidPublicKey(&pub_key_str, null)); try testing.expect(isValidPublicKey(&pub_key_str, role)); try testing.expect(isValidPrivateKey(&priv_key_str)); try testing.expect(!isValidSeed(&seed_str, next_role)); try testing.expect(!isValidSeed(&pub_key_str, null)); try testing.expect(!isValidSeed(&priv_key_str, null)); try testing.expect(!isValidPublicKey(&pub_key_str, next_role)); try testing.expect(!isValidPublicKey(&seed_str, null)); try testing.expect(!isValidPublicKey(&priv_key_str, null)); try testing.expect(!isValidPrivateKey(&seed_str)); try testing.expect(!isValidPrivateKey(&pub_key_str)); } try testing.expect(!isValidSeed("seed", null)); try testing.expect(!isValidPublicKey("public key", null)); try testing.expect(!isValidPrivateKey("private key")); } test "from seed" { const kp = try SeedKeyPair.generate(.account); const kp_from_raw = try SeedKeyPair.fromRawSeed(kp.role, kp.kp.secret_key[0..Ed25519.seed_length]); try testing.expect(std.meta.eql(kp, kp_from_raw)); const data = "Hello, World!"; const sig = try kp.sign(data); const seed = kp.seedText(); try testing.expect(mem.startsWith(u8, &seed, "SA")); const kp2 = try SeedKeyPair.fromTextSeed(&seed); try kp2.verify(data, sig); } test "from public key" { const kp = try SeedKeyPair.generate(.user); const pk_text = kp.publicKeyText(); const pk_text_clone = kp.publicKeyText(); try testing.expectEqualStrings(&pk_text, &pk_text_clone); const pk = try PublicKey.fromTextPublicKey(&pk_text); const pk_text_clone_2 = pk.publicKeyText(); try testing.expect(std.meta.eql(pk, kp.intoPublicKey())); try testing.expect(std.meta.eql(pk, PublicKey.fromRawPublicKey(kp.role, &kp.kp.public_key))); try testing.expectEqualStrings(&pk_text, &pk_text_clone_2); const data = "Hello, world!"; const sig = try kp.sign(data); try pk.verify(data, sig); // Create another user to sign and make sure verification fails const kp2 = try SeedKeyPair.generate(.user); const sig2 = try kp2.sign(data); try testing.expectError(error.InvalidSignature, pk.verify(data, sig2)); } test "from private key" { const kp = try SeedKeyPair.generate(.account); const pk_text = kp.privateKeyText(); const pk_text_clone = kp.privateKeyText(); try testing.expectEqualStrings(&pk_text, &pk_text_clone); const pk = try PrivateKey.fromTextPrivateKey(&pk_text); const pk_text_clone_2 = pk.privateKeyText(); try testing.expect(std.meta.eql(pk, kp.intoPrivateKey())); try testing.expect(std.meta.eql(kp, pk.intoSeedKeyPair(.account))); try testing.expect(std.meta.eql(pk, PrivateKey.fromRawPrivateKey(&kp.kp.secret_key))); try testing.expectEqualStrings(&pk_text, &pk_text_clone_2); const data = "Hello, World!"; const sig0 = try kp.sign(data); const sig1 = try pk.sign(data); try testing.expectEqualSlices(u8, &sig0, &sig1); try pk.verify(data, sig0); try kp.verify(data, sig1); const kp2 = try SeedKeyPair.generate(.account); const sig2 = try kp2.sign(data); try testing.expectError(error.InvalidSignature, pk.verify(data, sig2)); } test "bad decode" { const kp = try SeedKeyPair.fromTextSeed("SAAHPQF3GOP4IP5SHKHCN<KEY>APE<KEY>"); var bad_seed = kp.seedText(); bad_seed[1] = 'S'; try testing.expectError(error.InvalidChecksum, SeedKeyPair.fromTextSeed(&bad_seed)); var bad_pub_key = kp.publicKeyText(); bad_pub_key[bad_pub_key.len - 1] = 'O'; bad_pub_key[bad_pub_key.len - 2] = 'O'; try testing.expectError(error.InvalidChecksum, PublicKey.fromTextPublicKey(&bad_pub_key)); var bad_priv_key = kp.privateKeyText(); bad_priv_key[bad_priv_key.len - 1] = 'O'; bad_priv_key[bad_priv_key.len - 2] = 'O'; try testing.expectError(error.InvalidChecksum, PrivateKey.fromTextPrivateKey(&bad_priv_key)); } test "wipe" { const kp = try SeedKeyPair.generate(.account); const pub_key = kp.intoPublicKey(); const priv_key = kp.intoPrivateKey(); var kp_clone = kp; kp_clone.wipe(); try testing.expect(!std.meta.eql(kp_clone.kp, kp.kp)); var pub_key_clone = pub_key; pub_key_clone.wipe(); try testing.expect(!std.meta.eql(pub_key_clone.key, pub_key.key)); var priv_key_clone = priv_key; priv_key_clone.wipe(); try testing.expect(!std.meta.eql(priv_key_clone.kp, priv_key.kp)); } test "parse decorated JWT (bad)" { try testing.expectEqualStrings("foo", parseDecoratedJwt("foo")); } test "parse decorated seed (bad)" { try testing.expectError(error.NoNkeySeedFound, parseDecoratedNkey("foo")); } test "parse decorated seed and JWT" { const creds = \\-----BEGIN NATS USER JWT----- \\<KEY> \\------END NATS USER JWT------ \\ \\************************* IMPORTANT ************************* \\NKEY Seed printed below can be used to sign and prove identity. \\NKEYs are sensitive and should be treated as secrets. \\ \\-----BEGIN USER NKEY SEED----- \\SUAGIEYODKBBTUMOB666Z5KA4FCWAZV7HWSGRHOD7MK6UM5IYLWLACH7DQ \\------END USER NKEY SEED------ \\ \\************************************************************* ; const jwt = "<KEY>"; const seed = "SUAGIEYODKBBTUMOB666Z5KA4FCWAZV7HWSGRHOD7MK6UM5IYLWLACH7DQ"; var got_kp = try parseDecoratedUserNkey(creds); try testing.expectEqualStrings(seed, &got_kp.seedText()); got_kp = try parseDecoratedNkey(creds); try testing.expectEqualStrings(seed, &got_kp.seedText()); var got_jwt = parseDecoratedJwt(creds); try testing.expectEqualStrings(jwt, got_jwt); }
src/main.zig
const std = @import("std"); const assert = std.debug.assert; const zwin32 = @import("zwin32"); const w32 = zwin32.base; const dwrite = zwin32.dwrite; const dxgi = zwin32.dxgi; const d3d11 = zwin32.d3d11; const d3d12 = zwin32.d3d12; const d3d12d = zwin32.d3d12d; const d2d1 = zwin32.d2d1; const d3d11on12 = zwin32.d3d11on12; const wic = zwin32.wic; const HResultError = zwin32.HResultError; const hrPanic = zwin32.hrPanic; const hrPanicOnFail = zwin32.hrPanicOnFail; const hrErrorOnFail = zwin32.hrErrorOnFail; const ztracy = @import("ztracy"); const enable_dx_debug = @import("build_options").enable_dx_debug; const enable_dx_gpu_debug = @import("build_options").enable_dx_gpu_debug; const enable_d2d = @import("build_options").enable_d2d; // TODO(mziulek): For now, we always transition *all* subresources. const TransitionResourceBarrier = struct { state_before: d3d12.RESOURCE_STATES, state_after: d3d12.RESOURCE_STATES, resource: ResourceHandle, }; const num_swapbuffers = 4; const D2dState = struct { factory: *d2d1.IFactory7, device: *d2d1.IDevice6, context: *d2d1.IDeviceContext6, device11on12: *d3d11on12.IDevice2, device11: *d3d11.IDevice, context11: *d3d11.IDeviceContext, swapbuffers11: [num_swapbuffers]*d3d11.IResource, targets: [num_swapbuffers]*d2d1.IBitmap1, dwrite_factory: *dwrite.IFactory, }; pub const GraphicsContext = struct { pub const max_num_buffered_frames = 2; const num_rtv_descriptors = 128; const num_dsv_descriptors = 128; const num_cbv_srv_uav_cpu_descriptors = 16 * 1024; const num_cbv_srv_uav_gpu_descriptors = 8 * 1024; const max_num_buffered_resource_barriers = 16; const upload_heap_capacity = 18 * 1024 * 1024; device: *d3d12.IDevice9, cmdqueue: *d3d12.ICommandQueue, cmdlist: *d3d12.IGraphicsCommandList6, cmdallocs: [max_num_buffered_frames]*d3d12.ICommandAllocator, swapchain: *dxgi.ISwapChain3, swapchain_buffers: [num_swapbuffers]ResourceHandle, rtv_heap: DescriptorHeap, dsv_heap: DescriptorHeap, cbv_srv_uav_cpu_heap: DescriptorHeap, cbv_srv_uav_gpu_heaps: [max_num_buffered_frames + 1]DescriptorHeap, upload_memory_heaps: [max_num_buffered_frames]GpuMemoryHeap, resource_pool: ResourcePool, pipeline_pool: PipelinePool, current_pipeline: PipelineHandle, transition_resource_barriers: std.ArrayListUnmanaged(TransitionResourceBarrier), viewport_width: u32, viewport_height: u32, frame_fence: *d3d12.IFence, frame_fence_event: w32.HANDLE, frame_fence_counter: u64, frame_index: u32, back_buffer_index: u32, window: w32.HWND, is_cmdlist_opened: bool, d2d: ?D2dState, wic_factory: *wic.IImagingFactory, present_flags: w32.UINT, present_interval: w32.UINT, pub fn init(allocator: std.mem.Allocator, window: w32.HWND) GraphicsContext { const wic_factory = blk: { var wic_factory: *wic.IImagingFactory = undefined; hrPanicOnFail(w32.CoCreateInstance( &wic.CLSID_ImagingFactory, null, w32.CLSCTX_INPROC_SERVER, &wic.IID_IImagingFactory, @ptrCast(*?*anyopaque, &wic_factory), )); break :blk wic_factory; }; const factory = blk: { var factory: *dxgi.IFactory6 = undefined; hrPanicOnFail(dxgi.CreateDXGIFactory2( if (enable_dx_debug) dxgi.CREATE_FACTORY_DEBUG else 0, &dxgi.IID_IFactory6, @ptrCast(*?*anyopaque, &factory), )); break :blk factory; }; defer _ = factory.Release(); var present_flags: w32.UINT = 0; var present_interval: w32.UINT = 0; { var allow_tearing: w32.BOOL = w32.FALSE; var hr = factory.CheckFeatureSupport( .PRESENT_ALLOW_TEARING, &allow_tearing, @sizeOf(@TypeOf(allow_tearing)), ); if (hr == w32.S_OK and allow_tearing == w32.TRUE) { present_flags |= dxgi.PRESENT_ALLOW_TEARING; } } if (enable_dx_debug) { var maybe_debug: ?*d3d12d.IDebug1 = null; _ = d3d12.D3D12GetDebugInterface(&d3d12d.IID_IDebug1, @ptrCast(*?*anyopaque, &maybe_debug)); if (maybe_debug) |debug| { debug.EnableDebugLayer(); if (enable_dx_gpu_debug) { debug.SetEnableGPUBasedValidation(w32.TRUE); } _ = debug.Release(); } } const suitable_adapter = blk: { var adapter: ?*dxgi.IAdapter1 = null; var adapter_index: u32 = 0; var optional_adapter1: ?*dxgi.IAdapter1 = null; while (factory.EnumAdapterByGpuPreference( adapter_index, dxgi.GPU_PREFERENCE_HIGH_PERFORMANCE, &dxgi.IID_IAdapter1, &optional_adapter1, ) == w32.S_OK) { if (optional_adapter1) |adapter1| { var adapter1_desc: dxgi.ADAPTER_DESC1 = undefined; if (adapter1.GetDesc1(&adapter1_desc) == w32.S_OK) { if ((adapter1_desc.Flags & dxgi.ADAPTER_FLAG_SOFTWARE) != 0) { // Don't select the Basic Render Driver adapter. continue; } const hr = d3d12.D3D12CreateDevice( @ptrCast(*w32.IUnknown, adapter1), .FL_11_1, &d3d12.IID_IDevice9, null, ); if (hr == w32.S_OK or hr == w32.S_FALSE) { adapter = adapter1; break; } } } adapter_index += 1; } break :blk adapter; }; defer { if (suitable_adapter) |adapter| _ = adapter.Release(); } const device = blk: { var device: *d3d12.IDevice9 = undefined; const hr = d3d12.D3D12CreateDevice( if (suitable_adapter) |adapter| @ptrCast(*w32.IUnknown, adapter) else null, .FL_11_1, &d3d12.IID_IDevice9, @ptrCast(*?*anyopaque, &device), ); if (hr != w32.S_OK) { _ = w32.user32.messageBoxA( window, "Failed to create Direct3D 12 Device. This applications requires graphics card " ++ "with DirectX 12support.", "Your graphics card driver may be old", w32.user32.MB_OK | w32.user32.MB_ICONERROR, ) catch 0; w32.kernel32.ExitProcess(0); } break :blk device; }; // Check for Shader Model 6.6 support. { var data: d3d12.FEATURE_DATA_SHADER_MODEL = .{ .HighestShaderModel = .SM_6_7 }; const hr = device.CheckFeatureSupport(.SHADER_MODEL, &data, @sizeOf(d3d12.FEATURE_DATA_SHADER_MODEL)); if (hr != w32.S_OK or @enumToInt(data.HighestShaderModel) < @enumToInt(d3d12.SHADER_MODEL.SM_6_6)) { _ = w32.user32.messageBoxA( window, "This applications requires graphics card driver that supports Shader Model 6.6. " ++ "Please update your graphics driver and try again.", "Your graphics card driver may be old", w32.user32.MB_OK | w32.user32.MB_ICONERROR, ) catch 0; w32.kernel32.ExitProcess(0); } } // Check for Resource Binding Tier 3 support. { var data: d3d12.FEATURE_DATA_D3D12_OPTIONS = std.mem.zeroes(d3d12.FEATURE_DATA_D3D12_OPTIONS); const hr = device.CheckFeatureSupport(.OPTIONS, &data, @sizeOf(d3d12.FEATURE_DATA_D3D12_OPTIONS)); if (hr != w32.S_OK or @enumToInt(data.ResourceBindingTier) < @enumToInt(d3d12.RESOURCE_BINDING_TIER.TIER_3)) { _ = w32.user32.messageBoxA( window, "This applications requires graphics card driver that supports Resource Binding Tier 3. " ++ "Please update your graphics driver and try again.", "Your graphics card driver may be old", w32.user32.MB_OK | w32.user32.MB_ICONERROR, ) catch 0; w32.kernel32.ExitProcess(0); } } const cmdqueue = blk: { var cmdqueue: *d3d12.ICommandQueue = undefined; hrPanicOnFail(device.CreateCommandQueue(&.{ .Type = .DIRECT, .Priority = @enumToInt(d3d12.COMMAND_QUEUE_PRIORITY.NORMAL), .Flags = d3d12.COMMAND_QUEUE_FLAG_NONE, .NodeMask = 0, }, &d3d12.IID_ICommandQueue, @ptrCast(*?*anyopaque, &cmdqueue))); break :blk cmdqueue; }; var rect: w32.RECT = undefined; _ = w32.GetClientRect(window, &rect); const viewport_width = @intCast(u32, rect.right - rect.left); const viewport_height = @intCast(u32, rect.bottom - rect.top); const swapchain = blk: { var swapchain: *dxgi.ISwapChain = undefined; hrPanicOnFail(factory.CreateSwapChain( @ptrCast(*w32.IUnknown, cmdqueue), &dxgi.SWAP_CHAIN_DESC{ .BufferDesc = .{ .Width = viewport_width, .Height = viewport_height, .RefreshRate = .{ .Numerator = 0, .Denominator = 0 }, .Format = .R8G8B8A8_UNORM, .ScanlineOrdering = .UNSPECIFIED, .Scaling = .UNSPECIFIED, }, .SampleDesc = .{ .Count = 1, .Quality = 0 }, .BufferUsage = dxgi.USAGE_RENDER_TARGET_OUTPUT, .BufferCount = num_swapbuffers, .OutputWindow = window, .Windowed = w32.TRUE, .SwapEffect = .FLIP_DISCARD, .Flags = if ((present_flags & dxgi.PRESENT_ALLOW_TEARING) != 0) dxgi.SWAP_CHAIN_FLAG_ALLOW_TEARING else 0, }, @ptrCast(*?*dxgi.ISwapChain, &swapchain), )); defer _ = swapchain.Release(); var swapchain3: *dxgi.ISwapChain3 = undefined; hrPanicOnFail(swapchain.QueryInterface( &dxgi.IID_ISwapChain3, @ptrCast(*?*anyopaque, &swapchain3), )); break :blk swapchain3; }; var resource_pool = ResourcePool.init(allocator); var pipeline_pool = PipelinePool.init(allocator); var rtv_heap = DescriptorHeap.init(device, num_rtv_descriptors, .RTV, d3d12.DESCRIPTOR_HEAP_FLAG_NONE); var dsv_heap = DescriptorHeap.init(device, num_dsv_descriptors, .DSV, d3d12.DESCRIPTOR_HEAP_FLAG_NONE); var cbv_srv_uav_cpu_heap = DescriptorHeap.init( device, num_cbv_srv_uav_cpu_descriptors, .CBV_SRV_UAV, d3d12.DESCRIPTOR_HEAP_FLAG_NONE, ); var cbv_srv_uav_gpu_heaps: [max_num_buffered_frames + 1]DescriptorHeap = undefined; for (cbv_srv_uav_gpu_heaps) |_, heap_index| { // We create one large descriptor heap and then split it into ranges: // - range 0: contains persistent descriptors (each descriptor lives until heap is destroyed) // - range 1,2,..max_num_buffered_frames: contains non-persistent descriptors (1 frame lifetime) if (heap_index == 0) { cbv_srv_uav_gpu_heaps[0] = DescriptorHeap.init( device, num_cbv_srv_uav_gpu_descriptors * (max_num_buffered_frames + 1), .CBV_SRV_UAV, d3d12.DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, ); cbv_srv_uav_gpu_heaps[0].capacity = @divExact( cbv_srv_uav_gpu_heaps[0].capacity, max_num_buffered_frames + 1, ); } else { const range_capacity = cbv_srv_uav_gpu_heaps[0].capacity; const descriptor_size = cbv_srv_uav_gpu_heaps[0].descriptor_size; // Non-persistent heap does not own memory it is just a sub-range in a persistent heap cbv_srv_uav_gpu_heaps[heap_index] = cbv_srv_uav_gpu_heaps[0]; cbv_srv_uav_gpu_heaps[heap_index].heap = null; cbv_srv_uav_gpu_heaps[heap_index].base.cpu_handle.ptr += heap_index * range_capacity * descriptor_size; cbv_srv_uav_gpu_heaps[heap_index].base.gpu_handle.ptr += heap_index * range_capacity * descriptor_size; } } var upload_heaps: [max_num_buffered_frames]GpuMemoryHeap = undefined; for (upload_heaps) |_, heap_index| { upload_heaps[heap_index] = GpuMemoryHeap.init(device, upload_heap_capacity, .UPLOAD); } const swapchain_buffers = blk: { var swapchain_buffers: [num_swapbuffers]ResourceHandle = undefined; var swapbuffers: [num_swapbuffers]*d3d12.IResource = undefined; for (swapbuffers) |_, buffer_index| { hrPanicOnFail(swapchain.GetBuffer( @intCast(u32, buffer_index), &d3d12.IID_IResource, @ptrCast(*?*anyopaque, &swapbuffers[buffer_index]), )); device.CreateRenderTargetView( swapbuffers[buffer_index], &d3d12.RENDER_TARGET_VIEW_DESC{ .Format = .R8G8B8A8_UNORM, // TODO(mziulek): .R8G8B8A8_UNORM_SRGB? .ViewDimension = .TEXTURE2D, .u = .{ .Texture2D = .{ .MipSlice = 0, .PlaneSlice = 0, }, }, }, rtv_heap.allocateDescriptors(1).cpu_handle, ); swapchain_buffers[buffer_index] = resource_pool.addResource( swapbuffers[buffer_index], d3d12.RESOURCE_STATE_PRESENT, ); } break :blk swapchain_buffers; }; const d2d_state = if (enable_d2d) blk_d2d: { const dx11 = blk: { var device11: *d3d11.IDevice = undefined; var device_context11: *d3d11.IDeviceContext = undefined; hrPanicOnFail(d3d11on12.D3D11On12CreateDevice( @ptrCast(*w32.IUnknown, device), if (enable_dx_debug) d3d11.CREATE_DEVICE_DEBUG | d3d11.CREATE_DEVICE_BGRA_SUPPORT else d3d11.CREATE_DEVICE_BGRA_SUPPORT, null, 0, &[_]*w32.IUnknown{@ptrCast(*w32.IUnknown, cmdqueue)}, 1, 0, @ptrCast(*?*d3d11.IDevice, &device11), @ptrCast(*?*d3d11.IDeviceContext, &device_context11), null, )); break :blk .{ .device = device11, .device_context = device_context11 }; }; const device11on12 = blk: { var device11on12: *d3d11on12.IDevice2 = undefined; hrPanicOnFail(dx11.device.QueryInterface( &d3d11on12.IID_IDevice2, @ptrCast(*?*anyopaque, &device11on12), )); break :blk device11on12; }; const d2d_factory = blk: { var d2d_factory: *d2d1.IFactory7 = undefined; hrPanicOnFail(d2d1.D2D1CreateFactory( .SINGLE_THREADED, &d2d1.IID_IFactory7, if (enable_dx_debug) &d2d1.FACTORY_OPTIONS{ .debugLevel = .INFORMATION } else &d2d1.FACTORY_OPTIONS{ .debugLevel = .NONE }, @ptrCast(*?*anyopaque, &d2d_factory), )); break :blk d2d_factory; }; const dxgi_device = blk: { var dxgi_device: *dxgi.IDevice = undefined; hrPanicOnFail(device11on12.QueryInterface( &dxgi.IID_IDevice, @ptrCast(*?*anyopaque, &dxgi_device), )); break :blk dxgi_device; }; defer _ = dxgi_device.Release(); const d2d_device = blk: { var d2d_device: *d2d1.IDevice6 = undefined; hrPanicOnFail(d2d_factory.CreateDevice6( dxgi_device, @ptrCast(*?*d2d1.IDevice6, &d2d_device), )); break :blk d2d_device; }; const d2d_device_context = blk: { var d2d_device_context: *d2d1.IDeviceContext6 = undefined; hrPanicOnFail(d2d_device.CreateDeviceContext6( d2d1.DEVICE_CONTEXT_OPTIONS_NONE, @ptrCast(*?*d2d1.IDeviceContext6, &d2d_device_context), )); break :blk d2d_device_context; }; const dwrite_factory = blk: { var dwrite_factory: *dwrite.IFactory = undefined; hrPanicOnFail(dwrite.DWriteCreateFactory( .SHARED, &dwrite.IID_IFactory, @ptrCast(*?*anyopaque, &dwrite_factory), )); break :blk dwrite_factory; }; const swapbuffers11 = blk: { var swapbuffers11: [num_swapbuffers]*d3d11.IResource = undefined; for (swapbuffers11) |_, buffer_index| { hrPanicOnFail(device11on12.CreateWrappedResource( @ptrCast( *w32.IUnknown, resource_pool.lookupResource(swapchain_buffers[buffer_index]).?.raw.?, ), &d3d11on12.RESOURCE_FLAGS{ .BindFlags = d3d11.BIND_RENDER_TARGET, .MiscFlags = 0, .CPUAccessFlags = 0, .StructureByteStride = 0, }, d3d12.RESOURCE_STATE_RENDER_TARGET, d3d12.RESOURCE_STATE_PRESENT, &d3d11.IID_IResource, @ptrCast(*?*anyopaque, &swapbuffers11[buffer_index]), )); } break :blk swapbuffers11; }; const d2d_targets = blk: { var d2d_targets: [num_swapbuffers]*d2d1.IBitmap1 = undefined; for (d2d_targets) |_, target_index| { const swapbuffer11 = swapbuffers11[target_index]; var surface: *dxgi.ISurface = undefined; hrPanicOnFail(swapbuffer11.QueryInterface( &dxgi.IID_ISurface, @ptrCast(*?*anyopaque, &surface), )); defer _ = surface.Release(); hrPanicOnFail(d2d_device_context.CreateBitmapFromDxgiSurface( surface, &d2d1.BITMAP_PROPERTIES1{ .pixelFormat = .{ .format = .R8G8B8A8_UNORM, .alphaMode = .PREMULTIPLIED }, .dpiX = 96.0, .dpiY = 96.0, .bitmapOptions = d2d1.BITMAP_OPTIONS_TARGET | d2d1.BITMAP_OPTIONS_CANNOT_DRAW, .colorContext = null, }, @ptrCast(*?*d2d1.IBitmap1, &d2d_targets[target_index]), )); } break :blk d2d_targets; }; break :blk_d2d .{ .factory = d2d_factory, .device = d2d_device, .context = d2d_device_context, .device11on12 = device11on12, .device11 = dx11.device, .context11 = dx11.device_context, .swapbuffers11 = swapbuffers11, .targets = d2d_targets, .dwrite_factory = dwrite_factory, }; } else null; const frame_fence = blk: { var frame_fence: *d3d12.IFence = undefined; hrPanicOnFail(device.CreateFence( 0, d3d12.FENCE_FLAG_NONE, &d3d12.IID_IFence, @ptrCast(*?*anyopaque, &frame_fence), )); break :blk frame_fence; }; const frame_fence_event = w32.CreateEventEx( null, "frame_fence_event", 0, w32.EVENT_ALL_ACCESS, ) catch unreachable; const cmdallocs = blk: { var cmdallocs: [max_num_buffered_frames]*d3d12.ICommandAllocator = undefined; for (cmdallocs) |_, cmdalloc_index| { hrPanicOnFail(device.CreateCommandAllocator( .DIRECT, &d3d12.IID_ICommandAllocator, @ptrCast(*?*anyopaque, &cmdallocs[cmdalloc_index]), )); } break :blk cmdallocs; }; const cmdlist = blk: { var cmdlist: *d3d12.IGraphicsCommandList6 = undefined; hrPanicOnFail(device.CreateCommandList( 0, .DIRECT, cmdallocs[0], null, &d3d12.IID_IGraphicsCommandList6, @ptrCast(*?*anyopaque, &cmdlist), )); break :blk cmdlist; }; hrPanicOnFail(cmdlist.Close()); const is_cmdlist_opened = false; return GraphicsContext{ .device = device, .cmdqueue = cmdqueue, .cmdlist = cmdlist, .cmdallocs = cmdallocs, .swapchain = swapchain, .swapchain_buffers = swapchain_buffers, .frame_fence = frame_fence, .frame_fence_event = frame_fence_event, .frame_fence_counter = 0, .rtv_heap = rtv_heap, .dsv_heap = dsv_heap, .cbv_srv_uav_cpu_heap = cbv_srv_uav_cpu_heap, .cbv_srv_uav_gpu_heaps = cbv_srv_uav_gpu_heaps, .upload_memory_heaps = upload_heaps, .resource_pool = resource_pool, .pipeline_pool = pipeline_pool, .current_pipeline = .{}, .transition_resource_barriers = std.ArrayListUnmanaged(TransitionResourceBarrier).initCapacity( allocator, max_num_buffered_resource_barriers, ) catch unreachable, .viewport_width = viewport_width, .viewport_height = viewport_height, .frame_index = 0, .back_buffer_index = swapchain.GetCurrentBackBufferIndex(), .window = window, .is_cmdlist_opened = is_cmdlist_opened, .d2d = d2d_state, .wic_factory = wic_factory, .present_flags = present_flags, .present_interval = present_interval, }; } pub fn deinit(gctx: *GraphicsContext, allocator: std.mem.Allocator) void { gctx.finishGpuCommands(); gctx.transition_resource_barriers.deinit(allocator); w32.CloseHandle(gctx.frame_fence_event); gctx.resource_pool.deinit(allocator); gctx.pipeline_pool.deinit(allocator); gctx.rtv_heap.deinit(); gctx.dsv_heap.deinit(); gctx.cbv_srv_uav_cpu_heap.deinit(); if (enable_d2d) { _ = gctx.d2d.?.factory.Release(); _ = gctx.d2d.?.device.Release(); _ = gctx.d2d.?.context.Release(); _ = gctx.d2d.?.device11on12.Release(); _ = gctx.d2d.?.device11.Release(); _ = gctx.d2d.?.context11.Release(); _ = gctx.d2d.?.dwrite_factory.Release(); for (gctx.d2d.?.targets) |target| _ = target.Release(); for (gctx.d2d.?.swapbuffers11) |swapbuffer11| _ = swapbuffer11.Release(); } for (gctx.cbv_srv_uav_gpu_heaps) |*heap| heap.deinit(); for (gctx.upload_memory_heaps) |*heap| heap.deinit(); _ = gctx.device.Release(); _ = gctx.cmdqueue.Release(); _ = gctx.swapchain.Release(); _ = gctx.frame_fence.Release(); _ = gctx.cmdlist.Release(); for (gctx.cmdallocs) |cmdalloc| _ = cmdalloc.Release(); _ = gctx.wic_factory.Release(); gctx.* = undefined; } pub fn beginFrame(gctx: *GraphicsContext) void { assert(!gctx.is_cmdlist_opened); const cmdalloc = gctx.cmdallocs[gctx.frame_index]; hrPanicOnFail(cmdalloc.Reset()); hrPanicOnFail(gctx.cmdlist.Reset(cmdalloc, null)); gctx.is_cmdlist_opened = true; gctx.cmdlist.SetDescriptorHeaps( 1, &[_]*d3d12.IDescriptorHeap{gctx.cbv_srv_uav_gpu_heaps[0].heap.?}, ); gctx.cmdlist.RSSetViewports(1, &[_]d3d12.VIEWPORT{.{ .TopLeftX = 0.0, .TopLeftY = 0.0, .Width = @intToFloat(f32, gctx.viewport_width), .Height = @intToFloat(f32, gctx.viewport_height), .MinDepth = 0.0, .MaxDepth = 1.0, }}); gctx.cmdlist.RSSetScissorRects(1, &[_]d3d12.RECT{.{ .left = 0, .top = 0, .right = @intCast(c_long, gctx.viewport_width), .bottom = @intCast(c_long, gctx.viewport_height), }}); gctx.current_pipeline = .{}; } pub fn endFrame(gctx: *GraphicsContext) void { gctx.flushGpuCommands(); gctx.frame_fence_counter += 1; hrPanicOnFail(gctx.swapchain.Present(gctx.present_interval, gctx.present_flags)); // TODO(mziulek): // Handle DXGI_ERROR_DEVICE_REMOVED and DXGI_ERROR_DEVICE_RESET codes here - we need to re-create // all resources in that case. // Take a look at: // https://github.com/microsoft/DirectML/blob/master/Samples/DirectMLSuperResolution/DeviceResources.cpp ztracy.frameMark(); hrPanicOnFail(gctx.cmdqueue.Signal(gctx.frame_fence, gctx.frame_fence_counter)); const gpu_frame_counter = gctx.frame_fence.GetCompletedValue(); if ((gctx.frame_fence_counter - gpu_frame_counter) >= max_num_buffered_frames) { hrPanicOnFail(gctx.frame_fence.SetEventOnCompletion(gpu_frame_counter + 1, gctx.frame_fence_event)); w32.WaitForSingleObject(gctx.frame_fence_event, w32.INFINITE) catch unreachable; } gctx.frame_index = (gctx.frame_index + 1) % max_num_buffered_frames; gctx.back_buffer_index = gctx.swapchain.GetCurrentBackBufferIndex(); // Reset current non-persistent heap (+1 because heap 0 is persistent) gctx.cbv_srv_uav_gpu_heaps[gctx.frame_index + 1].size = 0; gctx.upload_memory_heaps[gctx.frame_index].size = 0; } pub fn beginDraw2d(gctx: *GraphicsContext) void { gctx.flushGpuCommands(); gctx.d2d.?.device11on12.AcquireWrappedResources( &[_]*d3d11.IResource{gctx.d2d.?.swapbuffers11[gctx.back_buffer_index]}, 1, ); gctx.d2d.?.context.SetTarget(@ptrCast(*d2d1.IImage, gctx.d2d.?.targets[gctx.back_buffer_index])); gctx.d2d.?.context.BeginDraw(); } pub fn endDraw2d(gctx: *GraphicsContext) void { var info_queue: *d3d12d.IInfoQueue = undefined; const mute_d2d_completely = true; if (enable_dx_debug) { // NOTE(mziulek): D2D1 is slow. It creates and destroys resources every frame. To see create/destroy // messages in debug output set 'mute_d2d_completely' to 'false'. hrPanicOnFail(gctx.device.QueryInterface( &d3d12d.IID_IInfoQueue, @ptrCast(*?*anyopaque, &info_queue), )); if (mute_d2d_completely) { info_queue.SetMuteDebugOutput(w32.TRUE); } else { var filter: d3d12.INFO_QUEUE_FILTER = std.mem.zeroes(d3d12.INFO_QUEUE_FILTER); hrPanicOnFail(info_queue.PushStorageFilter(&filter)); var hide = [_]d3d12.MESSAGE_ID{ .CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE, .COMMAND_LIST_DRAW_VERTEX_BUFFER_STRIDE_TOO_SMALL, .CREATEGRAPHICSPIPELINESTATE_DEPTHSTENCILVIEW_NOT_SET, }; hrPanicOnFail(info_queue.AddStorageFilterEntries(&d3d12.INFO_QUEUE_FILTER{ .AllowList = .{ .NumCategories = 0, .pCategoryList = null, .NumSeverities = 0, .pSeverityList = null, .NumIDs = 0, .pIDList = null, }, .DenyList = .{ .NumCategories = 0, .pCategoryList = null, .NumSeverities = 0, .pSeverityList = null, .NumIDs = hide.len, .pIDList = &hide, }, })); } } hrPanicOnFail(gctx.d2d.?.context.EndDraw(null, null)); gctx.d2d.?.device11on12.ReleaseWrappedResources( &[_]*d3d11.IResource{gctx.d2d.?.swapbuffers11[gctx.back_buffer_index]}, 1, ); gctx.d2d.?.context11.Flush(); if (enable_dx_debug) { if (mute_d2d_completely) { info_queue.SetMuteDebugOutput(w32.FALSE); } else { info_queue.PopStorageFilter(); } _ = info_queue.Release(); } // Above calls will set back buffer state to PRESENT. We need to reflect this change // in 'resource_pool' by manually setting state. gctx.resource_pool.lookupResource(gctx.swapchain_buffers[gctx.back_buffer_index]).?.state = d3d12.RESOURCE_STATE_PRESENT; } fn flushGpuCommands(gctx: *GraphicsContext) void { if (gctx.is_cmdlist_opened) { gctx.flushResourceBarriers(); hrPanicOnFail(gctx.cmdlist.Close()); gctx.is_cmdlist_opened = false; gctx.cmdqueue.ExecuteCommandLists( 1, &[_]*d3d12.ICommandList{@ptrCast(*d3d12.ICommandList, gctx.cmdlist)}, ); } } pub fn finishGpuCommands(gctx: *GraphicsContext) void { const was_cmdlist_opened = gctx.is_cmdlist_opened; gctx.flushGpuCommands(); gctx.frame_fence_counter += 1; hrPanicOnFail(gctx.cmdqueue.Signal(gctx.frame_fence, gctx.frame_fence_counter)); hrPanicOnFail(gctx.frame_fence.SetEventOnCompletion(gctx.frame_fence_counter, gctx.frame_fence_event)); w32.WaitForSingleObject(gctx.frame_fence_event, w32.INFINITE) catch unreachable; // Reset current non-persistent heap (+1 because heap 0 is persistent) gctx.cbv_srv_uav_gpu_heaps[gctx.frame_index + 1].size = 0; gctx.upload_memory_heaps[gctx.frame_index].size = 0; if (was_cmdlist_opened) { beginFrame(gctx); } } pub fn getBackBuffer(gctx: GraphicsContext) struct { resource_handle: ResourceHandle, descriptor_handle: d3d12.CPU_DESCRIPTOR_HANDLE, } { return .{ .resource_handle = gctx.swapchain_buffers[gctx.back_buffer_index], .descriptor_handle = .{ .ptr = gctx.rtv_heap.base.cpu_handle.ptr + gctx.back_buffer_index * gctx.rtv_heap.descriptor_size, }, }; } pub inline fn lookupResource(gctx: GraphicsContext, handle: ResourceHandle) ?*d3d12.IResource { const resource = gctx.resource_pool.lookupResource(handle); if (resource == null) return null; return resource.?.raw.?; } pub fn isResourceValid(gctx: GraphicsContext, handle: ResourceHandle) bool { return gctx.resource_pool.isResourceValid(handle); } pub fn getResourceSize(gctx: GraphicsContext, handle: ResourceHandle) u64 { const resource = gctx.resource_pool.lookupResource(handle); if (resource == null) return 0; assert(resource.?.desc.Dimension == .BUFFER); return resource.?.desc.Width; } pub fn getResourceDesc(gctx: GraphicsContext, handle: ResourceHandle) d3d12.RESOURCE_DESC { const resource = gctx.resource_pool.lookupResource(handle); if (resource == null) return d3d12.RESOURCE_DESC.initBuffer(0); return resource.?.desc; } pub fn createCommittedResource( gctx: *GraphicsContext, heap_type: d3d12.HEAP_TYPE, heap_flags: d3d12.HEAP_FLAGS, desc: *const d3d12.RESOURCE_DESC, initial_state: d3d12.RESOURCE_STATES, clear_value: ?*const d3d12.CLEAR_VALUE, ) HResultError!ResourceHandle { const resource = blk: { var resource: *d3d12.IResource = undefined; try hrErrorOnFail(gctx.device.CreateCommittedResource( &d3d12.HEAP_PROPERTIES.initType(heap_type), heap_flags, desc, initial_state, clear_value, &d3d12.IID_IResource, @ptrCast(*?*anyopaque, &resource), )); break :blk resource; }; return gctx.resource_pool.addResource(resource, initial_state); } pub fn destroyResource(gctx: GraphicsContext, handle: ResourceHandle) void { gctx.resource_pool.destroyResource(handle); } pub fn flushResourceBarriers(gctx: *GraphicsContext) void { if (gctx.transition_resource_barriers.items.len > 0) { var d3d12_barriers: [max_num_buffered_resource_barriers]d3d12.RESOURCE_BARRIER = undefined; var num_valid_barriers: u32 = 0; for (gctx.transition_resource_barriers.items) |barrier| { if (gctx.resource_pool.isResourceValid(barrier.resource)) { d3d12_barriers[num_valid_barriers] = .{ .Type = .TRANSITION, .Flags = d3d12.RESOURCE_BARRIER_FLAG_NONE, .u = .{ .Transition = .{ .pResource = gctx.lookupResource(barrier.resource).?, .Subresource = d3d12.RESOURCE_BARRIER_ALL_SUBRESOURCES, .StateBefore = barrier.state_before, .StateAfter = barrier.state_after, }, }, }; num_valid_barriers += 1; } } if (num_valid_barriers > 0) { gctx.cmdlist.ResourceBarrier(num_valid_barriers, &d3d12_barriers); } gctx.transition_resource_barriers.clearRetainingCapacity(); } } pub fn addTransitionBarrier( gctx: *GraphicsContext, handle: ResourceHandle, state_after: d3d12.RESOURCE_STATES, ) void { var resource = gctx.resource_pool.lookupResource(handle); if (resource == null) return; if (state_after != resource.?.state) { if (gctx.transition_resource_barriers.items.len == max_num_buffered_resource_barriers) gctx.flushResourceBarriers(); gctx.transition_resource_barriers.appendAssumeCapacity(.{ .resource = handle, .state_before = resource.?.state, .state_after = state_after, }); resource.?.state = state_after; } } pub fn createGraphicsShaderPipeline( gctx: *GraphicsContext, arena: std.mem.Allocator, pso_desc: *d3d12.GRAPHICS_PIPELINE_STATE_DESC, vs_cso_path: ?[]const u8, ps_cso_path: ?[]const u8, ) PipelineHandle { return createGraphicsShaderPipelineVsGsPs(gctx, arena, pso_desc, vs_cso_path, null, ps_cso_path); } pub fn createGraphicsShaderPipelineVsGsPs( gctx: *GraphicsContext, arena: std.mem.Allocator, pso_desc: *d3d12.GRAPHICS_PIPELINE_STATE_DESC, vs_cso_path: ?[]const u8, gs_cso_path: ?[]const u8, ps_cso_path: ?[]const u8, ) PipelineHandle { return createGraphicsShaderPipelineRsVsGsPs( gctx, arena, pso_desc, null, vs_cso_path, gs_cso_path, ps_cso_path, ); } pub fn createGraphicsShaderPipelineRsVsGsPs( gctx: *GraphicsContext, arena: std.mem.Allocator, pso_desc: *d3d12.GRAPHICS_PIPELINE_STATE_DESC, root_signature: ?*d3d12.IRootSignature, vs_cso_path: ?[]const u8, gs_cso_path: ?[]const u8, ps_cso_path: ?[]const u8, ) PipelineHandle { const tracy_zone = ztracy.zone(@src(), 1); defer tracy_zone.end(); if (vs_cso_path) |path| { const vs_file = std.fs.cwd().openFile(path, .{}) catch unreachable; defer vs_file.close(); const vs_code = vs_file.reader().readAllAlloc(arena, 256 * 1024) catch unreachable; pso_desc.VS = .{ .pShaderBytecode = vs_code.ptr, .BytecodeLength = vs_code.len }; } else { assert(pso_desc.VS.pShaderBytecode != null); } if (gs_cso_path) |path| { const gs_file = std.fs.cwd().openFile(path, .{}) catch unreachable; defer gs_file.close(); const gs_code = gs_file.reader().readAllAlloc(arena, 256 * 1024) catch unreachable; pso_desc.GS = .{ .pShaderBytecode = gs_code.ptr, .BytecodeLength = gs_code.len }; } if (ps_cso_path) |path| { const ps_file = std.fs.cwd().openFile(path, .{}) catch unreachable; defer ps_file.close(); const ps_code = ps_file.reader().readAllAlloc(arena, 256 * 1024) catch unreachable; pso_desc.PS = .{ .pShaderBytecode = ps_code.ptr, .BytecodeLength = ps_code.len }; } const hash = compute_hash: { var hasher = std.hash.Adler32.init(); hasher.update( @ptrCast([*]const u8, pso_desc.VS.pShaderBytecode.?)[0..pso_desc.VS.BytecodeLength], ); if (pso_desc.GS.pShaderBytecode != null) { hasher.update( @ptrCast([*]const u8, pso_desc.GS.pShaderBytecode.?)[0..pso_desc.GS.BytecodeLength], ); } if (pso_desc.PS.pShaderBytecode != null) { hasher.update( @ptrCast([*]const u8, pso_desc.PS.pShaderBytecode.?)[0..pso_desc.PS.BytecodeLength], ); } hasher.update(std.mem.asBytes(&pso_desc.BlendState)); hasher.update(std.mem.asBytes(&pso_desc.SampleMask)); hasher.update(std.mem.asBytes(&pso_desc.RasterizerState)); hasher.update(std.mem.asBytes(&pso_desc.DepthStencilState)); hasher.update(std.mem.asBytes(&pso_desc.IBStripCutValue)); hasher.update(std.mem.asBytes(&pso_desc.PrimitiveTopologyType)); hasher.update(std.mem.asBytes(&pso_desc.NumRenderTargets)); hasher.update(std.mem.asBytes(&pso_desc.RTVFormats)); hasher.update(std.mem.asBytes(&pso_desc.DSVFormat)); hasher.update(std.mem.asBytes(&pso_desc.SampleDesc)); // We don't support Stream Output. assert(pso_desc.StreamOutput.pSODeclaration == null); hasher.update(std.mem.asBytes(&pso_desc.InputLayout.NumElements)); if (pso_desc.InputLayout.pInputElementDescs) |elements| { var i: u32 = 0; while (i < pso_desc.InputLayout.NumElements) : (i += 1) { // TODO(mziulek): We ignore 'SemanticName' field here. hasher.update(std.mem.asBytes(&elements[i].Format)); hasher.update(std.mem.asBytes(&elements[i].InputSlot)); hasher.update(std.mem.asBytes(&elements[i].AlignedByteOffset)); hasher.update(std.mem.asBytes(&elements[i].InputSlotClass)); hasher.update(std.mem.asBytes(&elements[i].InstanceDataStepRate)); } } break :compute_hash hasher.final(); }; std.log.info("[graphics] Graphics pipeline hash: {d}", .{hash}); if (gctx.pipeline_pool.map.contains(hash)) { std.log.info("[graphics] Graphics pipeline cache hit detected.", .{}); const handle = gctx.pipeline_pool.map.getEntry(hash).?.value_ptr.*; return handle; } const rs = blk: { if (root_signature) |rs| { break :blk rs; } else { var rs: *d3d12.IRootSignature = undefined; hrPanicOnFail(gctx.device.CreateRootSignature( 0, pso_desc.VS.pShaderBytecode.?, pso_desc.VS.BytecodeLength, &d3d12.IID_IRootSignature, @ptrCast(*?*anyopaque, &rs), )); break :blk rs; } }; pso_desc.pRootSignature = rs; const pso = blk: { var pso: *d3d12.IPipelineState = undefined; hrPanicOnFail(gctx.device.CreateGraphicsPipelineState( pso_desc, &d3d12.IID_IPipelineState, @ptrCast(*?*anyopaque, &pso), )); break :blk pso; }; return gctx.pipeline_pool.addPipeline(pso, rs, .Graphics, hash); } pub fn createMeshShaderPipeline( gctx: *GraphicsContext, arena: std.mem.Allocator, pso_desc: *d3d12.MESH_SHADER_PIPELINE_STATE_DESC, as_cso_path: ?[]const u8, ms_cso_path: ?[]const u8, ps_cso_path: ?[]const u8, ) PipelineHandle { const tracy_zone = ztracy.zone(@src(), 1); defer tracy_zone.end(); if (as_cso_path) |path| { const as_file = std.fs.cwd().openFile(path, .{}) catch unreachable; defer as_file.close(); const as_code = as_file.reader().readAllAlloc(arena, 256 * 1024) catch unreachable; pso_desc.AS = .{ .pShaderBytecode = as_code.ptr, .BytecodeLength = as_code.len }; } if (ms_cso_path) |path| { const ms_file = std.fs.cwd().openFile(path, .{}) catch unreachable; defer ms_file.close(); const ms_code = ms_file.reader().readAllAlloc(arena, 256 * 1024) catch unreachable; pso_desc.MS = .{ .pShaderBytecode = ms_code.ptr, .BytecodeLength = ms_code.len }; } else { assert(pso_desc.MS.pShaderBytecode != null); } if (ps_cso_path) |path| { const ps_file = std.fs.cwd().openFile(path, .{}) catch unreachable; defer ps_file.close(); const ps_code = ps_file.reader().readAllAlloc(arena, 256 * 1024) catch unreachable; pso_desc.PS = .{ .pShaderBytecode = ps_code.ptr, .BytecodeLength = ps_code.len }; } else { assert(pso_desc.PS.pShaderBytecode != null); } const hash = compute_hash: { var hasher = std.hash.Adler32.init(); hasher.update( @ptrCast([*]const u8, pso_desc.MS.pShaderBytecode.?)[0..pso_desc.MS.BytecodeLength], ); if (pso_desc.AS.pShaderBytecode != null) { hasher.update( @ptrCast([*]const u8, pso_desc.AS.pShaderBytecode.?)[0..pso_desc.AS.BytecodeLength], ); } hasher.update( @ptrCast([*]const u8, pso_desc.PS.pShaderBytecode.?)[0..pso_desc.PS.BytecodeLength], ); hasher.update(std.mem.asBytes(&pso_desc.BlendState)); hasher.update(std.mem.asBytes(&pso_desc.SampleMask)); hasher.update(std.mem.asBytes(&pso_desc.RasterizerState)); hasher.update(std.mem.asBytes(&pso_desc.DepthStencilState)); hasher.update(std.mem.asBytes(&pso_desc.PrimitiveTopologyType)); hasher.update(std.mem.asBytes(&pso_desc.NumRenderTargets)); hasher.update(std.mem.asBytes(&pso_desc.RTVFormats)); hasher.update(std.mem.asBytes(&pso_desc.DSVFormat)); hasher.update(std.mem.asBytes(&pso_desc.SampleDesc)); break :compute_hash hasher.final(); }; std.log.info("[graphics] Mesh shader pipeline hash: {d}", .{hash}); if (gctx.pipeline_pool.map.contains(hash)) { std.log.info("[graphics] Mesh shader pipeline cache hit detected.", .{}); const handle = gctx.pipeline_pool.map.getEntry(hash).?.value_ptr.*; return handle; } const rs = blk: { var rs: *d3d12.IRootSignature = undefined; hrPanicOnFail(gctx.device.CreateRootSignature( 0, pso_desc.MS.pShaderBytecode.?, pso_desc.MS.BytecodeLength, &d3d12.IID_IRootSignature, @ptrCast(*?*anyopaque, &rs), )); break :blk rs; }; pso_desc.pRootSignature = rs; const pso = blk: { var stream = d3d12.PIPELINE_MESH_STATE_STREAM.init(pso_desc.*); var pso: *d3d12.IPipelineState = undefined; hrPanicOnFail(gctx.device.CreatePipelineState( &d3d12.PIPELINE_STATE_STREAM_DESC{ .SizeInBytes = @sizeOf(@TypeOf(stream)), .pPipelineStateSubobjectStream = &stream, }, &d3d12.IID_IPipelineState, @ptrCast(*?*anyopaque, &pso), )); break :blk pso; }; return gctx.pipeline_pool.addPipeline(pso, rs, .Graphics, hash); } pub fn createComputeShaderPipeline( gctx: *GraphicsContext, arena: std.mem.Allocator, pso_desc: *d3d12.COMPUTE_PIPELINE_STATE_DESC, cs_cso_path: ?[]const u8, ) PipelineHandle { const tracy_zone = ztracy.zone(@src(), 1); defer tracy_zone.end(); if (cs_cso_path) |path| { const cs_file = std.fs.cwd().openFile(path, .{}) catch unreachable; defer cs_file.close(); const cs_code = cs_file.reader().readAllAlloc(arena, 256 * 1024) catch unreachable; pso_desc.CS = .{ .pShaderBytecode = cs_code.ptr, .BytecodeLength = cs_code.len }; } else { assert(pso_desc.CS.pShaderBytecode != null); } const hash = compute_hash: { var hasher = std.hash.Adler32.init(); hasher.update( @ptrCast([*]const u8, pso_desc.CS.pShaderBytecode.?)[0..pso_desc.CS.BytecodeLength], ); break :compute_hash hasher.final(); }; std.log.info("[graphics] Compute pipeline hash: {d}", .{hash}); if (gctx.pipeline_pool.map.contains(hash)) { std.log.info("[graphics] Compute pipeline hit detected.", .{}); const handle = gctx.pipeline_pool.map.getEntry(hash).?.value_ptr.*; return handle; } const rs = blk: { var rs: *d3d12.IRootSignature = undefined; hrPanicOnFail(gctx.device.CreateRootSignature( 0, pso_desc.CS.pShaderBytecode.?, pso_desc.CS.BytecodeLength, &d3d12.IID_IRootSignature, @ptrCast(*?*anyopaque, &rs), )); break :blk rs; }; pso_desc.pRootSignature = rs; const pso = blk: { var pso: *d3d12.IPipelineState = undefined; hrPanicOnFail(gctx.device.CreateComputePipelineState( pso_desc, &d3d12.IID_IPipelineState, @ptrCast(*?*anyopaque, &pso), )); break :blk pso; }; return gctx.pipeline_pool.addPipeline(pso, rs, .Compute, hash); } pub fn setCurrentPipeline(gctx: *GraphicsContext, pipeline_handle: PipelineHandle) void { assert(gctx.is_cmdlist_opened); const pipeline = gctx.pipeline_pool.lookupPipeline(pipeline_handle); if (pipeline == null) return; if (pipeline_handle.index == gctx.current_pipeline.index and pipeline_handle.generation == gctx.current_pipeline.generation) { return; } gctx.cmdlist.SetPipelineState(pipeline.?.pso.?); switch (pipeline.?.ptype.?) { .Graphics => gctx.cmdlist.SetGraphicsRootSignature(pipeline.?.rs.?), .Compute => gctx.cmdlist.SetComputeRootSignature(pipeline.?.rs.?), } gctx.current_pipeline = pipeline_handle; } pub fn destroyPipeline(gctx: *GraphicsContext, handle: PipelineHandle) void { gctx.pipeline_pool.destroyPipeline(handle); } pub fn allocateUploadMemory( gctx: *GraphicsContext, comptime T: type, num_elements: u32, ) struct { cpu_slice: []T, gpu_base: d3d12.GPU_VIRTUAL_ADDRESS } { assert(num_elements > 0); const size = num_elements * @sizeOf(T); var memory = gctx.upload_memory_heaps[gctx.frame_index].allocate(size); if (memory.cpu_slice == null or memory.gpu_base == null) { std.log.info( "[graphics] Upload memory exhausted - waiting for a GPU... (cmdlist state is lost).", .{}, ); gctx.finishGpuCommands(); memory = gctx.upload_memory_heaps[gctx.frame_index].allocate(size); } return .{ .cpu_slice = std.mem.bytesAsSlice(T, @alignCast(@alignOf(T), memory.cpu_slice.?)), .gpu_base = memory.gpu_base.?, }; } pub fn allocateUploadBufferRegion( gctx: *GraphicsContext, comptime T: type, num_elements: u32, ) struct { cpu_slice: []T, buffer: *d3d12.IResource, buffer_offset: u64 } { assert(num_elements > 0); const size = num_elements * @sizeOf(T); const memory = gctx.allocateUploadMemory(T, num_elements); const aligned_size = (size + (GpuMemoryHeap.alloc_alignment - 1)) & ~(GpuMemoryHeap.alloc_alignment - 1); return .{ .cpu_slice = memory.cpu_slice, .buffer = gctx.upload_memory_heaps[gctx.frame_index].heap, .buffer_offset = gctx.upload_memory_heaps[gctx.frame_index].size - aligned_size, }; } pub fn allocateCpuDescriptors( gctx: *GraphicsContext, dtype: d3d12.DESCRIPTOR_HEAP_TYPE, num: u32, ) d3d12.CPU_DESCRIPTOR_HANDLE { assert(num > 0); switch (dtype) { .CBV_SRV_UAV => { assert(gctx.cbv_srv_uav_cpu_heap.size_temp == 0); return gctx.cbv_srv_uav_cpu_heap.allocateDescriptors(num).cpu_handle; }, .RTV => { assert(gctx.rtv_heap.size_temp == 0); return gctx.rtv_heap.allocateDescriptors(num).cpu_handle; }, .DSV => { assert(gctx.dsv_heap.size_temp == 0); return gctx.dsv_heap.allocateDescriptors(num).cpu_handle; }, .SAMPLER => unreachable, } } pub fn allocateTempCpuDescriptors( gctx: *GraphicsContext, dtype: d3d12.DESCRIPTOR_HEAP_TYPE, num: u32, ) d3d12.CPU_DESCRIPTOR_HANDLE { assert(num > 0); var dheap = switch (dtype) { .CBV_SRV_UAV => &gctx.cbv_srv_uav_cpu_heap, .RTV => &gctx.rtv_heap, .DSV => &gctx.dsv_heap, .SAMPLER => unreachable, }; const handle = dheap.allocateDescriptors(num).cpu_handle; dheap.size_temp += num; return handle; } pub fn deallocateAllTempCpuDescriptors( gctx: *GraphicsContext, dtype: d3d12.DESCRIPTOR_HEAP_TYPE, ) void { var dheap = switch (dtype) { .CBV_SRV_UAV => &gctx.cbv_srv_uav_cpu_heap, .RTV => &gctx.rtv_heap, .DSV => &gctx.dsv_heap, .SAMPLER => unreachable, }; assert(dheap.size_temp > 0); assert(dheap.size_temp <= dheap.size); dheap.size -= dheap.size_temp; dheap.size_temp = 0; } pub inline fn allocateGpuDescriptors(gctx: *GraphicsContext, num_descriptors: u32) Descriptor { // Allocate non-persistent descriptors return gctx.cbv_srv_uav_gpu_heaps[gctx.frame_index + 1].allocateDescriptors(num_descriptors); } pub fn allocatePersistentGpuDescriptors( gctx: *GraphicsContext, num_descriptors: u32, ) PersistentDescriptor { // Allocate descriptors from persistent heap (heap 0) const index = gctx.cbv_srv_uav_gpu_heaps[0].size; const base = gctx.cbv_srv_uav_gpu_heaps[0].allocateDescriptors(num_descriptors); return .{ .cpu_handle = base.cpu_handle, .gpu_handle = base.gpu_handle, .index = index, }; } pub fn copyDescriptorsToGpuHeap( gctx: *GraphicsContext, num: u32, src_base_handle: d3d12.CPU_DESCRIPTOR_HANDLE, ) d3d12.GPU_DESCRIPTOR_HANDLE { const base = gctx.allocateGpuDescriptors(num); gctx.device.CopyDescriptorsSimple(num, base.cpu_handle, src_base_handle, .CBV_SRV_UAV); return base.gpu_handle; } pub fn updateTex2dSubresource( gctx: *GraphicsContext, texture: ResourceHandle, subresource: u32, data: []const u8, row_pitch: u32, ) void { assert(gctx.is_cmdlist_opened); const resource = gctx.resource_pool.lookupResource(texture); if (resource == null) return; assert(resource.?.desc.Dimension == .TEXTURE2D); var layout: [1]d3d12.PLACED_SUBRESOURCE_FOOTPRINT = undefined; var required_size: u64 = undefined; gctx.device.GetCopyableFootprints( &resource.?.desc, subresource, layout.len, 0, &layout, null, null, &required_size, ); const upload = gctx.allocateUploadBufferRegion(u8, @intCast(u32, required_size)); layout[0].Offset = upload.buffer_offset; const pixel_size = resource.?.desc.Format.pixelSizeInBytes(); var y: u32 = 0; while (y < layout[0].Footprint.Height) : (y += 1) { var x: u32 = 0; while (x < layout[0].Footprint.Width * pixel_size) : (x += 1) { upload.cpu_slice[y * layout[0].Footprint.RowPitch + x] = data[y * row_pitch + x]; } } gctx.addTransitionBarrier(texture, d3d12.RESOURCE_STATE_COPY_DEST); gctx.flushResourceBarriers(); gctx.cmdlist.CopyTextureRegion(&d3d12.TEXTURE_COPY_LOCATION{ .pResource = gctx.lookupResource(texture).?, .Type = .SUBRESOURCE_INDEX, .u = .{ .SubresourceIndex = subresource, }, }, 0, 0, 0, &d3d12.TEXTURE_COPY_LOCATION{ .pResource = upload.buffer, .Type = .PLACED_FOOTPRINT, .u = .{ .PlacedFootprint = layout[0], }, }, null); } pub fn createAndUploadTex2dFromFile( gctx: *GraphicsContext, path: []const u8, params: struct { num_mip_levels: u32 = 0, texture_flags: d3d12.RESOURCE_FLAGS = d3d12.RESOURCE_FLAG_NONE, }, ) HResultError!ResourceHandle { assert(gctx.is_cmdlist_opened); // TODO(mziulek): Hardcoded array size. Make it more robust. var path_u16: [300]u16 = undefined; assert(path.len < path_u16.len - 1); const path_len = std.unicode.utf8ToUtf16Le(path_u16[0..], path) catch unreachable; path_u16[path_len] = 0; const bmp_decoder = blk: { var maybe_bmp_decoder: ?*wic.IBitmapDecoder = undefined; hrPanicOnFail(gctx.wic_factory.CreateDecoderFromFilename( @ptrCast(w32.LPCWSTR, &path_u16), null, w32.GENERIC_READ, .MetadataCacheOnDemand, &maybe_bmp_decoder, )); break :blk maybe_bmp_decoder.?; }; defer _ = bmp_decoder.Release(); const bmp_frame = blk: { var maybe_bmp_frame: ?*wic.IBitmapFrameDecode = null; hrPanicOnFail(bmp_decoder.GetFrame(0, &maybe_bmp_frame)); break :blk maybe_bmp_frame.?; }; defer _ = bmp_frame.Release(); const pixel_format = blk: { var pixel_format: w32.GUID = undefined; hrPanicOnFail(bmp_frame.GetPixelFormat(&pixel_format)); break :blk pixel_format; }; const eql = std.mem.eql; const asBytes = std.mem.asBytes; const num_components: u32 = blk: { if (eql(u8, asBytes(&pixel_format), asBytes(&wic.GUID_PixelFormat24bppRGB))) break :blk 4; if (eql(u8, asBytes(&pixel_format), asBytes(&wic.GUID_PixelFormat32bppRGB))) break :blk 4; if (eql(u8, asBytes(&pixel_format), asBytes(&wic.GUID_PixelFormat32bppRGBA))) break :blk 4; if (eql(u8, asBytes(&pixel_format), asBytes(&wic.GUID_PixelFormat32bppPRGBA))) break :blk 4; if (eql(u8, asBytes(&pixel_format), asBytes(&wic.GUID_PixelFormat24bppBGR))) break :blk 4; if (eql(u8, asBytes(&pixel_format), asBytes(&wic.GUID_PixelFormat32bppBGR))) break :blk 4; if (eql(u8, asBytes(&pixel_format), asBytes(&wic.GUID_PixelFormat32bppBGRA))) break :blk 4; if (eql(u8, asBytes(&pixel_format), asBytes(&wic.GUID_PixelFormat32bppPBGRA))) break :blk 4; if (eql(u8, asBytes(&pixel_format), asBytes(&wic.GUID_PixelFormat8bppGray))) break :blk 1; if (eql(u8, asBytes(&pixel_format), asBytes(&wic.GUID_PixelFormat8bppAlpha))) break :blk 1; unreachable; }; const wic_format = if (num_components == 1) &wic.GUID_PixelFormat8bppGray else &wic.GUID_PixelFormat32bppRGBA; const dxgi_format = if (num_components == 1) dxgi.FORMAT.R8_UNORM else dxgi.FORMAT.R8G8B8A8_UNORM; const image_conv = blk: { var maybe_image_conv: ?*wic.IFormatConverter = null; hrPanicOnFail(gctx.wic_factory.CreateFormatConverter(&maybe_image_conv)); break :blk maybe_image_conv.?; }; defer _ = image_conv.Release(); hrPanicOnFail(image_conv.Initialize( @ptrCast(*wic.IBitmapSource, bmp_frame), wic_format, .None, null, 0.0, .Custom, )); const image_wh = blk: { var width: u32 = undefined; var height: u32 = undefined; hrPanicOnFail(image_conv.GetSize(&width, &height)); break :blk .{ .w = width, .h = height }; }; const texture = try gctx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &blk: { var desc = d3d12.RESOURCE_DESC.initTex2d( dxgi_format, image_wh.w, image_wh.h, params.num_mip_levels, ); desc.Flags = params.texture_flags; break :blk desc; }, d3d12.RESOURCE_STATE_COPY_DEST, null, ); const desc = gctx.lookupResource(texture).?.GetDesc(); var layout: [1]d3d12.PLACED_SUBRESOURCE_FOOTPRINT = undefined; var required_size: u64 = undefined; gctx.device.GetCopyableFootprints(&desc, 0, 1, 0, &layout, null, null, &required_size); const upload = gctx.allocateUploadBufferRegion(u8, @intCast(u32, required_size)); layout[0].Offset = upload.buffer_offset; hrPanicOnFail(image_conv.CopyPixels( null, layout[0].Footprint.RowPitch, layout[0].Footprint.RowPitch * layout[0].Footprint.Height, upload.cpu_slice.ptr, )); gctx.cmdlist.CopyTextureRegion(&d3d12.TEXTURE_COPY_LOCATION{ .pResource = gctx.lookupResource(texture).?, .Type = .SUBRESOURCE_INDEX, .u = .{ .SubresourceIndex = 0 }, }, 0, 0, 0, &d3d12.TEXTURE_COPY_LOCATION{ .pResource = upload.buffer, .Type = .PLACED_FOOTPRINT, .u = .{ .PlacedFootprint = layout[0] }, }, null); return texture; } }; pub const MipmapGenerator = struct { const num_scratch_textures = 4; pipeline: PipelineHandle, scratch_textures: [num_scratch_textures]ResourceHandle, base_uav: d3d12.CPU_DESCRIPTOR_HANDLE, format: dxgi.FORMAT, pub fn init( arena: std.mem.Allocator, gctx: *GraphicsContext, format: dxgi.FORMAT, comptime content_dir: []const u8, ) MipmapGenerator { var width: u32 = 2048 / 2; var height: u32 = 2048 / 2; var scratch_textures: [num_scratch_textures]ResourceHandle = undefined; for (scratch_textures) |_, texture_index| { scratch_textures[texture_index] = gctx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &blk: { var desc = d3d12.RESOURCE_DESC.initTex2d(format, width, height, 1); desc.Flags = d3d12.RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; break :blk desc; }, d3d12.RESOURCE_STATE_UNORDERED_ACCESS, null, ) catch |err| hrPanic(err); width /= 2; height /= 2; } const base_uav = gctx.allocateCpuDescriptors(.CBV_SRV_UAV, num_scratch_textures); var cpu_handle = base_uav; for (scratch_textures) |_, texture_index| { gctx.device.CreateUnorderedAccessView( gctx.lookupResource(scratch_textures[texture_index]).?, null, null, cpu_handle, ); cpu_handle.ptr += gctx.cbv_srv_uav_cpu_heap.descriptor_size; } var desc = d3d12.COMPUTE_PIPELINE_STATE_DESC.initDefault(); const pipeline = gctx.createComputeShaderPipeline( arena, &desc, content_dir ++ "shaders/generate_mipmaps.cs.cso", ); return .{ .pipeline = pipeline, .scratch_textures = scratch_textures, .base_uav = base_uav, .format = format, }; } pub fn deinit(mipgen: *MipmapGenerator, gctx: *GraphicsContext) void { for (mipgen.scratch_textures) |_, texture_index| { gctx.destroyResource(mipgen.scratch_textures[texture_index]); } gctx.destroyPipeline(mipgen.pipeline); mipgen.* = undefined; } pub fn generateMipmaps( mipgen: *MipmapGenerator, gctx: *GraphicsContext, texture_handle: ResourceHandle, ) void { if (!gctx.resource_pool.isResourceValid(texture_handle)) return; const texture_desc = gctx.getResourceDesc(texture_handle); assert(mipgen.format == texture_desc.Format); assert(texture_desc.Width <= 2048 and texture_desc.Height <= 2048); assert(texture_desc.Width == texture_desc.Height); assert(texture_desc.MipLevels > 1); var array_slice: u32 = 0; while (array_slice < texture_desc.DepthOrArraySize) : (array_slice += 1) { const texture_srv = gctx.allocateTempCpuDescriptors(.CBV_SRV_UAV, 1); gctx.device.CreateShaderResourceView( gctx.lookupResource(texture_handle).?, &d3d12.SHADER_RESOURCE_VIEW_DESC{ .Format = .UNKNOWN, .ViewDimension = .TEXTURE2DARRAY, .Shader4ComponentMapping = d3d12.DEFAULT_SHADER_4_COMPONENT_MAPPING, .u = .{ .Texture2DArray = .{ .MipLevels = texture_desc.MipLevels, .FirstArraySlice = array_slice, .ArraySize = 1, .MostDetailedMip = 0, .PlaneSlice = 0, .ResourceMinLODClamp = 0.0, }, }, }, texture_srv, ); const table_base = gctx.copyDescriptorsToGpuHeap(1, texture_srv); _ = gctx.copyDescriptorsToGpuHeap(num_scratch_textures, mipgen.base_uav); gctx.deallocateAllTempCpuDescriptors(.CBV_SRV_UAV); gctx.setCurrentPipeline(mipgen.pipeline); var total_num_mips: u32 = texture_desc.MipLevels - 1; var current_src_mip_level: u32 = 0; while (true) { for (mipgen.scratch_textures) |scratch_texture| { gctx.addTransitionBarrier(scratch_texture, d3d12.RESOURCE_STATE_UNORDERED_ACCESS); } gctx.addTransitionBarrier(texture_handle, d3d12.RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); gctx.flushResourceBarriers(); const dispatch_num_mips = if (total_num_mips >= 4) 4 else total_num_mips; gctx.cmdlist.SetComputeRoot32BitConstant(0, current_src_mip_level, 0); gctx.cmdlist.SetComputeRoot32BitConstant(0, dispatch_num_mips, 1); gctx.cmdlist.SetComputeRootDescriptorTable(1, table_base); const num_groups_x = std.math.max( @intCast(u32, texture_desc.Width) >> @intCast(u5, 3 + current_src_mip_level), 1, ); const num_groups_y = std.math.max( texture_desc.Height >> @intCast(u5, 3 + current_src_mip_level), 1, ); gctx.cmdlist.Dispatch(num_groups_x, num_groups_y, 1); for (mipgen.scratch_textures) |scratch_texture| { gctx.addTransitionBarrier(scratch_texture, d3d12.RESOURCE_STATE_COPY_SOURCE); } gctx.addTransitionBarrier(texture_handle, d3d12.RESOURCE_STATE_COPY_DEST); gctx.flushResourceBarriers(); var mip_index: u32 = 0; while (mip_index < dispatch_num_mips) : (mip_index += 1) { const dst = d3d12.TEXTURE_COPY_LOCATION{ .pResource = gctx.lookupResource(texture_handle).?, .Type = .SUBRESOURCE_INDEX, .u = .{ .SubresourceIndex = mip_index + 1 + current_src_mip_level + array_slice * texture_desc.MipLevels }, }; const src = d3d12.TEXTURE_COPY_LOCATION{ .pResource = gctx.lookupResource(mipgen.scratch_textures[mip_index]).?, .Type = .SUBRESOURCE_INDEX, .u = .{ .SubresourceIndex = 0 }, }; const box = d3d12.BOX{ .left = 0, .top = 0, .front = 0, .right = @intCast(u32, texture_desc.Width) >> @intCast( u5, mip_index + 1 + current_src_mip_level, ), .bottom = texture_desc.Height >> @intCast(u5, mip_index + 1 + current_src_mip_level), .back = 1, }; gctx.cmdlist.CopyTextureRegion(&dst, 0, 0, 0, &src, &box); } assert(total_num_mips >= dispatch_num_mips); total_num_mips -= dispatch_num_mips; if (total_num_mips == 0) { break; } current_src_mip_level += dispatch_num_mips; } } } }; pub const ResourceHandle = struct { index: u16 align(4) = 0, generation: u16 = 0, }; const Resource = struct { raw: ?*d3d12.IResource, state: d3d12.RESOURCE_STATES, desc: d3d12.RESOURCE_DESC, }; const ResourcePool = struct { const max_num_resources = 256; resources: []Resource, generations: []u16, fn init(allocator: std.mem.Allocator) ResourcePool { return .{ .resources = blk: { var resources = allocator.alloc( Resource, max_num_resources + 1, ) catch unreachable; for (resources) |*res| { res.* = .{ .raw = null, .state = d3d12.RESOURCE_STATE_COMMON, .desc = d3d12.RESOURCE_DESC.initBuffer(0), }; } break :blk resources; }, .generations = blk: { var generations = allocator.alloc( u16, max_num_resources + 1, ) catch unreachable; for (generations) |*gen| gen.* = 0; break :blk generations; }, }; } fn deinit(pool: *ResourcePool, allocator: std.mem.Allocator) void { for (pool.resources) |resource| { if (resource.raw != null) _ = resource.raw.?.Release(); } allocator.free(pool.resources); allocator.free(pool.generations); pool.* = undefined; } fn addResource( pool: ResourcePool, raw: *d3d12.IResource, state: d3d12.RESOURCE_STATES, ) ResourceHandle { var slot_idx: u32 = 1; while (slot_idx <= max_num_resources) : (slot_idx += 1) { if (pool.resources[slot_idx].raw == null) break; } assert(slot_idx <= max_num_resources); pool.resources[slot_idx] = .{ .raw = raw, .state = state, .desc = raw.GetDesc() }; return .{ .index = @intCast(u16, slot_idx), .generation = blk: { pool.generations[slot_idx] += 1; break :blk pool.generations[slot_idx]; }, }; } fn destroyResource(pool: ResourcePool, handle: ResourceHandle) void { var resource = pool.lookupResource(handle); if (resource == null) return; _ = resource.?.raw.?.Release(); resource.?.* = .{ .raw = null, .state = d3d12.RESOURCE_STATE_COMMON, .desc = d3d12.RESOURCE_DESC.initBuffer(0), }; } fn isResourceValid(pool: ResourcePool, handle: ResourceHandle) bool { return handle.index > 0 and handle.index <= max_num_resources and handle.generation > 0 and handle.generation == pool.generations[handle.index] and pool.resources[handle.index].raw != null; } fn lookupResource(pool: ResourcePool, handle: ResourceHandle) ?*Resource { if (pool.isResourceValid(handle)) { return &pool.resources[handle.index]; } return null; } }; pub const PipelineHandle = struct { index: u16 align(4) = 0, generation: u16 = 0, }; const PipelineType = enum { Graphics, Compute, }; const Pipeline = struct { pso: ?*d3d12.IPipelineState, rs: ?*d3d12.IRootSignature, ptype: ?PipelineType, }; const PipelinePool = struct { const max_num_pipelines = 256; pipelines: []Pipeline, generations: []u16, map: std.AutoHashMapUnmanaged(u32, PipelineHandle), fn init(allocator: std.mem.Allocator) PipelinePool { return .{ .pipelines = blk: { var pipelines = allocator.alloc( Pipeline, max_num_pipelines + 1, ) catch unreachable; for (pipelines) |*pipeline| { pipeline.* = .{ .pso = null, .rs = null, .ptype = null }; } break :blk pipelines; }, .generations = blk: { var generations = allocator.alloc( u16, max_num_pipelines + 1, ) catch unreachable; for (generations) |*gen| gen.* = 0; break :blk generations; }, .map = blk: { var hm: std.AutoHashMapUnmanaged(u32, PipelineHandle) = .{}; hm.ensureTotalCapacity( allocator, max_num_pipelines, ) catch unreachable; break :blk hm; }, }; } fn deinit(pool: *PipelinePool, allocator: std.mem.Allocator) void { for (pool.pipelines) |pipeline| { if (pipeline.pso != null) _ = pipeline.pso.?.Release(); if (pipeline.rs != null) _ = pipeline.rs.?.Release(); } pool.map.deinit(allocator); allocator.free(pool.pipelines); allocator.free(pool.generations); pool.* = undefined; } fn addPipeline( pool: *PipelinePool, pso: *d3d12.IPipelineState, rs: *d3d12.IRootSignature, ptype: PipelineType, hash: u32, ) PipelineHandle { var slot_idx: u32 = 1; while (slot_idx <= max_num_pipelines) : (slot_idx += 1) { if (pool.pipelines[slot_idx].pso == null) break; } assert(slot_idx <= max_num_pipelines); pool.pipelines[slot_idx] = .{ .pso = pso, .rs = rs, .ptype = ptype }; const handle = PipelineHandle{ .index = @intCast(u16, slot_idx), .generation = blk: { pool.generations[slot_idx] += 1; break :blk pool.generations[slot_idx]; }, }; pool.map.putAssumeCapacity(hash, handle); return handle; } pub fn destroyPipeline(pool: *PipelinePool, handle: PipelineHandle) void { var pipeline = pool.lookupPipeline(handle); if (pipeline == null) return; _ = pipeline.?.pso.?.Release(); _ = pipeline.?.rs.?.Release(); const hash_to_delete = blk: { var it = pool.map.iterator(); while (it.next()) |kv| { if (kv.value_ptr.*.index == handle.index and kv.value_ptr.*.generation == handle.generation) { break :blk kv.key_ptr.*; } } unreachable; }; _ = pool.map.remove(hash_to_delete); pipeline.?.* = .{ .pso = null, .rs = null, .ptype = null, }; } fn isPipelineValid(pool: PipelinePool, handle: PipelineHandle) bool { return handle.index > 0 and handle.index <= max_num_pipelines and handle.generation > 0 and handle.generation == pool.generations[handle.index] and pool.pipelines[handle.index].pso != null and pool.pipelines[handle.index].rs != null and pool.pipelines[handle.index].ptype != null; } fn lookupPipeline(pool: PipelinePool, handle: PipelineHandle) ?*Pipeline { if (pool.isPipelineValid(handle)) { return &pool.pipelines[handle.index]; } return null; } }; const Descriptor = struct { cpu_handle: d3d12.CPU_DESCRIPTOR_HANDLE, gpu_handle: d3d12.GPU_DESCRIPTOR_HANDLE, }; pub const PersistentDescriptor = struct { cpu_handle: d3d12.CPU_DESCRIPTOR_HANDLE, gpu_handle: d3d12.GPU_DESCRIPTOR_HANDLE, index: u32, }; const DescriptorHeap = struct { heap: ?*d3d12.IDescriptorHeap, base: Descriptor, size: u32, size_temp: u32, capacity: u32, descriptor_size: u32, fn init( device: *d3d12.IDevice9, capacity: u32, heap_type: d3d12.DESCRIPTOR_HEAP_TYPE, flags: d3d12.DESCRIPTOR_HEAP_FLAGS, ) DescriptorHeap { assert(capacity > 0); const heap = blk: { var heap: ?*d3d12.IDescriptorHeap = null; hrPanicOnFail(device.CreateDescriptorHeap(&.{ .Type = heap_type, .NumDescriptors = capacity, .Flags = flags, .NodeMask = 0, }, &d3d12.IID_IDescriptorHeap, @ptrCast(*?*anyopaque, &heap))); break :blk heap.?; }; return DescriptorHeap{ .heap = heap, .base = .{ .cpu_handle = heap.GetCPUDescriptorHandleForHeapStart(), .gpu_handle = blk: { if ((flags & d3d12.DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) != 0) break :blk heap.GetGPUDescriptorHandleForHeapStart(); break :blk d3d12.GPU_DESCRIPTOR_HANDLE{ .ptr = 0 }; }, }, .size = 0, .size_temp = 0, .capacity = capacity, .descriptor_size = device.GetDescriptorHandleIncrementSize(heap_type), }; } fn deinit(dheap: *DescriptorHeap) void { if (dheap.heap != null) { _ = dheap.heap.?.Release(); } dheap.* = undefined; } fn allocateDescriptors(dheap: *DescriptorHeap, num_descriptors: u32) Descriptor { assert(num_descriptors > 0); assert((dheap.size + num_descriptors) < dheap.capacity); const cpu_handle = d3d12.CPU_DESCRIPTOR_HANDLE{ .ptr = dheap.base.cpu_handle.ptr + dheap.size * dheap.descriptor_size, }; const gpu_handle = d3d12.GPU_DESCRIPTOR_HANDLE{ .ptr = blk: { if (dheap.base.gpu_handle.ptr != 0) break :blk dheap.base.gpu_handle.ptr + dheap.size * dheap.descriptor_size; break :blk 0; }, }; dheap.size += num_descriptors; return .{ .cpu_handle = cpu_handle, .gpu_handle = gpu_handle }; } }; const GpuMemoryHeap = struct { const alloc_alignment: u32 = 512; heap: *d3d12.IResource, cpu_slice: []u8, gpu_base: d3d12.GPU_VIRTUAL_ADDRESS, size: u32, capacity: u32, fn init(device: *d3d12.IDevice9, capacity: u32, heap_type: d3d12.HEAP_TYPE) GpuMemoryHeap { assert(capacity > 0); const resource = blk: { var resource: *d3d12.IResource = undefined; hrPanicOnFail(device.CreateCommittedResource( &d3d12.HEAP_PROPERTIES.initType(heap_type), d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(capacity), d3d12.RESOURCE_STATE_GENERIC_READ, null, &d3d12.IID_IResource, @ptrCast(*?*anyopaque, &resource), )); break :blk resource; }; const cpu_base = blk: { var cpu_base: [*]u8 = undefined; hrPanicOnFail(resource.Map( 0, &d3d12.RANGE{ .Begin = 0, .End = 0 }, @ptrCast(*?*anyopaque, &cpu_base), )); break :blk cpu_base; }; return GpuMemoryHeap{ .heap = resource, .cpu_slice = cpu_base[0..capacity], .gpu_base = resource.GetGPUVirtualAddress(), .size = 0, .capacity = capacity, }; } fn deinit(mheap: *GpuMemoryHeap) void { _ = mheap.heap.Release(); mheap.* = undefined; } fn allocate( mheap: *GpuMemoryHeap, size: u32, ) struct { cpu_slice: ?[]u8, gpu_base: ?d3d12.GPU_VIRTUAL_ADDRESS } { assert(size > 0); const aligned_size = (size + (alloc_alignment - 1)) & ~(alloc_alignment - 1); if ((mheap.size + aligned_size) >= mheap.capacity) { return .{ .cpu_slice = null, .gpu_base = null }; } const cpu_slice = (mheap.cpu_slice.ptr + mheap.size)[0..size]; const gpu_base = mheap.gpu_base + mheap.size; mheap.size += aligned_size; return .{ .cpu_slice = cpu_slice, .gpu_base = gpu_base }; } };
libs/zd3d12/src/zd3d12.zig
// DO NOT MODIFY. This is not actually a source file; it is a textual representation of generated code. // Use only for debugging purposes. // Auto-generated constructor // Access: public Method <init> : V ( // (no arguments) ) { ALOAD 0 // Method descriptor: ()V INVOKESPECIAL java/lang/Object#<init> RETURN } // Access: private static Method registerClass72 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "com.redhat.demo.robotservice.model.Cmd" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields ASTORE 4 LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register LDC (Boolean) false ALOAD 4 // Method descriptor: (Z[Ljava/lang/reflect/Field;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass60 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.JaxrsFormProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass7 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "java.util.TreeSet" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass80 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "javax.inject.Named" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: public Method beforeAnalysis : V ( arg 1 = Lorg/graalvm/nativeimage/hosted/Feature$BeforeAnalysisAccess; ) { ** label1 ** label2 LDC (Type) Lorg/graalvm/nativeimage/impl/RuntimeClassInitializationSupport; // Method descriptor: (Ljava/lang/Class;)Ljava/lang/Object; INVOKESTATIC org/graalvm/nativeimage/ImageSingletons#lookup ASTORE 3 LDC (Type) Lio/quarkus/runner/AutoFeature; // Method descriptor: ()Ljava/lang/ClassLoader; INVOKEVIRTUAL java/lang/Class#getClassLoader ASTORE 2 ** label3 LDC (String) "io.quarkus.runtime.ExecutorRecorder" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 4 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 4 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label4 GOTO label5 ** label6 ASTORE 5 ALOAD 5 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label7 GOTO label5 // Try from label3 to label4 // Catch java/lang/Throwable by going to label6 ** label5 ** label8 LDC (String) "org.jboss.logmanager.formatters.TrueColorHolder" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 6 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 6 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label9 GOTO label10 ** label11 ASTORE 7 ALOAD 7 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label12 GOTO label10 // Try from label8 to label9 // Catch java/lang/Throwable by going to label11 ** label10 ** label13 LDC (String) "io.vertx.core.net.impl.PartialPooledByteBufAllocator" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 8 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 8 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label14 GOTO label15 ** label16 ASTORE 9 ALOAD 9 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label17 GOTO label15 // Try from label13 to label14 // Catch java/lang/Throwable by going to label16 ** label15 ** label18 LDC (String) "io.vertx.core.http.impl.VertxHttp2ClientUpgradeCodec" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 10 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 10 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label19 GOTO label20 ** label21 ASTORE 11 ALOAD 11 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label22 GOTO label20 // Try from label18 to label19 // Catch java/lang/Throwable by going to label21 ** label20 ** label23 LDC (String) "io.netty.handler.ssl.ReferenceCountedOpenSslClientContext" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 12 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 12 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label24 GOTO label25 ** label26 ASTORE 13 ALOAD 13 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label27 GOTO label25 // Try from label23 to label24 // Catch java/lang/Throwable by going to label26 ** label25 ** label28 LDC (String) "io.netty.handler.ssl.JdkNpnApplicationProtocolNegotiator" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 14 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 14 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label29 GOTO label30 ** label31 ASTORE 15 ALOAD 15 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label32 GOTO label30 // Try from label28 to label29 // Catch java/lang/Throwable by going to label31 ** label30 ** label33 LDC (String) "io.netty.buffer.ByteBufAllocator" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 16 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 16 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label34 GOTO label35 ** label36 ASTORE 17 ALOAD 17 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label37 GOTO label35 // Try from label33 to label34 // Catch java/lang/Throwable by going to label36 ** label35 ** label38 LDC (String) "io.netty.buffer.PooledByteBufAllocator" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 18 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 18 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label39 GOTO label40 ** label41 ASTORE 19 ALOAD 19 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label42 GOTO label40 // Try from label38 to label39 // Catch java/lang/Throwable by going to label41 ** label40 ** label43 LDC (String) "io.netty.handler.ssl.ReferenceCountedOpenSslEngine" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 20 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 20 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label44 GOTO label45 ** label46 ASTORE 21 ALOAD 21 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label47 GOTO label45 // Try from label43 to label44 // Catch java/lang/Throwable by going to label46 ** label45 ** label48 LDC (String) "io.netty.handler.ssl.ConscryptAlpnSslEngine" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 22 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 22 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label49 GOTO label50 ** label51 ASTORE 23 ALOAD 23 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label52 GOTO label50 // Try from label48 to label49 // Catch java/lang/Throwable by going to label51 ** label50 ** label53 LDC (String) "io.netty.buffer.ByteBufUtil" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 24 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 24 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label54 GOTO label55 ** label56 ASTORE 25 ALOAD 25 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label57 GOTO label55 // Try from label53 to label54 // Catch java/lang/Throwable by going to label56 ** label55 ** label58 LDC (String) "io.netty.handler.codec.http.websocketx.WebSocket00FrameEncoder" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 26 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 26 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label59 GOTO label60 ** label61 ASTORE 27 ALOAD 27 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label62 GOTO label60 // Try from label58 to label59 // Catch java/lang/Throwable by going to label61 ** label60 ** label63 LDC (String) "io.netty.handler.ssl.util.ThreadLocalInsecureRandom" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 28 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 28 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label64 GOTO label65 ** label66 ASTORE 29 ALOAD 29 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label67 GOTO label65 // Try from label63 to label64 // Catch java/lang/Throwable by going to label66 ** label65 ** label68 LDC (String) "io.netty.buffer.ByteBufUtil$HexUtil" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 30 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 30 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label69 GOTO label70 ** label71 ASTORE 31 ALOAD 31 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label72 GOTO label70 // Try from label68 to label69 // Catch java/lang/Throwable by going to label71 ** label70 ** label73 LDC (String) "io.netty.handler.codec.http.HttpObjectEncoder" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 32 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 32 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label74 GOTO label75 ** label76 ASTORE 33 ALOAD 33 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label77 GOTO label75 // Try from label73 to label74 // Catch java/lang/Throwable by going to label76 ** label75 ** label78 LDC (String) "io.netty.handler.codec.http2.DefaultHttp2FrameWriter" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 34 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 34 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label79 GOTO label80 ** label81 ASTORE 35 ALOAD 35 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label82 GOTO label80 // Try from label78 to label79 // Catch java/lang/Throwable by going to label81 ** label80 ** label83 LDC (String) "io.netty.handler.ssl.ReferenceCountedOpenSslContext" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 36 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 36 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label84 GOTO label85 ** label86 ASTORE 37 ALOAD 37 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label87 GOTO label85 // Try from label83 to label84 // Catch java/lang/Throwable by going to label86 ** label85 ** label88 LDC (String) "io.netty.handler.codec.http2.Http2CodecUtil" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 38 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 38 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label89 GOTO label90 ** label91 ASTORE 39 ALOAD 39 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label92 GOTO label90 // Try from label88 to label89 // Catch java/lang/Throwable by going to label91 ** label90 ** label93 LDC (String) "io.quarkus.runtime.generated.RunTimeConfig" LDC (Boolean) false ALOAD 2 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 40 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 40 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#initializeAtRunTime ** label94 GOTO label95 ** label96 ASTORE 41 ALOAD 41 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label97 GOTO label95 // Try from label93 to label94 // Catch java/lang/Throwable by going to label96 ** label95 LDC (Type) Lio/quarkus/runner/AutoFeature; // Method descriptor: ()Ljava/lang/ClassLoader; INVOKEVIRTUAL java/lang/Class#getClassLoader ASTORE 42 ** label98 LDC (String) "io.quarkus.netty.runtime.graal.Holder_io_netty_util_concurrent_ScheduledFutureTask" LDC (Boolean) false ALOAD 42 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 43 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 43 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#rerunInitialization ** label99 GOTO label100 ** label101 ASTORE 44 ALOAD 44 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label102 GOTO label100 // Try from label98 to label99 // Catch java/lang/Throwable by going to label101 ** label100 ** label103 LDC (String) "java.util.concurrent.ThreadLocalRandom" LDC (Boolean) false ALOAD 42 // Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 45 ALOAD 3 CHECKCAST org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport ALOAD 45 LDC (String) "Quarkus" // Method descriptor: (Ljava/lang/Class;Ljava/lang/String;)V INVOKEINTERFACE org/graalvm/nativeimage/impl/RuntimeClassInitializationSupport#rerunInitialization ** label104 GOTO label105 ** label106 ASTORE 46 ALOAD 46 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label107 GOTO label105 // Try from label103 to label104 // Catch java/lang/Throwable by going to label106 ** label105 LDC (Type) Lcom/oracle/svm/core/jdk/proxy/DynamicProxyRegistry; // Method descriptor: (Ljava/lang/Class;)Ljava/lang/Object; INVOKESTATIC org/graalvm/nativeimage/ImageSingletons#lookup ASTORE 49 LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 47 LDC (String) "javax.ws.rs.ext.Providers" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 48 ALOAD 47 LDC (Integer) 0 ALOAD 48 AASTORE ALOAD 49 CHECKCAST com/oracle/svm/core/jdk/proxy/DynamicProxyRegistry ALOAD 47 // Method descriptor: ([Ljava/lang/Class;)V INVOKEINTERFACE com/oracle/svm/core/jdk/proxy/DynamicProxyRegistry#addProxyClass LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 50 LDC (String) "org.jboss.resteasy.spi.ResteasyConfiguration" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 51 ALOAD 50 LDC (Integer) 0 ALOAD 51 AASTORE ALOAD 49 CHECKCAST com/oracle/svm/core/jdk/proxy/DynamicProxyRegistry ALOAD 50 // Method descriptor: ([Ljava/lang/Class;)V INVOKEINTERFACE com/oracle/svm/core/jdk/proxy/DynamicProxyRegistry#addProxyClass LDC (String) "META-INF/services/javax.ws.rs.ext.Providers" // Method descriptor: (Ljava/lang/String;)V INVOKESTATIC io/quarkus/runtime/ResourceHelper#registerResources LDC (String) "META-INF/build-config.properties" // Method descriptor: (Ljava/lang/String;)V INVOKESTATIC io/quarkus/runtime/ResourceHelper#registerResources LDC (String) "META-INF/quarkus-default-config.properties" // Method descriptor: (Ljava/lang/String;)V INVOKESTATIC io/quarkus/runtime/ResourceHelper#registerResources LDC (String) "META-INF/services/javax.ws.rs.client.ClientBuilder" // Method descriptor: (Ljava/lang/String;)V INVOKESTATIC io/quarkus/runtime/ResourceHelper#registerResources LDC (String) "META-INF/services/org.jboss.logmanager.EmbeddedConfigurator" // Method descriptor: (Ljava/lang/String;)V INVOKESTATIC io/quarkus/runtime/ResourceHelper#registerResources LDC (String) "META-INF/services/org.eclipse.yasson.spi.JsonbComponentInstanceCreator" // Method descriptor: (Ljava/lang/String;)V INVOKESTATIC io/quarkus/runtime/ResourceHelper#registerResources LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 52 ALOAD 52 LDC (Integer) 0 LDC (Type) Ljava/lang/String; AASTORE LDC (Type) Lcom/oracle/svm/core/jdk/LocalizationSupport; LDC (String) "addBundleToCache" ALOAD 52 // Method descriptor: (Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethod ASTORE 54 ALOAD 54 CHECKCAST java/lang/reflect/AccessibleObject LDC (Boolean) true // Method descriptor: (Z)V INVOKEVIRTUAL java/lang/reflect/AccessibleObject#setAccessible LDC (Type) Lcom/oracle/svm/core/jdk/LocalizationSupport; // Method descriptor: (Ljava/lang/Class;)Ljava/lang/Object; INVOKESTATIC org/graalvm/nativeimage/ImageSingletons#lookup ASTORE 55 ** label108 LDC (Integer) 1 ANEWARRAY java/lang/Object ASTORE 53 ALOAD 53 LDC (Integer) 0 LDC (String) "yasson-messages" AASTORE ALOAD 54 ALOAD 55 ALOAD 53 // Method descriptor: (Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object; INVOKEVIRTUAL java/lang/reflect/Method#invoke POP ** label109 GOTO label110 ** label111 POP ** label112 GOTO label110 // Try from label108 to label109 // Catch java/lang/Throwable by going to label111 ** label110 ** label113 LDC (Integer) 1 ANEWARRAY java/lang/Object ASTORE 56 ALOAD 56 LDC (Integer) 0 LDC (String) "messages" AASTORE ALOAD 54 ALOAD 55 ALOAD 56 // Method descriptor: (Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object; INVOKEVIRTUAL java/lang/reflect/Method#invoke POP ** label114 GOTO label115 ** label116 POP ** label117 GOTO label115 // Try from label113 to label114 // Catch java/lang/Throwable by going to label116 ** label115 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass0 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass1 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass2 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass3 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass4 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass5 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass6 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass7 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass8 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass9 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass10 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass11 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass12 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass13 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass14 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass15 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass16 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass17 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass18 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass19 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass20 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass21 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass22 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass23 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass24 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass25 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass26 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass27 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass28 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass29 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass30 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass31 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass32 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass33 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass34 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass35 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass36 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass37 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass38 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass39 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass40 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass41 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass42 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass43 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass44 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass45 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass46 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass47 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass48 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass49 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass50 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass51 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass52 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass53 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass54 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass55 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass56 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass57 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass58 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass59 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass60 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass61 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass62 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass63 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass64 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass65 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass66 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass67 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass68 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass69 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass70 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass71 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass72 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass73 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass74 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass75 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass76 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass77 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass78 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass79 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass80 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass81 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass82 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass83 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass84 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass85 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass86 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass87 // Method descriptor: ()V INVOKESTATIC io/quarkus/runner/AutoFeature#registerClass88 ** label118 GOTO label119 ** label120 ASTORE 57 ALOAD 57 // Method descriptor: ()V INVOKEVIRTUAL java/lang/Throwable#printStackTrace ** label121 GOTO label119 // Try from label2 to label118 // Catch java/lang/Throwable by going to label120 ** label119 RETURN ** label122 } // Access: private static Method registerClass28 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "com.redhat.demo.robotservice.rest.RobotEndPoint" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields ASTORE 4 LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register LDC (Boolean) false ALOAD 4 // Method descriptor: (Z[Ljava/lang/reflect/Field;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass16 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.microprofile.client.async.AsyncInterceptorRxInvokerProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass48 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.MultiValuedParamConverterProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass36 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.ReactiveStreamProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass24 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "com.fasterxml.jackson.databind.ser.std.SqlDateSerializer" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass68 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.microprofile.config.ServletContextConfigSourceImpl" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass12 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "io.quarkus.vertx.core.runtime.VertxLogDelegateFactory" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass56 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.StreamingOutputProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass44 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.SourceProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass88 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "io.quarkus.jsonb.QuarkusJsonbComponentInstanceCreator" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass32 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.sse.SseEventProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass76 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.eclipse.microprofile.rest.client.inject.RestClient" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass20 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "[Ljavax.ws.rs.client.ClientResponseFilter;" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass64 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.api.validation.ResteasyConstraintViolation" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields ASTORE 4 LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register LDC (Boolean) false ALOAD 4 // Method descriptor: (Z[Ljava/lang/reflect/Field;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass2 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "java.util.HashSet" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass52 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.ByteArrayProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass40 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.CompletionStageProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass84 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "io.quarkus.resteasy.runtime.ResteasyFilter" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass61 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.FileRangeWriter" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass6 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "java.util.TreeMap" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass81 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "io.quarkus.netty.MainEventLoopGroup" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass29 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.api.validation.ViolationReport" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields ASTORE 4 LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register LDC (Boolean) false ALOAD 4 // Method descriptor: (Z[Ljava/lang/reflect/Field;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass17 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.core.providerfactory.ResteasyProviderFactoryImpl" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass49 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.jsonp.JsonArrayProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass37 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.interceptors.CacheControlFeature" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass25 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "com.redhat.demo.robotservice.LocalRobotProxyService" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields ASTORE 4 LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register LDC (Boolean) false ALOAD 4 // Method descriptor: (Z[Ljava/lang/reflect/Field;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass69 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.microprofile.config.FilterConfigSource" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass1 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "java.util.HashMap" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass13 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.apache.commons.logging.impl.LogFactoryImpl" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass57 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.ReaderProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass45 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.FileProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass33 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.jsonp.JsonObjectProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass77 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.eclipse.microprofile.config.inject.ConfigProperty" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass21 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "[Ljavax.ws.rs.ext.ReaderInterceptor;" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass65 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.microprofile.config.ServletConfigSource" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass5 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "java.util.LinkedHashSet" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass53 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.StringTextStar" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass41 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.interceptors.ClientContentEncodingAnnotationFeature" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass85 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "io.undertow.servlet.handlers.DefaultServlet" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass73 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "javax.enterprise.inject.Default" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass50 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.DocumentProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass9 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "io.netty.channel.socket.nio.NioSocketChannel" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass82 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "javax.enterprise.context.Initialized" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass70 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.microprofile.config.FilterConfigSourceImpl" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass18 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.client.jaxrs.internal.proxy.ProxyBuilderImpl" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass38 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.interceptors.ServerContentEncodingAnnotationFeature" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass26 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.jsonb.AbstractJsonBindingProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields ASTORE 4 LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register LDC (Boolean) false ALOAD 4 // Method descriptor: (Z[Ljava/lang/reflect/Field;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass0 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "java.util.ArrayList" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass14 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.apache.commons.logging.impl.Jdk14Logger" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass58 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.sse.SseEventSinkInterceptor" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass46 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.context.ContextFeature" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass34 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.DefaultTextPlain" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass78 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "io.quarkus.netty.BossEventLoopGroup" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass22 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass66 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.microprofile.config.ServletConfigSourceImpl" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass4 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "java.util.LinkedHashMap" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass10 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "io.netty.channel.socket.nio.NioServerSocketChannel" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass54 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "io.quarkus.resteasy.runtime.RolesFilterRegistrar" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass42 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.DefaultNumberWriter" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass86 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "io.quarkus.undertow.runtime.HttpSessionContext" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass30 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.IIOImageProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass74 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "javax.enterprise.context.BeforeDestroyed" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass62 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.InputStreamProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass8 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.eclipse.yasson.JsonBindingProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass83 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "javax.enterprise.inject.Intercepted" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass71 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "com.redhat.demo.robotservice.model.Command" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields ASTORE 4 LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register LDC (Boolean) false ALOAD 4 // Method descriptor: (Z[Ljava/lang/reflect/Field;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass19 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "[Ljavax.ws.rs.client.ClientRequestFilter;" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass39 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.FormUrlEncodedProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass27 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "com.redhat.demo.robotservice.ProxyTestService" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields ASTORE 4 LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register LDC (Boolean) false ALOAD 4 // Method descriptor: (Z[Ljava/lang/reflect/Field;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass15 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.microprofile.client.DefaultResponseExceptionMapper" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass59 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.DataSourceProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass47 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.interceptors.MessageSanitizerContainerResponseFilter" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass35 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.client.jaxrs.internal.CompletionStageRxInvokerProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass79 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "javax.enterprise.inject.Any" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass23 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass67 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.microprofile.config.ServletContextConfigSource" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass11 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.glassfish.json.JsonProviderImpl" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass55 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.jsonp.JsonStructureProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass43 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.jsonb.JsonBindingProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass87 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "io.quarkus.runtime.logging.InitialConfigurator" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass31 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.sse.SseEventOutputProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass75 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "javax.enterprise.context.Destroyed" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods ASTORE 3 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 3 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass63 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.jsonp.JsonValueProvider" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass3 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "java.util.LinkedList" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 } // Access: private static Method registerClass51 : V ( // (no arguments) ) { ** label1 ** label2 LDC (String) "org.jboss.resteasy.plugins.providers.DefaultBooleanWriter" // Method descriptor: (Ljava/lang/String;)Ljava/lang/Class; INVOKESTATIC java/lang/Class#forName ASTORE 0 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Constructor; INVOKEVIRTUAL java/lang/Class#getDeclaredConstructors ASTORE 2 ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Method; INVOKEVIRTUAL java/lang/Class#getDeclaredMethods POP ALOAD 0 // Method descriptor: ()[Ljava/lang/reflect/Field; INVOKEVIRTUAL java/lang/Class#getDeclaredFields POP LDC (Integer) 1 ANEWARRAY java/lang/Class ASTORE 1 ALOAD 1 LDC (Integer) 0 ALOAD 0 AASTORE ALOAD 1 // Method descriptor: ([Ljava/lang/Class;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ALOAD 2 CHECKCAST [Ljava/lang/reflect/Executable; // Method descriptor: ([Ljava/lang/reflect/Executable;)V INVOKESTATIC org/graalvm/nativeimage/hosted/RuntimeReflection#register ** label3 GOTO label4 ** label5 POP ** label6 GOTO label4 // Try from label2 to label3 // Catch java/lang/Throwable by going to label5 ** label4 RETURN ** label7 }
localproxyservice/target/generated-sources/gizmo/io/quarkus/runner/AutoFeature.zig
const pokemon = @import("pokemon"); const search = @import("search.zig"); const std = @import("std"); const utils = @import("utils"); const constants = @import("gen3-constants.zig"); const fun = @import("../../lib/fun-with-zig/index.zig"); const os = std.os; const debug = std.debug; const mem = std.mem; const math = std.math; const io = std.io; const gen3 = pokemon.gen3; const common = pokemon.common; const lu16 = fun.platform.lu16; const lu32 = fun.platform.lu32; const lu64 = fun.platform.lu64; const Info = gen3.constants.Info; const TrainerSection = gen3.constants.TrainerSection; const MoveSection = gen3.constants.MoveSection; const MachineLearnsetSection = gen3.constants.MachineLearnsetSection; const BaseStatsSection = gen3.constants.BaseStatsSection; const EvolutionSection = gen3.constants.EvolutionSection; const LevelUpLearnsetPointerSection = gen3.constants.LevelUpLearnsetPointerSection; const HmSection = gen3.constants.HmSection; const TmSection = gen3.constants.TmSection; const ItemSection = gen3.constants.ItemSection; const WildPokemonHeaderSection = gen3.constants.WildPokemonHeaderSection; pub fn findInfoInFile(data: []const u8, version: pokemon.Version) !Info { const ignored_trainer_fields = [][]const u8{ "party", "name" }; const maybe_trainers = switch (version) { pokemon.Version.Emerald => search.findStructs( gen3.Trainer, ignored_trainer_fields, data, constants.em_first_trainers, constants.em_last_trainers, ), pokemon.Version.Ruby, pokemon.Version.Sapphire => search.findStructs( gen3.Trainer, ignored_trainer_fields, data, constants.rs_first_trainers, constants.rs_last_trainers, ), pokemon.Version.FireRed, pokemon.Version.LeafGreen => search.findStructs( gen3.Trainer, ignored_trainer_fields, data, constants.frls_first_trainers, constants.frls_last_trainers, ), else => null, }; const trainers = maybe_trainers orelse return error.UnableToFindTrainerOffset; const moves = search.findStructs( gen3.Move, [][]const u8{}, data, constants.first_moves, constants.last_moves, ) orelse { return error.UnableToFindMoveOffset; }; const machine_learnset = search.findStructs( lu64, [][]const u8{}, data, constants.first_machine_learnsets, constants.last_machine_learnsets, ) orelse { return error.UnableToFindTmHmLearnsetOffset; }; const ignored_base_stat_fields = [][]const u8{ "padding", "egg_group1_pad", "egg_group2_pad" }; const base_stats = search.findStructs( gen3.BasePokemon, ignored_base_stat_fields, data, constants.first_base_stats, constants.last_base_stats, ) orelse { return error.UnableToFindBaseStatsOffset; }; const evolution_table = search.findStructs( [5]common.Evolution, [][]const u8{"padding"}, data, constants.first_evolutions, constants.last_evolutions, ) orelse { return error.UnableToFindEvolutionTableOffset; }; const level_up_learnset_pointers = blk: { var first_pointers = []?u8{null} ** (constants.first_levelup_learnsets.len * 4); for (constants.first_levelup_learnsets) |maybe_learnset, i| { if (maybe_learnset) |learnset| { const p = mem.indexOf(u8, data, learnset) orelse return error.UnableToFindLevelUpLearnsetOffset; const l = lu32.init(@intCast(u32, p) + 0x8000000); for (first_pointers[i * 4 ..][0..4]) |*b, j| { b.* = l.bytes[j]; } } } var last_pointers = []?u8{null} ** (constants.last_levelup_learnsets.len * 4); for (constants.last_levelup_learnsets) |maybe_learnset, i| { if (maybe_learnset) |learnset| { const p = mem.indexOf(u8, data, learnset) orelse return error.UnableToFindLevelUpLearnsetOffset; const l = lu32.init(@intCast(u32, p) + 0x8000000); for (last_pointers[i * 4 ..][0..4]) |*b, j| { b.* = l.bytes[j]; } } } const pointers = search.findPattern(u8, data, first_pointers, last_pointers) orelse return error.UnableToFindLevelUpLearnsetOffset; break :blk @bytesToSlice(gen3.Ref(gen3.LevelUpMove), pointers); }; const hms_start = mem.indexOf(u8, data, constants.hms) orelse return error.UnableToFindHmOffset; const hms = @bytesToSlice(lu16, data[hms_start..][0..constants.hms.len]); // TODO: Pokémon Emerald have 2 tm tables. I'll figure out some hack for that // if it turns out that both tables are actually used. For now, I'll // assume that the first table is the only one used. const tms_start = mem.indexOf(u8, data, constants.tms) orelse return error.UnableToFindTmOffset; const tms = @bytesToSlice(lu16, data[tms_start..][0..constants.tms.len]); const ignored_item_fields = [][]const u8{ "name", "description", "field_use_func", "battle_use_func" }; const maybe_items = switch (version) { pokemon.Version.Emerald => search.findStructs( gen3.Item, ignored_item_fields, data, constants.em_first_items, constants.em_last_items, ), pokemon.Version.Ruby, pokemon.Version.Sapphire => search.findStructs( gen3.Item, ignored_item_fields, data, constants.rs_first_items, constants.rs_last_items, ), pokemon.Version.FireRed, pokemon.Version.LeafGreen => search.findStructs( gen3.Item, ignored_item_fields, data, constants.frlg_first_items, constants.frlg_last_items, ), else => null, }; const items = maybe_items orelse return error.UnableToFindItemsOffset; const ignored_wild_pokemon_header_fields = [][]const u8{ "pad", "land_pokemons", "surf_pokemons", "rock_smash_pokemons", "fishing_pokemons", }; const maybe_wild_pokemon_headers = switch (version) { pokemon.Version.Emerald => search.findStructs( gen3.WildPokemonHeader, ignored_wild_pokemon_header_fields, data, constants.em_first_wild_mon_headers, constants.em_last_wild_mon_headers, ), pokemon.Version.Ruby, pokemon.Version.Sapphire => search.findStructs( gen3.WildPokemonHeader, ignored_wild_pokemon_header_fields, data, constants.rs_first_wild_mon_headers, constants.rs_last_wild_mon_headers, ), pokemon.Version.FireRed, pokemon.Version.LeafGreen => search.findStructs( gen3.WildPokemonHeader, ignored_wild_pokemon_header_fields, data, constants.frlg_first_wild_mon_headers, constants.frlg_last_wild_mon_headers, ), else => null, }; const wild_pokemon_headers = maybe_wild_pokemon_headers orelse return error.UnableToFindWildPokemonHeaders; return Info{ .game_title = undefined, .gamecode = undefined, .version = version, .trainers = TrainerSection.init(data, trainers), .moves = MoveSection.init(data, moves), .machine_learnsets = MachineLearnsetSection.init(data, machine_learnset), .base_stats = BaseStatsSection.init(data, base_stats), .evolutions = EvolutionSection.init(data, evolution_table), .level_up_learnset_pointers = LevelUpLearnsetPointerSection.init(data, level_up_learnset_pointers), .hms = HmSection.init(data, hms), .tms = TmSection.init(data, tms), .items = ItemSection.init(data, items), .wild_pokemon_headers = WildPokemonHeaderSection.init(data, wild_pokemon_headers), }; }
tools/offset-finder/gen3.zig
const std = @import("../index.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; pub fn isInf(x: var) bool { const T = @typeOf(x); switch (T) { f16 => { const bits = @bitCast(u16, x); return bits & 0x7FFF == 0x7C00; }, f32 => { const bits = @bitCast(u32, x); return bits & 0x7FFFFFFF == 0x7F800000; }, f64 => { const bits = @bitCast(u64, x); return bits & (maxInt(u64) >> 1) == (0x7FF << 52); }, f128 => { const bits = @bitCast(u128, x); return bits & (maxInt(u128) >> 1) == (0x7FFF << 112); }, else => { @compileError("isInf not implemented for " ++ @typeName(T)); }, } } pub fn isPositiveInf(x: var) bool { const T = @typeOf(x); switch (T) { f16 => { return @bitCast(u16, x) == 0x7C00; }, f32 => { return @bitCast(u32, x) == 0x7F800000; }, f64 => { return @bitCast(u64, x) == 0x7FF << 52; }, f128 => { return @bitCast(u128, x) == 0x7FFF << 112; }, else => { @compileError("isPositiveInf not implemented for " ++ @typeName(T)); }, } } pub fn isNegativeInf(x: var) bool { const T = @typeOf(x); switch (T) { f16 => { return @bitCast(u16, x) == 0xFC00; }, f32 => { return @bitCast(u32, x) == 0xFF800000; }, f64 => { return @bitCast(u64, x) == 0xFFF << 52; }, f128 => { return @bitCast(u128, x) == 0xFFFF << 112; }, else => { @compileError("isNegativeInf not implemented for " ++ @typeName(T)); }, } } test "math.isInf" { expect(!isInf(f16(0.0))); expect(!isInf(f16(-0.0))); expect(!isInf(f32(0.0))); expect(!isInf(f32(-0.0))); expect(!isInf(f64(0.0))); expect(!isInf(f64(-0.0))); expect(!isInf(f128(0.0))); expect(!isInf(f128(-0.0))); expect(isInf(math.inf(f16))); expect(isInf(-math.inf(f16))); expect(isInf(math.inf(f32))); expect(isInf(-math.inf(f32))); expect(isInf(math.inf(f64))); expect(isInf(-math.inf(f64))); expect(isInf(math.inf(f128))); expect(isInf(-math.inf(f128))); } test "math.isPositiveInf" { expect(!isPositiveInf(f16(0.0))); expect(!isPositiveInf(f16(-0.0))); expect(!isPositiveInf(f32(0.0))); expect(!isPositiveInf(f32(-0.0))); expect(!isPositiveInf(f64(0.0))); expect(!isPositiveInf(f64(-0.0))); expect(!isPositiveInf(f128(0.0))); expect(!isPositiveInf(f128(-0.0))); expect(isPositiveInf(math.inf(f16))); expect(!isPositiveInf(-math.inf(f16))); expect(isPositiveInf(math.inf(f32))); expect(!isPositiveInf(-math.inf(f32))); expect(isPositiveInf(math.inf(f64))); expect(!isPositiveInf(-math.inf(f64))); expect(isPositiveInf(math.inf(f128))); expect(!isPositiveInf(-math.inf(f128))); } test "math.isNegativeInf" { expect(!isNegativeInf(f16(0.0))); expect(!isNegativeInf(f16(-0.0))); expect(!isNegativeInf(f32(0.0))); expect(!isNegativeInf(f32(-0.0))); expect(!isNegativeInf(f64(0.0))); expect(!isNegativeInf(f64(-0.0))); expect(!isNegativeInf(f128(0.0))); expect(!isNegativeInf(f128(-0.0))); expect(!isNegativeInf(math.inf(f16))); expect(isNegativeInf(-math.inf(f16))); expect(!isNegativeInf(math.inf(f32))); expect(isNegativeInf(-math.inf(f32))); expect(!isNegativeInf(math.inf(f64))); expect(isNegativeInf(-math.inf(f64))); expect(!isNegativeInf(math.inf(f128))); expect(isNegativeInf(-math.inf(f128))); }
std/math/isinf.zig
const midi = @import("../midi.zig"); const std = @import("std"); const mem = std.mem; pub const Header = struct { chunk: Chunk, format: u16, tracks: u16, division: u16, pub const size = 6; }; pub const Chunk = struct { kind: [4]u8, len: u32, pub const file_header = "MThd"; pub const track_header = "MTrk"; }; pub const MetaEvent = struct { kind_byte: u8, len: u28, pub fn kind(event: MetaEvent) Kind { return switch (event.kind_byte) { 0x00 => .SequenceNumber, 0x01 => .TextEvent, 0x02 => .CopyrightNotice, 0x03 => .TrackName, 0x04 => .InstrumentName, 0x05 => .Luric, 0x06 => .Marker, 0x20 => .MidiChannelPrefix, 0x2F => .EndOfTrack, 0x51 => .SetTempo, 0x54 => .SmpteOffset, 0x58 => .TimeSignature, 0x59 => .KeySignature, 0x7F => .SequencerSpecificMetaEvent, else => .Undefined, }; } pub const Kind = enum { Undefined, SequenceNumber, TextEvent, CopyrightNotice, TrackName, InstrumentName, Luric, Marker, CuePoint, MidiChannelPrefix, EndOfTrack, SetTempo, SmpteOffset, TimeSignature, KeySignature, SequencerSpecificMetaEvent, }; }; pub const TrackEvent = struct { delta_time: u28, kind: Kind, pub const Kind = union(enum) { MidiEvent: midi.Message, MetaEvent: MetaEvent, }; }; pub const File = struct { format: u16, division: u16, header_data: []const u8 = &[_]u8{}, chunks: []const FileChunk = &[_]FileChunk{}, pub const FileChunk = struct { kind: [4]u8, bytes: []const u8, }; pub fn deinit(file: File, allocator: *mem.Allocator) void { for (file.chunks) |chunk| allocator.free(chunk.bytes); allocator.free(file.chunks); allocator.free(file.header_data); } }; pub const TrackIterator = struct { stream: io.FixedBufferStream([]const u8), last_event: ?TrackEvent = null, pub fn init(bytes: []const u8) TrackIterator { return .{ .stream = io.fixedBufferStream(bytes) }; } pub const Result = struct { event: TrackEvent, data: []const u8, }; pub fn next(it: *TrackIterator) ?Result { const s = it.stream.inStream(); var event = decode.trackEvent(s, it.last_event) catch return null; it.last_event = event; const start = it.stream.pos; switch (event.kind) { .MetaEvent => |meta_event| { it.stream.pos += meta_event.len; break :blk it.stream.pos; }, .MidiEvent => |midi_event| blk: { if (midi_event.kind() == .ExclusiveStart) { while ((try s.readByte()) != 0xF7) {} break :blk it.stream.pos - 1; } break :blk it.stream.pos; }, } return Result{ .event = event, .data = stream.buffer[start..end], }; } };
midi/file.zig
const Archive = @This(); const std = @import("std"); const assert = std.debug.assert; const elf = std.elf; const fs = std.fs; const log = std.log.scoped(.elf); const mem = std.mem; const Allocator = mem.Allocator; const Object = @import("Object.zig"); file: fs.File, name: []const u8, /// Parsed table of contents. /// Each symbol name points to a list of all definition /// sites within the current static archive. toc: std.StringArrayHashMapUnmanaged(std.ArrayListUnmanaged(u32)) = .{}, extnames_strtab: std.ArrayListUnmanaged(u8) = .{}, // Archive files start with the ARMAG identifying string. Then follows a // `struct ar_hdr', and as many bytes of member file data as its `ar_size' // member indicates, for each member file. /// String that begins an archive file. const ARMAG: *const [SARMAG:0]u8 = "!<arch>\n"; /// Size of that string. const SARMAG: u4 = 8; /// String in ar_fmag at the end of each header. const ARFMAG: *const [2:0]u8 = "`\n"; const SYM64NAME: *const [7:0]u8 = "/SYM64/"; const ar_hdr = extern struct { /// Member file name, sometimes / terminated. ar_name: [16]u8, /// File date, decimal seconds since Epoch. ar_date: [12]u8, /// User ID, in ASCII format. ar_uid: [6]u8, /// Group ID, in ASCII format. ar_gid: [6]u8, /// File mode, in ASCII octal. ar_mode: [8]u8, /// File size, in ASCII decimal. ar_size: [10]u8, /// Always contains ARFMAG. ar_fmag: [2]u8, fn date(self: ar_hdr) !u64 { const value = getValue(&self.ar_date); return std.fmt.parseInt(u64, value, 10); } fn size(self: ar_hdr) !u32 { const value = getValue(&self.ar_size); return std.fmt.parseInt(u32, value, 10); } fn getValue(raw: []const u8) []const u8 { return mem.trimRight(u8, raw, &[_]u8{@as(u8, 0x20)}); } fn read(reader: anytype) !ar_hdr { const header = try reader.readStruct(ar_hdr); if (!mem.eql(u8, &header.ar_fmag, ARFMAG)) { log.debug("invalid header delimiter: expected '{s}', found '{s}'", .{ ARFMAG, header.ar_fmag }); return error.NotArchive; } return header; } }; pub fn deinit(self: *Archive, allocator: Allocator) void { self.extnames_strtab.deinit(allocator); for (self.toc.keys()) |*key| { allocator.free(key.*); } for (self.toc.values()) |*value| { value.deinit(allocator); } self.toc.deinit(allocator); allocator.free(self.name); } pub fn parse(self: *Archive, allocator: Allocator) !void { const reader = self.file.reader(); const magic = try reader.readBytesNoEof(SARMAG); if (!mem.eql(u8, &magic, ARMAG)) { log.debug("invalid magic: expected '{s}', found '{s}'", .{ ARMAG, magic }); return error.NotArchive; } { // Parse lookup table const hdr = try ar_hdr.read(reader); const size = try hdr.size(); const ar_name = ar_hdr.getValue(&hdr.ar_name); if (!mem.eql(u8, ar_name, "/")) { log.err("expected symbol lookup table as first data section; instead found {s}", .{&hdr.ar_name}); return error.NoSymbolLookupTableInArchive; } var buffer = try allocator.alloc(u8, size); defer allocator.free(buffer); try reader.readNoEof(buffer); var inner_stream = std.io.fixedBufferStream(buffer); var inner_reader = inner_stream.reader(); const nsyms = try inner_reader.readIntBig(u32); var offsets = std.ArrayList(u32).init(allocator); defer offsets.deinit(); try offsets.ensureTotalCapacity(nsyms); var i: usize = 0; while (i < nsyms) : (i += 1) { const offset = try inner_reader.readIntBig(u32); offsets.appendAssumeCapacity(offset); } i = 0; var pos: usize = try inner_stream.getPos(); while (i < nsyms) : (i += 1) { const sym_name = mem.sliceTo(@ptrCast([*:0]const u8, buffer.ptr + pos), 0); const owned_name = try allocator.dupe(u8, sym_name); const res = try self.toc.getOrPut(allocator, owned_name); defer if (res.found_existing) allocator.free(owned_name); if (!res.found_existing) { res.value_ptr.* = .{}; } try res.value_ptr.append(allocator, offsets.items[i]); pos += sym_name.len + 1; } } blk: { // Try parsing extended names table const hdr = try ar_hdr.read(reader); const size = try hdr.size(); const name = ar_hdr.getValue(&hdr.ar_name); if (!mem.eql(u8, name, "//")) { break :blk; } var buffer = try allocator.alloc(u8, size); defer allocator.free(buffer); try reader.readNoEof(buffer); try self.extnames_strtab.appendSlice(allocator, buffer); } try reader.context.seekTo(0); } fn getExtName(self: Archive, off: u32) []const u8 { assert(off < self.extnames_strtab.items.len); return mem.sliceTo(@ptrCast([*:'\n']const u8, self.extnames_strtab.items.ptr + off), 0); } pub fn parseObject(self: Archive, allocator: Allocator, target: std.Target, offset: u32) !Object { const reader = self.file.reader(); try reader.context.seekTo(offset); const hdr = try ar_hdr.read(reader); const name = blk: { const name = ar_hdr.getValue(&hdr.ar_name); if (name[0] == '/') { const off = try std.fmt.parseInt(u32, name[1..], 10); break :blk self.getExtName(off); } break :blk name; }; const object_name = name[0 .. name.len - 1]; // to account for trailing '/' log.debug("extracting object '{s}' from archive '{s}'", .{ object_name, self.name }); const full_name = blk: { var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; const path = try std.os.realpath(self.name, &buffer); break :blk try std.fmt.allocPrint(allocator, "{s}({s})", .{ path, object_name }); }; var object = Object{ .file = try fs.cwd().openFile(self.name, .{}), .name = full_name, .file_offset = @intCast(u32, try reader.context.getPos()), }; try object.parse(allocator, target); try reader.context.seekTo(0); return object; }
src/Elf/Archive.zig
const expect = std.testing.expect; const std = @import("std"); const Allocator = std.mem.Allocator; const FixedHeader = @import("../packet.zig").Packet.FixedHeader; pub const ReturnCode = enum(u8) { ok = 0, unacceptable_protocol_version, invalid_client_id, server_unavailable, malformed_credentials, unauthorized, }; pub const ConnAck = struct { session_present: bool, return_code: ReturnCode, const Flags = packed struct { session_present: bool, _reserved: u7 = 0, }; pub fn parse(fixed_header: FixedHeader, allocator: *Allocator, inner_reader: anytype) !ConnAck { const reader = std.io.limitedReader(inner_reader, fixed_header.remaining_length).reader(); const flags_byte = try reader.readByte(); const flags = @bitCast(Flags, flags_byte); const session_present = flags.session_present; const return_code_byte = try reader.readByte(); const return_code = @intToEnum(ReturnCode, return_code_byte); return ConnAck{ .session_present = session_present, .return_code = return_code, }; } pub fn serialize(self: ConnAck, writer: anytype) !void { const flags = Flags{ .session_present = self.session_present, }; const flags_byte = @bitCast(u8, flags); try writer.writeByte(flags_byte); const return_code_byte = @enumToInt(self.return_code); try writer.writeByte(return_code_byte); } pub fn serializedLength(self: ConnAck) u32 { // Fixed return comptime @sizeOf(Flags) + @sizeOf(ReturnCode); } pub fn fixedHeaderFlags(self: ConnAck) u4 { return 0b0000; } pub fn deinit(self: *ConnAck, allocator: *Allocator) void {} }; test "ConnAck payload parsing" { const allocator = std.testing.allocator; const buffer = // Session present flag to true "\x01" ++ // ok return code "\x00"; const stream = std.io.fixedBufferStream(buffer).reader(); const PacketType = @import("../packet.zig").PacketType; const fixed_header = FixedHeader{ .packet_type = PacketType.connack, .flags = 0, .remaining_length = @intCast(u32, buffer.len), }; var connack = try ConnAck.parse(fixed_header, allocator, stream); defer connack.deinit(allocator); try expect(connack.session_present == true); try expect(connack.return_code == ReturnCode.ok); } test "ConnAck serialized length" { const Flags = ConnAck.Flags; const connack = ConnAck{ .session_present = true, .return_code = ReturnCode.ok, }; try expect(connack.serializedLength() == 2); } test "serialize/parse roundtrip" { const connack = ConnAck{ .session_present = true, .return_code = ReturnCode.unauthorized, }; var buffer = [_]u8{0} ** 100; var stream = std.io.fixedBufferStream(&buffer); var writer = stream.writer(); try connack.serialize(writer); const written = try stream.getPos(); stream.reset(); const reader = stream.reader(); const PacketType = @import("../packet.zig").PacketType; const fixed_header = FixedHeader{ .packet_type = PacketType.connack, .flags = 0, .remaining_length = @intCast(u32, written), }; const allocator = std.testing.allocator; var deser_connack = try ConnAck.parse(fixed_header, allocator, reader); defer deser_connack.deinit(allocator); try expect(connack.session_present == deser_connack.session_present); try expect(connack.return_code == deser_connack.return_code); }
src/mqtt4/packet/connack.zig
const graphics = @import("didot-graphics"); const objects = @import("didot-objects"); const glfw = @import("glfw"); const gl = @import("gl"); const std = @import("std"); const single_threaded = @import("builtin").single_threaded; const Allocator = std.mem.Allocator; const Window = graphics.Window; pub const Scene = objects.Scene; const System = struct { function: anytype, type: type, }; pub const Systems = struct { items: []const System = &[0]System {}, pub fn addSystem(comptime self: *Systems, system: anytype) void { const T = @TypeOf(system); const arr = [1]System { .{ .type = T, .function = system } }; self.items = self.items ++ arr; } }; pub fn log( comptime message_level: std.log.Level, comptime scope: @Type(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { if (@enumToInt(message_level) <= @enumToInt(std.log.level)) { const level_txt = switch (message_level) { .emerg => "emergency", .alert => "alert", .crit => "critical", .err => "error", .warn => "warning", .notice => "notice", .info => "info", .debug => "debug", }; const prefix2 = if (scope == .default) " -> " else " (" ++ @tagName(scope) ++ ") -> "; if (@import("builtin").cpu.arch == .wasm64) { // TODO } else { const stderr = std.io.getStdErr().writer(); std.debug.getStderrMutex().lock(); defer std.debug.getStderrMutex().unlock(); nosuspend stderr.print("[" ++ level_txt ++ "]" ++ prefix2 ++ format ++ "\n", args) catch return; } } } const SystemList = std.ArrayList(usize); pub fn checkGlError(tag: i32) void { const err = gl.glGetError(); if (err != gl.GL_NO_ERROR) { std.log.scoped(.didot).err("GL error {} at {}", .{err, tag}); } else { std.log.scoped(.didot).err("GL ok at {}", .{tag}); } } /// Helper class for using Didot. pub fn Application(comptime systems: Systems) type { const App = struct { const Self = @This(); /// How many time per second updates should be called, defaults to 60 updates/s. updateTarget: u32 = 60, window: Window = undefined, /// The current scene, this is set by init() and start(). /// It can also be set manually to change scene in-game. scene: *Scene = undefined, title: [:0]const u8 = "Didot Game", allocator: Allocator = undefined, /// Optional function to be called on application init. initFn: ?fn(allocator: Allocator, app: *Self) callconv(if (std.io.is_async) .Async else .Unspecified) anyerror!void = null, closing: bool = false, timer: std.time.Timer = undefined, /// Initialize the application using the given allocator and scene. /// This creates a window, init primitives and call the init function if set. pub fn init(self: *Self, allocator: Allocator, scene: *Scene) !void { var window = try Window.create(); errdefer window.deinit(); window.setTitle(self.title); self.scene = scene; errdefer scene.deinit(); self.window = window; self.window.setMain(); self.allocator = allocator; self.timer = try std.time.Timer.start(); objects.initPrimitives(); try scene.assetManager.put("Mesh/Cube", .{ .objectPtr = @ptrToInt(&objects.PrimitiveCubeMesh), .unloadable = false, .objectType = .Mesh }); try scene.assetManager.put("Mesh/Plane", .{ .objectPtr = @ptrToInt(&objects.PrimitivePlaneMesh), .unloadable = false, .objectType = .Mesh }); if (self.initFn) |func| { if (std.io.is_async) { var stack = try allocator.alignedAlloc(u8, 16, @frameSize(func)); defer allocator.free(stack); var result: anyerror!void = undefined; try await @asyncCall(stack, &result, func, .{allocator, self}); } else { try func(allocator, self); } } } fn printErr(err: anyerror) void { std.log.err("{s}", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } } fn updateTick(self: *Self, comptime doSleep: bool) void { // var arena = std.heap.ArenaAllocator.init(self.allocator); // const allocator = &arena.allocator; // defer arena.deinit(); // std.debug.print("tick \n", .{}); const time_per_frame = (1 / @intToFloat(f64, self.updateTarget)) * std.time.ns_per_s; const time = self.timer.lap(); const dt = @floatCast(f32, time_per_frame / @intToFloat(f64, time)); _ = dt; inline for (systems.items) |sys| { const info = @typeInfo(sys.type).Fn; var tuple: std.meta.ArgsTuple(sys.type) = undefined; var skip: bool = false; comptime var isForEach: bool = false; comptime var forEachTypes: []const type = &[0]type {}; inline for (info.args) |arg, i| { const key = comptime std.fmt.comptimePrint("{}", .{i}); const Type = arg.arg_type.?; if (comptime std.mem.eql(u8, @typeName(Type), "SystemQuery")) { var query = Type { .scene = self.scene }; @field(tuple, key) = query; } else if (comptime std.meta.trait.isSingleItemPtr(Type)) { isForEach = true; forEachTypes = forEachTypes ++ &[_]type {Type}; } else { @compileError("Invalid argument type: " ++ @typeName(Type)); } } if (!skip) { const opts: std.builtin.CallOptions = .{}; if (isForEach) { const tupleTypes = [1]type {type} ** forEachTypes.len; const TupleType = std.meta.Tuple(&tupleTypes); comptime var queryTuple: TupleType = undefined; comptime { inline for (forEachTypes) |compType, i| { const name = std.fmt.comptimePrint("{}", .{i}); @field(queryTuple, name) = compType; } } var query = objects.Query(queryTuple) { .scene = self.scene }; var it = query.iterator(); while (it.next()) |o| { inline for (info.args) |arg, i| { if (comptime std.meta.trait.isSingleItemPtr(arg.arg_type.?)) { const key = comptime std.fmt.comptimePrint("{}", .{i}); const name = @typeName(std.meta.Child(arg.arg_type.?)); comptime var fieldName: [name.len]u8 = undefined; fieldName = name.*; fieldName[0] = comptime std.ascii.toLower(fieldName[0]); @field(tuple, key) = @field(o, &fieldName); } } try @call(opts, sys.function, tuple); } } else { try @call(opts, sys.function, tuple); } } } const updateLength = self.timer.read(); if (doSleep) { const wait = @floatToInt(u64, std.math.max(0, @floor( (1.0 / @intToFloat(f64, self.updateTarget)) * std.time.ns_per_s - @intToFloat(f64, updateLength))) ); std.time.sleep(wait); } } fn updateLoop(self: *Self) void { while (!self.closing) { self.updateTick(true); } } /// Start the game loop, that is doing rendering. /// It is also ensuring game updates and updating the window. pub fn loop(self: *Self) !void { var thread: std.Thread = undefined; if (!single_threaded) { if (std.io.is_async) { _ = async self.updateLoop(); } else { thread = try std.Thread.spawn(.{}, updateLoop, .{ self }); try thread.setName("Update-Thread"); } } while (self.window.update()) { if (single_threaded) { self.updateTick(false); } try self.scene.render(self.window); } self.closing = true; if (!single_threaded and !std.io.is_async) { thread.join(); // thread must be closed before scene is de-init (to avoid use-after-free) } self.closing = false; self.deinit(); } pub fn deinit(self: *Self) void { self.window.deinit(); self.scene.deinitAll(); } /// Helper method to call both init() and loop(). pub fn run(self: *Self, allocator: Allocator, scene: *Scene) !void { try self.init(allocator, scene); try self.loop(); } }; return App; } test "app" { comptime var systems = Systems {}; var app = Application(systems) {}; try app.init(std.testing.allocator, try Scene.create(std.testing.allocator, null)); app.window.setShouldClose(true); try app.loop(); }
didot-app/app.zig
const std = @import("std"); const DirectoryEntryMetadata = @import("DirectoryEntryMetadata.zig"); const PathComponents = @import("PathComponents.zig"); pub const DirectoryEntry = struct { path_components: PathComponents, metadata: DirectoryEntryMetadata, }; pub fn Iterator(comptime ReaderType: type) type { return struct { buffered_reader: std.io.BufferedReader(4096, ReaderType), skip_preload_data: bool = true, extension_len: usize = 0, path_len: usize = 0, extension_buf: [8]u8 = undefined, path_buf: [2048]u8 = undefined, filename_buf: [512]u8 = undefined, state: State = .extension, const Self = @This(); pub fn init(reader: ReaderType) Self { return .{ .buffered_reader = std.io.bufferedReader(reader), }; } const State = enum { /// Next string will be an extension extension, /// Next string will be a path path, /// Next string will be a filename filename, }; /// Memory such as file names referenced in this returned entry /// becomes invalid with subsequent calls to `next` pub fn next(self: *Self) !?DirectoryEntry { const reader = self.buffered_reader.reader(); var extension: ?[]const u8 = self.extension_buf[0..self.extension_len]; var path: ?[]const u8 = self.path_buf[0..self.path_len]; var filename: ?[]const u8 = undefined; loop: while (true) { switch (self.state) { .extension => { if (try reader.readUntilDelimiterOrEof(&self.extension_buf, 0)) |next_str| { if (next_str.len == 0) { // End of directory tree return null; } else { extension = next_str; self.extension_len = next_str.len; self.state = .path; } } else return null; }, .path => { if (try reader.readUntilDelimiterOrEof(&self.path_buf, 0)) |next_str| { if (next_str.len == 0) { self.state = .extension; } else { path = next_str; self.path_len = next_str.len; self.state = .filename; } } else return null; }, .filename => { if (try reader.readUntilDelimiterOrEof(&self.filename_buf, 0)) |next_str| { if (next_str.len == 0) { self.state = .path; } else { filename = next_str; break :loop; } } else return null; }, } } if (std.mem.eql(u8, extension.?, " ")) extension = null; if (std.mem.eql(u8, path.?, " ")) path = null; if (std.mem.eql(u8, filename.?, " ")) filename = null; const metadata = try DirectoryEntryMetadata.read(reader); if (self.skip_preload_data and metadata.preload_bytes > 0) { try reader.skipBytes(metadata.preload_bytes, .{}); } return DirectoryEntry{ .path_components = .{ .path = path, .filename = filename, .extension = extension, }, .metadata = metadata, }; } }; }
src/vpk/iterator.zig
const std = @import("std"); const expect = std.testing.expect; const cstd = @cImport({ @cInclude("stdlib.h"); }); pub fn envtpl(writer: anytype, line: []const u8) !void { var opening_brace_pos: ?usize = null; var closing_brace_pos: ?usize = null; for (line) |c, i| { switch (c) { '$' => blk: { opening_brace_pos = std.mem.indexOfPos(u8, line, i + 1, "{"); // offset by opening brace, closing brace, and at least one char closing_brace_pos = std.mem.indexOfPos(u8, line, i + 3, "}"); // If there aren't braces, it's just something that starts with $ if (opening_brace_pos == null or closing_brace_pos == null) { try writer.print("{c}", .{c}); break :blk; } const name = line[i + 2 .. closing_brace_pos.?]; const value = std.os.getenv(name); if (value) |v| { try writer.print("{s}", .{value}); } }, else => { // Only print the actual contents if we aren't inside a template string if (opening_brace_pos == null or closing_brace_pos == null or closing_brace_pos.? < i) { try writer.print("{c}", .{c}); } }, } } } test "envtpl with variables" { _ = cstd.setenv("ENVTPL_TEST_USER", "Matt", 1); defer _ = cstd.unsetenv("ENVTPL_TEST_USER"); _ = cstd.setenv("ENVTPL_TEST_HOME", "/users/matt", 1); defer _ = cstd.unsetenv("ENVTPL_TEST_HOME"); var list = std.ArrayList(u8).init(std.testing.allocator); defer list.deinit(); try envtpl(list.writer(), "Hello ${ENVTPL_TEST_USER}, you live at ${ENVTPL_TEST_HOME}!"); try expect(std.mem.eql(u8, "Hello Matt, you live at /users/matt!", list.items)); } test "envtpl without curly braces" { var list = std.ArrayList(u8).init(std.testing.allocator); defer list.deinit(); try envtpl(list.writer(), "Hello $USER!"); try expect(std.mem.eql(u8, "Hello $USER!", list.items)); } test "envtpl without opening curly brace" { var list = std.ArrayList(u8).init(std.testing.allocator); defer list.deinit(); try envtpl(list.writer(), "Hello $USER}!"); try expect(std.mem.eql(u8, "Hello $USER}!", list.items)); } test "envtpl without closing curly brace" { var list = std.ArrayList(u8).init(std.testing.allocator); defer list.deinit(); try envtpl(list.writer(), "Hello ${USER!"); try expect(std.mem.eql(u8, "Hello ${USER!", list.items)); } test "envtpl with empty braces" { var list = std.ArrayList(u8).init(std.testing.allocator); defer list.deinit(); try envtpl(list.writer(), "Hello ${}!"); try expect(std.mem.eql(u8, "Hello ${}!", list.items)); } test "envtpl with subsequent variables" { _ = cstd.setenv("ENVTPL_TEST_HOME_DIR", "/users/", 1); defer _ = cstd.unsetenv("ENVTPL_TEST_HOME_DIR"); _ = cstd.setenv("ENVTPL_TEST_USER", "matt", 1); defer _ = cstd.unsetenv("ENVTPL_TEST_USER"); var list = std.ArrayList(u8).init(std.testing.allocator); defer list.deinit(); try envtpl(list.writer(), "The home directory is ${ENVTPL_TEST_HOME_DIR}${ENVTPL_TEST_USER}"); try expect(std.mem.eql(u8, "The home directory is /users/matt", list.items)); } test "envtpl with unset var" { _ = cstd.unsetenv("ENVTPL_TEST_USER"); var list = std.ArrayList(u8).init(std.testing.allocator); defer list.deinit(); try envtpl(list.writer(), "Hello ${ENVTPL_TEST_USER}!"); try expect(std.mem.eql(u8, "Hello !", list.items)); }
src/envtpl.zig
const std = @import("std"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; const GeneralPurposeAllocator = std.heap.GeneralPurposeAllocator(.{}); const tb = @import("tigerbeetle/src/tigerbeetle.zig"); const StateMachine = @import("tigerbeetle/src/state_machine.zig").StateMachine; const Operation = StateMachine.Operation; const MessageBus = @import("tigerbeetle/src/message_bus.zig").MessageBusClient; const Message = @import("tigerbeetle/src/message_pool.zig").MessagePool.Message; const IO = @import("tigerbeetle/src/io.zig").IO; const config = @import("tigerbeetle/src/config.zig"); const vsr = @import("tigerbeetle/src/vsr.zig"); const Header = vsr.Header; const Client = vsr.Client(StateMachine, MessageBus); const NativeCallback = fn ( operation: u8, results: [*c]const u8, size: usize, ) callconv(.C) void; pub const log_level: std.log.Level = .err; const Results = struct { pub const SUCCESS = 0; pub const ALREADY_INITIALIZED = 1; pub const IO_URING_FAILED = 2; pub const INVALID_ADDRESS = 3; pub const ADDRESS_LIMIT_EXCEEDED = 4; pub const INVALID_HANDLE = 5; pub const MESSAGE_POOL_EXHAUSTED = 6; pub const TICK_FAILED = 8; pub const OUT_OF_MEMORY = 9; }; const Context = struct { client: Client, io: *IO, message_bus: MessageBus, addresses: []std.net.Address, fn create( client_id: u128, cluster: u32, addresses_raw: []const u8, ) !*Context { const context = try allocator.create(Context); errdefer allocator.destroy(context); context.io = &io; context.addresses = try vsr.parse_addresses(allocator, addresses_raw); errdefer allocator.free(context.addresses); assert(context.addresses.len > 0); context.message_bus = try MessageBus.init( allocator, cluster, context.addresses, client_id, context.io, ); errdefer context.message_bus.deinit(); context.client = try Client.init( allocator, client_id, cluster, @intCast(u8, context.addresses.len), &context.message_bus, ); errdefer context.client.deinit(); context.message_bus.set_on_message(*Client, &context.client, Client.on_message); return context; } fn destroy(context: *Context) void { context.client.deinit(); context.message_bus.deinit(); allocator.free(context.addresses); allocator.destroy(context); } }; // Globals var gp: GeneralPurposeAllocator = undefined; var allocator: *Allocator = undefined; var io: IO = undefined; var initialized: bool = false; // C-ABI exports pub export fn TB_Init() callconv(.C) u32 { if (initialized) { return Results.ALREADY_INITIALIZED; } gp = GeneralPurposeAllocator{}; errdefer _ = gp.deinit(); allocator = &gp.allocator; io = IO.init(32, 0) catch { return Results.IO_URING_FAILED; }; errdefer io.deinit(); initialized = true; return Results.SUCCESS; } pub export fn TB_Deinit() callconv(.C) u32 { io.deinit(); _ = gp.deinit(); gp = undefined; allocator = undefined; io = undefined; initialized = false; return Results.SUCCESS; } pub export fn TB_CreateClient(client_id: u128, cluster: u32, addresses_raw: [*c]u8, handle: *usize) callconv(.C) u32 { var context = Context.create(client_id, cluster, std.mem.spanZ(addresses_raw)) catch |err| switch (err) { error.AddressInvalid, error.PortInvalid, error.PortOverflow, error.AddressHasTrailingComma, error.AddressHasMoreThanOneColon => return Results.INVALID_ADDRESS, error.AddressLimitExceeded => return Results.ADDRESS_LIMIT_EXCEEDED, error.OutOfMemory => return Results.OUT_OF_MEMORY, }; handle.* = @ptrToInt(context); return Results.SUCCESS; } pub export fn TB_DestroyClient(handle: usize) callconv(.C) u32 { if (handle == 0) return Results.INVALID_HANDLE; const context = @intToPtr(*Context, handle); context.destroy(); return Results.SUCCESS; } pub export fn TB_GetMessage(handle: usize, message_handle: *usize, body_buffer: *usize, body_buffer_len: *usize) callconv(.C) u32 { if (handle == 0) return Results.INVALID_HANDLE; const context = @intToPtr(*Context, handle); var message = context.client.get_message() orelse { return Results.MESSAGE_POOL_EXHAUSTED; }; var buffer = message.buffer[@sizeOf(Header)..]; message_handle.* = @ptrToInt(message); body_buffer.* = @ptrToInt(buffer.ptr); body_buffer_len.* = buffer.len; return Results.SUCCESS; } pub export fn TB_UnrefMessage(handle: usize, message_handle: usize) callconv(.C) u32 { if (handle == 0) return Results.INVALID_HANDLE; const context = @intToPtr(*Context, handle); if (message_handle == 0) return Results.INVALID_HANDLE; const message = @intToPtr(*Message, message_handle); context.client.unref(message); return Results.SUCCESS; } pub export fn TB_Request(handle: usize, operation: u8, message_handle: usize, message_body_size: usize, callback_ptr: NativeCallback) callconv(.C) u32 { if (handle == 0) return Results.INVALID_HANDLE; const context = @intToPtr(*Context, handle); if (message_handle == 0) return Results.INVALID_HANDLE; const message = @intToPtr(*Message, message_handle); defer context.client.unref(message); const user_data = std.meta.cast(u128, @ptrToInt(callback_ptr)); context.client.request(user_data, on_callback, @intToEnum(StateMachine.Operation, operation), message, message_body_size); return Results.SUCCESS; } pub export fn TB_Tick(handle: usize) callconv(.C) u32 { if (handle == 0) return Results.INVALID_HANDLE; const context = @intToPtr(*Context, handle); context.client.tick(); context.io.tick() catch return Results.TICK_FAILED; return Results.SUCCESS; } pub export fn TB_RunFor(handle: usize, ms: u32) callconv(.C) u32 { if (handle == 0) return Results.INVALID_HANDLE; const context = @intToPtr(*Context, handle); context.io.run_for_ns(ms * std.time.ns_per_ms) catch return Results.TICK_FAILED; return Results.SUCCESS; } fn on_callback(user_data: u128, operation: StateMachine.Operation, results: anyerror![]const u8) void { var callback = @intToPtr(NativeCallback, std.meta.cast(usize, user_data)); var data = results catch return; callback(@enumToInt(operation), data.ptr, data.len); }
src/libtigerbeetle/src/lib.zig
const c = @import("c.zig"); const utils = @import("utils.zig"); const std = @import("std"); usingnamespace @import("log.zig"); // DEF /// Buffer bits pub const BufferBit = enum { depth, stencil, colour }; /// Buffer types pub const BufferType = enum { array, elementarray }; /// Draw types pub const DrawType = enum { static, dynamic, stream }; /// Draw modes pub const DrawMode = enum { points = 0x0000, lines = 0x0001, lineloop = 0x0002, linestrip = 0x0003, triangles = 0x0004, trianglestrip = 0x0005, trianglefan = 0x0006, }; /// Shader types pub const ShaderType = enum { vertex, fragment, geometry }; /// Texture types pub const TextureType = enum { t2D, }; // zig fmt: off /// Texture formats pub const TextureFormat = enum { rgb, rgb8, rgb32f, rgba, rgba8, rgba32f, red, alpha }; // zig fmt: on /// Texture paramater types pub const TextureParamaterType = enum { min_filter, mag_filter, wrap_s, wrap_t, wrap_r, }; /// Texture paramater pub const TextureParamater = enum { filter_linear, filter_nearest, wrap_repeat, wrap_mirrored_repeat, wrap_clamp_to_edge, wrap_clamp_to_border, }; // ENDDEF // COMMON /// Initializes OpenGL(GLAD) pub fn init() void { _ = c.gladLoaderLoadGL(); } /// Deinitializes OpenGL(GLAD) pub fn deinit() void { c.gladLoaderUnloadGL(); } /// Specifies the red, green, blue, and alpha values used by clearBuffers to clear the colour buffers. /// Values are clamped to the range [0,1]. pub fn clearColour(r: f32, g: f32, b: f32, a: f32) void { c.glClearColor(r, g, b, a); } /// Clear buffers to preset values pub fn clearBuffers(comptime bit: BufferBit) void { c.glClear(pdecideBufferBit(bit)); } /// Set the viewport pub fn viewport(x: i32, y: i32, w: i32, h: i32) void { c.glViewport(x, y, w, h); } /// Set the ortho pub fn ortho(l: f32, r: f32, b: f32, t: f32, nr: f32, fr: f32) void { c.glOrtho(l, r, b, t, nr, fr); } /// Render primitives from array data pub fn drawArrays(mode: DrawMode, first: i32, count: i32) void { c.glDrawArrays(@enumToInt(mode), first, count); } /// Render primitives from array data pub fn drawElements(mode: DrawMode, size: i32, comptime typ: type, indices: ?*const c_void) void { const t = comptime pdecideGLTYPE(typ); c.glDrawElements(@enumToInt(mode), size, t, indices); } /// Enables/Disables the blending pub fn setBlending(status: bool) void { if (status) { c.glEnable(c.GL_BLEND); c.glBlendFunc(c.GL_SRC_ALPHA, c.GL_ONE_MINUS_SRC_ALPHA); } else c.glDisable(c.GL_BLEND); } // ENDCOMMON // BUFFERS /// Generate vertex array object names pub fn vertexArraysGen(n: i32, arrays: [*]u32) void { c.glGenVertexArrays(n, arrays); } /// Delete vertex array objects pub fn vertexArraysDelete(n: i32, arrays: [*]const u32) void { c.glDeleteVertexArrays(n, arrays); } /// Generate buffer object names pub fn buffersGen(n: i32, arrays: [*]u32) void { c.glGenBuffers(n, arrays); } /// Delete named buffer objects pub fn buffersDelete(n: i32, arrays: [*]const u32) void { c.glDeleteBuffers(n, arrays); } /// Bind a vertex array object pub fn vertexArrayBind(array: u32) void { c.glBindVertexArray(array); } /// Bind a named buffer object pub fn bufferBind(comptime target: BufferType, buffer: u32) void { c.glBindBuffer(pdecideBufferType(target), buffer); } /// Creates and initializes a buffer object's data store pub fn bufferData(comptime target: BufferType, size: u32, data: ?*const c_void, comptime usage: DrawType) void { c.glBufferData(pdecideBufferType(target), size, data, pdecideDrawType(usage)); } /// Updates a subset of a buffer object's data store pub fn bufferSubData(comptime target: BufferType, offset: i32, size: u32, data: ?*const c_void) void { c.glBufferSubData(pdecideBufferType(target), offset, size, data); } // ENDBUFFERS // SHADER /// Creates a shader pub fn shaderCreateBasic(comptime typ: ShaderType) u32 { return c.glCreateShader(pdecideShaderType(typ)); } /// Deletes the shader pub fn shaderDelete(sh: u32) void { c.glDeleteShader(sh); } /// Compiles the shader source with given shader type pub fn shaderCompile(alloc: *std.mem.Allocator, source: []const u8, comptime typ: ShaderType) !u32 { var result: u32 = shaderCreateBasic(typ); c.glShaderSource(result, 1, @ptrCast([*]const [*]const u8, &source), null); c.glCompileShader(result); var fuck: i32 = 0; c.glGetShaderiv(result, c.GL_COMPILE_STATUS, &fuck); if (fuck == 0) { var len: i32 = 0; c.glGetShaderiv(result, c.GL_INFO_LOG_LENGTH, &len); var msg = try alloc.alloc(u8, @intCast(usize, len)); c.glGetShaderInfoLog(result, len, &len, @ptrCast([*c]u8, msg)); std.log.alert("{}: {}", .{ source, msg }); shaderDelete(result); alloc.free(msg); try utils.check(true, "kira/gl -> unable to compile shader!", .{}); } return result; } /// Creates a program object pub fn shaderProgramCreateBasic() u32 { return c.glCreateProgram(); } /// Creates a program object from vertex and fragment source pub fn shaderProgramCreate(alloc: *std.mem.Allocator, vertex: []const u8, fragment: []const u8) !u32 { const vx = try shaderCompile(alloc, vertex, ShaderType.vertex); const fg = try shaderCompile(alloc, fragment, ShaderType.fragment); defer { shaderDelete(vx); shaderDelete(fg); } const result = shaderProgramCreateBasic(); shaderAttach(result, vx); shaderAttach(result, fg); shaderProgramLink(result); shaderProgramValidate(result); return result; } /// Deletes a program object pub fn shaderProgramDelete(pr: u32) void { c.glDeleteProgram(pr); } /// Installs a program object as part of current rendering state pub fn shaderProgramUse(pr: u32) void { c.glUseProgram(pr); } /// Attaches a shader object to a program object pub fn shaderAttach(pr: u32, sh: u32) void { c.glAttachShader(pr, sh); } /// Links a program object pub fn shaderProgramLink(pr: u32) void { c.glLinkProgram(pr); } /// Validates a program object pub fn shaderProgramValidate(pr: u32) void { c.glValidateProgram(pr); } /// Get uniform location from shader object pub fn shaderProgramGetUniformLocation(sh: u32, name: []const u8) i32 { return c.glGetUniformLocation(sh, @ptrCast([*c]const u8, name)); } /// Sets the int data pub fn shaderProgramSetInt(loc: i32, value: i32) void { c.glUniform1i(loc, value); } /// Sets the float data pub fn shaderProgramSetFloat(loc: i32, value: f32) void { c.glUniform1f(loc, value); } /// Sets the vec2 data pub fn shaderProgramSetVec2f(loc: i32, value: [*]const f32) void { c.glUniform2fv(loc, 1, value); } /// Sets the vec3 data pub fn shaderProgramSetVec3f(loc: i32, value: [*]const f32) void { c.glUniform3fv(loc, 1, value); } /// Sets the matrix data pub fn shaderProgramSetMat4x4f(loc: i32, data: [*]const f32) void { c.glUniformMatrix4fv(loc, 1, c.GL_FALSE, data); } /// Enable or disable a generic vertex attribute array pub fn shaderProgramSetVertexAttribArray(index: u32, status: bool) void { if (status) { c.glEnableVertexAttribArray(index); } else { c.glDisableVertexAttribArray(index); } } /// Define an array of generic vertex attribute data pub fn shaderProgramSetVertexAttribPointer(index: u32, size: i32, comptime typ: type, normalize: bool, stride: i32, ptr: ?*const c_void) void { const t = comptime pdecideGLTYPE(typ); c.glVertexAttribPointer(index, size, t, if (normalize) c.GL_TRUE else c.GL_FALSE, stride, ptr); } // ENDSHADER // TEXTURE /// Generate texture names pub fn texturesGen(count: i32, textures: [*]u32) void { c.glGenTextures(count, textures); } /// Delete named textures pub fn texturesDelete(count: i32, textures: [*]const u32) void { c.glDeleteTextures(count, textures); } /// Generate mipmaps for a specified texture target pub fn texturesGenMipmap(comptime target: TextureType) void { c.glGenMipmap(pdecideTextureType(target)); } /// Bind a named texture to a texturing target pub fn textureBind(comptime target: TextureType, texture: u32) void { c.glBindTexture(pdecideTextureType(target), texture); } /// Specify a two-dimensional texture image pub fn textureTexImage2D(comptime target: TextureType, level: i32, comptime internalformat: TextureFormat, width: i32, height: i32, border: i32, comptime format: TextureFormat, comptime typ: type, data: ?*c_void) void { c.glTexImage2D(pdecideTextureType(target), level, @intCast(i32, pdecideTextureFormat(internalformat)), width, height, border, pdecideTextureFormat(format), pdecideGLTYPE(typ), data); } /// Set texture parameters pub fn textureTexParameteri(comptime target: TextureType, comptime pname: TextureParamaterType, comptime param: TextureParamater) void { c.glTexParameteri(pdecideTextureType(target), pdecideTextureParamType(pname), pdecideTextureParam(param)); } // ENDTEXTURE // PRIVATE /// Decides the buffer bit type from given BufferBit fn pdecideBufferBit(comptime typ: BufferBit) u32 { switch (typ) { BufferBit.depth => return c.GL_DEPTH_BUFFER_BIT, BufferBit.stencil => return c.GL_STENCIL_BUFFER_BIT, BufferBit.colour => return c.GL_COLOR_BUFFER_BIT, } } /// Decides the buffer type from given BufferType fn pdecideBufferType(comptime typ: BufferType) u32 { switch (typ) { BufferType.array => return c.GL_ARRAY_BUFFER, BufferType.elementarray => return c.GL_ELEMENT_ARRAY_BUFFER, } } /// Decides the draw type from given DrawType fn pdecideDrawType(comptime typ: DrawType) u32 { switch (typ) { DrawType.static => return c.GL_STATIC_DRAW, DrawType.dynamic => return c.GL_DYNAMIC_DRAW, DrawType.stream => return c.GL_STREAM_DRAW, } } /// Decides the Shader type from given ShaderType fn pdecideShaderType(comptime typ: ShaderType) u32 { switch (typ) { ShaderType.vertex => return c.GL_VERTEX_SHADER, ShaderType.fragment => return c.GL_FRAGMENT_SHADER, ShaderType.geometry => return c.GL_GEOMETRY_SHADER, } } /// Decides the Texture type from given TextureType fn pdecideTextureType(comptime typ: TextureType) u32 { switch (typ) { TextureType.t2D => return c.GL_TEXTURE_2D, } } /// Decides the Texture format from given TextureFormat fn pdecideTextureFormat(comptime typ: TextureFormat) u32 { switch (typ) { TextureFormat.rgb => return c.GL_RGB, TextureFormat.rgb8 => return c.GL_RGB8, TextureFormat.rgb32f => return c.GL_RGB32F, TextureFormat.rgba => return c.GL_RGBA, TextureFormat.rgba8 => return c.GL_RGBA8, TextureFormat.rgba32f => return c.GL_RGBA32F, TextureFormat.red => return c.GL_RED, TextureFormat.alpha => return c.GL_ALPHA, } } /// Decides the Texture parameter type from given TextureParamaterType fn pdecideTextureParamType(comptime typ: TextureParamaterType) u32 { switch (typ) { TextureParamaterType.min_filter => return c.GL_TEXTURE_MIN_FILTER, TextureParamaterType.mag_filter => return c.GL_TEXTURE_MAG_FILTER, TextureParamaterType.wrap_s => return c.GL_TEXTURE_WRAP_S, TextureParamaterType.wrap_t => return c.GL_TEXTURE_WRAP_T, TextureParamaterType.wrap_r => return c.GL_TEXTURE_WRAP_R, } } /// Decides the Texture parameter from given TextureParamater fn pdecideTextureParam(comptime typ: TextureParamater) i32 { switch (typ) { TextureParamater.filter_linear => return c.GL_LINEAR, TextureParamater.filter_nearest => return c.GL_NEAREST, TextureParamater.wrap_repeat => return c.GL_REPEAT, TextureParamater.wrap_mirrored_repeat => return c.GL_MIRRORED_REPEAT, TextureParamater.wrap_clamp_to_edge => return c.GL_CLAMP_TO_EDGE, TextureParamater.wrap_clamp_to_border => return c.GL_CLAMP_TO_BORDER, } } /// Decides the GL_TYPE from given zig type fn pdecideGLTYPE(comptime typ: type) u32 { switch (typ) { u8 => return c.GL_UNSIGNED_BYTE, u32 => return c.GL_UNSIGNED_INT, i32 => return c.GL_INT, f32 => return c.GL_FLOAT, else => @compileError("Unknown gl type"), } } // ENDPRIVATE
src/kiragine/kira/gl.zig
const std = @import("std"); const print = std.debug.print; pub const Case = enum { lower, upper }; fn isUtf8ControlCode(c: []const u8) bool { return c.len == 2 and c[0] == '\xC2' and c[1] >= '\x80' and c[1] <= '\x9F'; } /// Like std.unicode.Utf8Iterator, but handles invalid UTF-8 without panicing pub const InvalidUtf8Iterator = struct { bytes: []const u8, i: usize, /// On invalid UTF-8, returns an error pub fn nextCodepointSlice(it: *InvalidUtf8Iterator) !?[]const u8 { if (it.i >= it.bytes.len) { return null; } const cp_len = try std.unicode.utf8ByteSequenceLength(it.bytes[it.i]); it.i += cp_len; return it.bytes[it.i - cp_len .. it.i]; } }; /// Copied from std/fmt.zig but works so that UTF8 still gets printed as a string /// Useful for avoiding things like printing the Operating System Command (0x9D) control character /// which can really break terminal printing /// Also allows invalid UTF-8 to be printed (the invalid bytes will likely be escaped). fn FormatUtf8SliceEscape(comptime case: Case) type { const charset = "0123456789" ++ if (case == .upper) "ABCDEF" else "abcdef"; return struct { pub fn f( bytes: []const u8, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = fmt; _ = options; var buf: [4]u8 = undefined; buf[0] = '\\'; buf[1] = 'x'; var it = InvalidUtf8Iterator{ .bytes = bytes, .i = 0 }; while (it.nextCodepointSlice() catch c: { // On invalid UTF-8, treat the first byte as the 'codepoint slice' // and then move past that char. // This should always write an escaped character within the loop. it.i += 1; break :c it.bytes[it.i - 1 .. it.i]; }) |c| { if (c.len == 1) { if (std.ascii.isPrint(c[0])) { try writer.writeByte(c[0]); } else { buf[2] = charset[c[0] >> 4]; buf[3] = charset[c[0] & 15]; try writer.writeAll(&buf); } } else { if (!isUtf8ControlCode(c)) { try writer.writeAll(c); } else { buf[2] = charset[c[1] >> 4]; buf[3] = charset[c[1] & 15]; try writer.writeAll(&buf); } } } } }; } const formatUtf8SliceEscapeLower = FormatUtf8SliceEscape(.lower).f; const formatUtf8SliceEscapeUpper = FormatUtf8SliceEscape(.upper).f; /// Return a Formatter for a []const u8 where every C0 and C1 control /// character is escaped as \xNN, where NN is the character in lowercase /// hexadecimal notation. pub fn fmtUtf8SliceEscapeLower(bytes: []const u8) std.fmt.Formatter(formatUtf8SliceEscapeLower) { return .{ .data = bytes }; } /// Return a Formatter for a []const u8 where every C0 and C1 control /// character is escaped as \xNN, where NN is the character in uppercase /// hexadecimal notation. pub fn fmtUtf8SliceEscapeUpper(bytes: []const u8) std.fmt.Formatter(formatUtf8SliceEscapeUpper) { return .{ .data = bytes }; }
src/util.zig
const std = @import("std"); var a: *std.mem.Allocator = undefined; const stdout = std.io.getStdOut().writer(); //prepare stdout to write in //const LENGTH = 5; // testing const LENGTH = 12; // prod //const MAJORITY_THRESHOLD = 6; // testing const MAJORITY_THRESHOLD = 500; // prod fn run(input: [:0]u8) u32 { // Store the current bit position we're comparing comptime var bit_pos: u8 = 0; // Stores bit counts to build final value. // Could be unrolled into 5 or 12 counters to gain some nanoseconds var bit_count = [_]u32{0} ** LENGTH; var line_count: u32 = 0; var gamma: u12 = 0; // showcase arbitrary bit length // var gamma: u5 = 0; // testing // Iterate over the full input var i: usize = 0; inline while (bit_pos < LENGTH) : (bit_pos += 1){ //std.debug.print("current bit pos: {}\n", .{bit_pos}); i = bit_pos; while (i < input.len){ if (bit_count[bit_pos] >= MAJORITY_THRESHOLD or line_count > MAJORITY_THRESHOLD){ // Further operations won't change result break; } //std.debug.print("{c}\n", .{input[i]}); if (input[i] == '1'){ bit_count[bit_pos] += 1; } i += 13; //prod //i += 6; //test } } bit_pos = 0; inline while (bit_pos < LENGTH) : (bit_pos += 1) { if (bit_count[bit_pos] >= MAJORITY_THRESHOLD) { // check if there's more 1s than 0s. Assuming >= based on part 2 gamma += (@as(u12, 1) << (LENGTH - @intCast(u4, bit_pos) - 1)); // we can only store gamma as epsilon = ~gamma (in u12) //gamma += (@as(u5, 1) << (LENGTH - @intCast(u3, bit_pos) - 1)); // testing } } return @as(u32, gamma) * ~gamma; // preventively cast as u32 to avoid overflow } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); // create memory allocator for strings defer arena.deinit(); // clear memory var arg_it = std.process.args(); _ = arg_it.skip(); // skip over exe name a = &arena.allocator; // get ref to allocator const input: [:0]u8 = try (arg_it.next(a)).?; // get the first argument const start: i128 = std.time.nanoTimestamp(); // start time const answer = run(input); // compute answer const elapsed_nano: f128 = @intToFloat(f128, std.time.nanoTimestamp() - start); const elapsed_milli: f64 = @floatCast(f64, @divFloor(elapsed_nano, 1_000_000)); try stdout.print("_duration:{d}\n{}\n", .{ elapsed_milli, answer }); // emit actual lines parsed by AOC } test "ez" { const input = \\00100 \\11110 \\10110 \\10111 \\10101 \\01111 \\00111 \\11100 \\10000 \\11001 \\00010 \\01010 ; var buf = input.*; try std.testing.expect(run(&buf) == 198); }
day-03/part-1/lelithium.zig
const std = @import("std"); const fun = @import("fun"); const debug = std.debug; const heap = std.heap; const io = std.io; const math = std.math; const mem = std.mem; const os = std.os; const scan = fun.scan.scan; pub fn main() !void { const stdin = &(try io.getStdIn()).inStream().stream; const stdout = &(try io.getStdOut()).outStream().stream; var ps = io.PeekStream(1, os.File.InStream.Error).init(stdin); var direct_allocator = heap.DirectAllocator.init(); const allocator = &direct_allocator.allocator; defer direct_allocator.deinit(); const input = try scan(&ps, "{} players; last marble is worth {} points", struct { players: usize, last_marble: usize, }); try stdout.print("{}\n", try simulateElfGame(allocator, input.players, input.last_marble)); try stdout.print("{}\n", try simulateElfGame(allocator, input.players, input.last_marble * 100)); } fn simulateElfGame(child_allocator: *mem.Allocator, players: usize, last_marble: usize) !usize { const scores = try child_allocator.alloc(usize, players); defer child_allocator.free(scores); mem.set(usize, scores, 0); const Circle = std.LinkedList(usize); const marbles_allocated = (last_marble - (last_marble / 23)) + 1; const buf = try child_allocator.alloc(u8, marbles_allocated * @sizeOf(Circle)); defer child_allocator.free(buf); var fba = heap.FixedBufferAllocator.init(buf[0..]); const allocator = &fba.allocator; var player: usize = 0; var marble: usize = 1; var circle = std.LinkedList(usize).init(); var curr = try circle.createNode(0, allocator); curr.prev = curr; curr.next = curr; circle.first = curr; circle.last = curr; circle.len = 1; while (marble <= last_marble) : ({ player = (player + 1) % players; marble += 1; }) { if (marble % 23 == 0) { var i: usize = 0; while (i < 7) : (i+= 1) curr = curr.prev.?; scores[player] += curr.data + marble; circle.remove(curr); curr = curr.next.?; } else { const next = try circle.createNode(marble, allocator); curr = curr.next.?; circle.insertAfter(curr, next); curr = next; } } return mem.max(usize, scores); }
src/day9.zig
const std = @import("std"); const zargo = @import("zargo.zig"); export fn zargo_engine_init(backend: zargo.Backend, window_width: u32, window_height: u32, debug: bool) ?*zargo.Engine { var e = std.heap.c_allocator.create(zargo.Engine) catch return null; errdefer std.heap.c_allocator.free(e); e.init(std.heap.c_allocator, backend, window_width, window_height, debug) catch return null; return e; } export fn zargo_engine_set_window_size(e: ?*zargo.Engine, width: u32, height: u32) void { if (e) |engine| { engine.setWindowSize(width, height); } else unreachable; } export fn zargo_engine_area(e: ?*zargo.Engine, r: ?*zargo.CRectangle) void { if (e != null and r != null) { r.?.* = zargo.CEngineInterface.area(e.?); } else unreachable; } export fn zargo_engine_clear(e: ?*zargo.Engine, color: *[4]u8) void { if (e) |engine| { engine.clear(color.*); } else unreachable; } export fn zargo_engine_close(e: ?*zargo.Engine) void { if (e) |engine| { engine.close(); std.heap.c_allocator.destroy(engine); } else unreachable; } export fn zargo_engine_fill_unit(e: ?*zargo.Engine, t: ?*zargo.Transform, color: *[4]u8, copy_alpha: bool) void { if (e != null and t != null) { e.?.fillUnit(t.?.*, color.*, copy_alpha); } else unreachable; } export fn zargo_engine_fill_rect(e: ?*zargo.Engine, r: ?*zargo.CRectangle, color: *[4]u8, copy_alpha: bool) void { if (e != null and r != null) { zargo.CEngineInterface.fillRect(e.?, r.?.*, color.*, copy_alpha); } else unreachable; } export fn zargo_engine_blend_unit(e: ?*zargo.Engine, mask: ?*zargo.CImage, dst_transform: ?*zargo.Transform, src_transform: ?*zargo.Transform, color1: *[4]u8, color2: *[4]u8) void { if (e != null and mask != null) { var src = if (src_transform) |v| v.* else mask.?.area().transformation(); var dst = if (dst_transform) |v| v.* else zargo.CEngineInterface.area(e.?).transformation(); zargo.CEngineInterface.blendUnit(e.?, mask.?.*, dst, src, color1.*, color2.*); } else unreachable; } export fn zargo_engine_blend_rect(e: ?*zargo.Engine, mask: ?*zargo.CImage, dst_rect: ?*zargo.CRectangle, src_rect: ?*zargo.CRectangle, color1: *[4]u8, color2: *[4]u8) void { if (e != null and mask != null) { var src = if (src_rect) |v| v.* else mask.?.area(); var dst = if (dst_rect) |v| v.* else zargo.CEngineInterface.area(e.?); zargo.CEngineInterface.blendRect(e.?, mask.?.*, dst, src, color1.*, color2.*); } else unreachable; } export fn zargo_engine_load_image(e: ?*zargo.Engine, i: ?*zargo.CImage, path: [*:0]u8) void { if (e) |engine| { if (i) |image| { image.* = zargo.CEngineInterface.loadImage(engine, std.mem.span(path)); } else unreachable; } else unreachable; } export fn zargo_engine_draw_image(e: ?*zargo.Engine, i: ?*zargo.CImage, dst_transform: ?*zargo.Transform, src_transform: ?*zargo.Transform, alpha: u8) void { if (e != null and i != null) { var src = if (src_transform) |v| v.* else i.?.area().transformation(); var dst = if (dst_transform) |v| v.* else zargo.CEngineInterface.area(e.?).transformation(); zargo.CEngineInterface.drawImage(e.?, i.?.*, dst, src, alpha); } else unreachable; } export fn zargo_transform_identity(t: ?*zargo.Transform) void { if (t) |transform| { transform.* = zargo.Transform.identity(); } else unreachable; } export fn zargo_transform_translate(in: ?*zargo.Transform, out: ?*zargo.Transform, dx: f32, dy: f32) void { if (in) |t| { (out orelse t).* = t.translate(dx, dy); } else unreachable; } export fn zargo_transform_rotate(in: ?*zargo.Transform, out: ?*zargo.Transform, angle: f32) void { if (in) |t| { const res = t.rotate(angle); (out orelse t).* = res; } else unreachable; } export fn zargo_transform_scale(in: ?*zargo.Transform, out: ?*zargo.Transform, factorX: f32, factorY: f32) void { if (in) |t| { (out orelse t).* = t.scale(factorX, factorY); } else unreachable; } export fn zargo_transform_compose(l: ?*zargo.Transform, r: ?*zargo.Transform, out: ?*zargo.Transform) void { if (l != null and r != null and out != null) { const res = l.?.compose(r.?.*); out.?.* = res; } else unreachable; } export fn zargo_rectangle_translation(in: ?*zargo.CRectangle, out: ?*zargo.Transform) void { if (in != null and out != null) { out.?.* = in.?.translation(); } else unreachable; } export fn zargo_rectangle_transformation(in: ?*zargo.CRectangle, out: ?*zargo.Transform) void { if (in != null and out != null) { out.?.* = in.?.transformation(); } else unreachable; } export fn zargo_rectangle_move(in: ?*zargo.CRectangle, out: ?*zargo.CRectangle, dx: i32, dy: i32) void { if (in) |r| { const res = r.move(dx, dy); (out orelse r).* = res; } else unreachable; } export fn zargo_rectangle_grow(in: ?*zargo.CRectangle, out: ?*zargo.CRectangle, dw: i32, dh: i32) void { if (in) |r| { const res = r.grow(dw, dh); (out orelse r).* = res; } else unreachable; } export fn zargo_rectangle_scale(in: ?*zargo.CRectangle, out: ?*zargo.CRectangle, factorX: f32, factorY: f32) void { if (in) |r| { const res = r.scale(factorX, factorY); (out orelse r).* = res; } else unreachable; } export fn zargo_rectangle_position(in: ?*zargo.CRectangle, out: ?*zargo.CRectangle, width: u32, height: u32, horiz: zargo.CRectangle.HAlign, vert: zargo.CRectangle.VAlign) void { if (in) |r| { const res = r.position(@intCast(u31, width), @intCast(u31, height), horiz, vert); (out orelse r).* = res; } else unreachable; } export fn zargo_image_empty(i: ?*zargo.CImage) void { if (i) |image| { image.* = zargo.CImage.empty(); } else unreachable; } export fn zargo_image_is_empty(i: ?*zargo.CImage) bool { if (i) |image| { return image.isEmpty(); } else unreachable; } export fn zargo_image_area(in: ?*zargo.Image, out: ?*zargo.CRectangle) void { if (in != null and out != null) { out.?.* = zargo.CRectangle.from(in.?.area()); } else unreachable; } export fn zargo_image_draw(i: ?*zargo.CImage, e: ?*zargo.Engine, dst_area: ?*zargo.CRectangle, src_area: ?*zargo.CRectangle, alpha: u8) void { if (e != null and i != null) { var src = if (src_area) |v| v.* else i.?.area(); var dst = if (dst_area) |v| v.* else zargo.CEngineInterface.area(e.?); i.?.draw(e.?, dst, src, alpha); } else unreachable; } export fn zargo_canvas_create(out: ?*zargo.CCanvas, e: ?*zargo.Engine, width: u32, height: u32, with_alpha: bool) void { if (e != null and out != null) { out.?.* = zargo.CCanvas.create(e.?, width, height, with_alpha) catch zargo.CCanvas{ .e = e.?, .previous_framebuffer = .invalid, .framebuffer = .invalid, .target_image = zargo.Image.empty(), .alpha = false, .prev_width = 0, .prev_height = 0, }; } else unreachable; } export fn zargo_canvas_rectangle(c: ?*zargo.CCanvas, out: ?*zargo.CRectangle) void { if (c != null and out != null) { out.?.* = c.?.rectangle(); } else unreachable; } export fn zargo_canvas_finish(c: ?*zargo.CCanvas, out: ?*zargo.CImage) void { if (c != null and out != null) { out.?.* = c.?.finish() catch zargo.CImage.empty(); } else unreachable; } export fn zargo_canvas_close(c: ?*zargo.CCanvas) void { if (c) |canvas| { canvas.close(); } else unreachable; }
src/libzargo.zig
const std = @import("std"); const string = []const u8; // LSP types // https://microsoft.github.io/language-server-protocol/specifications/specification-3-16/ pub const Position = struct { line: i64, character: i64, }; pub const Range = struct { start: Position, end: Position, }; pub const Location = struct { uri: string, range: Range, }; /// Id of a request pub const RequestId = union(enum) { String: string, Integer: i64, Float: f64, }; /// Hover response pub const Hover = struct { contents: MarkupContent, }; /// Params of a response (result) pub const ResponseParams = union(enum) { SignatureHelp: SignatureHelp, CompletionList: CompletionList, Location: Location, Hover: Hover, DocumentSymbols: []DocumentSymbol, SemanticTokensFull: struct { data: []const u32 }, TextEdits: []TextEdit, Locations: []Location, WorkspaceEdit: WorkspaceEdit, InitializeResult: InitializeResult, ConfigurationParams: ConfigurationParams, }; /// JSONRPC notifications pub const Notification = struct { pub const Params = union(enum) { LogMessage: struct { type: MessageType, message: string, }, PublishDiagnostics: struct { uri: string, diagnostics: []Diagnostic, }, ShowMessage: struct { type: MessageType, message: string, }, }; jsonrpc: string = "2.0", method: string, params: Params, }; /// JSONRPC response pub const Response = struct { jsonrpc: string = "2.0", id: RequestId, result: ResponseParams, }; pub const Request = struct { jsonrpc: string = "2.0", method: []const u8, params: ?ResponseParams, }; /// Type of a debug message pub const MessageType = enum(i64) { Error = 1, Warning = 2, Info = 3, Log = 4, pub fn jsonStringify(value: MessageType, options: std.json.StringifyOptions, out_stream: anytype) !void { try std.json.stringify(@enumToInt(value), options, out_stream); } }; pub const DiagnosticSeverity = enum(i64) { Error = 1, Warning = 2, Information = 3, Hint = 4, pub fn jsonStringify(value: DiagnosticSeverity, options: std.json.StringifyOptions, out_stream: anytype) !void { try std.json.stringify(@enumToInt(value), options, out_stream); } }; pub const Diagnostic = struct { range: Range, severity: DiagnosticSeverity, code: string, source: string, message: string, }; pub const TextDocument = struct { uri: string, // This is a substring of mem starting at 0 text: [:0]const u8, // This holds the memory that we have actually allocated. mem: []u8, const Held = struct { document: *const TextDocument, popped: u8, start_index: usize, end_index: usize, pub fn data(self: @This()) [:0]const u8 { return self.document.mem[self.start_index..self.end_index :0]; } pub fn release(self: *@This()) void { self.document.mem[self.end_index] = self.popped; } }; pub fn borrowNullTerminatedSlice(self: *const @This(), start_idx: usize, end_idx: usize) Held { std.debug.assert(end_idx >= start_idx); const popped_char = self.mem[end_idx]; self.mem[end_idx] = 0; return .{ .document = self, .popped = popped_char, .start_index = start_idx, .end_index = end_idx, }; } }; pub const WorkspaceEdit = struct { changes: ?std.StringHashMap([]TextEdit), pub fn jsonStringify(self: WorkspaceEdit, options: std.json.StringifyOptions, writer: anytype) @TypeOf(writer).Error!void { try writer.writeByte('{'); if (self.changes) |changes| { try writer.writeAll("\"changes\": {"); var it = changes.iterator(); var idx: usize = 0; while (it.next()) |entry| : (idx += 1) { if (idx != 0) try writer.writeAll(", "); try writer.writeByte('"'); try writer.writeAll(entry.key_ptr.*); try writer.writeAll("\":"); try std.json.stringify(entry.value_ptr.*, options, writer); } try writer.writeByte('}'); } try writer.writeByte('}'); } }; pub const TextEdit = struct { range: Range, newText: string, }; pub const MarkupContent = struct { pub const Kind = enum(u1) { PlainText = 0, Markdown = 1, pub fn jsonStringify(value: Kind, options: std.json.StringifyOptions, out_stream: anytype) !void { const str = switch (value) { .PlainText => "plaintext", .Markdown => "markdown", }; try std.json.stringify(str, options, out_stream); } }; kind: Kind = .Markdown, value: string, }; pub const CompletionList = struct { isIncomplete: bool, items: []const CompletionItem, }; pub const InsertTextFormat = enum(i64) { PlainText = 1, Snippet = 2, pub fn jsonStringify(value: InsertTextFormat, options: std.json.StringifyOptions, out_stream: anytype) !void { try std.json.stringify(@enumToInt(value), options, out_stream); } }; pub const CompletionItem = struct { const Kind = enum(i64) { Text = 1, Method = 2, Function = 3, Constructor = 4, Field = 5, Variable = 6, Class = 7, Interface = 8, Module = 9, Property = 10, Unit = 11, Value = 12, Enum = 13, Keyword = 14, Snippet = 15, Color = 16, File = 17, Reference = 18, Folder = 19, EnumMember = 20, Constant = 21, Struct = 22, Event = 23, Operator = 24, TypeParameter = 25, pub fn jsonStringify(value: Kind, options: std.json.StringifyOptions, out_stream: anytype) !void { try std.json.stringify(@enumToInt(value), options, out_stream); } }; label: string, kind: Kind, textEdit: ?TextEdit = null, filterText: ?string = null, insertText: string = "", insertTextFormat: ?InsertTextFormat = .PlainText, detail: ?string = null, documentation: ?MarkupContent = null, }; pub const DocumentSymbol = struct { pub const Kind = enum(u32) { File = 1, Module = 2, Namespace = 3, Package = 4, Class = 5, Method = 6, Property = 7, Field = 8, Constructor = 9, Enum = 10, Interface = 11, Function = 12, Variable = 13, Constant = 14, String = 15, Number = 16, Boolean = 17, Array = 18, Object = 19, Key = 20, Null = 21, EnumMember = 22, Struct = 23, Event = 24, Operator = 25, TypeParameter = 26, pub fn jsonStringify(value: Kind, options: std.json.StringifyOptions, out_stream: anytype) !void { try std.json.stringify(@enumToInt(value), options, out_stream); } }; name: string, detail: ?string = null, kind: Kind, deprecated: bool = false, range: Range, selectionRange: Range, children: []const DocumentSymbol = &[_]DocumentSymbol{}, }; pub const WorkspaceFolder = struct { uri: string, name: string, }; pub const SignatureInformation = struct { pub const ParameterInformation = struct { // TODO Can also send a pair of encoded offsets label: string, documentation: ?MarkupContent, }; label: string, documentation: ?MarkupContent, parameters: ?[]const ParameterInformation, activeParameter: ?u32, }; pub const SignatureHelp = struct { signatures: ?[]const SignatureInformation, activeSignature: ?u32, activeParameter: ?u32, }; // Only includes options we set in our initialize result. const InitializeResult = struct { offsetEncoding: string, capabilities: struct { signatureHelpProvider: struct { triggerCharacters: []const string, retriggerCharacters: []const string, }, textDocumentSync: enum(u32) { None = 0, Full = 1, Incremental = 2, pub fn jsonStringify(value: @This(), options: std.json.StringifyOptions, out_stream: anytype) !void { try std.json.stringify(@enumToInt(value), options, out_stream); } }, renameProvider: bool, completionProvider: struct { resolveProvider: bool, triggerCharacters: []const string, }, documentHighlightProvider: bool, hoverProvider: bool, codeActionProvider: bool, declarationProvider: bool, definitionProvider: bool, typeDefinitionProvider: bool, implementationProvider: bool, referencesProvider: bool, documentSymbolProvider: bool, colorProvider: bool, documentFormattingProvider: bool, documentRangeFormattingProvider: bool, foldingRangeProvider: bool, selectionRangeProvider: bool, workspaceSymbolProvider: bool, rangeProvider: bool, documentProvider: bool, workspace: ?struct { workspaceFolders: ?struct { supported: bool, changeNotifications: bool, }, }, semanticTokensProvider: struct { full: bool, range: bool, legend: struct { tokenTypes: []const string, tokenModifiers: []const string, }, }, }, serverInfo: struct { name: string, version: ?string = null, }, }; pub const ConfigurationParams = struct { items: []const ConfigurationItem, pub const ConfigurationItem = struct { scopeUri: ?[]const u8, section: ?[]const u8, }; };
src/types.zig
const std = @import("std"); const debug = std.debug; const fmt = std.fmt; const mem = std.mem; /// Group operations over Edwards25519. pub const Edwards25519 = struct { /// The underlying prime field. pub const Fe = @import("field.zig").Fe; /// Field arithmetic mod the order of the main subgroup. pub const scalar = @import("scalar.zig"); /// Length in bytes of a compressed representation of a point. pub const encoded_length: usize = 32; x: Fe, y: Fe, z: Fe, t: Fe, is_base: bool = false, /// Decode an Edwards25519 point from its compressed (Y+sign) coordinates. pub fn fromBytes(s: [encoded_length]u8) !Edwards25519 { const z = Fe.one; const y = Fe.fromBytes(s); var u = y.sq(); var v = u.mul(Fe.edwards25519d); u = u.sub(z); v = v.add(z); const v3 = v.sq().mul(v); var x = v3.sq().mul(v).mul(u).pow2523().mul(v3).mul(u); const vxx = x.sq().mul(v); const has_m_root = vxx.sub(u).isZero(); const has_p_root = vxx.add(u).isZero(); if ((@boolToInt(has_m_root) | @boolToInt(has_p_root)) == 0) { // best-effort to avoid two conditional branches return error.InvalidEncoding; } x.cMov(x.mul(Fe.sqrtm1), 1 - @boolToInt(has_m_root)); x.cMov(x.neg(), @boolToInt(x.isNegative()) ^ (s[31] >> 7)); const t = x.mul(y); return Edwards25519{ .x = x, .y = y, .z = z, .t = t }; } /// Encode an Edwards25519 point. pub fn toBytes(p: Edwards25519) [encoded_length]u8 { const zi = p.z.invert(); var s = p.y.mul(zi).toBytes(); s[31] ^= @as(u8, @boolToInt(p.x.mul(zi).isNegative())) << 7; return s; } /// Check that the encoding of a point is canonical. pub fn rejectNonCanonical(s: [32]u8) !void { return Fe.rejectNonCanonical(s, true); } /// The edwards25519 base point. pub const basePoint = Edwards25519{ .x = Fe{ .limbs = .{ 3990542415680775, 3398198340507945, 4322667446711068, 2814063955482877, 2839572215813860 } }, .y = Fe{ .limbs = .{ 1801439850948184, 1351079888211148, 450359962737049, 900719925474099, 1801439850948198 } }, .z = Fe.one, .t = Fe{ .limbs = .{ 1841354044333475, 16398895984059, 755974180946558, 900171276175154, 1821297809914039 } }, .is_base = true, }; /// The edwards25519 neutral element. pub const neutralElement = Edwards25519{ .x = Fe{ .limbs = .{ 2251799813685229, 2251799813685247, 2251799813685247, 2251799813685247, 2251799813685247 } }, .y = Fe{ .limbs = .{ 1507481815385608, 2223447444246085, 1083941587175919, 2059929906842505, 1581435440146976 } }, .z = Fe{ .limbs = .{ 1507481815385608, 2223447444246085, 1083941587175919, 2059929906842505, 1581435440146976 } }, .t = Fe{ .limbs = .{ 2251799813685229, 2251799813685247, 2251799813685247, 2251799813685247, 2251799813685247 } }, .is_base = false, }; const identityElement = Edwards25519{ .x = Fe.zero, .y = Fe.one, .z = Fe.one, .t = Fe.zero }; /// Reject the neutral element. pub fn rejectIdentity(p: Edwards25519) !void { if (p.x.isZero()) { return error.IdentityElement; } } /// Multiply a point by the cofactor pub fn clearCofactor(p: Edwards25519) Edwards25519 { return p.dbl().dbl().dbl(); } /// Flip the sign of the X coordinate. pub inline fn neg(p: Edwards25519) Edwards25519 { return .{ .x = p.x.neg(), .y = p.y, .z = p.z, .t = p.t.neg() }; } /// Double an Edwards25519 point. pub fn dbl(p: Edwards25519) Edwards25519 { const t0 = p.x.add(p.y).sq(); var x = p.x.sq(); var z = p.y.sq(); const y = z.add(x); z = z.sub(x); x = t0.sub(y); const t = p.z.sq2().sub(z); return .{ .x = x.mul(t), .y = y.mul(z), .z = z.mul(t), .t = x.mul(y), }; } /// Add two Edwards25519 points. pub fn add(p: Edwards25519, q: Edwards25519) Edwards25519 { const a = p.y.sub(p.x).mul(q.y.sub(q.x)); const b = p.x.add(p.y).mul(q.x.add(q.y)); const c = p.t.mul(q.t).mul(Fe.edwards25519d2); var d = p.z.mul(q.z); d = d.add(d); const x = b.sub(a); const y = b.add(a); const z = d.add(c); const t = d.sub(c); return .{ .x = x.mul(t), .y = y.mul(z), .z = z.mul(t), .t = x.mul(y), }; } /// Substract two Edwards25519 points. pub fn sub(p: Edwards25519, q: Edwards25519) Edwards25519 { return p.add(q.neg()); } inline fn cMov(p: *Edwards25519, a: Edwards25519, c: u64) void { p.x.cMov(a.x, c); p.y.cMov(a.y, c); p.z.cMov(a.z, c); p.t.cMov(a.t, c); } inline fn pcSelect(comptime n: usize, pc: [n]Edwards25519, b: u8) Edwards25519 { var t = Edwards25519.identityElement; comptime var i: u8 = 1; inline while (i < pc.len) : (i += 1) { t.cMov(pc[i], ((@as(usize, b ^ i) -% 1) >> 8) & 1); } return t; } fn nonAdjacentForm(s: [32]u8) [2 * 32]i8 { var e: [2 * 32]i8 = undefined; for (s) |x, i| { e[i * 2 + 0] = @as(i8, @truncate(u4, x)); e[i * 2 + 1] = @as(i8, @truncate(u4, x >> 4)); } // Now, e[0..63] is between 0 and 15, e[63] is between 0 and 7 var carry: i8 = 0; for (e[0..63]) |*x| { x.* += carry; carry = (x.* + 8) >> 4; x.* -= carry * 16; } e[63] += carry; // Now, e[*] is between -8 and 8, including e[63] return e; } // Scalar multiplication with a 4-bit window and the first 8 multiples. // This requires the scalar to be converted to non-adjacent form. // Based on real-world benchmarks, we only use this for multi-scalar multiplication. // NAF could be useful to half the size of precomputation tables, but we intentionally // avoid these to keep the standard library lightweight. fn pcMul(pc: [9]Edwards25519, s: [32]u8, comptime vartime: bool) !Edwards25519 { std.debug.assert(vartime); const e = nonAdjacentForm(s); var q = Edwards25519.identityElement; var pos: usize = 2 * 32 - 1; while (true) : (pos -= 1) { const slot = e[pos]; if (slot > 0) { q = q.add(pc[@intCast(usize, slot)]); } else if (slot < 0) { q = q.sub(pc[@intCast(usize, -slot)]); } if (pos == 0) break; q = q.dbl().dbl().dbl().dbl(); } try q.rejectIdentity(); return q; } // Scalar multiplication with a 4-bit window and the first 15 multiples. fn pcMul16(pc: [16]Edwards25519, s: [32]u8, comptime vartime: bool) !Edwards25519 { var q = Edwards25519.identityElement; var pos: usize = 252; while (true) : (pos -= 4) { const slot = @truncate(u4, (s[pos >> 3] >> @truncate(u3, pos))); if (vartime) { if (slot != 0) { q = q.add(pc[slot]); } } else { q = q.add(pcSelect(16, pc, slot)); } if (pos == 0) break; q = q.dbl().dbl().dbl().dbl(); } try q.rejectIdentity(); return q; } fn precompute(p: Edwards25519, comptime count: usize) [1 + count]Edwards25519 { var pc: [1 + count]Edwards25519 = undefined; pc[0] = Edwards25519.identityElement; pc[1] = p; var i: usize = 2; while (i <= count) : (i += 1) { pc[i] = if (i % 2 == 0) pc[i / 2].dbl() else pc[i - 1].add(p); } return pc; } const basePointPc = comptime pc: { @setEvalBranchQuota(10000); break :pc precompute(Edwards25519.basePoint, 15); }; /// Multiply an Edwards25519 point by a scalar without clamping it. /// Return error.WeakPublicKey if the resulting point is /// the identity element. pub fn mul(p: Edwards25519, s: [32]u8) !Edwards25519 { const pc = if (p.is_base) basePointPc else pc: { const xpc = precompute(p, 15); xpc[4].rejectIdentity() catch |_| return error.WeakPublicKey; break :pc xpc; }; return pcMul16(pc, s, false); } /// Multiply an Edwards25519 point by a *PUBLIC* scalar *IN VARIABLE TIME* /// This can be used for signature verification. pub fn mulPublic(p: Edwards25519, s: [32]u8) !Edwards25519 { if (p.is_base) { return pcMul16(basePointPc, s, true); } else { const pc = precompute(p, 8); pc[4].rejectIdentity() catch |_| return error.WeakPublicKey; return pcMul(pc, s, true); } } /// Multiscalar multiplication *IN VARIABLE TIME* for public data /// Computes ps0*ss0 + ps1*ss1 + ps2*ss2... faster than doing many of these operations individually pub fn mulMulti(comptime count: usize, ps: [count]Edwards25519, ss: [count][32]u8) !Edwards25519 { var pcs: [count][9]Edwards25519 = undefined; for (ps) |p, i| { if (p.is_base) { @setEvalBranchQuota(10000); pcs[i] = comptime precompute(Edwards25519.basePoint, 8); } else { pcs[i] = precompute(p, 8); pcs[i][4].rejectIdentity() catch |_| return error.WeakPublicKey; } } var es: [count][2 * 32]i8 = undefined; for (ss) |s, i| { es[i] = nonAdjacentForm(s); } var q = Edwards25519.identityElement; var pos: usize = 2 * 32 - 1; while (true) : (pos -= 1) { for (es) |e, i| { const slot = e[pos]; if (slot > 0) { q = q.add(pcs[i][@intCast(usize, slot)]); } else if (slot < 0) { q = q.sub(pcs[i][@intCast(usize, -slot)]); } } if (pos == 0) break; q = q.dbl().dbl().dbl().dbl(); } try q.rejectIdentity(); return q; } /// Multiply an Edwards25519 point by a scalar after "clamping" it. /// Clamping forces the scalar to be a multiple of the cofactor in /// order to prevent small subgroups attacks. /// This is strongly recommended for DH operations. /// Return error.WeakPublicKey if the resulting point is /// the identity element. pub fn clampedMul(p: Edwards25519, s: [32]u8) !Edwards25519 { var t: [32]u8 = s; scalar.clamp(&t); return mul(p, t); } // montgomery -- recover y = sqrt(x^3 + A*x^2 + x) fn xmontToYmont(x: Fe) !Fe { var x2 = x.sq(); const x3 = x.mul(x2); x2 = x2.mul32(Fe.edwards25519a_32); return x.add(x2).add(x3).sqrt(); } // montgomery affine coordinates to edwards extended coordinates fn montToEd(x: Fe, y: Fe) Edwards25519 { const x_plus_one = x.add(Fe.one); const x_minus_one = x.sub(Fe.one); const x_plus_one_y_inv = x_plus_one.mul(y).invert(); // 1/((x+1)*y) // xed = sqrt(-A-2)*x/y const xed = x.mul(Fe.edwards25519sqrtam2).mul(x_plus_one_y_inv).mul(x_plus_one); // yed = (x-1)/(x+1) or 1 if the denominator is 0 var yed = x_plus_one_y_inv.mul(y).mul(x_minus_one); yed.cMov(Fe.one, @boolToInt(x_plus_one_y_inv.isZero())); return Edwards25519{ .x = xed, .y = yed, .z = Fe.one, .t = xed.mul(yed), }; } /// Elligator2 map - Returns Montgomery affine coordinates pub fn elligator2(r: Fe) struct { x: Fe, y: Fe, not_square: bool } { const rr2 = r.sq2().add(Fe.one).invert(); var x = rr2.mul32(Fe.edwards25519a_32).neg(); // x=x1 var x2 = x.sq(); const x3 = x2.mul(x); x2 = x2.mul32(Fe.edwards25519a_32); // x2 = A*x1^2 const gx1 = x3.add(x).add(x2); // gx1 = x1^3 + A*x1^2 + x1 const not_square = !gx1.isSquare(); // gx1 not a square => x = -x1-A x.cMov(x.neg(), @boolToInt(not_square)); x2 = Fe.zero; x2.cMov(Fe.edwards25519a, @boolToInt(not_square)); x = x.sub(x2); // We have y = sqrt(gx1) or sqrt(gx2) with gx2 = gx1*(A+x1)/(-x1) // but it is about as fast to just recompute y from the curve equation. const y = xmontToYmont(x) catch unreachable; return .{ .x = x, .y = y, .not_square = not_square }; } /// Map a 64-bit hash into an Edwards25519 point pub fn fromHash(h: [64]u8) Edwards25519 { const fe_f = Fe.fromBytes64(h); var elr = elligator2(fe_f); const y_sign = elr.not_square; const y_neg = elr.y.neg(); elr.y.cMov(y_neg, @boolToInt(elr.y.isNegative()) ^ @boolToInt(y_sign)); return montToEd(elr.x, elr.y).clearCofactor(); } fn stringToPoints(comptime n: usize, ctx: []const u8, s: []const u8) [n]Edwards25519 { debug.assert(n <= 2); const H = std.crypto.hash.sha2.Sha512; const h_l: usize = 48; var xctx = ctx; var hctx: [H.digest_length]u8 = undefined; if (ctx.len > 0xff) { var st = H.init(.{}); st.update("H2C-OVERSIZE-DST-"); st.update(ctx); st.final(&hctx); xctx = hctx[0..]; } const empty_block = [_]u8{0} ** H.block_length; var t = [3]u8{ 0, n * h_l, 0 }; var xctx_len_u8 = [1]u8{@intCast(u8, xctx.len)}; var st = H.init(.{}); st.update(empty_block[0..]); st.update(s); st.update(t[0..]); st.update(xctx); st.update(xctx_len_u8[0..]); var u_0: [H.digest_length]u8 = undefined; st.final(&u_0); var u: [n * H.digest_length]u8 = undefined; var i: usize = 0; while (i < n * H.digest_length) : (i += H.digest_length) { mem.copy(u8, u[i..][0..H.digest_length], u_0[0..]); var j: usize = 0; while (i > 0 and j < H.digest_length) : (j += 1) { u[i + j] ^= u[i + j - H.digest_length]; } t[2] += 1; st = H.init(.{}); st.update(u[i..][0..H.digest_length]); st.update(t[2..3]); st.update(xctx); st.update(xctx_len_u8[0..]); st.final(u[i..][0..H.digest_length]); } var px: [n]Edwards25519 = undefined; i = 0; while (i < n) : (i += 1) { mem.set(u8, u_0[0 .. H.digest_length - h_l], 0); mem.copy(u8, u_0[H.digest_length - h_l ..][0..h_l], u[i * h_l ..][0..h_l]); px[i] = fromHash(u_0); } return px; } /// Hash a context `ctx` and a string `s` into an Edwards25519 point /// /// This function implements the edwards25519_XMD:SHA-512_ELL2_RO_ and edwards25519_XMD:SHA-512_ELL2_NU_ /// methods from the "Hashing to Elliptic Curves" standard document. /// /// Although not strictly required by the standard, it is recommended to avoid NUL characters in /// the context in order to be compatible with other implementations. pub fn fromString(comptime random_oracle: bool, ctx: []const u8, s: []const u8) Edwards25519 { if (random_oracle) { const px = stringToPoints(2, ctx, s); return px[0].add(px[1]); } else { return stringToPoints(1, ctx, s)[0]; } } /// Map a 32 bit uniform bit string into an edwards25519 point pub fn fromUniform(r: [32]u8) Edwards25519 { var s = r; const x_sign = s[31] >> 7; s[31] &= 0x7f; const elr = elligator2(Fe.fromBytes(s)); var p = montToEd(elr.x, elr.y); const p_neg = p.neg(); p.cMov(p_neg, @boolToInt(p.x.isNegative()) ^ x_sign); return p.clearCofactor(); } }; const htest = @import("../test.zig"); test "edwards25519 packing/unpacking" { const s = [_]u8{170} ++ [_]u8{0} ** 31; var b = Edwards25519.basePoint; const pk = try b.mul(s); var buf: [128]u8 = undefined; std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{pk.toBytes()}), "074BC7E0FCBD587FDBC0969444245FADC562809C8F6E97E949AF62484B5B81A6"); const small_order_ss: [7][32]u8 = .{ .{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0 (order 4) }, .{ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 1 (order 1) }, .{ 0x26, 0xe8, 0x95, 0x8f, 0xc2, 0xb2, 0x27, 0xb0, 0x45, 0xc3, 0xf4, 0x89, 0xf2, 0xef, 0x98, 0xf0, 0xd5, 0xdf, 0xac, 0x05, 0xd3, 0xc6, 0x33, 0x39, 0xb1, 0x38, 0x02, 0x88, 0x6d, 0x53, 0xfc, 0x05, // 270738550114484064931822528722565878893680426757531351946374360975030340202(order 8) }, .{ 0xc7, 0x17, 0x6a, 0x70, 0x3d, 0x4d, 0xd8, 0x4f, 0xba, 0x3c, 0x0b, 0x76, 0x0d, 0x10, 0x67, 0x0f, 0x2a, 0x20, 0x53, 0xfa, 0x2c, 0x39, 0xcc, 0xc6, 0x4e, 0xc7, 0xfd, 0x77, 0x92, 0xac, 0x03, 0x7a, // 55188659117513257062467267217118295137698188065244968500265048394206261417927 (order 8) }, .{ 0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, // p-1 (order 2) }, .{ 0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, // p (=0, order 4) }, .{ 0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, // p+1 (=1, order 1) }, }; for (small_order_ss) |small_order_s| { const small_p = try Edwards25519.fromBytes(small_order_s); std.testing.expectError(error.WeakPublicKey, small_p.mul(s)); } } test "edwards25519 point addition/substraction" { var s1: [32]u8 = undefined; var s2: [32]u8 = undefined; std.crypto.random.bytes(&s1); std.crypto.random.bytes(&s2); const p = try Edwards25519.basePoint.clampedMul(s1); const q = try Edwards25519.basePoint.clampedMul(s2); const r = p.add(q).add(q).sub(q).sub(q); try r.rejectIdentity(); std.testing.expectError(error.IdentityElement, r.sub(p).rejectIdentity()); std.testing.expectError(error.IdentityElement, p.sub(p).rejectIdentity()); std.testing.expectError(error.IdentityElement, p.sub(q).add(q).sub(p).rejectIdentity()); } test "edwards25519 uniform-to-point" { var r = [32]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; var p = Edwards25519.fromUniform(r); htest.assertEqual("0691eee3cf70a0056df6bfa03120635636581b5c4ea571dfc680f78c7e0b4137", p.toBytes()[0..]); r[31] = 0xff; p = Edwards25519.fromUniform(r); htest.assertEqual("f70718e68ef42d90ca1d936bb2d7e159be6c01d8095d39bd70487c82fe5c973a", p.toBytes()[0..]); } // Test vectors from draft-irtf-cfrg-hash-to-curve-10 test "edwards25519 hash-to-curve operation" { var p = Edwards25519.fromString(true, "QUUX-V01-CS02-with-edwards25519_XMD:SHA-512_ELL2_RO_", "abc"); htest.assertEqual("31558a26887f23fb8218f143e69d5f0af2e7831130bd5b432ef23883b895831a", p.toBytes()[0..]); p = Edwards25519.fromString(false, "QUUX-V01-CS02-with-edwards25519_XMD:SHA-512_ELL2_NU_", "abc"); htest.assertEqual("42fa27c8f5a1ae0aa38bb59d5938e5145622ba5dedd11d11736fa2f9502d73e7", p.toBytes()[0..]); }
lib/std/crypto/25519/edwards25519.zig
const builtin = @import("builtin"); const std = @import("std.zig"); const io = std.io; const os = std.os; const math = std.math; const mem = std.mem; const debug = std.debug; const InStream = std.stream.InStream; pub const AT_NULL = 0; pub const AT_IGNORE = 1; pub const AT_EXECFD = 2; pub const AT_PHDR = 3; pub const AT_PHENT = 4; pub const AT_PHNUM = 5; pub const AT_PAGESZ = 6; pub const AT_BASE = 7; pub const AT_FLAGS = 8; pub const AT_ENTRY = 9; pub const AT_NOTELF = 10; pub const AT_UID = 11; pub const AT_EUID = 12; pub const AT_GID = 13; pub const AT_EGID = 14; pub const AT_CLKTCK = 17; pub const AT_PLATFORM = 15; pub const AT_HWCAP = 16; pub const AT_FPUCW = 18; pub const AT_DCACHEBSIZE = 19; pub const AT_ICACHEBSIZE = 20; pub const AT_UCACHEBSIZE = 21; pub const AT_IGNOREPPC = 22; pub const AT_SECURE = 23; pub const AT_BASE_PLATFORM = 24; pub const AT_RANDOM = 25; pub const AT_HWCAP2 = 26; pub const AT_EXECFN = 31; pub const AT_SYSINFO = 32; pub const AT_SYSINFO_EHDR = 33; pub const AT_L1I_CACHESHAPE = 34; pub const AT_L1D_CACHESHAPE = 35; pub const AT_L2_CACHESHAPE = 36; pub const AT_L3_CACHESHAPE = 37; pub const AT_L1I_CACHESIZE = 40; pub const AT_L1I_CACHEGEOMETRY = 41; pub const AT_L1D_CACHESIZE = 42; pub const AT_L1D_CACHEGEOMETRY = 43; pub const AT_L2_CACHESIZE = 44; pub const AT_L2_CACHEGEOMETRY = 45; pub const AT_L3_CACHESIZE = 46; pub const AT_L3_CACHEGEOMETRY = 47; pub const DT_NULL = 0; pub const DT_NEEDED = 1; pub const DT_PLTRELSZ = 2; pub const DT_PLTGOT = 3; pub const DT_HASH = 4; pub const DT_STRTAB = 5; pub const DT_SYMTAB = 6; pub const DT_RELA = 7; pub const DT_RELASZ = 8; pub const DT_RELAENT = 9; pub const DT_STRSZ = 10; pub const DT_SYMENT = 11; pub const DT_INIT = 12; pub const DT_FINI = 13; pub const DT_SONAME = 14; pub const DT_RPATH = 15; pub const DT_SYMBOLIC = 16; pub const DT_REL = 17; pub const DT_RELSZ = 18; pub const DT_RELENT = 19; pub const DT_PLTREL = 20; pub const DT_DEBUG = 21; pub const DT_TEXTREL = 22; pub const DT_JMPREL = 23; pub const DT_BIND_NOW = 24; pub const DT_INIT_ARRAY = 25; pub const DT_FINI_ARRAY = 26; pub const DT_INIT_ARRAYSZ = 27; pub const DT_FINI_ARRAYSZ = 28; pub const DT_RUNPATH = 29; pub const DT_FLAGS = 30; pub const DT_ENCODING = 32; pub const DT_PREINIT_ARRAY = 32; pub const DT_PREINIT_ARRAYSZ = 33; pub const DT_SYMTAB_SHNDX = 34; pub const DT_NUM = 35; pub const DT_LOOS = 0x6000000d; pub const DT_HIOS = 0x6ffff000; pub const DT_LOPROC = 0x70000000; pub const DT_HIPROC = 0x7fffffff; pub const DT_PROCNUM = DT_MIPS_NUM; pub const DT_VALRNGLO = 0x6ffffd00; pub const DT_GNU_PRELINKED = 0x6ffffdf5; pub const DT_GNU_CONFLICTSZ = 0x6ffffdf6; pub const DT_GNU_LIBLISTSZ = 0x6ffffdf7; pub const DT_CHECKSUM = 0x6ffffdf8; pub const DT_PLTPADSZ = 0x6ffffdf9; pub const DT_MOVEENT = 0x6ffffdfa; pub const DT_MOVESZ = 0x6ffffdfb; pub const DT_FEATURE_1 = 0x6ffffdfc; pub const DT_POSFLAG_1 = 0x6ffffdfd; pub const DT_SYMINSZ = 0x6ffffdfe; pub const DT_SYMINENT = 0x6ffffdff; pub const DT_VALRNGHI = 0x6ffffdff; pub const DT_VALNUM = 12; pub const DT_ADDRRNGLO = 0x6ffffe00; pub const DT_GNU_HASH = 0x6ffffef5; pub const DT_TLSDESC_PLT = 0x6ffffef6; pub const DT_TLSDESC_GOT = 0x6ffffef7; pub const DT_GNU_CONFLICT = 0x6ffffef8; pub const DT_GNU_LIBLIST = 0x6ffffef9; pub const DT_CONFIG = 0x6ffffefa; pub const DT_DEPAUDIT = 0x6ffffefb; pub const DT_AUDIT = 0x6ffffefc; pub const DT_PLTPAD = 0x6ffffefd; pub const DT_MOVETAB = 0x6ffffefe; pub const DT_SYMINFO = 0x6ffffeff; pub const DT_ADDRRNGHI = 0x6ffffeff; pub const DT_ADDRNUM = 11; pub const DT_VERSYM = 0x6ffffff0; pub const DT_RELACOUNT = 0x6ffffff9; pub const DT_RELCOUNT = 0x6ffffffa; pub const DT_FLAGS_1 = 0x6ffffffb; pub const DT_VERDEF = 0x6ffffffc; pub const DT_VERDEFNUM = 0x6ffffffd; pub const DT_VERNEED = 0x6ffffffe; pub const DT_VERNEEDNUM = 0x6fffffff; pub const DT_VERSIONTAGNUM = 16; pub const DT_AUXILIARY = 0x7ffffffd; pub const DT_FILTER = 0x7fffffff; pub const DT_EXTRANUM = 3; pub const DT_SPARC_REGISTER = 0x70000001; pub const DT_SPARC_NUM = 2; pub const DT_MIPS_RLD_VERSION = 0x70000001; pub const DT_MIPS_TIME_STAMP = 0x70000002; pub const DT_MIPS_ICHECKSUM = 0x70000003; pub const DT_MIPS_IVERSION = 0x70000004; pub const DT_MIPS_FLAGS = 0x70000005; pub const DT_MIPS_BASE_ADDRESS = 0x70000006; pub const DT_MIPS_MSYM = 0x70000007; pub const DT_MIPS_CONFLICT = 0x70000008; pub const DT_MIPS_LIBLIST = 0x70000009; pub const DT_MIPS_LOCAL_GOTNO = 0x7000000a; pub const DT_MIPS_CONFLICTNO = 0x7000000b; pub const DT_MIPS_LIBLISTNO = 0x70000010; pub const DT_MIPS_SYMTABNO = 0x70000011; pub const DT_MIPS_UNREFEXTNO = 0x70000012; pub const DT_MIPS_GOTSYM = 0x70000013; pub const DT_MIPS_HIPAGENO = 0x70000014; pub const DT_MIPS_RLD_MAP = 0x70000016; pub const DT_MIPS_DELTA_CLASS = 0x70000017; pub const DT_MIPS_DELTA_CLASS_NO = 0x70000018; pub const DT_MIPS_DELTA_INSTANCE = 0x70000019; pub const DT_MIPS_DELTA_INSTANCE_NO = 0x7000001a; pub const DT_MIPS_DELTA_RELOC = 0x7000001b; pub const DT_MIPS_DELTA_RELOC_NO = 0x7000001c; pub const DT_MIPS_DELTA_SYM = 0x7000001d; pub const DT_MIPS_DELTA_SYM_NO = 0x7000001e; pub const DT_MIPS_DELTA_CLASSSYM = 0x70000020; pub const DT_MIPS_DELTA_CLASSSYM_NO = 0x70000021; pub const DT_MIPS_CXX_FLAGS = 0x70000022; pub const DT_MIPS_PIXIE_INIT = 0x70000023; pub const DT_MIPS_SYMBOL_LIB = 0x70000024; pub const DT_MIPS_LOCALPAGE_GOTIDX = 0x70000025; pub const DT_MIPS_LOCAL_GOTIDX = 0x70000026; pub const DT_MIPS_HIDDEN_GOTIDX = 0x70000027; pub const DT_MIPS_PROTECTED_GOTIDX = 0x70000028; pub const DT_MIPS_OPTIONS = 0x70000029; pub const DT_MIPS_INTERFACE = 0x7000002a; pub const DT_MIPS_DYNSTR_ALIGN = 0x7000002b; pub const DT_MIPS_INTERFACE_SIZE = 0x7000002c; pub const DT_MIPS_RLD_TEXT_RESOLVE_ADDR = 0x7000002d; pub const DT_MIPS_PERF_SUFFIX = 0x7000002e; pub const DT_MIPS_COMPACT_SIZE = 0x7000002f; pub const DT_MIPS_GP_VALUE = 0x70000030; pub const DT_MIPS_AUX_DYNAMIC = 0x70000031; pub const DT_MIPS_PLTGOT = 0x70000032; pub const DT_MIPS_RWPLT = 0x70000034; pub const DT_MIPS_RLD_MAP_REL = 0x70000035; pub const DT_MIPS_NUM = 0x36; pub const DT_ALPHA_PLTRO = (DT_LOPROC + 0); pub const DT_ALPHA_NUM = 1; pub const DT_PPC_GOT = (DT_LOPROC + 0); pub const DT_PPC_OPT = (DT_LOPROC + 1); pub const DT_PPC_NUM = 2; pub const DT_PPC64_GLINK = (DT_LOPROC + 0); pub const DT_PPC64_OPD = (DT_LOPROC + 1); pub const DT_PPC64_OPDSZ = (DT_LOPROC + 2); pub const DT_PPC64_OPT = (DT_LOPROC + 3); pub const DT_PPC64_NUM = 4; pub const DT_IA_64_PLT_RESERVE = (DT_LOPROC + 0); pub const DT_IA_64_NUM = 1; pub const DT_NIOS2_GP = 0x70000002; pub const PT_NULL = 0; pub const PT_LOAD = 1; pub const PT_DYNAMIC = 2; pub const PT_INTERP = 3; pub const PT_NOTE = 4; pub const PT_SHLIB = 5; pub const PT_PHDR = 6; pub const PT_TLS = 7; pub const PT_NUM = 8; pub const PT_LOOS = 0x60000000; pub const PT_GNU_EH_FRAME = 0x6474e550; pub const PT_GNU_STACK = 0x6474e551; pub const PT_GNU_RELRO = 0x6474e552; pub const PT_LOSUNW = 0x6ffffffa; pub const PT_SUNWBSS = 0x6ffffffa; pub const PT_SUNWSTACK = 0x6ffffffb; pub const PT_HISUNW = 0x6fffffff; pub const PT_HIOS = 0x6fffffff; pub const PT_LOPROC = 0x70000000; pub const PT_HIPROC = 0x7fffffff; pub const SHT_NULL = 0; pub const SHT_PROGBITS = 1; pub const SHT_SYMTAB = 2; pub const SHT_STRTAB = 3; pub const SHT_RELA = 4; pub const SHT_HASH = 5; pub const SHT_DYNAMIC = 6; pub const SHT_NOTE = 7; pub const SHT_NOBITS = 8; pub const SHT_REL = 9; pub const SHT_SHLIB = 10; pub const SHT_DYNSYM = 11; pub const SHT_INIT_ARRAY = 14; pub const SHT_FINI_ARRAY = 15; pub const SHT_PREINIT_ARRAY = 16; pub const SHT_GROUP = 17; pub const SHT_SYMTAB_SHNDX = 18; pub const SHT_LOOS = 0x60000000; pub const SHT_HIOS = 0x6fffffff; pub const SHT_LOPROC = 0x70000000; pub const SHT_HIPROC = 0x7fffffff; pub const SHT_LOUSER = 0x80000000; pub const SHT_HIUSER = 0xffffffff; pub const STB_LOCAL = 0; pub const STB_GLOBAL = 1; pub const STB_WEAK = 2; pub const STB_NUM = 3; pub const STB_LOOS = 10; pub const STB_GNU_UNIQUE = 10; pub const STB_HIOS = 12; pub const STB_LOPROC = 13; pub const STB_HIPROC = 15; pub const STB_MIPS_SPLIT_COMMON = 13; pub const STT_NOTYPE = 0; pub const STT_OBJECT = 1; pub const STT_FUNC = 2; pub const STT_SECTION = 3; pub const STT_FILE = 4; pub const STT_COMMON = 5; pub const STT_TLS = 6; pub const STT_NUM = 7; pub const STT_LOOS = 10; pub const STT_GNU_IFUNC = 10; pub const STT_HIOS = 12; pub const STT_LOPROC = 13; pub const STT_HIPROC = 15; pub const STT_SPARC_REGISTER = 13; pub const STT_PARISC_MILLICODE = 13; pub const STT_HP_OPAQUE = (STT_LOOS + 0x1); pub const STT_HP_STUB = (STT_LOOS + 0x2); pub const STT_ARM_TFUNC = STT_LOPROC; pub const STT_ARM_16BIT = STT_HIPROC; pub const VER_FLG_BASE = 0x1; pub const VER_FLG_WEAK = 0x2; /// An unknown type. pub const ET_NONE = 0; /// A relocatable file. pub const ET_REL = 1; /// An executable file. pub const ET_EXEC = 2; /// A shared object. pub const ET_DYN = 3; /// A core file. pub const ET_CORE = 4; pub const FileType = enum { Relocatable, Executable, Shared, Core, }; pub const Arch = enum { Sparc, x86, Mips, PowerPc, Arm, SuperH, IA_64, x86_64, AArch64, }; pub const SectionHeader = struct { name: u32, sh_type: u32, flags: u64, addr: u64, offset: u64, size: u64, link: u32, info: u32, addr_align: u64, ent_size: u64, }; pub const Elf = struct { seekable_stream: *io.SeekableStream(anyerror, anyerror), in_stream: *io.InStream(anyerror), auto_close_stream: bool, is_64: bool, endian: builtin.Endian, file_type: FileType, arch: Arch, entry_addr: u64, program_header_offset: u64, section_header_offset: u64, string_section_index: u64, string_section: *SectionHeader, section_headers: []SectionHeader, allocator: *mem.Allocator, prealloc_file: os.File, /// Call close when done. pub fn openPath(elf: *Elf, allocator: *mem.Allocator, path: []const u8) !void { @compileError("TODO implement"); } /// Call close when done. pub fn openFile(elf: *Elf, allocator: *mem.Allocator, file: os.File) !void { @compileError("TODO implement"); } pub fn openStream( elf: *Elf, allocator: *mem.Allocator, seekable_stream: *io.SeekableStream(anyerror, anyerror), in: *io.InStream(anyerror), ) !void { elf.auto_close_stream = false; elf.allocator = allocator; elf.seekable_stream = seekable_stream; elf.in_stream = in; var magic: [4]u8 = undefined; try in.readNoEof(magic[0..]); if (!mem.eql(u8, magic, "\x7fELF")) return error.InvalidFormat; elf.is_64 = switch (try in.readByte()) { 1 => false, 2 => true, else => return error.InvalidFormat, }; elf.endian = switch (try in.readByte()) { 1 => builtin.Endian.Little, 2 => builtin.Endian.Big, else => return error.InvalidFormat, }; const version_byte = try in.readByte(); if (version_byte != 1) return error.InvalidFormat; // skip over padding try seekable_stream.seekForward(9); elf.file_type = switch (try in.readInt(u16, elf.endian)) { 1 => FileType.Relocatable, 2 => FileType.Executable, 3 => FileType.Shared, 4 => FileType.Core, else => return error.InvalidFormat, }; elf.arch = switch (try in.readInt(u16, elf.endian)) { 0x02 => Arch.Sparc, 0x03 => Arch.x86, 0x08 => Arch.Mips, 0x14 => Arch.PowerPc, 0x28 => Arch.Arm, 0x2A => Arch.SuperH, 0x32 => Arch.IA_64, 0x3E => Arch.x86_64, 0xb7 => Arch.AArch64, else => return error.InvalidFormat, }; const elf_version = try in.readInt(u32, elf.endian); if (elf_version != 1) return error.InvalidFormat; if (elf.is_64) { elf.entry_addr = try in.readInt(u64, elf.endian); elf.program_header_offset = try in.readInt(u64, elf.endian); elf.section_header_offset = try in.readInt(u64, elf.endian); } else { elf.entry_addr = u64(try in.readInt(u32, elf.endian)); elf.program_header_offset = u64(try in.readInt(u32, elf.endian)); elf.section_header_offset = u64(try in.readInt(u32, elf.endian)); } // skip over flags try seekable_stream.seekForward(4); const header_size = try in.readInt(u16, elf.endian); if ((elf.is_64 and header_size != 64) or (!elf.is_64 and header_size != 52)) { return error.InvalidFormat; } const ph_entry_size = try in.readInt(u16, elf.endian); const ph_entry_count = try in.readInt(u16, elf.endian); const sh_entry_size = try in.readInt(u16, elf.endian); const sh_entry_count = try in.readInt(u16, elf.endian); elf.string_section_index = u64(try in.readInt(u16, elf.endian)); if (elf.string_section_index >= sh_entry_count) return error.InvalidFormat; const sh_byte_count = u64(sh_entry_size) * u64(sh_entry_count); const end_sh = try math.add(u64, elf.section_header_offset, sh_byte_count); const ph_byte_count = u64(ph_entry_size) * u64(ph_entry_count); const end_ph = try math.add(u64, elf.program_header_offset, ph_byte_count); const stream_end = try seekable_stream.getEndPos(); if (stream_end < end_sh or stream_end < end_ph) { return error.InvalidFormat; } try seekable_stream.seekTo(elf.section_header_offset); elf.section_headers = try elf.allocator.alloc(SectionHeader, sh_entry_count); errdefer elf.allocator.free(elf.section_headers); if (elf.is_64) { if (sh_entry_size != 64) return error.InvalidFormat; for (elf.section_headers) |*elf_section| { elf_section.name = try in.readInt(u32, elf.endian); elf_section.sh_type = try in.readInt(u32, elf.endian); elf_section.flags = try in.readInt(u64, elf.endian); elf_section.addr = try in.readInt(u64, elf.endian); elf_section.offset = try in.readInt(u64, elf.endian); elf_section.size = try in.readInt(u64, elf.endian); elf_section.link = try in.readInt(u32, elf.endian); elf_section.info = try in.readInt(u32, elf.endian); elf_section.addr_align = try in.readInt(u64, elf.endian); elf_section.ent_size = try in.readInt(u64, elf.endian); } } else { if (sh_entry_size != 40) return error.InvalidFormat; for (elf.section_headers) |*elf_section| { // TODO (multiple occurrences) allow implicit cast from %u32 -> %u64 ? elf_section.name = try in.readInt(u32, elf.endian); elf_section.sh_type = try in.readInt(u32, elf.endian); elf_section.flags = u64(try in.readInt(u32, elf.endian)); elf_section.addr = u64(try in.readInt(u32, elf.endian)); elf_section.offset = u64(try in.readInt(u32, elf.endian)); elf_section.size = u64(try in.readInt(u32, elf.endian)); elf_section.link = try in.readInt(u32, elf.endian); elf_section.info = try in.readInt(u32, elf.endian); elf_section.addr_align = u64(try in.readInt(u32, elf.endian)); elf_section.ent_size = u64(try in.readInt(u32, elf.endian)); } } for (elf.section_headers) |*elf_section| { if (elf_section.sh_type != SHT_NOBITS) { const file_end_offset = try math.add(u64, elf_section.offset, elf_section.size); if (stream_end < file_end_offset) return error.InvalidFormat; } } elf.string_section = &elf.section_headers[elf.string_section_index]; if (elf.string_section.sh_type != SHT_STRTAB) { // not a string table return error.InvalidFormat; } } pub fn close(elf: *Elf) void { elf.allocator.free(elf.section_headers); if (elf.auto_close_stream) elf.prealloc_file.close(); } pub fn findSection(elf: *Elf, name: []const u8) !?*SectionHeader { section_loop: for (elf.section_headers) |*elf_section| { if (elf_section.sh_type == SHT_NULL) continue; const name_offset = elf.string_section.offset + elf_section.name; try elf.seekable_stream.seekTo(name_offset); for (name) |expected_c| { const target_c = try elf.in_stream.readByte(); if (target_c == 0 or expected_c != target_c) continue :section_loop; } { const null_byte = try elf.in_stream.readByte(); if (null_byte == 0) return elf_section; } } return null; } pub fn seekToSection(elf: *Elf, elf_section: *SectionHeader) !void { try elf.seekable_stream.seekTo(elf_section.offset); } }; pub const EI_NIDENT = 16; pub const Elf32_Half = u16; pub const Elf64_Half = u16; pub const Elf32_Word = u32; pub const Elf32_Sword = i32; pub const Elf64_Word = u32; pub const Elf64_Sword = i32; pub const Elf32_Xword = u64; pub const Elf32_Sxword = i64; pub const Elf64_Xword = u64; pub const Elf64_Sxword = i64; pub const Elf32_Addr = u32; pub const Elf64_Addr = u64; pub const Elf32_Off = u32; pub const Elf64_Off = u64; pub const Elf32_Section = u16; pub const Elf64_Section = u16; pub const Elf32_Versym = Elf32_Half; pub const Elf64_Versym = Elf64_Half; pub const Elf32_Ehdr = extern struct { e_ident: [EI_NIDENT]u8, e_type: Elf32_Half, e_machine: Elf32_Half, e_version: Elf32_Word, e_entry: Elf32_Addr, e_phoff: Elf32_Off, e_shoff: Elf32_Off, e_flags: Elf32_Word, e_ehsize: Elf32_Half, e_phentsize: Elf32_Half, e_phnum: Elf32_Half, e_shentsize: Elf32_Half, e_shnum: Elf32_Half, e_shstrndx: Elf32_Half, }; pub const Elf64_Ehdr = extern struct { e_ident: [EI_NIDENT]u8, e_type: Elf64_Half, e_machine: Elf64_Half, e_version: Elf64_Word, e_entry: Elf64_Addr, e_phoff: Elf64_Off, e_shoff: Elf64_Off, e_flags: Elf64_Word, e_ehsize: Elf64_Half, e_phentsize: Elf64_Half, e_phnum: Elf64_Half, e_shentsize: Elf64_Half, e_shnum: Elf64_Half, e_shstrndx: Elf64_Half, }; pub const Elf32_Shdr = extern struct { sh_name: Elf32_Word, sh_type: Elf32_Word, sh_flags: Elf32_Word, sh_addr: Elf32_Addr, sh_offset: Elf32_Off, sh_size: Elf32_Word, sh_link: Elf32_Word, sh_info: Elf32_Word, sh_addralign: Elf32_Word, sh_entsize: Elf32_Word, }; pub const Elf64_Shdr = extern struct { sh_name: Elf64_Word, sh_type: Elf64_Word, sh_flags: Elf64_Xword, sh_addr: Elf64_Addr, sh_offset: Elf64_Off, sh_size: Elf64_Xword, sh_link: Elf64_Word, sh_info: Elf64_Word, sh_addralign: Elf64_Xword, sh_entsize: Elf64_Xword, }; pub const Elf32_Chdr = extern struct { ch_type: Elf32_Word, ch_size: Elf32_Word, ch_addralign: Elf32_Word, }; pub const Elf64_Chdr = extern struct { ch_type: Elf64_Word, ch_reserved: Elf64_Word, ch_size: Elf64_Xword, ch_addralign: Elf64_Xword, }; pub const Elf32_Sym = extern struct { st_name: Elf32_Word, st_value: Elf32_Addr, st_size: Elf32_Word, st_info: u8, st_other: u8, st_shndx: Elf32_Section, }; pub const Elf64_Sym = extern struct { st_name: Elf64_Word, st_info: u8, st_other: u8, st_shndx: Elf64_Section, st_value: Elf64_Addr, st_size: Elf64_Xword, }; pub const Elf32_Syminfo = extern struct { si_boundto: Elf32_Half, si_flags: Elf32_Half, }; pub const Elf64_Syminfo = extern struct { si_boundto: Elf64_Half, si_flags: Elf64_Half, }; pub const Elf32_Rel = extern struct { r_offset: Elf32_Addr, r_info: Elf32_Word, }; pub const Elf64_Rel = extern struct { r_offset: Elf64_Addr, r_info: Elf64_Xword, }; pub const Elf32_Rela = extern struct { r_offset: Elf32_Addr, r_info: Elf32_Word, r_addend: Elf32_Sword, }; pub const Elf64_Rela = extern struct { r_offset: Elf64_Addr, r_info: Elf64_Xword, r_addend: Elf64_Sxword, }; pub const Elf32_Phdr = extern struct { p_type: Elf32_Word, p_offset: Elf32_Off, p_vaddr: Elf32_Addr, p_paddr: Elf32_Addr, p_filesz: Elf32_Word, p_memsz: Elf32_Word, p_flags: Elf32_Word, p_align: Elf32_Word, }; pub const Elf64_Phdr = extern struct { p_type: Elf64_Word, p_flags: Elf64_Word, p_offset: Elf64_Off, p_vaddr: Elf64_Addr, p_paddr: Elf64_Addr, p_filesz: Elf64_Xword, p_memsz: Elf64_Xword, p_align: Elf64_Xword, }; pub const Elf32_Dyn = extern struct { d_tag: Elf32_Sword, d_un: extern union { d_val: Elf32_Word, d_ptr: Elf32_Addr, }, }; pub const Elf64_Dyn = extern struct { d_tag: Elf64_Sxword, d_un: extern union { d_val: Elf64_Xword, d_ptr: Elf64_Addr, }, }; pub const Elf32_Verdef = extern struct { vd_version: Elf32_Half, vd_flags: Elf32_Half, vd_ndx: Elf32_Half, vd_cnt: Elf32_Half, vd_hash: Elf32_Word, vd_aux: Elf32_Word, vd_next: Elf32_Word, }; pub const Elf64_Verdef = extern struct { vd_version: Elf64_Half, vd_flags: Elf64_Half, vd_ndx: Elf64_Half, vd_cnt: Elf64_Half, vd_hash: Elf64_Word, vd_aux: Elf64_Word, vd_next: Elf64_Word, }; pub const Elf32_Verdaux = extern struct { vda_name: Elf32_Word, vda_next: Elf32_Word, }; pub const Elf64_Verdaux = extern struct { vda_name: Elf64_Word, vda_next: Elf64_Word, }; pub const Elf32_Verneed = extern struct { vn_version: Elf32_Half, vn_cnt: Elf32_Half, vn_file: Elf32_Word, vn_aux: Elf32_Word, vn_next: Elf32_Word, }; pub const Elf64_Verneed = extern struct { vn_version: Elf64_Half, vn_cnt: Elf64_Half, vn_file: Elf64_Word, vn_aux: Elf64_Word, vn_next: Elf64_Word, }; pub const Elf32_Vernaux = extern struct { vna_hash: Elf32_Word, vna_flags: Elf32_Half, vna_other: Elf32_Half, vna_name: Elf32_Word, vna_next: Elf32_Word, }; pub const Elf64_Vernaux = extern struct { vna_hash: Elf64_Word, vna_flags: Elf64_Half, vna_other: Elf64_Half, vna_name: Elf64_Word, vna_next: Elf64_Word, }; pub const Elf32_auxv_t = extern struct { a_type: u32, a_un: extern union { a_val: u32, }, }; pub const Elf64_auxv_t = extern struct { a_type: u64, a_un: extern union { a_val: u64, }, }; pub const Elf32_Nhdr = extern struct { n_namesz: Elf32_Word, n_descsz: Elf32_Word, n_type: Elf32_Word, }; pub const Elf64_Nhdr = extern struct { n_namesz: Elf64_Word, n_descsz: Elf64_Word, n_type: Elf64_Word, }; pub const Elf32_Move = extern struct { m_value: Elf32_Xword, m_info: Elf32_Word, m_poffset: Elf32_Word, m_repeat: Elf32_Half, m_stride: Elf32_Half, }; pub const Elf64_Move = extern struct { m_value: Elf64_Xword, m_info: Elf64_Xword, m_poffset: Elf64_Xword, m_repeat: Elf64_Half, m_stride: Elf64_Half, }; pub const Elf32_gptab = extern union { gt_header: extern struct { gt_current_g_value: Elf32_Word, gt_unused: Elf32_Word, }, gt_entry: extern struct { gt_g_value: Elf32_Word, gt_bytes: Elf32_Word, }, }; pub const Elf32_RegInfo = extern struct { ri_gprmask: Elf32_Word, ri_cprmask: [4]Elf32_Word, ri_gp_value: Elf32_Sword, }; pub const Elf_Options = extern struct { kind: u8, size: u8, @"section": Elf32_Section, info: Elf32_Word, }; pub const Elf_Options_Hw = extern struct { hwp_flags1: Elf32_Word, hwp_flags2: Elf32_Word, }; pub const Elf32_Lib = extern struct { l_name: Elf32_Word, l_time_stamp: Elf32_Word, l_checksum: Elf32_Word, l_version: Elf32_Word, l_flags: Elf32_Word, }; pub const Elf64_Lib = extern struct { l_name: Elf64_Word, l_time_stamp: Elf64_Word, l_checksum: Elf64_Word, l_version: Elf64_Word, l_flags: Elf64_Word, }; pub const Elf32_Conflict = Elf32_Addr; pub const Elf_MIPS_ABIFlags_v0 = extern struct { version: Elf32_Half, isa_level: u8, isa_rev: u8, gpr_size: u8, cpr1_size: u8, cpr2_size: u8, fp_abi: u8, isa_ext: Elf32_Word, ases: Elf32_Word, flags1: Elf32_Word, flags2: Elf32_Word, }; pub const Auxv = switch (@sizeOf(usize)) { 4 => Elf32_auxv_t, 8 => Elf64_auxv_t, else => @compileError("expected pointer size of 32 or 64"), }; pub const Ehdr = switch (@sizeOf(usize)) { 4 => Elf32_Ehdr, 8 => Elf64_Ehdr, else => @compileError("expected pointer size of 32 or 64"), }; pub const Phdr = switch (@sizeOf(usize)) { 4 => Elf32_Phdr, 8 => Elf64_Phdr, else => @compileError("expected pointer size of 32 or 64"), }; pub const Shdr = switch (@sizeOf(usize)) { 4 => Elf32_Shdr, 8 => Elf64_Shdr, else => @compileError("expected pointer size of 32 or 64"), }; pub const Sym = switch (@sizeOf(usize)) { 4 => Elf32_Sym, 8 => Elf64_Sym, else => @compileError("expected pointer size of 32 or 64"), }; pub const Verdef = switch (@sizeOf(usize)) { 4 => Elf32_Verdef, 8 => Elf64_Verdef, else => @compileError("expected pointer size of 32 or 64"), }; pub const Verdaux = switch (@sizeOf(usize)) { 4 => Elf32_Verdaux, 8 => Elf64_Verdaux, else => @compileError("expected pointer size of 32 or 64"), };
std/elf.zig
const kernel = @import("../../kernel.zig"); const arch = kernel.arch; const Physical = kernel.arch.Physical; const page_size = kernel.arch.page_size; const AddressPair = kernel.Memory.AddressPair; /// Kernel pagetable before KPTI enabled pub var kernel_init_pagetable: [*]usize = undefined; // use optional type const log = kernel.log.scoped(.Virtual); const pagetable_t = [*]usize; const pte_t = usize; const MAXVA: usize = (1 << (9 + 9 + 9 + 12 - 1)); fn page_round_up(address: u64) u64 { return kernel.align_forward(address, kernel.arch.page_size); } fn page_round_down(address: u64) u64 { return kernel.align_backward(address, kernel.arch.page_size); } /// kernel_vm_init initialize the kernel_init_pagetable during initialization phase pub fn init() void { kernel.address_space.range.start = 0xf000_0000; kernel.address_space.range.end = 0x1000_0000; // Initialize the kernel pagetable const new_page = Physical.allocate1(1) orelse @panic("Failed to allocate kernel pagetable. Out of memory"); kernel.zero_a_page(new_page); kernel_init_pagetable = @intToPtr([*]usize, new_page); log.debug("mapping UART", .{}); // Map UART directMap( kernel_init_pagetable, arch.UART0, 1, arch.PTE_READ | arch.PTE_WRITE, false, ); log.debug("mapping kernel", .{}); directMap(kernel_init_pagetable, kernel.arch.Physical.kernel_region.address, kernel.arch.Physical.kernel_region.page_count, // TODO: PTE_EXEC can cause security issues arch.PTE_READ | arch.PTE_EXEC | arch.PTE_WRITE, false); // Map all free memory for (kernel.arch.Physical.available_regions) |region| { directMap(kernel_init_pagetable, region.descriptor.address, region.descriptor.page_count, // this can cause issues arch.PTE_READ | arch.PTE_WRITE, false); } for (kernel.arch.Physical.reserved_regions) |region| { if (kernel.arch.Physical.kernel_region.address == region.address) continue; log.debug("mapping region (0x{x}, {})", .{ region.address, region.page_count }); directMap( kernel_init_pagetable, region.address, region.page_count, // this can cause issues arch.PTE_READ, false, ); } enablePaging(); log.debug("enabled paging", .{}); var total_allocated_page_count: u64 = 0; for (Physical.available_regions) |region| { total_allocated_page_count += region.allocated_page_count; } log.debug("Total page count allocated for mapping: {}", .{total_allocated_page_count}); } /// enable_paging setup paging for initialization-time paging pub fn enablePaging() void { //logger.debug("Enabling paging for pagetable at 0x{x:0>16}", .{@ptrToInt(pagetable)}); // Set CSR satp arch.SATP.write(arch.MAKE_SATP(@ptrToInt(kernel_init_pagetable))); // for safety arch.flush_tlb(); } /// directMap map the physical memory to virtual memory /// the start and the end must be page start pub fn directMap(pagetable: pagetable_t, start: usize, page_count: usize, permission: usize, allow_remap: bool) void { map_pages(pagetable, start, start, page_count, permission, allow_remap); } pub fn map(start: u64, page_count: u64) void { directMap(kernel_init_pagetable, start, page_count, arch.PTE_READ | arch.PTE_WRITE, false); } fn map_pages(pagetable: pagetable_t, virtual_addr: usize, physical_addr: usize, page_count: usize, permission: usize, allow_remap: bool) void { kernel.assert(@src(), page_count != 0); kernel.assert(@src(), kernel.is_aligned(virtual_addr, page_size)); kernel.assert(@src(), kernel.is_aligned(physical_addr, page_size)); // Security check for permission if (permission & ~(arch.PTE_FLAG_MASK) != 0) { // logger.err("Illegal permission, [permission] = {x:0>16}", .{permission}); @panic("illegal permission"); } var page_i: u64 = 0; var virtual_page = virtual_addr; var physical_page = physical_addr; while (page_i < page_count) : ({ virtual_page += arch.page_size; physical_page += arch.page_size; page_i += 1; }) { const optional_pte = walk(pagetable, virtual_page, true); if (optional_pte) |pte| { // Existing entry if ((@intToPtr(*usize, pte).* & arch.PTE_VALID != 0) and !allow_remap) { //logger.err("mapping pages failed, [virtual_addr] = 0x{x:0>16}, [physical_addr] = 0x{x:0>16}, [size] = {d}", .{ virtual_page, physical_page, size }); @panic("mapping pages failed 1"); } // Map a physical to virtual page @intToPtr(*usize, pte).* = arch.PA_TO_PTE(physical_page) | permission | arch.PTE_VALID; } else { // Walk is going wrong somewhere @panic("mapping pages failed 2"); } } } /// walk is used to find the corresponding physical address of certain virtual address /// allocate a new page if required fn walk(pagetable: pagetable_t, virtual_addr: usize, alloc: bool) ?pte_t { // Safety check if (virtual_addr >= MAXVA) { //logger.err("Virtual address overflow: [virtual_addr] = 0x{x:0>16}", .{virtual_addr}); @panic("walk: virtual_addr overflow"); } var level: usize = 2; var pg_iter: pagetable_t = pagetable; while (level > 0) : (level -= 1) { const index = arch.PAGE_INDEX(level, virtual_addr); const pte: *usize = &pg_iter[index]; if (pte.* & arch.PTE_VALID != 0) { // Next level if valid pg_iter = @intToPtr([*]usize, arch.PTE_TO_PA(pte.*)); } else { if (alloc) { // Allocate a new page if not valid and need to allocate // This already identity maps the page as it has to zero the page out if (Physical.allocate1(1)) |page_physical| { kernel.zero_a_page(kernel.arch.Virtual.AddressSpace.physical_to_virtual(page_physical)); pg_iter = @intToPtr([*]usize, page_physical); pte.* = arch.PA_TO_PTE(page_physical) | arch.PTE_VALID; } else { //logger.err("allocate pagetable physical memory failed", .{}); @panic("Out of memory"); } } else { return null; } } } const index = arch.PAGE_INDEX(0, virtual_addr); return @ptrToInt(&pg_iter[index]); } /// translate_addr translate a virtual address to a physical address pub fn translate_addr(pagetable: pagetable_t, virtual_addr: usize) ?usize { const optional_pte = walk(pagetable, virtual_addr, false); if (optional_pte) |pte| { return arch.PTE_TO_PA(@intToPtr(*usize, pte).*); } else return null; } /// vmprint print out the pagetable /// for debug usage pub fn vmprint(pagetable: pagetable_t) void { //logger.debug("page table 0x{x}", .{@ptrToInt(pagetable)}); if (@ptrToInt(pagetable) == 0) { @panic("null pagetable"); } const prefix = "|| || ||"; vmprint_walk(pagetable, 0, prefix); } fn vmprint_walk(pagetable: pagetable_t, level: usize, prefix: []const u8) void { // SV39 512 entry per block var i: usize = 0; while (i < 512) : (i += 1) { const pte: pte_t = pagetable[i]; if (pte & arch.PTE_VALID == 0) { continue; } if (pte & (arch.PTE_READ | arch.PTE_WRITE | arch.PTE_EXEC) == 0) { // points to a lower-level page table const child = arch.PTE_TO_PA(pte); // Recurring vmprint_walk(@intToPtr([*]usize, child), level + 1, prefix); } } } pub const Range = struct { start: u64, end: u64, }; pub const Region = struct {}; pub const AddressSpace = struct { arch: arch.AddressSpace, range: Range, lock: kernel.Spinlock, pub fn allocate(self: *@This(), size: u64, flags: u32) ?AddressPair { self.lock.acquire(); defer self.lock.release(); const reserved = self.reserve(size, flags) orelse return null; // TODO: commit return reserved; } pub fn reserve(self: *@This(), size: u64, flags: u32) ?AddressPair { _ = flags; const needed_page_count = kernel.bytes_to_pages(size); if (needed_page_count == 0) @panic("Reserved called without needing memory"); kernel.assert(@src(), self.lock.is_locked()); // TODO: This is wrong in so many ways const physical = Physical.allocate(needed_page_count) orelse return null; return AddressPair{ .physical = physical, .virtual = physical_to_virtual(physical), }; } // TODO: pub fn physical_to_virtual(physical: u64) u64 { return physical; } // TODO: pub fn virtual_to_physical(virtual: u64) u64 { return virtual; } };
src/kernel/arch/riscv64/virtual.zig
const std = @import("std"); const shared = @import("../shared.zig"); const lib = @import("../../main.zig"); const js = @import("js.zig"); const lasting_allocator = lib.internal.lasting_allocator; const EventType = shared.BackendEventType; pub const GuiWidget = struct { userdata: usize = 0, object: usize = 0, element: js.ElementId = 0, /// Only works for buttons clickHandler: ?fn (data: usize) void = null, mouseButtonHandler: ?fn (button: MouseButton, pressed: bool, x: u32, y: u32, data: usize) void = null, keyTypeHandler: ?fn (str: []const u8, data: usize) void = null, scrollHandler: ?fn (dx: f32, dy: f32, data: usize) void = null, resizeHandler: ?fn (width: u32, height: u32, data: usize) void = null, /// Only works for canvas (althought technically it isn't required to) drawHandler: ?fn (ctx: Canvas.DrawContext, data: usize) void = null, changedTextHandler: ?fn (data: usize) void = null, processEventFn: fn (object: usize, event: js.EventId) void, pub fn init(comptime T: type, allocator: *std.mem.Allocator, name: []const u8) !*GuiWidget { const self = try allocator.create(GuiWidget); self.* = .{ .processEventFn = T.processEvent, .element = js.createElement(name) }; return self; } }; pub const MessageType = enum { Information, Warning, Error }; pub fn showNativeMessageDialog(msgType: MessageType, comptime fmt: []const u8, args: anytype) void { const msg = std.fmt.allocPrintZ(lib.internal.scratch_allocator, fmt, args) catch { std.log.err("Could not launch message dialog, original text: " ++ fmt, args); return; }; defer lib.internal.scratch_allocator.free(msg); std.log.info("native message dialog (TODO): ({}) {s}", .{ msgType, msg }); } pub const PeerType = *GuiWidget; pub const MouseButton = enum { Left, Middle, Right }; pub fn init() !void { // TODO } var globalWindow: ?*Window = null; pub const Window = struct { child: ?PeerType = null, pub fn create() !Window { return Window{}; } pub fn show(self: *Window) void { // TODO: handle multiple windows if (globalWindow != null) { js.print("one window already showed!"); return; } globalWindow = self; } pub fn resize(_: *Window, _: c_int, _: c_int) void { // TODO } pub fn setChild(self: *Window, peer: ?PeerType) void { if (peer) |p| { js.setRoot(p.element); self.child = peer; } else { // TODO: js.clearRoot(); } } }; pub fn Events(comptime T: type) type { return struct { const Self = @This(); pub fn setupEvents() !void {} pub inline fn setUserData(self: *T, data: anytype) void { comptime { if (!std.meta.trait.isSingleItemPtr(@TypeOf(data))) { @compileError(std.fmt.comptimePrint("Expected single item pointer, got {s}", .{@typeName(@TypeOf(data))})); } } self.peer.userdata = @ptrToInt(data); self.peer.object = @ptrToInt(self); } pub inline fn setCallback(self: *T, comptime eType: EventType, cb: anytype) !void { _ = cb; _ = self; //const data = getEventUserData(self.peer); switch (eType) { .Click => self.peer.clickHandler = cb, .Draw => self.peer.drawHandler = cb, .MouseButton => {}, .Scroll => {}, .TextChanged => self.peer.changedTextHandler = cb, .Resize => { self.peer.resizeHandler = cb; self.requestDraw() catch {}; }, .KeyType => {}, } } pub fn setOpacity(self: *T, opacity: f64) void { _ = self; _ = opacity; } /// Requests a redraw pub fn requestDraw(self: *T) !void { _ = self; js.print("request draw"); if (@hasDecl(T, "_requestDraw")) { try self._requestDraw(); } } pub fn processEvent(object: usize, event: js.EventId) void { const self = @intToPtr(*T, object); if (js.getEventTarget(event) == self.peer.element) { // handle event switch (js.getEventType(event)) { .OnClick => { if (self.peer.clickHandler) |handler| { handler(self.peer.userdata); } }, .TextChange => { if (self.peer.changedTextHandler) |handler| { handler(self.peer.userdata); } }, .Resize => unreachable, } } else if (T == Container) { // if we're a container, iterate over our children to propagate the event for (self.children.items) |child| { child.processEventFn(child.object, event); } } } pub fn getWidth(self: *const T) c_int { return std.math.max(10, js.getWidth(self.peer.element)); } pub fn getHeight(self: *const T) c_int { return std.math.max(10, js.getHeight(self.peer.element)); } pub fn deinit(self: *const T) void { // TODO: actually remove the element _ = self; @panic("TODO"); } }; } pub const TextField = struct { peer: *GuiWidget, pub usingnamespace Events(TextField); pub fn create() !TextField { return TextField{ .peer = try GuiWidget.init(TextField, lasting_allocator, "input") }; } pub fn setText(self: *TextField, text: []const u8) void { js.setText(self.peer.element, text.ptr, text.len); } pub fn getText(self: *TextField) [:0]const u8 { const len = js.getTextLen(self.peer.element); // TODO: fix the obvious memory leak const text = lasting_allocator.allocSentinel(u8, len, 0) catch unreachable; js.getText(self.peer.element, text.ptr); return text; } }; pub const Label = struct { peer: *GuiWidget, pub usingnamespace Events(Label); pub fn create() !Label { return Label{ .peer = try GuiWidget.init(Label, lasting_allocator, "span") }; } pub fn setAlignment(_: *Label, _: f32) void {} pub fn setText(self: *Label, text: [:0]const u8) void { js.setText(self.peer.element, text.ptr, text.len); } pub fn getText(_: *Label) [:0]const u8 { return undefined; } }; pub const Button = struct { peer: *GuiWidget, pub usingnamespace Events(Button); pub fn create() !Button { return Button{ .peer = try GuiWidget.init(Button, lasting_allocator, "button") }; } pub fn setLabel(self: *Button, label: [:0]const u8) void { js.setText(self.peer.element, label.ptr, label.len); _ = self; _ = label; } pub fn getLabel(_: *Button) [:0]const u8 { return undefined; } }; pub const Canvas = struct { peer: *GuiWidget, pub usingnamespace Events(Canvas); pub const DrawContext = struct { ctx: js.CanvasContextId, pub fn setColor(self: *const DrawContext, r: f32, g: f32, b: f32) void { self.setColorRGBA(r, g, b, 1); } pub fn setColorRGBA(self: *const DrawContext, r: f32, g: f32, b: f32, a: f32) void { js.setColor(self.ctx, @floatToInt(u8, r * 255), @floatToInt(u8, g * 255), @floatToInt(u8, b * 255), @floatToInt(u8, a * 255)); } pub fn rectangle(self: *const DrawContext, x: u32, y: u32, w: u32, h: u32) void { js.rectPath(self.ctx, x, y, w, h); } pub fn line(self: *const DrawContext, x1: u32, y1: u32, x2: u32, y2: u32) void { js.moveTo(self.ctx, x1, y1); js.lineTo(self.ctx, x2, y2); js.stroke(self.ctx); } pub fn ellipse(self: *const DrawContext, x: u32, y: u32, w: f32, h: f32) void { // TODO _ = self; _ = x; _ = y; _ = w; _ = h; } pub fn stroke(self: *const DrawContext) void { js.stroke(self.ctx); } pub fn fill(self: *const DrawContext) void { js.fill(self.ctx); } }; pub fn create() !Canvas { return Canvas{ .peer = try GuiWidget.init(Canvas, lasting_allocator, "canvas") }; } pub fn _requestDraw(self: *Canvas) !void { const ctxId = js.openContext(self.peer.element); const ctx = DrawContext{ .ctx = ctxId }; if (self.peer.drawHandler) |handler| { handler(ctx, self.peer.userdata); } } }; pub const Container = struct { peer: *GuiWidget, children: std.ArrayList(*GuiWidget), pub usingnamespace Events(Container); pub fn create() !Container { return Container{ .peer = try GuiWidget.init(Container, lasting_allocator, "div"), .children = std.ArrayList(*GuiWidget).init(lasting_allocator), }; } pub fn add(self: *Container, peer: PeerType) void { js.appendElement(self.peer.element, peer.element); self.children.append(peer) catch unreachable; } pub fn move(self: *const Container, peer: PeerType, x: u32, y: u32) void { _ = self; js.setPos(peer.element, x, y); } pub fn resize(self: *const Container, peer: PeerType, w: u32, h: u32) void { _ = self; js.setSize(peer.element, w, h); if (peer.resizeHandler) |handler| { handler(w, h, peer.userdata); } } }; pub fn milliTimestamp() i64 { return @floatToInt(i64, @floor(js.now())); } fn executeMain() anyerror!void { try mainFn(); } const mainFn = @import("root").main; var frame: @Frame(executeMain) = undefined; var result: anyerror!void = error.None; var suspending: bool = false; var resumePtr: anyframe = undefined; pub const backendExport = struct { pub const os = struct { pub const system = struct { pub const E = enum(u8) { SUCCESS = 0, INVAL = 1, INTR = 2, FAULT = 3, }; pub const timespec = struct { tv_sec: isize, tv_nsec: isize }; pub fn getErrno(r: usize) E { if (r & ~@as(usize, 0xFF) == ~@as(usize, 0xFF)) { return @intToEnum(E, r & 0xFF); } else { return E.SUCCESS; } } pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize { _ = rem; const ms = @intCast(u64, req.tv_sec) * 1000 + @intCast(u64, req.tv_nsec) / 1000; sleep(ms); return 0; } }; }; /// Precision DEFINITELY not guarenteed (can have up to 20ms delays) pub fn sleep(duration: u64) void { const start = milliTimestamp(); while (milliTimestamp() < start + @intCast(i64, duration)) { suspending = true; suspend { resumePtr = @frame(); } } } pub fn panic(msg: []const u8, _: ?*std.builtin.StackTrace) noreturn { js.print(msg); @breakpoint(); while (true) {} } pub export fn _start() callconv(.C) void { _ = @asyncCall(&frame, &result, executeMain, .{}); } pub export fn _zgtContinue() callconv(.C) void { if (suspending) { suspending = false; resume resumePtr; } } }; pub fn runStep(step: shared.EventLoopStep) callconv(.Async) bool { _ = step; while (js.hasEvent()) { const eventId = js.popEvent(); switch (js.getEventType(eventId)) { .Resize => { if (globalWindow) |window| { if (window.child) |child| { child.resizeHandler.?(0, 0, child.userdata); } } }, else => { if (globalWindow) |window| { if (window.child) |child| { child.processEventFn(child.object, eventId); } } }, } } suspending = true; suspend { resumePtr = @frame(); } return true; }
src/backends/wasm/backend.zig
const is_test = @import("builtin").is_test; const std = @import("std"); const math = std.math; const Log2Int = std.math.Log2Int; const maxInt = std.math.maxInt; const minInt = std.math.minInt; const DBG = false; pub fn fixint(comptime fp_t: type, comptime fixint_t: type, a: fp_t) fixint_t { @setRuntimeSafety(is_test); const rep_t = switch (fp_t) { f32 => u32, f64 => u64, f128 => u128, else => unreachable, }; const significandBits = switch (fp_t) { f32 => 23, f64 => 52, f128 => 112, else => unreachable, }; const typeWidth = rep_t.bit_count; const exponentBits = (typeWidth - significandBits - 1); const signBit = (@as(rep_t, 1) << (significandBits + exponentBits)); const maxExponent = ((1 << exponentBits) - 1); const exponentBias = (maxExponent >> 1); const implicitBit = (@as(rep_t, 1) << significandBits); const significandMask = (implicitBit - 1); // Break a into sign, exponent, significand const aRep: rep_t = @bitCast(rep_t, a); const absMask = signBit - 1; const aAbs: rep_t = aRep & absMask; const negative = (aRep & signBit) != 0; const exponent = @intCast(i32, aAbs >> significandBits) - exponentBias; const significand: rep_t = (aAbs & significandMask) | implicitBit; // If exponent is negative, the uint_result is zero. if (exponent < 0) return 0; // The unsigned result needs to be large enough to handle an fixint_t or rep_t const fixuint_t = std.meta.Int(false, fixint_t.bit_count); const UintResultType = if (fixint_t.bit_count > rep_t.bit_count) fixuint_t else rep_t; var uint_result: UintResultType = undefined; // If the value is too large for the integer type, saturate. if (@intCast(usize, exponent) >= fixint_t.bit_count) { return if (negative) @as(fixint_t, minInt(fixint_t)) else @as(fixint_t, maxInt(fixint_t)); } // If 0 <= exponent < significandBits, right shift else left shift if (exponent < significandBits) { uint_result = @intCast(UintResultType, significand) >> @intCast(Log2Int(UintResultType), significandBits - exponent); } else { uint_result = @intCast(UintResultType, significand) << @intCast(Log2Int(UintResultType), exponent - significandBits); } // Cast to final signed result if (negative) { return if (uint_result >= -math.minInt(fixint_t)) math.minInt(fixint_t) else -@intCast(fixint_t, uint_result); } else { return if (uint_result >= math.maxInt(fixint_t)) math.maxInt(fixint_t) else @intCast(fixint_t, uint_result); } } test "import fixint" { _ = @import("fixint_test.zig"); }
lib/std/special/compiler_rt/fixint.zig
const Object = @This(); const std = @import("std"); const assert = std.debug.assert; const dwarf = std.dwarf; const fs = std.fs; const io = std.io; const log = std.log.scoped(.object); const macho = std.macho; const mem = std.mem; const reloc = @import("reloc.zig"); const Allocator = mem.Allocator; const Relocation = reloc.Relocation; const Symbol = @import("Symbol.zig"); const parseName = @import("Zld.zig").parseName; usingnamespace @import("commands.zig"); allocator: *Allocator, arch: ?std.Target.Cpu.Arch = null, header: ?macho.mach_header_64 = null, file: ?fs.File = null, file_offset: ?u32 = null, name: ?[]const u8 = null, load_commands: std.ArrayListUnmanaged(LoadCommand) = .{}, sections: std.ArrayListUnmanaged(Section) = .{}, segment_cmd_index: ?u16 = null, symtab_cmd_index: ?u16 = null, dysymtab_cmd_index: ?u16 = null, build_version_cmd_index: ?u16 = null, data_in_code_cmd_index: ?u16 = null, text_section_index: ?u16 = null, mod_init_func_section_index: ?u16 = null, // __DWARF segment sections dwarf_debug_info_index: ?u16 = null, dwarf_debug_abbrev_index: ?u16 = null, dwarf_debug_str_index: ?u16 = null, dwarf_debug_line_index: ?u16 = null, dwarf_debug_ranges_index: ?u16 = null, symbols: std.ArrayListUnmanaged(*Symbol) = .{}, initializers: std.ArrayListUnmanaged(*Symbol) = .{}, data_in_code_entries: std.ArrayListUnmanaged(macho.data_in_code_entry) = .{}, tu_path: ?[]const u8 = null, tu_mtime: ?u64 = null, pub const Section = struct { inner: macho.section_64, code: []u8, relocs: ?[]*Relocation, pub fn deinit(self: *Section, allocator: *Allocator) void { allocator.free(self.code); if (self.relocs) |relocs| { for (relocs) |rel| { allocator.destroy(rel); } allocator.free(relocs); } } }; const DebugInfo = struct { inner: dwarf.DwarfInfo, debug_info: []u8, debug_abbrev: []u8, debug_str: []u8, debug_line: []u8, debug_ranges: []u8, pub fn parseFromObject(allocator: *Allocator, object: *const Object) !?DebugInfo { var debug_info = blk: { const index = object.dwarf_debug_info_index orelse return null; break :blk try object.readSection(allocator, index); }; var debug_abbrev = blk: { const index = object.dwarf_debug_abbrev_index orelse return null; break :blk try object.readSection(allocator, index); }; var debug_str = blk: { const index = object.dwarf_debug_str_index orelse return null; break :blk try object.readSection(allocator, index); }; var debug_line = blk: { const index = object.dwarf_debug_line_index orelse return null; break :blk try object.readSection(allocator, index); }; var debug_ranges = blk: { if (object.dwarf_debug_ranges_index) |ind| { break :blk try object.readSection(allocator, ind); } break :blk try allocator.alloc(u8, 0); }; var inner: dwarf.DwarfInfo = .{ .endian = .Little, .debug_info = debug_info, .debug_abbrev = debug_abbrev, .debug_str = debug_str, .debug_line = debug_line, .debug_ranges = debug_ranges, }; try dwarf.openDwarfDebugInfo(&inner, allocator); return DebugInfo{ .inner = inner, .debug_info = debug_info, .debug_abbrev = debug_abbrev, .debug_str = debug_str, .debug_line = debug_line, .debug_ranges = debug_ranges, }; } pub fn deinit(self: *DebugInfo, allocator: *Allocator) void { allocator.free(self.debug_info); allocator.free(self.debug_abbrev); allocator.free(self.debug_str); allocator.free(self.debug_line); allocator.free(self.debug_ranges); self.inner.abbrev_table_list.deinit(); self.inner.compile_unit_list.deinit(); self.inner.func_list.deinit(); } }; pub fn init(allocator: *Allocator) Object { return .{ .allocator = allocator, }; } pub fn deinit(self: *Object) void { for (self.load_commands.items) |*lc| { lc.deinit(self.allocator); } self.load_commands.deinit(self.allocator); for (self.sections.items) |*sect| { sect.deinit(self.allocator); } self.sections.deinit(self.allocator); for (self.symbols.items) |sym| { sym.deinit(self.allocator); self.allocator.destroy(sym); } self.symbols.deinit(self.allocator); self.data_in_code_entries.deinit(self.allocator); self.initializers.deinit(self.allocator); if (self.name) |n| { self.allocator.free(n); } if (self.tu_path) |tu_path| { self.allocator.free(tu_path); } } pub fn closeFile(self: Object) void { if (self.file) |f| { f.close(); } } pub fn parse(self: *Object) !void { var reader = self.file.?.reader(); if (self.file_offset) |offset| { try reader.context.seekTo(offset); } self.header = try reader.readStruct(macho.mach_header_64); if (self.header.?.filetype != macho.MH_OBJECT) { log.err("invalid filetype: expected 0x{x}, found 0x{x}", .{ macho.MH_OBJECT, self.header.?.filetype }); return error.MalformedObject; } const this_arch: std.Target.Cpu.Arch = switch (self.header.?.cputype) { macho.CPU_TYPE_ARM64 => .aarch64, macho.CPU_TYPE_X86_64 => .x86_64, else => |value| { log.err("unsupported cpu architecture 0x{x}", .{value}); return error.UnsupportedCpuArchitecture; }, }; if (this_arch != self.arch.?) { log.err("mismatched cpu architecture: expected {s}, found {s}", .{ self.arch.?, this_arch }); return error.MismatchedCpuArchitecture; } try self.readLoadCommands(reader); try self.parseSymbols(); try self.parseSections(); try self.parseDataInCode(); try self.parseInitializers(); try self.parseDebugInfo(); } pub fn readLoadCommands(self: *Object, reader: anytype) !void { const offset = self.file_offset orelse 0; try self.load_commands.ensureCapacity(self.allocator, self.header.?.ncmds); var i: u16 = 0; while (i < self.header.?.ncmds) : (i += 1) { var cmd = try LoadCommand.read(self.allocator, reader); switch (cmd.cmd()) { macho.LC_SEGMENT_64 => { self.segment_cmd_index = i; var seg = cmd.Segment; for (seg.sections.items) |*sect, j| { const index = @intCast(u16, j); const segname = parseName(&sect.segname); const sectname = parseName(&sect.sectname); if (mem.eql(u8, segname, "__DWARF")) { if (mem.eql(u8, sectname, "__debug_info")) { self.dwarf_debug_info_index = index; } else if (mem.eql(u8, sectname, "__debug_abbrev")) { self.dwarf_debug_abbrev_index = index; } else if (mem.eql(u8, sectname, "__debug_str")) { self.dwarf_debug_str_index = index; } else if (mem.eql(u8, sectname, "__debug_line")) { self.dwarf_debug_line_index = index; } else if (mem.eql(u8, sectname, "__debug_ranges")) { self.dwarf_debug_ranges_index = index; } } else if (mem.eql(u8, segname, "__TEXT")) { if (mem.eql(u8, sectname, "__text")) { self.text_section_index = index; } } else if (mem.eql(u8, segname, "__DATA")) { if (mem.eql(u8, sectname, "__mod_init_func")) { self.mod_init_func_section_index = index; } } sect.offset += offset; if (sect.reloff > 0) { sect.reloff += offset; } } seg.inner.fileoff += offset; }, macho.LC_SYMTAB => { self.symtab_cmd_index = i; cmd.Symtab.symoff += offset; cmd.Symtab.stroff += offset; }, macho.LC_DYSYMTAB => { self.dysymtab_cmd_index = i; }, macho.LC_BUILD_VERSION => { self.build_version_cmd_index = i; }, macho.LC_DATA_IN_CODE => { self.data_in_code_cmd_index = i; cmd.LinkeditData.dataoff += offset; }, else => { log.debug("Unknown load command detected: 0x{x}.", .{cmd.cmd()}); }, } self.load_commands.appendAssumeCapacity(cmd); } } pub fn parseSections(self: *Object) !void { const seg = self.load_commands.items[self.segment_cmd_index.?].Segment; log.debug("parsing sections in {s}", .{self.name.?}); try self.sections.ensureCapacity(self.allocator, seg.sections.items.len); for (seg.sections.items) |sect| { log.debug("parsing section '{s},{s}'", .{ parseName(&sect.segname), parseName(&sect.sectname) }); // Read sections' code var code = try self.allocator.alloc(u8, sect.size); _ = try self.file.?.preadAll(code, sect.offset); var section = Section{ .inner = sect, .code = code, .relocs = null, }; // Parse relocations if (sect.nreloc > 0) { var raw_relocs = try self.allocator.alloc(u8, @sizeOf(macho.relocation_info) * sect.nreloc); defer self.allocator.free(raw_relocs); _ = try self.file.?.preadAll(raw_relocs, sect.reloff); section.relocs = try reloc.parse( self.allocator, self.arch.?, section.code, mem.bytesAsSlice(macho.relocation_info, raw_relocs), self.symbols.items, ); } self.sections.appendAssumeCapacity(section); } } pub fn parseInitializers(self: *Object) !void { const index = self.mod_init_func_section_index orelse return; const section = self.sections.items[index]; log.debug("parsing initializers in {s}", .{self.name.?}); // Parse C++ initializers const relocs = section.relocs orelse unreachable; try self.initializers.ensureCapacity(self.allocator, relocs.len); for (relocs) |rel| { self.initializers.appendAssumeCapacity(rel.target.symbol); } mem.reverse(*Symbol, self.initializers.items); } pub fn parseSymbols(self: *Object) !void { const index = self.symtab_cmd_index orelse return; const symtab_cmd = self.load_commands.items[index].Symtab; var symtab = try self.allocator.alloc(u8, @sizeOf(macho.nlist_64) * symtab_cmd.nsyms); defer self.allocator.free(symtab); _ = try self.file.?.preadAll(symtab, symtab_cmd.symoff); const slice = @alignCast(@alignOf(macho.nlist_64), mem.bytesAsSlice(macho.nlist_64, symtab)); var strtab = try self.allocator.alloc(u8, symtab_cmd.strsize); defer self.allocator.free(strtab); _ = try self.file.?.preadAll(strtab, symtab_cmd.stroff); for (slice) |sym| { const sym_name = mem.spanZ(@ptrCast([*:0]const u8, strtab.ptr + sym.n_strx)); if (Symbol.isStab(sym)) { log.err("stab {s} in {s}", .{ sym_name, self.name.? }); return error.UnhandledSymbolType; } if (Symbol.isIndr(sym)) { log.err("indirect symbol {s} in {s}", .{ sym_name, self.name.? }); return error.UnhandledSymbolType; } if (Symbol.isAbs(sym)) { log.err("absolute symbol {s} in {s}", .{ sym_name, self.name.? }); return error.UnhandledSymbolType; } const name = try self.allocator.dupe(u8, sym_name); const symbol: *Symbol = symbol: { if (Symbol.isSect(sym)) { const linkage: Symbol.Regular.Linkage = linkage: { if (!Symbol.isExt(sym)) break :linkage .translation_unit; if (Symbol.isWeakDef(sym) or Symbol.isPext(sym)) break :linkage .linkage_unit; break :linkage .global; }; const regular = try self.allocator.create(Symbol.Regular); errdefer self.allocator.destroy(regular); regular.* = .{ .base = .{ .@"type" = .regular, .name = name, }, .linkage = linkage, .address = sym.n_value, .section = sym.n_sect - 1, .weak_ref = Symbol.isWeakRef(sym), .file = self, }; break :symbol &regular.base; } if (sym.n_value != 0) { log.err("common symbol {s} in {s}", .{ sym_name, self.name.? }); return error.UnhandledSymbolType; // const comm_size = sym.n_value; // const comm_align = (sym.n_desc >> 8) & 0x0f; // log.warn("Common symbol: size 0x{x}, align 0x{x}", .{ comm_size, comm_align }); } const undef = try self.allocator.create(Symbol.Unresolved); errdefer self.allocator.destroy(undef); undef.* = .{ .base = .{ .@"type" = .unresolved, .name = name, }, .file = self, }; break :symbol &undef.base; }; try self.symbols.append(self.allocator, symbol); } } pub fn parseDebugInfo(self: *Object) !void { var debug_info = blk: { var di = try DebugInfo.parseFromObject(self.allocator, self); break :blk di orelse return; }; defer debug_info.deinit(self.allocator); log.debug("parsing debug info in '{s}'", .{self.name.?}); // We assume there is only one CU. const compile_unit = debug_info.inner.findCompileUnit(0x0) catch |err| switch (err) { error.MissingDebugInfo => { // TODO audit cases with missing debug info and audit our dwarf.zig module. log.debug("invalid or missing debug info in {s}; skipping", .{self.name.?}); return; }, else => |e| return e, }; const name = try compile_unit.die.getAttrString(&debug_info.inner, dwarf.AT_name); const comp_dir = try compile_unit.die.getAttrString(&debug_info.inner, dwarf.AT_comp_dir); self.tu_path = try std.fs.path.join(self.allocator, &[_][]const u8{ comp_dir, name }); self.tu_mtime = mtime: { var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; const stat = try self.file.?.stat(); break :mtime @intCast(u64, @divFloor(stat.mtime, 1_000_000_000)); }; for (self.symbols.items) |sym| { if (sym.cast(Symbol.Regular)) |reg| { const size: u64 = blk: for (debug_info.inner.func_list.items) |func| { if (func.pc_range) |range| { if (reg.address >= range.start and reg.address < range.end) { break :blk range.end - range.start; } } } else 0; reg.stab = .{ .kind = kind: { if (size > 0) break :kind .function; switch (reg.linkage) { .translation_unit => break :kind .static, else => break :kind .global, } }, .size = size, }; } } } fn readSection(self: Object, allocator: *Allocator, index: u16) ![]u8 { const seg = self.load_commands.items[self.segment_cmd_index.?].Segment; const sect = seg.sections.items[index]; var buffer = try allocator.alloc(u8, sect.size); _ = try self.file.?.preadAll(buffer, sect.offset); return buffer; } pub fn parseDataInCode(self: *Object) !void { const index = self.data_in_code_cmd_index orelse return; const data_in_code = self.load_commands.items[index].LinkeditData; var buffer = try self.allocator.alloc(u8, data_in_code.datasize); defer self.allocator.free(buffer); _ = try self.file.?.preadAll(buffer, data_in_code.dataoff); var stream = io.fixedBufferStream(buffer); var reader = stream.reader(); while (true) { const dice = reader.readStruct(macho.data_in_code_entry) catch |err| switch (err) { error.EndOfStream => break, else => |e| return e, }; try self.data_in_code_entries.append(self.allocator, dice); } } pub fn isObject(file: fs.File) !bool { const header = try file.reader().readStruct(macho.mach_header_64); try file.seekTo(0); return header.filetype == macho.MH_OBJECT; }
src/link/MachO/Object.zig
const fmath = @import("index.zig"); pub fn log(x: var) -> @typeOf(x) { const T = @typeOf(x); switch (T) { f32 => @inlineCall(logf, x), f64 => @inlineCall(logd, x), else => @compileError("log not implemented for " ++ @typeName(T)), } } fn logf(x_: f32) -> f32 { const ln2_hi: f32 = 6.9313812256e-01; const ln2_lo: f32 = 9.0580006145e-06; const Lg1: f32 = 0xaaaaaa.0p-24; const Lg2: f32 = 0xccce13.0p-25; const Lg3: f32 = 0x91e9ee.0p-25; const Lg4: f32 = 0xf89e26.0p-26; var x = x_; var ix = @bitCast(u32, x); var k: i32 = 0; // x < 2^(-126) if (ix < 0x00800000 or ix >> 31 != 0) { // log(+-0) = -inf if (ix << 1 == 0) { return -1 / (x * x); } // log(-#) = nan if (ix >> 31 != 0) { return (x - x) / 0.0 } // subnormal, scale x k -= 25; x *= 0x1.0p25; ix = @bitCast(u32, x); } else if (ix >= 0x7F800000) { return x; } else if (ix == 0x3F800000) { return 0; } // x into [sqrt(2) / 2, sqrt(2)] ix += 0x3F800000 - 0x3F3504F3; k += i32(ix >> 23) - 0x7F; ix = (ix & 0x007FFFFF) + 0x3F3504F3; x = @bitCast(f32, ix); const f = x - 1.0; const s = f / (2.0 + f); const z = s * s; const w = z * z; const t1 = w * (Lg2 + w * Lg4); const t2 = z * (Lg1 + w * Lg3); const R = t2 + t1; const hfsq = 0.5 * f * f; const dk = f32(k); s * (hfsq + R) + dk * ln2_lo - hfsq + f + dk * ln2_hi } fn logd(x_: f64) -> f64 { const ln2_hi: f64 = 6.93147180369123816490e-01; const ln2_lo: f64 = 1.90821492927058770002e-10; const Lg1: f64 = 6.666666666666735130e-01; const Lg2: f64 = 3.999999999940941908e-01; const Lg3: f64 = 2.857142874366239149e-01; const Lg4: f64 = 2.222219843214978396e-01; const Lg5: f64 = 1.818357216161805012e-01; const Lg6: f64 = 1.531383769920937332e-01; const Lg7: f64 = 1.479819860511658591e-01; var x = x_; var ix = @bitCast(u64, x); var hx = u32(ix >> 32); var k: i32 = 0; if (hx < 0x00100000 or hx >> 31 != 0) { // log(+-0) = -inf if (ix << 1 == 0) { return -1 / (x * x); } // log(-#) = nan if (hx >> 31 != 0) { return (x - x) / 0.0; } // subnormal, scale x k -= 54; x *= 0x1.0p54; hx = u32(@bitCast(u64, ix) >> 32) } else if (hx >= 0x7FF00000) { return x; } else if (hx == 0x3FF00000 and ix << 32 == 0) { return 0; } // x into [sqrt(2) / 2, sqrt(2)] hx += 0x3FF00000 - 0x3FE6A09E; k += i32(hx >> 20) - 0x3FF; hx = (hx & 0x000FFFFF) + 0x3FE6A09E; ix = (u64(hx) << 32) | (ix & 0xFFFFFFFF); x = @bitCast(f64, ix); const f = x - 1.0; const hfsq = 0.5 * f * f; const s = f / (2.0 + f); const z = s * s; const w = z * z; const t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); const t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); const R = t2 + t1; const dk = f64(k); s * (hfsq + R) + dk * ln2_lo - hfsq + f + dk * ln2_hi } test "log" { fmath.assert(log(f32(0.2)) == logf(0.2)); fmath.assert(log(f64(0.2)) == logd(0.2)); } test "logf" { const epsilon = 0.000001; fmath.assert(fmath.approxEq(f32, logf(0.2), -1.609438, epsilon)); fmath.assert(fmath.approxEq(f32, logf(0.8923), -0.113953, epsilon)); fmath.assert(fmath.approxEq(f32, logf(1.5), 0.405465, epsilon)); fmath.assert(fmath.approxEq(f32, logf(37.45), 3.623007, epsilon)); fmath.assert(fmath.approxEq(f32, logf(89.123), 4.490017, epsilon)); fmath.assert(fmath.approxEq(f32, logf(123123.234375), 11.720941, epsilon)); } test "logd" { const epsilon = 0.000001; fmath.assert(fmath.approxEq(f64, logd(0.2), -1.609438, epsilon)); fmath.assert(fmath.approxEq(f64, logd(0.8923), -0.113953, epsilon)); fmath.assert(fmath.approxEq(f64, logd(1.5), 0.405465, epsilon)); fmath.assert(fmath.approxEq(f64, logd(37.45), 3.623007, epsilon)); fmath.assert(fmath.approxEq(f64, logd(89.123), 4.490017, epsilon)); fmath.assert(fmath.approxEq(f64, logd(123123.234375), 11.720941, epsilon)); }
src/log.zig
pub const SDDL_REVISION_1 = @as(u32, 1); pub const SDDL_REVISION = @as(u32, 1); pub const SDDL_ALIAS_SIZE = @as(u32, 2); pub const INHERITED_ACCESS_ENTRY = @as(u32, 16); pub const INHERITED_PARENT = @as(u32, 268435456); pub const INHERITED_GRANDPARENT = @as(u32, 536870912); pub const TRUSTEE_ACCESS_ALLOWED = @as(i32, 1); pub const TRUSTEE_ACCESS_READ = @as(i32, 2); pub const TRUSTEE_ACCESS_WRITE = @as(i32, 4); pub const TRUSTEE_ACCESS_EXPLICIT = @as(i32, 1); pub const TRUSTEE_ACCESS_ALL = @as(i32, -1); pub const ACTRL_RESERVED = @as(u32, 0); pub const ACTRL_PERM_1 = @as(u32, 1); pub const ACTRL_PERM_2 = @as(u32, 2); pub const ACTRL_PERM_3 = @as(u32, 4); pub const ACTRL_PERM_4 = @as(u32, 8); pub const ACTRL_PERM_5 = @as(u32, 16); pub const ACTRL_PERM_6 = @as(u32, 32); pub const ACTRL_PERM_7 = @as(u32, 64); pub const ACTRL_PERM_8 = @as(u32, 128); pub const ACTRL_PERM_9 = @as(u32, 256); pub const ACTRL_PERM_10 = @as(u32, 512); pub const ACTRL_PERM_11 = @as(u32, 1024); pub const ACTRL_PERM_12 = @as(u32, 2048); pub const ACTRL_PERM_13 = @as(u32, 4096); pub const ACTRL_PERM_14 = @as(u32, 8192); pub const ACTRL_PERM_15 = @as(u32, 16384); pub const ACTRL_PERM_16 = @as(u32, 32768); pub const ACTRL_PERM_17 = @as(u32, 65536); pub const ACTRL_PERM_18 = @as(u32, 131072); pub const ACTRL_PERM_19 = @as(u32, 262144); pub const ACTRL_PERM_20 = @as(u32, 524288); pub const ACTRL_ACCESS_PROTECTED = @as(u32, 1); pub const ACTRL_SYSTEM_ACCESS = @as(u32, 67108864); pub const ACTRL_DELETE = @as(u32, 134217728); pub const ACTRL_READ_CONTROL = @as(u32, 268435456); pub const ACTRL_CHANGE_ACCESS = @as(u32, 536870912); pub const ACTRL_CHANGE_OWNER = @as(u32, 1073741824); pub const ACTRL_SYNCHRONIZE = @as(u32, 2147483648); pub const ACTRL_STD_RIGHTS_ALL = @as(u32, 4160749568); pub const ACTRL_FILE_READ = @as(u32, 1); pub const ACTRL_FILE_WRITE = @as(u32, 2); pub const ACTRL_FILE_APPEND = @as(u32, 4); pub const ACTRL_FILE_READ_PROP = @as(u32, 8); pub const ACTRL_FILE_WRITE_PROP = @as(u32, 16); pub const ACTRL_FILE_EXECUTE = @as(u32, 32); pub const ACTRL_FILE_READ_ATTRIB = @as(u32, 128); pub const ACTRL_FILE_WRITE_ATTRIB = @as(u32, 256); pub const ACTRL_FILE_CREATE_PIPE = @as(u32, 512); pub const ACTRL_DIR_LIST = @as(u32, 1); pub const ACTRL_DIR_CREATE_OBJECT = @as(u32, 2); pub const ACTRL_DIR_CREATE_CHILD = @as(u32, 4); pub const ACTRL_DIR_DELETE_CHILD = @as(u32, 64); pub const ACTRL_DIR_TRAVERSE = @as(u32, 32); pub const ACTRL_KERNEL_TERMINATE = @as(u32, 1); pub const ACTRL_KERNEL_THREAD = @as(u32, 2); pub const ACTRL_KERNEL_VM = @as(u32, 4); pub const ACTRL_KERNEL_VM_READ = @as(u32, 8); pub const ACTRL_KERNEL_VM_WRITE = @as(u32, 16); pub const ACTRL_KERNEL_DUP_HANDLE = @as(u32, 32); pub const ACTRL_KERNEL_PROCESS = @as(u32, 64); pub const ACTRL_KERNEL_SET_INFO = @as(u32, 128); pub const ACTRL_KERNEL_GET_INFO = @as(u32, 256); pub const ACTRL_KERNEL_CONTROL = @as(u32, 512); pub const ACTRL_KERNEL_ALERT = @as(u32, 1024); pub const ACTRL_KERNEL_GET_CONTEXT = @as(u32, 2048); pub const ACTRL_KERNEL_SET_CONTEXT = @as(u32, 4096); pub const ACTRL_KERNEL_TOKEN = @as(u32, 8192); pub const ACTRL_KERNEL_IMPERSONATE = @as(u32, 16384); pub const ACTRL_KERNEL_DIMPERSONATE = @as(u32, 32768); pub const ACTRL_PRINT_SADMIN = @as(u32, 1); pub const ACTRL_PRINT_SLIST = @as(u32, 2); pub const ACTRL_PRINT_PADMIN = @as(u32, 4); pub const ACTRL_PRINT_PUSE = @as(u32, 8); pub const ACTRL_PRINT_JADMIN = @as(u32, 16); pub const ACTRL_SVC_GET_INFO = @as(u32, 1); pub const ACTRL_SVC_SET_INFO = @as(u32, 2); pub const ACTRL_SVC_STATUS = @as(u32, 4); pub const ACTRL_SVC_LIST = @as(u32, 8); pub const ACTRL_SVC_START = @as(u32, 16); pub const ACTRL_SVC_STOP = @as(u32, 32); pub const ACTRL_SVC_PAUSE = @as(u32, 64); pub const ACTRL_SVC_INTERROGATE = @as(u32, 128); pub const ACTRL_SVC_UCONTROL = @as(u32, 256); pub const ACTRL_REG_QUERY = @as(u32, 1); pub const ACTRL_REG_SET = @as(u32, 2); pub const ACTRL_REG_CREATE_CHILD = @as(u32, 4); pub const ACTRL_REG_LIST = @as(u32, 8); pub const ACTRL_REG_NOTIFY = @as(u32, 16); pub const ACTRL_REG_LINK = @as(u32, 32); pub const ACTRL_WIN_CLIPBRD = @as(u32, 1); pub const ACTRL_WIN_GLOBAL_ATOMS = @as(u32, 2); pub const ACTRL_WIN_CREATE = @as(u32, 4); pub const ACTRL_WIN_LIST_DESK = @as(u32, 8); pub const ACTRL_WIN_LIST = @as(u32, 16); pub const ACTRL_WIN_READ_ATTRIBS = @as(u32, 32); pub const ACTRL_WIN_WRITE_ATTRIBS = @as(u32, 64); pub const ACTRL_WIN_SCREEN = @as(u32, 128); pub const ACTRL_WIN_EXIT = @as(u32, 256); pub const ACTRL_ACCESS_NO_OPTIONS = @as(u32, 0); pub const ACTRL_ACCESS_SUPPORTS_OBJECT_ENTRIES = @as(u32, 1); pub const AUDIT_TYPE_LEGACY = @as(u32, 1); pub const AUDIT_TYPE_WMI = @as(u32, 2); pub const AP_ParamTypeBits = @as(u32, 8); pub const AP_ParamTypeMask = @as(i32, 255); pub const _AUTHZ_SS_MAXSIZE = @as(u32, 128); pub const APF_AuditFailure = @as(u32, 0); pub const APF_AuditSuccess = @as(u32, 1); pub const APF_ValidFlags = @as(u32, 1); pub const AUTHZP_WPD_EVENT = @as(u32, 16); pub const AUTHZ_ALLOW_MULTIPLE_SOURCE_INSTANCES = @as(u32, 1); pub const AUTHZ_MIGRATED_LEGACY_PUBLISHER = @as(u32, 2); pub const AUTHZ_AUDIT_INSTANCE_INFORMATION = @as(u32, 2); pub const AUTHZ_SKIP_TOKEN_GROUPS = @as(u32, 2); pub const AUTHZ_REQUIRE_S4U_LOGON = @as(u32, 4); pub const AUTHZ_COMPUTE_PRIVILEGES = @as(u32, 8); pub const AUTHZ_SECURITY_ATTRIBUTE_TYPE_INVALID = @as(u32, 0); pub const AUTHZ_SECURITY_ATTRIBUTE_TYPE_INT64 = @as(u32, 1); pub const AUTHZ_SECURITY_ATTRIBUTE_TYPE_UINT64 = @as(u32, 2); pub const AUTHZ_SECURITY_ATTRIBUTE_TYPE_STRING = @as(u32, 3); pub const AUTHZ_SECURITY_ATTRIBUTE_TYPE_FQBN = @as(u32, 4); pub const AUTHZ_SECURITY_ATTRIBUTE_TYPE_SID = @as(u32, 5); pub const AUTHZ_SECURITY_ATTRIBUTE_TYPE_BOOLEAN = @as(u32, 6); pub const AUTHZ_SECURITY_ATTRIBUTE_TYPE_OCTET_STRING = @as(u32, 16); pub const AUTHZ_SECURITY_ATTRIBUTES_INFORMATION_VERSION_V1 = @as(u32, 1); pub const AUTHZ_SECURITY_ATTRIBUTES_INFORMATION_VERSION = @as(u32, 1); pub const AUTHZ_RPC_INIT_INFO_CLIENT_VERSION_V1 = @as(u32, 1); pub const AUTHZ_INIT_INFO_VERSION_V1 = @as(u32, 1); pub const AUTHZ_WPD_CATEGORY_FLAG = @as(u32, 16); pub const AUTHZ_FLAG_ALLOW_MULTIPLE_SOURCE_INSTANCES = @as(u32, 1); pub const OLESCRIPT_E_SYNTAX = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147352319)); //-------------------------------------------------------------------------------- // Section: Types (112) //-------------------------------------------------------------------------------- pub const AUTHZ_RESOURCE_MANAGER_FLAGS = enum(u32) { NO_AUDIT = 1, INITIALIZE_UNDER_IMPERSONATION = 2, NO_CENTRAL_ACCESS_POLICIES = 4, _, pub fn initFlags(o: struct { NO_AUDIT: u1 = 0, INITIALIZE_UNDER_IMPERSONATION: u1 = 0, NO_CENTRAL_ACCESS_POLICIES: u1 = 0, }) AUTHZ_RESOURCE_MANAGER_FLAGS { return @intToEnum(AUTHZ_RESOURCE_MANAGER_FLAGS, (if (o.NO_AUDIT == 1) @enumToInt(AUTHZ_RESOURCE_MANAGER_FLAGS.NO_AUDIT) else 0) | (if (o.INITIALIZE_UNDER_IMPERSONATION == 1) @enumToInt(AUTHZ_RESOURCE_MANAGER_FLAGS.INITIALIZE_UNDER_IMPERSONATION) else 0) | (if (o.NO_CENTRAL_ACCESS_POLICIES == 1) @enumToInt(AUTHZ_RESOURCE_MANAGER_FLAGS.NO_CENTRAL_ACCESS_POLICIES) else 0) ); } }; pub const AUTHZ_RM_FLAG_NO_AUDIT = AUTHZ_RESOURCE_MANAGER_FLAGS.NO_AUDIT; pub const AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION = AUTHZ_RESOURCE_MANAGER_FLAGS.INITIALIZE_UNDER_IMPERSONATION; pub const AUTHZ_RM_FLAG_NO_CENTRAL_ACCESS_POLICIES = AUTHZ_RESOURCE_MANAGER_FLAGS.NO_CENTRAL_ACCESS_POLICIES; pub const AUTHZ_ACCESS_CHECK_FLAGS = enum(u32) { D = 1, }; pub const AUTHZ_ACCESS_CHECK_NO_DEEP_COPY_SD = AUTHZ_ACCESS_CHECK_FLAGS.D; pub const AUTHZ_INITIALIZE_OBJECT_ACCESS_AUDIT_EVENT_FLAGS = enum(u32) { SUCCESS_AUDIT = 1, FAILURE_AUDIT = 2, ALLOC_STRINGS = 4, }; pub const AUTHZ_NO_SUCCESS_AUDIT = AUTHZ_INITIALIZE_OBJECT_ACCESS_AUDIT_EVENT_FLAGS.SUCCESS_AUDIT; pub const AUTHZ_NO_FAILURE_AUDIT = AUTHZ_INITIALIZE_OBJECT_ACCESS_AUDIT_EVENT_FLAGS.FAILURE_AUDIT; pub const AUTHZ_NO_ALLOC_STRINGS = AUTHZ_INITIALIZE_OBJECT_ACCESS_AUDIT_EVENT_FLAGS.ALLOC_STRINGS; pub const TREE_SEC_INFO = enum(u32) { SET = 1, RESET = 2, RESET_KEEP_EXPLICIT = 3, }; pub const TREE_SEC_INFO_SET = TREE_SEC_INFO.SET; pub const TREE_SEC_INFO_RESET = TREE_SEC_INFO.RESET; pub const TREE_SEC_INFO_RESET_KEEP_EXPLICIT = TREE_SEC_INFO.RESET_KEEP_EXPLICIT; pub const AUTHZ_GENERATE_RESULTS = enum(u32) { SUCCESS_AUDIT = 1, FAILURE_AUDIT = 2, }; pub const AUTHZ_GENERATE_SUCCESS_AUDIT = AUTHZ_GENERATE_RESULTS.SUCCESS_AUDIT; pub const AUTHZ_GENERATE_FAILURE_AUDIT = AUTHZ_GENERATE_RESULTS.FAILURE_AUDIT; pub const ACTRL_ACCESS_ENTRY_ACCESS_FLAGS = enum(u32) { CCESS_ALLOWED = 1, CCESS_DENIED = 2, UDIT_SUCCESS = 4, UDIT_FAILURE = 8, }; pub const ACTRL_ACCESS_ALLOWED = ACTRL_ACCESS_ENTRY_ACCESS_FLAGS.CCESS_ALLOWED; pub const ACTRL_ACCESS_DENIED = ACTRL_ACCESS_ENTRY_ACCESS_FLAGS.CCESS_DENIED; pub const ACTRL_AUDIT_SUCCESS = ACTRL_ACCESS_ENTRY_ACCESS_FLAGS.UDIT_SUCCESS; pub const ACTRL_AUDIT_FAILURE = ACTRL_ACCESS_ENTRY_ACCESS_FLAGS.UDIT_FAILURE; pub const AUTHZ_SECURITY_ATTRIBUTE_FLAGS = enum(u32) { NON_INHERITABLE = 1, VALUE_CASE_SENSITIVE = 2, _, pub fn initFlags(o: struct { NON_INHERITABLE: u1 = 0, VALUE_CASE_SENSITIVE: u1 = 0, }) AUTHZ_SECURITY_ATTRIBUTE_FLAGS { return @intToEnum(AUTHZ_SECURITY_ATTRIBUTE_FLAGS, (if (o.NON_INHERITABLE == 1) @enumToInt(AUTHZ_SECURITY_ATTRIBUTE_FLAGS.NON_INHERITABLE) else 0) | (if (o.VALUE_CASE_SENSITIVE == 1) @enumToInt(AUTHZ_SECURITY_ATTRIBUTE_FLAGS.VALUE_CASE_SENSITIVE) else 0) ); } }; pub const AUTHZ_SECURITY_ATTRIBUTE_NON_INHERITABLE = AUTHZ_SECURITY_ATTRIBUTE_FLAGS.NON_INHERITABLE; pub const AUTHZ_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE = AUTHZ_SECURITY_ATTRIBUTE_FLAGS.VALUE_CASE_SENSITIVE; pub const SE_OBJECT_TYPE = enum(i32) { UNKNOWN_OBJECT_TYPE = 0, FILE_OBJECT = 1, SERVICE = 2, PRINTER = 3, REGISTRY_KEY = 4, LMSHARE = 5, KERNEL_OBJECT = 6, WINDOW_OBJECT = 7, DS_OBJECT = 8, DS_OBJECT_ALL = 9, PROVIDER_DEFINED_OBJECT = 10, WMIGUID_OBJECT = 11, REGISTRY_WOW64_32KEY = 12, REGISTRY_WOW64_64KEY = 13, }; pub const SE_UNKNOWN_OBJECT_TYPE = SE_OBJECT_TYPE.UNKNOWN_OBJECT_TYPE; pub const SE_FILE_OBJECT = SE_OBJECT_TYPE.FILE_OBJECT; pub const SE_SERVICE = SE_OBJECT_TYPE.SERVICE; pub const SE_PRINTER = SE_OBJECT_TYPE.PRINTER; pub const SE_REGISTRY_KEY = SE_OBJECT_TYPE.REGISTRY_KEY; pub const SE_LMSHARE = SE_OBJECT_TYPE.LMSHARE; pub const SE_KERNEL_OBJECT = SE_OBJECT_TYPE.KERNEL_OBJECT; pub const SE_WINDOW_OBJECT = SE_OBJECT_TYPE.WINDOW_OBJECT; pub const SE_DS_OBJECT = SE_OBJECT_TYPE.DS_OBJECT; pub const SE_DS_OBJECT_ALL = SE_OBJECT_TYPE.DS_OBJECT_ALL; pub const SE_PROVIDER_DEFINED_OBJECT = SE_OBJECT_TYPE.PROVIDER_DEFINED_OBJECT; pub const SE_WMIGUID_OBJECT = SE_OBJECT_TYPE.WMIGUID_OBJECT; pub const SE_REGISTRY_WOW64_32KEY = SE_OBJECT_TYPE.REGISTRY_WOW64_32KEY; pub const SE_REGISTRY_WOW64_64KEY = SE_OBJECT_TYPE.REGISTRY_WOW64_64KEY; pub const TRUSTEE_TYPE = enum(i32) { UNKNOWN = 0, USER = 1, GROUP = 2, DOMAIN = 3, ALIAS = 4, WELL_KNOWN_GROUP = 5, DELETED = 6, INVALID = 7, COMPUTER = 8, }; pub const TRUSTEE_IS_UNKNOWN = TRUSTEE_TYPE.UNKNOWN; pub const TRUSTEE_IS_USER = TRUSTEE_TYPE.USER; pub const TRUSTEE_IS_GROUP = TRUSTEE_TYPE.GROUP; pub const TRUSTEE_IS_DOMAIN = TRUSTEE_TYPE.DOMAIN; pub const TRUSTEE_IS_ALIAS = TRUSTEE_TYPE.ALIAS; pub const TRUSTEE_IS_WELL_KNOWN_GROUP = TRUSTEE_TYPE.WELL_KNOWN_GROUP; pub const TRUSTEE_IS_DELETED = TRUSTEE_TYPE.DELETED; pub const TRUSTEE_IS_INVALID = TRUSTEE_TYPE.INVALID; pub const TRUSTEE_IS_COMPUTER = TRUSTEE_TYPE.COMPUTER; pub const TRUSTEE_FORM = enum(i32) { IS_SID = 0, IS_NAME = 1, BAD_FORM = 2, IS_OBJECTS_AND_SID = 3, IS_OBJECTS_AND_NAME = 4, }; pub const TRUSTEE_IS_SID = TRUSTEE_FORM.IS_SID; pub const TRUSTEE_IS_NAME = TRUSTEE_FORM.IS_NAME; pub const TRUSTEE_BAD_FORM = TRUSTEE_FORM.BAD_FORM; pub const TRUSTEE_IS_OBJECTS_AND_SID = TRUSTEE_FORM.IS_OBJECTS_AND_SID; pub const TRUSTEE_IS_OBJECTS_AND_NAME = TRUSTEE_FORM.IS_OBJECTS_AND_NAME; pub const MULTIPLE_TRUSTEE_OPERATION = enum(i32) { NO_MULTIPLE_TRUSTEE = 0, TRUSTEE_IS_IMPERSONATE = 1, }; pub const NO_MULTIPLE_TRUSTEE = MULTIPLE_TRUSTEE_OPERATION.NO_MULTIPLE_TRUSTEE; pub const TRUSTEE_IS_IMPERSONATE = MULTIPLE_TRUSTEE_OPERATION.TRUSTEE_IS_IMPERSONATE; pub const OBJECTS_AND_SID = extern struct { ObjectsPresent: SYSTEM_AUDIT_OBJECT_ACE_FLAGS, ObjectTypeGuid: Guid, InheritedObjectTypeGuid: Guid, pSid: ?*SID, }; pub const OBJECTS_AND_NAME_A = extern struct { ObjectsPresent: SYSTEM_AUDIT_OBJECT_ACE_FLAGS, ObjectType: SE_OBJECT_TYPE, ObjectTypeName: ?PSTR, InheritedObjectTypeName: ?PSTR, ptstrName: ?PSTR, }; pub const OBJECTS_AND_NAME_W = extern struct { ObjectsPresent: SYSTEM_AUDIT_OBJECT_ACE_FLAGS, ObjectType: SE_OBJECT_TYPE, ObjectTypeName: ?PWSTR, InheritedObjectTypeName: ?PWSTR, ptstrName: ?PWSTR, }; pub const TRUSTEE_A = extern struct { pMultipleTrustee: ?*TRUSTEE_A, MultipleTrusteeOperation: MULTIPLE_TRUSTEE_OPERATION, TrusteeForm: TRUSTEE_FORM, TrusteeType: TRUSTEE_TYPE, ptstrName: ?[*]u8, }; pub const TRUSTEE_W = extern struct { pMultipleTrustee: ?*TRUSTEE_W, MultipleTrusteeOperation: MULTIPLE_TRUSTEE_OPERATION, TrusteeForm: TRUSTEE_FORM, TrusteeType: TRUSTEE_TYPE, ptstrName: ?[*]u16, }; pub const ACCESS_MODE = enum(i32) { NOT_USED_ACCESS = 0, GRANT_ACCESS = 1, SET_ACCESS = 2, DENY_ACCESS = 3, REVOKE_ACCESS = 4, SET_AUDIT_SUCCESS = 5, SET_AUDIT_FAILURE = 6, }; pub const NOT_USED_ACCESS = ACCESS_MODE.NOT_USED_ACCESS; pub const GRANT_ACCESS = ACCESS_MODE.GRANT_ACCESS; pub const SET_ACCESS = ACCESS_MODE.SET_ACCESS; pub const DENY_ACCESS = ACCESS_MODE.DENY_ACCESS; pub const REVOKE_ACCESS = ACCESS_MODE.REVOKE_ACCESS; pub const SET_AUDIT_SUCCESS = ACCESS_MODE.SET_AUDIT_SUCCESS; pub const SET_AUDIT_FAILURE = ACCESS_MODE.SET_AUDIT_FAILURE; pub const EXPLICIT_ACCESS_A = extern struct { grfAccessPermissions: u32, grfAccessMode: ACCESS_MODE, grfInheritance: ACE_FLAGS, Trustee: TRUSTEE_A, }; pub const EXPLICIT_ACCESS_W = extern struct { grfAccessPermissions: u32, grfAccessMode: ACCESS_MODE, grfInheritance: ACE_FLAGS, Trustee: TRUSTEE_W, }; pub const ACTRL_ACCESS_ENTRYA = extern struct { Trustee: TRUSTEE_A, fAccessFlags: ACTRL_ACCESS_ENTRY_ACCESS_FLAGS, Access: u32, ProvSpecificAccess: u32, Inheritance: ACE_FLAGS, lpInheritProperty: ?PSTR, }; pub const ACTRL_ACCESS_ENTRYW = extern struct { Trustee: TRUSTEE_W, fAccessFlags: ACTRL_ACCESS_ENTRY_ACCESS_FLAGS, Access: u32, ProvSpecificAccess: u32, Inheritance: ACE_FLAGS, lpInheritProperty: ?PWSTR, }; pub const ACTRL_ACCESS_ENTRY_LISTA = extern struct { cEntries: u32, pAccessList: ?*ACTRL_ACCESS_ENTRYA, }; pub const ACTRL_ACCESS_ENTRY_LISTW = extern struct { cEntries: u32, pAccessList: ?*ACTRL_ACCESS_ENTRYW, }; pub const ACTRL_PROPERTY_ENTRYA = extern struct { lpProperty: ?PSTR, pAccessEntryList: ?*ACTRL_ACCESS_ENTRY_LISTA, fListFlags: u32, }; pub const ACTRL_PROPERTY_ENTRYW = extern struct { lpProperty: ?PWSTR, pAccessEntryList: ?*ACTRL_ACCESS_ENTRY_LISTW, fListFlags: u32, }; pub const ACTRL_ACCESSA = extern struct { cEntries: u32, pPropertyAccessList: ?*ACTRL_PROPERTY_ENTRYA, }; pub const ACTRL_ACCESSW = extern struct { cEntries: u32, pPropertyAccessList: ?*ACTRL_PROPERTY_ENTRYW, }; pub const TRUSTEE_ACCESSA = extern struct { lpProperty: ?PSTR, Access: u32, fAccessFlags: u32, fReturnedAccess: u32, }; pub const TRUSTEE_ACCESSW = extern struct { lpProperty: ?PWSTR, Access: u32, fAccessFlags: u32, fReturnedAccess: u32, }; pub const ACTRL_OVERLAPPED = extern struct { Anonymous: extern union { Provider: ?*anyopaque, Reserved1: u32, }, Reserved2: u32, hEvent: ?HANDLE, }; pub const ACTRL_ACCESS_INFOA = extern struct { fAccessPermission: u32, lpAccessPermissionName: ?PSTR, }; pub const ACTRL_ACCESS_INFOW = extern struct { fAccessPermission: u32, lpAccessPermissionName: ?PWSTR, }; pub const ACTRL_CONTROL_INFOA = extern struct { lpControlId: ?PSTR, lpControlName: ?PSTR, }; pub const ACTRL_CONTROL_INFOW = extern struct { lpControlId: ?PWSTR, lpControlName: ?PWSTR, }; pub const PROG_INVOKE_SETTING = enum(i32) { InvokeNever = 1, InvokeEveryObject = 2, InvokeOnError = 3, CancelOperation = 4, RetryOperation = 5, InvokePrePostError = 6, }; pub const ProgressInvokeNever = PROG_INVOKE_SETTING.InvokeNever; pub const ProgressInvokeEveryObject = PROG_INVOKE_SETTING.InvokeEveryObject; pub const ProgressInvokeOnError = PROG_INVOKE_SETTING.InvokeOnError; pub const ProgressCancelOperation = PROG_INVOKE_SETTING.CancelOperation; pub const ProgressRetryOperation = PROG_INVOKE_SETTING.RetryOperation; pub const ProgressInvokePrePostError = PROG_INVOKE_SETTING.InvokePrePostError; pub const FN_OBJECT_MGR_FUNCTIONS = extern struct { Placeholder: u32, }; pub const INHERITED_FROMA = extern struct { GenerationGap: i32, AncestorName: ?PSTR, }; pub const INHERITED_FROMW = extern struct { GenerationGap: i32, AncestorName: ?PWSTR, }; pub const AUDIT_PARAM_TYPE = enum(i32) { None = 1, String = 2, Ulong = 3, Pointer = 4, Sid = 5, LogonId = 6, ObjectTypeList = 7, Luid = 8, Guid = 9, Time = 10, Int64 = 11, IpAddress = 12, LogonIdWithSid = 13, }; pub const APT_None = AUDIT_PARAM_TYPE.None; pub const APT_String = AUDIT_PARAM_TYPE.String; pub const APT_Ulong = AUDIT_PARAM_TYPE.Ulong; pub const APT_Pointer = AUDIT_PARAM_TYPE.Pointer; pub const APT_Sid = AUDIT_PARAM_TYPE.Sid; pub const APT_LogonId = AUDIT_PARAM_TYPE.LogonId; pub const APT_ObjectTypeList = AUDIT_PARAM_TYPE.ObjectTypeList; pub const APT_Luid = AUDIT_PARAM_TYPE.Luid; pub const APT_Guid = AUDIT_PARAM_TYPE.Guid; pub const APT_Time = AUDIT_PARAM_TYPE.Time; pub const APT_Int64 = AUDIT_PARAM_TYPE.Int64; pub const APT_IpAddress = AUDIT_PARAM_TYPE.IpAddress; pub const APT_LogonIdWithSid = AUDIT_PARAM_TYPE.LogonIdWithSid; pub const AUDIT_OBJECT_TYPE = extern struct { ObjectType: Guid, Flags: u16, Level: u16, AccessMask: u32, }; pub const AUDIT_OBJECT_TYPES = extern struct { Count: u16, Flags: u16, pObjectTypes: ?*AUDIT_OBJECT_TYPE, }; pub const AUDIT_IP_ADDRESS = extern struct { pIpAddress: [128]u8, }; pub const AUDIT_PARAM = extern struct { Type: AUDIT_PARAM_TYPE, Length: u32, Flags: u32, Anonymous1: extern union { Data0: usize, String: ?PWSTR, u: usize, psid: ?*SID, pguid: ?*Guid, LogonId_LowPart: u32, pObjectTypes: ?*AUDIT_OBJECT_TYPES, pIpAddress: ?*AUDIT_IP_ADDRESS, }, Anonymous2: extern union { Data1: usize, LogonId_HighPart: i32, }, }; pub const AUDIT_PARAMS = extern struct { Length: u32, Flags: u32, Count: u16, Parameters: ?*AUDIT_PARAM, }; pub const AUTHZ_AUDIT_EVENT_TYPE_LEGACY = extern struct { CategoryId: u16, AuditId: u16, ParameterCount: u16, }; pub const AUTHZ_AUDIT_EVENT_TYPE_UNION = extern union { Legacy: AUTHZ_AUDIT_EVENT_TYPE_LEGACY, }; pub const AUTHZ_AUDIT_EVENT_TYPE_OLD = extern struct { Version: u32, dwFlags: u32, RefCount: i32, hAudit: usize, LinkId: LUID, u: AUTHZ_AUDIT_EVENT_TYPE_UNION, }; pub const AUTHZ_CAP_CHANGE_SUBSCRIPTION_HANDLE__ = extern struct { unused: i32, }; pub const AUTHZ_ACCESS_REQUEST = extern struct { DesiredAccess: u32, PrincipalSelfSid: ?PSID, ObjectTypeList: ?*OBJECT_TYPE_LIST, ObjectTypeListLength: u32, OptionalArguments: ?*anyopaque, }; pub const AUTHZ_ACCESS_REPLY = extern struct { ResultListLength: u32, GrantedAccessMask: ?*u32, SaclEvaluationResults: ?*AUTHZ_GENERATE_RESULTS, Error: ?*u32, }; pub const PFN_AUTHZ_DYNAMIC_ACCESS_CHECK = fn( hAuthzClientContext: AUTHZ_CLIENT_CONTEXT_HANDLE, pAce: ?*ACE_HEADER, pArgs: ?*anyopaque, pbAceApplicable: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_AUTHZ_COMPUTE_DYNAMIC_GROUPS = fn( hAuthzClientContext: AUTHZ_CLIENT_CONTEXT_HANDLE, Args: ?*anyopaque, pSidAttrArray: ?*?*SID_AND_ATTRIBUTES, pSidCount: ?*u32, pRestrictedSidAttrArray: ?*?*SID_AND_ATTRIBUTES, pRestrictedSidCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_AUTHZ_FREE_DYNAMIC_GROUPS = fn( pSidAttrArray: ?*SID_AND_ATTRIBUTES, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_AUTHZ_GET_CENTRAL_ACCESS_POLICY = fn( hAuthzClientContext: AUTHZ_CLIENT_CONTEXT_HANDLE, capid: ?PSID, pArgs: ?*anyopaque, pCentralAccessPolicyApplicable: ?*BOOL, ppCentralAccessPolicy: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_AUTHZ_FREE_CENTRAL_ACCESS_POLICY = fn( pCentralAccessPolicy: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const AUTHZ_SECURITY_ATTRIBUTE_FQBN_VALUE = extern struct { Version: u64, pName: ?PWSTR, }; pub const AUTHZ_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE = extern struct { pValue: ?*anyopaque, ValueLength: u32, }; pub const AUTHZ_SECURITY_ATTRIBUTE_OPERATION = enum(i32) { NONE = 0, REPLACE_ALL = 1, ADD = 2, DELETE = 3, REPLACE = 4, }; pub const AUTHZ_SECURITY_ATTRIBUTE_OPERATION_NONE = AUTHZ_SECURITY_ATTRIBUTE_OPERATION.NONE; pub const AUTHZ_SECURITY_ATTRIBUTE_OPERATION_REPLACE_ALL = AUTHZ_SECURITY_ATTRIBUTE_OPERATION.REPLACE_ALL; pub const AUTHZ_SECURITY_ATTRIBUTE_OPERATION_ADD = AUTHZ_SECURITY_ATTRIBUTE_OPERATION.ADD; pub const AUTHZ_SECURITY_ATTRIBUTE_OPERATION_DELETE = AUTHZ_SECURITY_ATTRIBUTE_OPERATION.DELETE; pub const AUTHZ_SECURITY_ATTRIBUTE_OPERATION_REPLACE = AUTHZ_SECURITY_ATTRIBUTE_OPERATION.REPLACE; pub const AUTHZ_SID_OPERATION = enum(i32) { NONE = 0, REPLACE_ALL = 1, ADD = 2, DELETE = 3, REPLACE = 4, }; pub const AUTHZ_SID_OPERATION_NONE = AUTHZ_SID_OPERATION.NONE; pub const AUTHZ_SID_OPERATION_REPLACE_ALL = AUTHZ_SID_OPERATION.REPLACE_ALL; pub const AUTHZ_SID_OPERATION_ADD = AUTHZ_SID_OPERATION.ADD; pub const AUTHZ_SID_OPERATION_DELETE = AUTHZ_SID_OPERATION.DELETE; pub const AUTHZ_SID_OPERATION_REPLACE = AUTHZ_SID_OPERATION.REPLACE; pub const AUTHZ_SECURITY_ATTRIBUTE_V1 = extern struct { pName: ?PWSTR, ValueType: u16, Reserved: u16, Flags: AUTHZ_SECURITY_ATTRIBUTE_FLAGS, ValueCount: u32, Values: extern union { pInt64: ?*i64, pUint64: ?*u64, ppString: ?*?PWSTR, pFqbn: ?*AUTHZ_SECURITY_ATTRIBUTE_FQBN_VALUE, pOctetString: ?*AUTHZ_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE, }, }; pub const AUTHZ_SECURITY_ATTRIBUTES_INFORMATION = extern struct { Version: u16, Reserved: u16, AttributeCount: u32, Attribute: extern union { pAttributeV1: ?*AUTHZ_SECURITY_ATTRIBUTE_V1, }, }; pub const AUTHZ_RPC_INIT_INFO_CLIENT = extern struct { version: u16, ObjectUuid: ?PWSTR, ProtSeq: ?PWSTR, NetworkAddr: ?PWSTR, Endpoint: ?PWSTR, Options: ?PWSTR, ServerSpn: ?PWSTR, }; pub const AUTHZ_INIT_INFO = extern struct { version: u16, szResourceManagerName: ?[*:0]const u16, pfnDynamicAccessCheck: ?PFN_AUTHZ_DYNAMIC_ACCESS_CHECK, pfnComputeDynamicGroups: ?PFN_AUTHZ_COMPUTE_DYNAMIC_GROUPS, pfnFreeDynamicGroups: ?PFN_AUTHZ_FREE_DYNAMIC_GROUPS, pfnGetCentralAccessPolicy: ?PFN_AUTHZ_GET_CENTRAL_ACCESS_POLICY, pfnFreeCentralAccessPolicy: ?PFN_AUTHZ_FREE_CENTRAL_ACCESS_POLICY, }; pub const AUTHZ_CONTEXT_INFORMATION_CLASS = enum(i32) { UserSid = 1, GroupsSids = 2, RestrictedSids = 3, Privileges = 4, ExpirationTime = 5, ServerContext = 6, Identifier = 7, Source = 8, All = 9, AuthenticationId = 10, SecurityAttributes = 11, DeviceSids = 12, UserClaims = 13, DeviceClaims = 14, AppContainerSid = 15, CapabilitySids = 16, }; pub const AuthzContextInfoUserSid = AUTHZ_CONTEXT_INFORMATION_CLASS.UserSid; pub const AuthzContextInfoGroupsSids = AUTHZ_CONTEXT_INFORMATION_CLASS.GroupsSids; pub const AuthzContextInfoRestrictedSids = AUTHZ_CONTEXT_INFORMATION_CLASS.RestrictedSids; pub const AuthzContextInfoPrivileges = AUTHZ_CONTEXT_INFORMATION_CLASS.Privileges; pub const AuthzContextInfoExpirationTime = AUTHZ_CONTEXT_INFORMATION_CLASS.ExpirationTime; pub const AuthzContextInfoServerContext = AUTHZ_CONTEXT_INFORMATION_CLASS.ServerContext; pub const AuthzContextInfoIdentifier = AUTHZ_CONTEXT_INFORMATION_CLASS.Identifier; pub const AuthzContextInfoSource = AUTHZ_CONTEXT_INFORMATION_CLASS.Source; pub const AuthzContextInfoAll = AUTHZ_CONTEXT_INFORMATION_CLASS.All; pub const AuthzContextInfoAuthenticationId = AUTHZ_CONTEXT_INFORMATION_CLASS.AuthenticationId; pub const AuthzContextInfoSecurityAttributes = AUTHZ_CONTEXT_INFORMATION_CLASS.SecurityAttributes; pub const AuthzContextInfoDeviceSids = AUTHZ_CONTEXT_INFORMATION_CLASS.DeviceSids; pub const AuthzContextInfoUserClaims = AUTHZ_CONTEXT_INFORMATION_CLASS.UserClaims; pub const AuthzContextInfoDeviceClaims = AUTHZ_CONTEXT_INFORMATION_CLASS.DeviceClaims; pub const AuthzContextInfoAppContainerSid = AUTHZ_CONTEXT_INFORMATION_CLASS.AppContainerSid; pub const AuthzContextInfoCapabilitySids = AUTHZ_CONTEXT_INFORMATION_CLASS.CapabilitySids; pub const AUTHZ_AUDIT_EVENT_INFORMATION_CLASS = enum(i32) { Flags = 1, OperationType = 2, ObjectType = 3, ObjectName = 4, AdditionalInfo = 5, }; pub const AuthzAuditEventInfoFlags = AUTHZ_AUDIT_EVENT_INFORMATION_CLASS.Flags; pub const AuthzAuditEventInfoOperationType = AUTHZ_AUDIT_EVENT_INFORMATION_CLASS.OperationType; pub const AuthzAuditEventInfoObjectType = AUTHZ_AUDIT_EVENT_INFORMATION_CLASS.ObjectType; pub const AuthzAuditEventInfoObjectName = AUTHZ_AUDIT_EVENT_INFORMATION_CLASS.ObjectName; pub const AuthzAuditEventInfoAdditionalInfo = AUTHZ_AUDIT_EVENT_INFORMATION_CLASS.AdditionalInfo; pub const AUTHZ_REGISTRATION_OBJECT_TYPE_NAME_OFFSET = extern struct { szObjectTypeName: ?PWSTR, dwOffset: u32, }; pub const AUTHZ_SOURCE_SCHEMA_REGISTRATION = extern struct { dwFlags: u32, szEventSourceName: ?PWSTR, szEventMessageFile: ?PWSTR, szEventSourceXmlSchemaFile: ?PWSTR, szEventAccessStringsFile: ?PWSTR, szExecutableImagePath: ?PWSTR, Anonymous: extern union { pReserved: ?*anyopaque, pProviderGuid: ?*Guid, }, dwObjectTypeNameCount: u32, ObjectTypeNames: [1]AUTHZ_REGISTRATION_OBJECT_TYPE_NAME_OFFSET, }; const CLSID_AzAuthorizationStore_Value = Guid.initString("b2bcff59-a757-4b0b-a1bc-ea69981da69e"); pub const CLSID_AzAuthorizationStore = &CLSID_AzAuthorizationStore_Value; const CLSID_AzBizRuleContext_Value = Guid.initString("5c2dc96f-8d51-434b-b33c-379bccae77c3"); pub const CLSID_AzBizRuleContext = &CLSID_AzBizRuleContext_Value; const CLSID_AzPrincipalLocator_Value = Guid.initString("483afb5d-70df-4e16-abdc-a1de4d015a3e"); pub const CLSID_AzPrincipalLocator = &CLSID_AzPrincipalLocator_Value; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzAuthorizationStore_Value = Guid.initString("edbd9ca9-9b82-4f6a-9e8b-98301e450f14"); pub const IID_IAzAuthorizationStore = &IID_IAzAuthorizationStore_Value; pub const IAzAuthorizationStore = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IAzAuthorizationStore, pbstrDescription: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IAzAuthorizationStore, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ApplicationData: fn( self: *const IAzAuthorizationStore, pbstrApplicationData: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ApplicationData: fn( self: *const IAzAuthorizationStore, bstrApplicationData: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DomainTimeout: fn( self: *const IAzAuthorizationStore, plProp: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DomainTimeout: fn( self: *const IAzAuthorizationStore, lProp: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ScriptEngineTimeout: fn( self: *const IAzAuthorizationStore, plProp: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ScriptEngineTimeout: fn( self: *const IAzAuthorizationStore, lProp: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaxScriptEngines: fn( self: *const IAzAuthorizationStore, plProp: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaxScriptEngines: fn( self: *const IAzAuthorizationStore, lProp: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GenerateAudits: fn( self: *const IAzAuthorizationStore, pbProp: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_GenerateAudits: fn( self: *const IAzAuthorizationStore, bProp: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Writable: fn( self: *const IAzAuthorizationStore, pfProp: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProperty: fn( self: *const IAzAuthorizationStore, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProperty: fn( self: *const IAzAuthorizationStore, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPropertyItem: fn( self: *const IAzAuthorizationStore, lPropId: AZ_PROP_CONSTANTS, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePropertyItem: fn( self: *const IAzAuthorizationStore, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PolicyAdministrators: fn( self: *const IAzAuthorizationStore, pvarAdmins: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PolicyReaders: fn( self: *const IAzAuthorizationStore, pvarReaders: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPolicyAdministrator: fn( self: *const IAzAuthorizationStore, bstrAdmin: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePolicyAdministrator: fn( self: *const IAzAuthorizationStore, bstrAdmin: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPolicyReader: fn( self: *const IAzAuthorizationStore, bstrReader: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePolicyReader: fn( self: *const IAzAuthorizationStore, bstrReader: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IAzAuthorizationStore, lFlags: AZ_PROP_CONSTANTS, bstrPolicyURL: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateCache: fn( self: *const IAzAuthorizationStore, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Delete: fn( self: *const IAzAuthorizationStore, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Applications: fn( self: *const IAzAuthorizationStore, ppAppCollection: ?*?*IAzApplications, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenApplication: fn( self: *const IAzAuthorizationStore, bstrApplicationName: ?BSTR, varReserved: VARIANT, ppApplication: ?*?*IAzApplication, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateApplication: fn( self: *const IAzAuthorizationStore, bstrApplicationName: ?BSTR, varReserved: VARIANT, ppApplication: ?*?*IAzApplication, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteApplication: fn( self: *const IAzAuthorizationStore, bstrApplicationName: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ApplicationGroups: fn( self: *const IAzAuthorizationStore, ppGroupCollection: ?*?*IAzApplicationGroups, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateApplicationGroup: fn( self: *const IAzAuthorizationStore, bstrGroupName: ?BSTR, varReserved: VARIANT, ppGroup: ?*?*IAzApplicationGroup, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenApplicationGroup: fn( self: *const IAzAuthorizationStore, bstrGroupName: ?BSTR, varReserved: VARIANT, ppGroup: ?*?*IAzApplicationGroup, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteApplicationGroup: fn( self: *const IAzAuthorizationStore, bstrGroupName: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Submit: fn( self: *const IAzAuthorizationStore, lFlags: i32, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DelegatedPolicyUsers: fn( self: *const IAzAuthorizationStore, pvarDelegatedPolicyUsers: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddDelegatedPolicyUser: fn( self: *const IAzAuthorizationStore, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteDelegatedPolicyUser: fn( self: *const IAzAuthorizationStore, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TargetMachine: fn( self: *const IAzAuthorizationStore, pbstrTargetMachine: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ApplyStoreSacl: fn( self: *const IAzAuthorizationStore, pbApplyStoreSacl: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ApplyStoreSacl: fn( self: *const IAzAuthorizationStore, bApplyStoreSacl: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PolicyAdministratorsName: fn( self: *const IAzAuthorizationStore, pvarAdmins: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PolicyReadersName: fn( self: *const IAzAuthorizationStore, pvarReaders: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPolicyAdministratorName: fn( self: *const IAzAuthorizationStore, bstrAdmin: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePolicyAdministratorName: fn( self: *const IAzAuthorizationStore, bstrAdmin: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPolicyReaderName: fn( self: *const IAzAuthorizationStore, bstrReader: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePolicyReaderName: fn( self: *const IAzAuthorizationStore, bstrReader: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DelegatedPolicyUsersName: fn( self: *const IAzAuthorizationStore, pvarDelegatedPolicyUsers: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddDelegatedPolicyUserName: fn( self: *const IAzAuthorizationStore, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteDelegatedPolicyUserName: fn( self: *const IAzAuthorizationStore, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CloseApplication: fn( self: *const IAzAuthorizationStore, bstrApplicationName: ?BSTR, lFlag: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_Description(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_Description(@ptrCast(*const IAzAuthorizationStore, self), pbstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).put_Description(@ptrCast(*const IAzAuthorizationStore, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_ApplicationData(self: *const T, pbstrApplicationData: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_ApplicationData(@ptrCast(*const IAzAuthorizationStore, self), pbstrApplicationData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_put_ApplicationData(self: *const T, bstrApplicationData: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).put_ApplicationData(@ptrCast(*const IAzAuthorizationStore, self), bstrApplicationData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_DomainTimeout(self: *const T, plProp: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_DomainTimeout(@ptrCast(*const IAzAuthorizationStore, self), plProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_put_DomainTimeout(self: *const T, lProp: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).put_DomainTimeout(@ptrCast(*const IAzAuthorizationStore, self), lProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_ScriptEngineTimeout(self: *const T, plProp: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_ScriptEngineTimeout(@ptrCast(*const IAzAuthorizationStore, self), plProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_put_ScriptEngineTimeout(self: *const T, lProp: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).put_ScriptEngineTimeout(@ptrCast(*const IAzAuthorizationStore, self), lProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_MaxScriptEngines(self: *const T, plProp: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_MaxScriptEngines(@ptrCast(*const IAzAuthorizationStore, self), plProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_put_MaxScriptEngines(self: *const T, lProp: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).put_MaxScriptEngines(@ptrCast(*const IAzAuthorizationStore, self), lProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_GenerateAudits(self: *const T, pbProp: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_GenerateAudits(@ptrCast(*const IAzAuthorizationStore, self), pbProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_put_GenerateAudits(self: *const T, bProp: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).put_GenerateAudits(@ptrCast(*const IAzAuthorizationStore, self), bProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_Writable(self: *const T, pfProp: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_Writable(@ptrCast(*const IAzAuthorizationStore, self), pfProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_GetProperty(self: *const T, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).GetProperty(@ptrCast(*const IAzAuthorizationStore, self), lPropId, varReserved, pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_SetProperty(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).SetProperty(@ptrCast(*const IAzAuthorizationStore, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_AddPropertyItem(self: *const T, lPropId: AZ_PROP_CONSTANTS, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).AddPropertyItem(@ptrCast(*const IAzAuthorizationStore, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_DeletePropertyItem(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).DeletePropertyItem(@ptrCast(*const IAzAuthorizationStore, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_PolicyAdministrators(self: *const T, pvarAdmins: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_PolicyAdministrators(@ptrCast(*const IAzAuthorizationStore, self), pvarAdmins); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_PolicyReaders(self: *const T, pvarReaders: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_PolicyReaders(@ptrCast(*const IAzAuthorizationStore, self), pvarReaders); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_AddPolicyAdministrator(self: *const T, bstrAdmin: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).AddPolicyAdministrator(@ptrCast(*const IAzAuthorizationStore, self), bstrAdmin, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_DeletePolicyAdministrator(self: *const T, bstrAdmin: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).DeletePolicyAdministrator(@ptrCast(*const IAzAuthorizationStore, self), bstrAdmin, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_AddPolicyReader(self: *const T, bstrReader: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).AddPolicyReader(@ptrCast(*const IAzAuthorizationStore, self), bstrReader, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_DeletePolicyReader(self: *const T, bstrReader: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).DeletePolicyReader(@ptrCast(*const IAzAuthorizationStore, self), bstrReader, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_Initialize(self: *const T, lFlags: AZ_PROP_CONSTANTS, bstrPolicyURL: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).Initialize(@ptrCast(*const IAzAuthorizationStore, self), lFlags, bstrPolicyURL, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_UpdateCache(self: *const T, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).UpdateCache(@ptrCast(*const IAzAuthorizationStore, self), varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_Delete(self: *const T, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).Delete(@ptrCast(*const IAzAuthorizationStore, self), varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_Applications(self: *const T, ppAppCollection: ?*?*IAzApplications) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_Applications(@ptrCast(*const IAzAuthorizationStore, self), ppAppCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_OpenApplication(self: *const T, bstrApplicationName: ?BSTR, varReserved: VARIANT, ppApplication: ?*?*IAzApplication) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).OpenApplication(@ptrCast(*const IAzAuthorizationStore, self), bstrApplicationName, varReserved, ppApplication); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_CreateApplication(self: *const T, bstrApplicationName: ?BSTR, varReserved: VARIANT, ppApplication: ?*?*IAzApplication) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).CreateApplication(@ptrCast(*const IAzAuthorizationStore, self), bstrApplicationName, varReserved, ppApplication); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_DeleteApplication(self: *const T, bstrApplicationName: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).DeleteApplication(@ptrCast(*const IAzAuthorizationStore, self), bstrApplicationName, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_ApplicationGroups(self: *const T, ppGroupCollection: ?*?*IAzApplicationGroups) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_ApplicationGroups(@ptrCast(*const IAzAuthorizationStore, self), ppGroupCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_CreateApplicationGroup(self: *const T, bstrGroupName: ?BSTR, varReserved: VARIANT, ppGroup: ?*?*IAzApplicationGroup) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).CreateApplicationGroup(@ptrCast(*const IAzAuthorizationStore, self), bstrGroupName, varReserved, ppGroup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_OpenApplicationGroup(self: *const T, bstrGroupName: ?BSTR, varReserved: VARIANT, ppGroup: ?*?*IAzApplicationGroup) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).OpenApplicationGroup(@ptrCast(*const IAzAuthorizationStore, self), bstrGroupName, varReserved, ppGroup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_DeleteApplicationGroup(self: *const T, bstrGroupName: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).DeleteApplicationGroup(@ptrCast(*const IAzAuthorizationStore, self), bstrGroupName, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_Submit(self: *const T, lFlags: i32, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).Submit(@ptrCast(*const IAzAuthorizationStore, self), lFlags, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_DelegatedPolicyUsers(self: *const T, pvarDelegatedPolicyUsers: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_DelegatedPolicyUsers(@ptrCast(*const IAzAuthorizationStore, self), pvarDelegatedPolicyUsers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_AddDelegatedPolicyUser(self: *const T, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).AddDelegatedPolicyUser(@ptrCast(*const IAzAuthorizationStore, self), bstrDelegatedPolicyUser, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_DeleteDelegatedPolicyUser(self: *const T, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).DeleteDelegatedPolicyUser(@ptrCast(*const IAzAuthorizationStore, self), bstrDelegatedPolicyUser, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_TargetMachine(self: *const T, pbstrTargetMachine: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_TargetMachine(@ptrCast(*const IAzAuthorizationStore, self), pbstrTargetMachine); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_ApplyStoreSacl(self: *const T, pbApplyStoreSacl: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_ApplyStoreSacl(@ptrCast(*const IAzAuthorizationStore, self), pbApplyStoreSacl); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_put_ApplyStoreSacl(self: *const T, bApplyStoreSacl: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).put_ApplyStoreSacl(@ptrCast(*const IAzAuthorizationStore, self), bApplyStoreSacl); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_PolicyAdministratorsName(self: *const T, pvarAdmins: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_PolicyAdministratorsName(@ptrCast(*const IAzAuthorizationStore, self), pvarAdmins); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_PolicyReadersName(self: *const T, pvarReaders: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_PolicyReadersName(@ptrCast(*const IAzAuthorizationStore, self), pvarReaders); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_AddPolicyAdministratorName(self: *const T, bstrAdmin: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).AddPolicyAdministratorName(@ptrCast(*const IAzAuthorizationStore, self), bstrAdmin, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_DeletePolicyAdministratorName(self: *const T, bstrAdmin: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).DeletePolicyAdministratorName(@ptrCast(*const IAzAuthorizationStore, self), bstrAdmin, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_AddPolicyReaderName(self: *const T, bstrReader: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).AddPolicyReaderName(@ptrCast(*const IAzAuthorizationStore, self), bstrReader, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_DeletePolicyReaderName(self: *const T, bstrReader: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).DeletePolicyReaderName(@ptrCast(*const IAzAuthorizationStore, self), bstrReader, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_get_DelegatedPolicyUsersName(self: *const T, pvarDelegatedPolicyUsers: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).get_DelegatedPolicyUsersName(@ptrCast(*const IAzAuthorizationStore, self), pvarDelegatedPolicyUsers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_AddDelegatedPolicyUserName(self: *const T, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).AddDelegatedPolicyUserName(@ptrCast(*const IAzAuthorizationStore, self), bstrDelegatedPolicyUser, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_DeleteDelegatedPolicyUserName(self: *const T, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).DeleteDelegatedPolicyUserName(@ptrCast(*const IAzAuthorizationStore, self), bstrDelegatedPolicyUser, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore_CloseApplication(self: *const T, bstrApplicationName: ?BSTR, lFlag: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore.VTable, self.vtable).CloseApplication(@ptrCast(*const IAzAuthorizationStore, self), bstrApplicationName, lFlag); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2008' const IID_IAzAuthorizationStore2_Value = Guid.initString("b11e5584-d577-4273-b6c5-0973e0f8e80d"); pub const IID_IAzAuthorizationStore2 = &IID_IAzAuthorizationStore2_Value; pub const IAzAuthorizationStore2 = extern struct { pub const VTable = extern struct { base: IAzAuthorizationStore.VTable, OpenApplication2: fn( self: *const IAzAuthorizationStore2, bstrApplicationName: ?BSTR, varReserved: VARIANT, ppApplication: ?*?*IAzApplication2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateApplication2: fn( self: *const IAzAuthorizationStore2, bstrApplicationName: ?BSTR, varReserved: VARIANT, ppApplication: ?*?*IAzApplication2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IAzAuthorizationStore.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore2_OpenApplication2(self: *const T, bstrApplicationName: ?BSTR, varReserved: VARIANT, ppApplication: ?*?*IAzApplication2) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore2.VTable, self.vtable).OpenApplication2(@ptrCast(*const IAzAuthorizationStore2, self), bstrApplicationName, varReserved, ppApplication); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore2_CreateApplication2(self: *const T, bstrApplicationName: ?BSTR, varReserved: VARIANT, ppApplication: ?*?*IAzApplication2) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore2.VTable, self.vtable).CreateApplication2(@ptrCast(*const IAzAuthorizationStore2, self), bstrApplicationName, varReserved, ppApplication); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzAuthorizationStore3_Value = Guid.initString("abc08425-0c86-4fa0-9be3-7189956c926e"); pub const IID_IAzAuthorizationStore3 = &IID_IAzAuthorizationStore3_Value; pub const IAzAuthorizationStore3 = extern struct { pub const VTable = extern struct { base: IAzAuthorizationStore2.VTable, IsUpdateNeeded: fn( self: *const IAzAuthorizationStore3, pbIsUpdateNeeded: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BizruleGroupSupported: fn( self: *const IAzAuthorizationStore3, pbSupported: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpgradeStoresFunctionalLevel: fn( self: *const IAzAuthorizationStore3, lFunctionalLevel: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsFunctionalLevelUpgradeSupported: fn( self: *const IAzAuthorizationStore3, lFunctionalLevel: i32, pbSupported: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSchemaVersion: fn( self: *const IAzAuthorizationStore3, plMajorVersion: ?*i32, plMinorVersion: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IAzAuthorizationStore2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore3_IsUpdateNeeded(self: *const T, pbIsUpdateNeeded: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore3.VTable, self.vtable).IsUpdateNeeded(@ptrCast(*const IAzAuthorizationStore3, self), pbIsUpdateNeeded); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore3_BizruleGroupSupported(self: *const T, pbSupported: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore3.VTable, self.vtable).BizruleGroupSupported(@ptrCast(*const IAzAuthorizationStore3, self), pbSupported); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore3_UpgradeStoresFunctionalLevel(self: *const T, lFunctionalLevel: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore3.VTable, self.vtable).UpgradeStoresFunctionalLevel(@ptrCast(*const IAzAuthorizationStore3, self), lFunctionalLevel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore3_IsFunctionalLevelUpgradeSupported(self: *const T, lFunctionalLevel: i32, pbSupported: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore3.VTable, self.vtable).IsFunctionalLevelUpgradeSupported(@ptrCast(*const IAzAuthorizationStore3, self), lFunctionalLevel, pbSupported); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzAuthorizationStore3_GetSchemaVersion(self: *const T, plMajorVersion: ?*i32, plMinorVersion: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzAuthorizationStore3.VTable, self.vtable).GetSchemaVersion(@ptrCast(*const IAzAuthorizationStore3, self), plMajorVersion, plMinorVersion); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzApplication_Value = Guid.initString("987bc7c7-b813-4d27-bede-6ba5ae867e95"); pub const IID_IAzApplication = &IID_IAzApplication_Value; pub const IAzApplication = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IAzApplication, pbstrName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Name: fn( self: *const IAzApplication, bstrName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IAzApplication, pbstrDescription: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IAzApplication, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ApplicationData: fn( self: *const IAzApplication, pbstrApplicationData: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ApplicationData: fn( self: *const IAzApplication, bstrApplicationData: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AuthzInterfaceClsid: fn( self: *const IAzApplication, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AuthzInterfaceClsid: fn( self: *const IAzApplication, bstrProp: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Version: fn( self: *const IAzApplication, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Version: fn( self: *const IAzApplication, bstrProp: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GenerateAudits: fn( self: *const IAzApplication, pbProp: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_GenerateAudits: fn( self: *const IAzApplication, bProp: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ApplyStoreSacl: fn( self: *const IAzApplication, pbProp: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ApplyStoreSacl: fn( self: *const IAzApplication, bProp: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Writable: fn( self: *const IAzApplication, pfProp: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProperty: fn( self: *const IAzApplication, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProperty: fn( self: *const IAzApplication, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PolicyAdministrators: fn( self: *const IAzApplication, pvarAdmins: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PolicyReaders: fn( self: *const IAzApplication, pvarReaders: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPolicyAdministrator: fn( self: *const IAzApplication, bstrAdmin: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePolicyAdministrator: fn( self: *const IAzApplication, bstrAdmin: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPolicyReader: fn( self: *const IAzApplication, bstrReader: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePolicyReader: fn( self: *const IAzApplication, bstrReader: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Scopes: fn( self: *const IAzApplication, ppScopeCollection: ?*?*IAzScopes, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenScope: fn( self: *const IAzApplication, bstrScopeName: ?BSTR, varReserved: VARIANT, ppScope: ?*?*IAzScope, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateScope: fn( self: *const IAzApplication, bstrScopeName: ?BSTR, varReserved: VARIANT, ppScope: ?*?*IAzScope, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteScope: fn( self: *const IAzApplication, bstrScopeName: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Operations: fn( self: *const IAzApplication, ppOperationCollection: ?*?*IAzOperations, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenOperation: fn( self: *const IAzApplication, bstrOperationName: ?BSTR, varReserved: VARIANT, ppOperation: ?*?*IAzOperation, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateOperation: fn( self: *const IAzApplication, bstrOperationName: ?BSTR, varReserved: VARIANT, ppOperation: ?*?*IAzOperation, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteOperation: fn( self: *const IAzApplication, bstrOperationName: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Tasks: fn( self: *const IAzApplication, ppTaskCollection: ?*?*IAzTasks, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenTask: fn( self: *const IAzApplication, bstrTaskName: ?BSTR, varReserved: VARIANT, ppTask: ?*?*IAzTask, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateTask: fn( self: *const IAzApplication, bstrTaskName: ?BSTR, varReserved: VARIANT, ppTask: ?*?*IAzTask, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteTask: fn( self: *const IAzApplication, bstrTaskName: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ApplicationGroups: fn( self: *const IAzApplication, ppGroupCollection: ?*?*IAzApplicationGroups, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenApplicationGroup: fn( self: *const IAzApplication, bstrGroupName: ?BSTR, varReserved: VARIANT, ppGroup: ?*?*IAzApplicationGroup, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateApplicationGroup: fn( self: *const IAzApplication, bstrGroupName: ?BSTR, varReserved: VARIANT, ppGroup: ?*?*IAzApplicationGroup, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteApplicationGroup: fn( self: *const IAzApplication, bstrGroupName: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Roles: fn( self: *const IAzApplication, ppRoleCollection: ?*?*IAzRoles, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenRole: fn( self: *const IAzApplication, bstrRoleName: ?BSTR, varReserved: VARIANT, ppRole: ?*?*IAzRole, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateRole: fn( self: *const IAzApplication, bstrRoleName: ?BSTR, varReserved: VARIANT, ppRole: ?*?*IAzRole, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteRole: fn( self: *const IAzApplication, bstrRoleName: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitializeClientContextFromToken: fn( self: *const IAzApplication, ullTokenHandle: u64, varReserved: VARIANT, ppClientContext: ?*?*IAzClientContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPropertyItem: fn( self: *const IAzApplication, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePropertyItem: fn( self: *const IAzApplication, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Submit: fn( self: *const IAzApplication, lFlags: i32, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitializeClientContextFromName: fn( self: *const IAzApplication, ClientName: ?BSTR, DomainName: ?BSTR, varReserved: VARIANT, ppClientContext: ?*?*IAzClientContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DelegatedPolicyUsers: fn( self: *const IAzApplication, pvarDelegatedPolicyUsers: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddDelegatedPolicyUser: fn( self: *const IAzApplication, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteDelegatedPolicyUser: fn( self: *const IAzApplication, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitializeClientContextFromStringSid: fn( self: *const IAzApplication, SidString: ?BSTR, lOptions: i32, varReserved: VARIANT, ppClientContext: ?*?*IAzClientContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PolicyAdministratorsName: fn( self: *const IAzApplication, pvarAdmins: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PolicyReadersName: fn( self: *const IAzApplication, pvarReaders: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPolicyAdministratorName: fn( self: *const IAzApplication, bstrAdmin: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePolicyAdministratorName: fn( self: *const IAzApplication, bstrAdmin: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPolicyReaderName: fn( self: *const IAzApplication, bstrReader: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePolicyReaderName: fn( self: *const IAzApplication, bstrReader: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DelegatedPolicyUsersName: fn( self: *const IAzApplication, pvarDelegatedPolicyUsers: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddDelegatedPolicyUserName: fn( self: *const IAzApplication, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteDelegatedPolicyUserName: fn( self: *const IAzApplication, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_Name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_Name(@ptrCast(*const IAzApplication, self), pbstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_put_Name(self: *const T, bstrName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).put_Name(@ptrCast(*const IAzApplication, self), bstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_Description(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_Description(@ptrCast(*const IAzApplication, self), pbstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).put_Description(@ptrCast(*const IAzApplication, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_ApplicationData(self: *const T, pbstrApplicationData: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_ApplicationData(@ptrCast(*const IAzApplication, self), pbstrApplicationData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_put_ApplicationData(self: *const T, bstrApplicationData: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).put_ApplicationData(@ptrCast(*const IAzApplication, self), bstrApplicationData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_AuthzInterfaceClsid(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_AuthzInterfaceClsid(@ptrCast(*const IAzApplication, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_put_AuthzInterfaceClsid(self: *const T, bstrProp: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).put_AuthzInterfaceClsid(@ptrCast(*const IAzApplication, self), bstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_Version(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_Version(@ptrCast(*const IAzApplication, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_put_Version(self: *const T, bstrProp: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).put_Version(@ptrCast(*const IAzApplication, self), bstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_GenerateAudits(self: *const T, pbProp: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_GenerateAudits(@ptrCast(*const IAzApplication, self), pbProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_put_GenerateAudits(self: *const T, bProp: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).put_GenerateAudits(@ptrCast(*const IAzApplication, self), bProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_ApplyStoreSacl(self: *const T, pbProp: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_ApplyStoreSacl(@ptrCast(*const IAzApplication, self), pbProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_put_ApplyStoreSacl(self: *const T, bProp: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).put_ApplyStoreSacl(@ptrCast(*const IAzApplication, self), bProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_Writable(self: *const T, pfProp: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_Writable(@ptrCast(*const IAzApplication, self), pfProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_GetProperty(self: *const T, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).GetProperty(@ptrCast(*const IAzApplication, self), lPropId, varReserved, pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_SetProperty(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).SetProperty(@ptrCast(*const IAzApplication, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_PolicyAdministrators(self: *const T, pvarAdmins: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_PolicyAdministrators(@ptrCast(*const IAzApplication, self), pvarAdmins); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_PolicyReaders(self: *const T, pvarReaders: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_PolicyReaders(@ptrCast(*const IAzApplication, self), pvarReaders); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_AddPolicyAdministrator(self: *const T, bstrAdmin: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).AddPolicyAdministrator(@ptrCast(*const IAzApplication, self), bstrAdmin, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_DeletePolicyAdministrator(self: *const T, bstrAdmin: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).DeletePolicyAdministrator(@ptrCast(*const IAzApplication, self), bstrAdmin, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_AddPolicyReader(self: *const T, bstrReader: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).AddPolicyReader(@ptrCast(*const IAzApplication, self), bstrReader, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_DeletePolicyReader(self: *const T, bstrReader: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).DeletePolicyReader(@ptrCast(*const IAzApplication, self), bstrReader, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_Scopes(self: *const T, ppScopeCollection: ?*?*IAzScopes) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_Scopes(@ptrCast(*const IAzApplication, self), ppScopeCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_OpenScope(self: *const T, bstrScopeName: ?BSTR, varReserved: VARIANT, ppScope: ?*?*IAzScope) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).OpenScope(@ptrCast(*const IAzApplication, self), bstrScopeName, varReserved, ppScope); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_CreateScope(self: *const T, bstrScopeName: ?BSTR, varReserved: VARIANT, ppScope: ?*?*IAzScope) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).CreateScope(@ptrCast(*const IAzApplication, self), bstrScopeName, varReserved, ppScope); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_DeleteScope(self: *const T, bstrScopeName: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).DeleteScope(@ptrCast(*const IAzApplication, self), bstrScopeName, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_Operations(self: *const T, ppOperationCollection: ?*?*IAzOperations) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_Operations(@ptrCast(*const IAzApplication, self), ppOperationCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_OpenOperation(self: *const T, bstrOperationName: ?BSTR, varReserved: VARIANT, ppOperation: ?*?*IAzOperation) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).OpenOperation(@ptrCast(*const IAzApplication, self), bstrOperationName, varReserved, ppOperation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_CreateOperation(self: *const T, bstrOperationName: ?BSTR, varReserved: VARIANT, ppOperation: ?*?*IAzOperation) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).CreateOperation(@ptrCast(*const IAzApplication, self), bstrOperationName, varReserved, ppOperation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_DeleteOperation(self: *const T, bstrOperationName: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).DeleteOperation(@ptrCast(*const IAzApplication, self), bstrOperationName, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_Tasks(self: *const T, ppTaskCollection: ?*?*IAzTasks) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_Tasks(@ptrCast(*const IAzApplication, self), ppTaskCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_OpenTask(self: *const T, bstrTaskName: ?BSTR, varReserved: VARIANT, ppTask: ?*?*IAzTask) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).OpenTask(@ptrCast(*const IAzApplication, self), bstrTaskName, varReserved, ppTask); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_CreateTask(self: *const T, bstrTaskName: ?BSTR, varReserved: VARIANT, ppTask: ?*?*IAzTask) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).CreateTask(@ptrCast(*const IAzApplication, self), bstrTaskName, varReserved, ppTask); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_DeleteTask(self: *const T, bstrTaskName: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).DeleteTask(@ptrCast(*const IAzApplication, self), bstrTaskName, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_ApplicationGroups(self: *const T, ppGroupCollection: ?*?*IAzApplicationGroups) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_ApplicationGroups(@ptrCast(*const IAzApplication, self), ppGroupCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_OpenApplicationGroup(self: *const T, bstrGroupName: ?BSTR, varReserved: VARIANT, ppGroup: ?*?*IAzApplicationGroup) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).OpenApplicationGroup(@ptrCast(*const IAzApplication, self), bstrGroupName, varReserved, ppGroup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_CreateApplicationGroup(self: *const T, bstrGroupName: ?BSTR, varReserved: VARIANT, ppGroup: ?*?*IAzApplicationGroup) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).CreateApplicationGroup(@ptrCast(*const IAzApplication, self), bstrGroupName, varReserved, ppGroup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_DeleteApplicationGroup(self: *const T, bstrGroupName: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).DeleteApplicationGroup(@ptrCast(*const IAzApplication, self), bstrGroupName, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_Roles(self: *const T, ppRoleCollection: ?*?*IAzRoles) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_Roles(@ptrCast(*const IAzApplication, self), ppRoleCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_OpenRole(self: *const T, bstrRoleName: ?BSTR, varReserved: VARIANT, ppRole: ?*?*IAzRole) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).OpenRole(@ptrCast(*const IAzApplication, self), bstrRoleName, varReserved, ppRole); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_CreateRole(self: *const T, bstrRoleName: ?BSTR, varReserved: VARIANT, ppRole: ?*?*IAzRole) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).CreateRole(@ptrCast(*const IAzApplication, self), bstrRoleName, varReserved, ppRole); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_DeleteRole(self: *const T, bstrRoleName: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).DeleteRole(@ptrCast(*const IAzApplication, self), bstrRoleName, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_InitializeClientContextFromToken(self: *const T, ullTokenHandle: u64, varReserved: VARIANT, ppClientContext: ?*?*IAzClientContext) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).InitializeClientContextFromToken(@ptrCast(*const IAzApplication, self), ullTokenHandle, varReserved, ppClientContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_AddPropertyItem(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).AddPropertyItem(@ptrCast(*const IAzApplication, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_DeletePropertyItem(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).DeletePropertyItem(@ptrCast(*const IAzApplication, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_Submit(self: *const T, lFlags: i32, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).Submit(@ptrCast(*const IAzApplication, self), lFlags, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_InitializeClientContextFromName(self: *const T, ClientName: ?BSTR, DomainName: ?BSTR, varReserved: VARIANT, ppClientContext: ?*?*IAzClientContext) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).InitializeClientContextFromName(@ptrCast(*const IAzApplication, self), ClientName, DomainName, varReserved, ppClientContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_DelegatedPolicyUsers(self: *const T, pvarDelegatedPolicyUsers: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_DelegatedPolicyUsers(@ptrCast(*const IAzApplication, self), pvarDelegatedPolicyUsers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_AddDelegatedPolicyUser(self: *const T, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).AddDelegatedPolicyUser(@ptrCast(*const IAzApplication, self), bstrDelegatedPolicyUser, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_DeleteDelegatedPolicyUser(self: *const T, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).DeleteDelegatedPolicyUser(@ptrCast(*const IAzApplication, self), bstrDelegatedPolicyUser, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_InitializeClientContextFromStringSid(self: *const T, SidString: ?BSTR, lOptions: i32, varReserved: VARIANT, ppClientContext: ?*?*IAzClientContext) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).InitializeClientContextFromStringSid(@ptrCast(*const IAzApplication, self), SidString, lOptions, varReserved, ppClientContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_PolicyAdministratorsName(self: *const T, pvarAdmins: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_PolicyAdministratorsName(@ptrCast(*const IAzApplication, self), pvarAdmins); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_PolicyReadersName(self: *const T, pvarReaders: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_PolicyReadersName(@ptrCast(*const IAzApplication, self), pvarReaders); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_AddPolicyAdministratorName(self: *const T, bstrAdmin: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).AddPolicyAdministratorName(@ptrCast(*const IAzApplication, self), bstrAdmin, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_DeletePolicyAdministratorName(self: *const T, bstrAdmin: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).DeletePolicyAdministratorName(@ptrCast(*const IAzApplication, self), bstrAdmin, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_AddPolicyReaderName(self: *const T, bstrReader: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).AddPolicyReaderName(@ptrCast(*const IAzApplication, self), bstrReader, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_DeletePolicyReaderName(self: *const T, bstrReader: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).DeletePolicyReaderName(@ptrCast(*const IAzApplication, self), bstrReader, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_get_DelegatedPolicyUsersName(self: *const T, pvarDelegatedPolicyUsers: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).get_DelegatedPolicyUsersName(@ptrCast(*const IAzApplication, self), pvarDelegatedPolicyUsers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_AddDelegatedPolicyUserName(self: *const T, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).AddDelegatedPolicyUserName(@ptrCast(*const IAzApplication, self), bstrDelegatedPolicyUser, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication_DeleteDelegatedPolicyUserName(self: *const T, bstrDelegatedPolicyUser: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication.VTable, self.vtable).DeleteDelegatedPolicyUserName(@ptrCast(*const IAzApplication, self), bstrDelegatedPolicyUser, varReserved); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzApplication2_Value = Guid.initString("086a68af-a249-437c-b18d-d4d86d6a9660"); pub const IID_IAzApplication2 = &IID_IAzApplication2_Value; pub const IAzApplication2 = extern struct { pub const VTable = extern struct { base: IAzApplication.VTable, InitializeClientContextFromToken2: fn( self: *const IAzApplication2, ulTokenHandleLowPart: u32, ulTokenHandleHighPart: u32, varReserved: VARIANT, ppClientContext: ?*?*IAzClientContext2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitializeClientContext2: fn( self: *const IAzApplication2, IdentifyingString: ?BSTR, varReserved: VARIANT, ppClientContext: ?*?*IAzClientContext2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IAzApplication.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication2_InitializeClientContextFromToken2(self: *const T, ulTokenHandleLowPart: u32, ulTokenHandleHighPart: u32, varReserved: VARIANT, ppClientContext: ?*?*IAzClientContext2) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication2.VTable, self.vtable).InitializeClientContextFromToken2(@ptrCast(*const IAzApplication2, self), ulTokenHandleLowPart, ulTokenHandleHighPart, varReserved, ppClientContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication2_InitializeClientContext2(self: *const T, IdentifyingString: ?BSTR, varReserved: VARIANT, ppClientContext: ?*?*IAzClientContext2) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication2.VTable, self.vtable).InitializeClientContext2(@ptrCast(*const IAzApplication2, self), IdentifyingString, varReserved, ppClientContext); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzApplications_Value = Guid.initString("929b11a9-95c5-4a84-a29a-20ad42c2f16c"); pub const IID_IAzApplications = &IID_IAzApplications_Value; pub const IAzApplications = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IAzApplications, Index: i32, pvarObtPtr: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IAzApplications, plCount: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IAzApplications, ppEnumPtr: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplications_get_Item(self: *const T, Index: i32, pvarObtPtr: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplications.VTable, self.vtable).get_Item(@ptrCast(*const IAzApplications, self), Index, pvarObtPtr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplications_get_Count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplications.VTable, self.vtable).get_Count(@ptrCast(*const IAzApplications, self), plCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplications_get__NewEnum(self: *const T, ppEnumPtr: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplications.VTable, self.vtable).get__NewEnum(@ptrCast(*const IAzApplications, self), ppEnumPtr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzOperation_Value = Guid.initString("5e56b24f-ea01-4d61-be44-c49b5e4eaf74"); pub const IID_IAzOperation = &IID_IAzOperation_Value; pub const IAzOperation = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IAzOperation, pbstrName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Name: fn( self: *const IAzOperation, bstrName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IAzOperation, pbstrDescription: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IAzOperation, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ApplicationData: fn( self: *const IAzOperation, pbstrApplicationData: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ApplicationData: fn( self: *const IAzOperation, bstrApplicationData: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OperationID: fn( self: *const IAzOperation, plProp: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OperationID: fn( self: *const IAzOperation, lProp: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Writable: fn( self: *const IAzOperation, pfProp: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProperty: fn( self: *const IAzOperation, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProperty: fn( self: *const IAzOperation, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Submit: fn( self: *const IAzOperation, lFlags: i32, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperation_get_Name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperation.VTable, self.vtable).get_Name(@ptrCast(*const IAzOperation, self), pbstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperation_put_Name(self: *const T, bstrName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperation.VTable, self.vtable).put_Name(@ptrCast(*const IAzOperation, self), bstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperation_get_Description(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperation.VTable, self.vtable).get_Description(@ptrCast(*const IAzOperation, self), pbstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperation_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperation.VTable, self.vtable).put_Description(@ptrCast(*const IAzOperation, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperation_get_ApplicationData(self: *const T, pbstrApplicationData: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperation.VTable, self.vtable).get_ApplicationData(@ptrCast(*const IAzOperation, self), pbstrApplicationData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperation_put_ApplicationData(self: *const T, bstrApplicationData: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperation.VTable, self.vtable).put_ApplicationData(@ptrCast(*const IAzOperation, self), bstrApplicationData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperation_get_OperationID(self: *const T, plProp: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperation.VTable, self.vtable).get_OperationID(@ptrCast(*const IAzOperation, self), plProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperation_put_OperationID(self: *const T, lProp: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperation.VTable, self.vtable).put_OperationID(@ptrCast(*const IAzOperation, self), lProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperation_get_Writable(self: *const T, pfProp: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperation.VTable, self.vtable).get_Writable(@ptrCast(*const IAzOperation, self), pfProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperation_GetProperty(self: *const T, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperation.VTable, self.vtable).GetProperty(@ptrCast(*const IAzOperation, self), lPropId, varReserved, pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperation_SetProperty(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperation.VTable, self.vtable).SetProperty(@ptrCast(*const IAzOperation, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperation_Submit(self: *const T, lFlags: i32, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperation.VTable, self.vtable).Submit(@ptrCast(*const IAzOperation, self), lFlags, varReserved); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzOperations_Value = Guid.initString("90ef9c07-9706-49d9-af80-0438a5f3ec35"); pub const IID_IAzOperations = &IID_IAzOperations_Value; pub const IAzOperations = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IAzOperations, Index: i32, pvarObtPtr: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IAzOperations, plCount: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IAzOperations, ppEnumPtr: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperations_get_Item(self: *const T, Index: i32, pvarObtPtr: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperations.VTable, self.vtable).get_Item(@ptrCast(*const IAzOperations, self), Index, pvarObtPtr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperations_get_Count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperations.VTable, self.vtable).get_Count(@ptrCast(*const IAzOperations, self), plCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperations_get__NewEnum(self: *const T, ppEnumPtr: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperations.VTable, self.vtable).get__NewEnum(@ptrCast(*const IAzOperations, self), ppEnumPtr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzTask_Value = Guid.initString("cb94e592-2e0e-4a6c-a336-b89a6dc1e388"); pub const IID_IAzTask = &IID_IAzTask_Value; pub const IAzTask = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IAzTask, pbstrName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Name: fn( self: *const IAzTask, bstrName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IAzTask, pbstrDescription: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IAzTask, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ApplicationData: fn( self: *const IAzTask, pbstrApplicationData: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ApplicationData: fn( self: *const IAzTask, bstrApplicationData: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BizRule: fn( self: *const IAzTask, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BizRule: fn( self: *const IAzTask, bstrProp: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BizRuleLanguage: fn( self: *const IAzTask, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BizRuleLanguage: fn( self: *const IAzTask, bstrProp: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BizRuleImportedPath: fn( self: *const IAzTask, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BizRuleImportedPath: fn( self: *const IAzTask, bstrProp: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_IsRoleDefinition: fn( self: *const IAzTask, pfProp: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_IsRoleDefinition: fn( self: *const IAzTask, fProp: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Operations: fn( self: *const IAzTask, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Tasks: fn( self: *const IAzTask, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddOperation: fn( self: *const IAzTask, bstrOp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteOperation: fn( self: *const IAzTask, bstrOp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddTask: fn( self: *const IAzTask, bstrTask: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteTask: fn( self: *const IAzTask, bstrTask: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Writable: fn( self: *const IAzTask, pfProp: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProperty: fn( self: *const IAzTask, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProperty: fn( self: *const IAzTask, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPropertyItem: fn( self: *const IAzTask, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePropertyItem: fn( self: *const IAzTask, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Submit: fn( self: *const IAzTask, lFlags: i32, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_get_Name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).get_Name(@ptrCast(*const IAzTask, self), pbstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_put_Name(self: *const T, bstrName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).put_Name(@ptrCast(*const IAzTask, self), bstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_get_Description(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).get_Description(@ptrCast(*const IAzTask, self), pbstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).put_Description(@ptrCast(*const IAzTask, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_get_ApplicationData(self: *const T, pbstrApplicationData: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).get_ApplicationData(@ptrCast(*const IAzTask, self), pbstrApplicationData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_put_ApplicationData(self: *const T, bstrApplicationData: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).put_ApplicationData(@ptrCast(*const IAzTask, self), bstrApplicationData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_get_BizRule(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).get_BizRule(@ptrCast(*const IAzTask, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_put_BizRule(self: *const T, bstrProp: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).put_BizRule(@ptrCast(*const IAzTask, self), bstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_get_BizRuleLanguage(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).get_BizRuleLanguage(@ptrCast(*const IAzTask, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_put_BizRuleLanguage(self: *const T, bstrProp: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).put_BizRuleLanguage(@ptrCast(*const IAzTask, self), bstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_get_BizRuleImportedPath(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).get_BizRuleImportedPath(@ptrCast(*const IAzTask, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_put_BizRuleImportedPath(self: *const T, bstrProp: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).put_BizRuleImportedPath(@ptrCast(*const IAzTask, self), bstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_get_IsRoleDefinition(self: *const T, pfProp: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).get_IsRoleDefinition(@ptrCast(*const IAzTask, self), pfProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_put_IsRoleDefinition(self: *const T, fProp: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).put_IsRoleDefinition(@ptrCast(*const IAzTask, self), fProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_get_Operations(self: *const T, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).get_Operations(@ptrCast(*const IAzTask, self), pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_get_Tasks(self: *const T, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).get_Tasks(@ptrCast(*const IAzTask, self), pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_AddOperation(self: *const T, bstrOp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).AddOperation(@ptrCast(*const IAzTask, self), bstrOp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_DeleteOperation(self: *const T, bstrOp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).DeleteOperation(@ptrCast(*const IAzTask, self), bstrOp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_AddTask(self: *const T, bstrTask: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).AddTask(@ptrCast(*const IAzTask, self), bstrTask, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_DeleteTask(self: *const T, bstrTask: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).DeleteTask(@ptrCast(*const IAzTask, self), bstrTask, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_get_Writable(self: *const T, pfProp: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).get_Writable(@ptrCast(*const IAzTask, self), pfProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_GetProperty(self: *const T, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).GetProperty(@ptrCast(*const IAzTask, self), lPropId, varReserved, pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_SetProperty(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).SetProperty(@ptrCast(*const IAzTask, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_AddPropertyItem(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).AddPropertyItem(@ptrCast(*const IAzTask, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_DeletePropertyItem(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).DeletePropertyItem(@ptrCast(*const IAzTask, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask_Submit(self: *const T, lFlags: i32, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask.VTable, self.vtable).Submit(@ptrCast(*const IAzTask, self), lFlags, varReserved); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzTasks_Value = Guid.initString("b338ccab-4c85-4388-8c0a-c58592bad398"); pub const IID_IAzTasks = &IID_IAzTasks_Value; pub const IAzTasks = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IAzTasks, Index: i32, pvarObtPtr: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IAzTasks, plCount: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IAzTasks, ppEnumPtr: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTasks_get_Item(self: *const T, Index: i32, pvarObtPtr: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTasks.VTable, self.vtable).get_Item(@ptrCast(*const IAzTasks, self), Index, pvarObtPtr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTasks_get_Count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTasks.VTable, self.vtable).get_Count(@ptrCast(*const IAzTasks, self), plCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTasks_get__NewEnum(self: *const T, ppEnumPtr: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTasks.VTable, self.vtable).get__NewEnum(@ptrCast(*const IAzTasks, self), ppEnumPtr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzScope_Value = Guid.initString("00e52487-e08d-4514-b62e-877d5645f5ab"); pub const IID_IAzScope = &IID_IAzScope_Value; pub const IAzScope = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IAzScope, pbstrName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Name: fn( self: *const IAzScope, bstrName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IAzScope, pbstrDescription: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IAzScope, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ApplicationData: fn( self: *const IAzScope, pbstrApplicationData: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ApplicationData: fn( self: *const IAzScope, bstrApplicationData: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Writable: fn( self: *const IAzScope, pfProp: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProperty: fn( self: *const IAzScope, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProperty: fn( self: *const IAzScope, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPropertyItem: fn( self: *const IAzScope, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePropertyItem: fn( self: *const IAzScope, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PolicyAdministrators: fn( self: *const IAzScope, pvarAdmins: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PolicyReaders: fn( self: *const IAzScope, pvarReaders: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPolicyAdministrator: fn( self: *const IAzScope, bstrAdmin: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePolicyAdministrator: fn( self: *const IAzScope, bstrAdmin: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPolicyReader: fn( self: *const IAzScope, bstrReader: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePolicyReader: fn( self: *const IAzScope, bstrReader: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ApplicationGroups: fn( self: *const IAzScope, ppGroupCollection: ?*?*IAzApplicationGroups, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenApplicationGroup: fn( self: *const IAzScope, bstrGroupName: ?BSTR, varReserved: VARIANT, ppGroup: ?*?*IAzApplicationGroup, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateApplicationGroup: fn( self: *const IAzScope, bstrGroupName: ?BSTR, varReserved: VARIANT, ppGroup: ?*?*IAzApplicationGroup, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteApplicationGroup: fn( self: *const IAzScope, bstrGroupName: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Roles: fn( self: *const IAzScope, ppRoleCollection: ?*?*IAzRoles, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenRole: fn( self: *const IAzScope, bstrRoleName: ?BSTR, varReserved: VARIANT, ppRole: ?*?*IAzRole, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateRole: fn( self: *const IAzScope, bstrRoleName: ?BSTR, varReserved: VARIANT, ppRole: ?*?*IAzRole, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteRole: fn( self: *const IAzScope, bstrRoleName: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Tasks: fn( self: *const IAzScope, ppTaskCollection: ?*?*IAzTasks, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenTask: fn( self: *const IAzScope, bstrTaskName: ?BSTR, varReserved: VARIANT, ppTask: ?*?*IAzTask, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateTask: fn( self: *const IAzScope, bstrTaskName: ?BSTR, varReserved: VARIANT, ppTask: ?*?*IAzTask, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteTask: fn( self: *const IAzScope, bstrTaskName: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Submit: fn( self: *const IAzScope, lFlags: i32, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CanBeDelegated: fn( self: *const IAzScope, pfProp: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BizrulesWritable: fn( self: *const IAzScope, pfProp: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PolicyAdministratorsName: fn( self: *const IAzScope, pvarAdmins: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PolicyReadersName: fn( self: *const IAzScope, pvarReaders: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPolicyAdministratorName: fn( self: *const IAzScope, bstrAdmin: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePolicyAdministratorName: fn( self: *const IAzScope, bstrAdmin: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPolicyReaderName: fn( self: *const IAzScope, bstrReader: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePolicyReaderName: fn( self: *const IAzScope, bstrReader: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_get_Name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).get_Name(@ptrCast(*const IAzScope, self), pbstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_put_Name(self: *const T, bstrName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).put_Name(@ptrCast(*const IAzScope, self), bstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_get_Description(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).get_Description(@ptrCast(*const IAzScope, self), pbstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).put_Description(@ptrCast(*const IAzScope, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_get_ApplicationData(self: *const T, pbstrApplicationData: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).get_ApplicationData(@ptrCast(*const IAzScope, self), pbstrApplicationData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_put_ApplicationData(self: *const T, bstrApplicationData: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).put_ApplicationData(@ptrCast(*const IAzScope, self), bstrApplicationData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_get_Writable(self: *const T, pfProp: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).get_Writable(@ptrCast(*const IAzScope, self), pfProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_GetProperty(self: *const T, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).GetProperty(@ptrCast(*const IAzScope, self), lPropId, varReserved, pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_SetProperty(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).SetProperty(@ptrCast(*const IAzScope, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_AddPropertyItem(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).AddPropertyItem(@ptrCast(*const IAzScope, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_DeletePropertyItem(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).DeletePropertyItem(@ptrCast(*const IAzScope, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_get_PolicyAdministrators(self: *const T, pvarAdmins: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).get_PolicyAdministrators(@ptrCast(*const IAzScope, self), pvarAdmins); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_get_PolicyReaders(self: *const T, pvarReaders: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).get_PolicyReaders(@ptrCast(*const IAzScope, self), pvarReaders); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_AddPolicyAdministrator(self: *const T, bstrAdmin: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).AddPolicyAdministrator(@ptrCast(*const IAzScope, self), bstrAdmin, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_DeletePolicyAdministrator(self: *const T, bstrAdmin: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).DeletePolicyAdministrator(@ptrCast(*const IAzScope, self), bstrAdmin, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_AddPolicyReader(self: *const T, bstrReader: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).AddPolicyReader(@ptrCast(*const IAzScope, self), bstrReader, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_DeletePolicyReader(self: *const T, bstrReader: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).DeletePolicyReader(@ptrCast(*const IAzScope, self), bstrReader, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_get_ApplicationGroups(self: *const T, ppGroupCollection: ?*?*IAzApplicationGroups) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).get_ApplicationGroups(@ptrCast(*const IAzScope, self), ppGroupCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_OpenApplicationGroup(self: *const T, bstrGroupName: ?BSTR, varReserved: VARIANT, ppGroup: ?*?*IAzApplicationGroup) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).OpenApplicationGroup(@ptrCast(*const IAzScope, self), bstrGroupName, varReserved, ppGroup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_CreateApplicationGroup(self: *const T, bstrGroupName: ?BSTR, varReserved: VARIANT, ppGroup: ?*?*IAzApplicationGroup) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).CreateApplicationGroup(@ptrCast(*const IAzScope, self), bstrGroupName, varReserved, ppGroup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_DeleteApplicationGroup(self: *const T, bstrGroupName: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).DeleteApplicationGroup(@ptrCast(*const IAzScope, self), bstrGroupName, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_get_Roles(self: *const T, ppRoleCollection: ?*?*IAzRoles) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).get_Roles(@ptrCast(*const IAzScope, self), ppRoleCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_OpenRole(self: *const T, bstrRoleName: ?BSTR, varReserved: VARIANT, ppRole: ?*?*IAzRole) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).OpenRole(@ptrCast(*const IAzScope, self), bstrRoleName, varReserved, ppRole); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_CreateRole(self: *const T, bstrRoleName: ?BSTR, varReserved: VARIANT, ppRole: ?*?*IAzRole) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).CreateRole(@ptrCast(*const IAzScope, self), bstrRoleName, varReserved, ppRole); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_DeleteRole(self: *const T, bstrRoleName: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).DeleteRole(@ptrCast(*const IAzScope, self), bstrRoleName, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_get_Tasks(self: *const T, ppTaskCollection: ?*?*IAzTasks) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).get_Tasks(@ptrCast(*const IAzScope, self), ppTaskCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_OpenTask(self: *const T, bstrTaskName: ?BSTR, varReserved: VARIANT, ppTask: ?*?*IAzTask) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).OpenTask(@ptrCast(*const IAzScope, self), bstrTaskName, varReserved, ppTask); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_CreateTask(self: *const T, bstrTaskName: ?BSTR, varReserved: VARIANT, ppTask: ?*?*IAzTask) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).CreateTask(@ptrCast(*const IAzScope, self), bstrTaskName, varReserved, ppTask); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_DeleteTask(self: *const T, bstrTaskName: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).DeleteTask(@ptrCast(*const IAzScope, self), bstrTaskName, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_Submit(self: *const T, lFlags: i32, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).Submit(@ptrCast(*const IAzScope, self), lFlags, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_get_CanBeDelegated(self: *const T, pfProp: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).get_CanBeDelegated(@ptrCast(*const IAzScope, self), pfProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_get_BizrulesWritable(self: *const T, pfProp: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).get_BizrulesWritable(@ptrCast(*const IAzScope, self), pfProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_get_PolicyAdministratorsName(self: *const T, pvarAdmins: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).get_PolicyAdministratorsName(@ptrCast(*const IAzScope, self), pvarAdmins); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_get_PolicyReadersName(self: *const T, pvarReaders: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).get_PolicyReadersName(@ptrCast(*const IAzScope, self), pvarReaders); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_AddPolicyAdministratorName(self: *const T, bstrAdmin: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).AddPolicyAdministratorName(@ptrCast(*const IAzScope, self), bstrAdmin, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_DeletePolicyAdministratorName(self: *const T, bstrAdmin: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).DeletePolicyAdministratorName(@ptrCast(*const IAzScope, self), bstrAdmin, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_AddPolicyReaderName(self: *const T, bstrReader: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).AddPolicyReaderName(@ptrCast(*const IAzScope, self), bstrReader, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope_DeletePolicyReaderName(self: *const T, bstrReader: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope.VTable, self.vtable).DeletePolicyReaderName(@ptrCast(*const IAzScope, self), bstrReader, varReserved); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzScopes_Value = Guid.initString("78e14853-9f5e-406d-9b91-6bdba6973510"); pub const IID_IAzScopes = &IID_IAzScopes_Value; pub const IAzScopes = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IAzScopes, Index: i32, pvarObtPtr: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IAzScopes, plCount: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IAzScopes, ppEnumPtr: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScopes_get_Item(self: *const T, Index: i32, pvarObtPtr: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScopes.VTable, self.vtable).get_Item(@ptrCast(*const IAzScopes, self), Index, pvarObtPtr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScopes_get_Count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScopes.VTable, self.vtable).get_Count(@ptrCast(*const IAzScopes, self), plCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScopes_get__NewEnum(self: *const T, ppEnumPtr: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScopes.VTable, self.vtable).get__NewEnum(@ptrCast(*const IAzScopes, self), ppEnumPtr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzApplicationGroup_Value = Guid.initString("f1b744cd-58a6-4e06-9fbf-36f6d779e21e"); pub const IID_IAzApplicationGroup = &IID_IAzApplicationGroup_Value; pub const IAzApplicationGroup = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IAzApplicationGroup, pbstrName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Name: fn( self: *const IAzApplicationGroup, bstrName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Type: fn( self: *const IAzApplicationGroup, plProp: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Type: fn( self: *const IAzApplicationGroup, lProp: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LdapQuery: fn( self: *const IAzApplicationGroup, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LdapQuery: fn( self: *const IAzApplicationGroup, bstrProp: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AppMembers: fn( self: *const IAzApplicationGroup, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AppNonMembers: fn( self: *const IAzApplicationGroup, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Members: fn( self: *const IAzApplicationGroup, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NonMembers: fn( self: *const IAzApplicationGroup, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IAzApplicationGroup, pbstrDescription: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IAzApplicationGroup, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddAppMember: fn( self: *const IAzApplicationGroup, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAppMember: fn( self: *const IAzApplicationGroup, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddAppNonMember: fn( self: *const IAzApplicationGroup, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAppNonMember: fn( self: *const IAzApplicationGroup, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddMember: fn( self: *const IAzApplicationGroup, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteMember: fn( self: *const IAzApplicationGroup, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddNonMember: fn( self: *const IAzApplicationGroup, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteNonMember: fn( self: *const IAzApplicationGroup, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Writable: fn( self: *const IAzApplicationGroup, pfProp: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProperty: fn( self: *const IAzApplicationGroup, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProperty: fn( self: *const IAzApplicationGroup, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPropertyItem: fn( self: *const IAzApplicationGroup, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePropertyItem: fn( self: *const IAzApplicationGroup, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Submit: fn( self: *const IAzApplicationGroup, lFlags: i32, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddMemberName: fn( self: *const IAzApplicationGroup, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteMemberName: fn( self: *const IAzApplicationGroup, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddNonMemberName: fn( self: *const IAzApplicationGroup, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteNonMemberName: fn( self: *const IAzApplicationGroup, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MembersName: fn( self: *const IAzApplicationGroup, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NonMembersName: fn( self: *const IAzApplicationGroup, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_get_Name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).get_Name(@ptrCast(*const IAzApplicationGroup, self), pbstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_put_Name(self: *const T, bstrName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).put_Name(@ptrCast(*const IAzApplicationGroup, self), bstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_get_Type(self: *const T, plProp: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).get_Type(@ptrCast(*const IAzApplicationGroup, self), plProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_put_Type(self: *const T, lProp: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).put_Type(@ptrCast(*const IAzApplicationGroup, self), lProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_get_LdapQuery(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).get_LdapQuery(@ptrCast(*const IAzApplicationGroup, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_put_LdapQuery(self: *const T, bstrProp: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).put_LdapQuery(@ptrCast(*const IAzApplicationGroup, self), bstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_get_AppMembers(self: *const T, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).get_AppMembers(@ptrCast(*const IAzApplicationGroup, self), pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_get_AppNonMembers(self: *const T, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).get_AppNonMembers(@ptrCast(*const IAzApplicationGroup, self), pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_get_Members(self: *const T, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).get_Members(@ptrCast(*const IAzApplicationGroup, self), pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_get_NonMembers(self: *const T, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).get_NonMembers(@ptrCast(*const IAzApplicationGroup, self), pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_get_Description(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).get_Description(@ptrCast(*const IAzApplicationGroup, self), pbstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).put_Description(@ptrCast(*const IAzApplicationGroup, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_AddAppMember(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).AddAppMember(@ptrCast(*const IAzApplicationGroup, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_DeleteAppMember(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).DeleteAppMember(@ptrCast(*const IAzApplicationGroup, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_AddAppNonMember(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).AddAppNonMember(@ptrCast(*const IAzApplicationGroup, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_DeleteAppNonMember(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).DeleteAppNonMember(@ptrCast(*const IAzApplicationGroup, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_AddMember(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).AddMember(@ptrCast(*const IAzApplicationGroup, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_DeleteMember(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).DeleteMember(@ptrCast(*const IAzApplicationGroup, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_AddNonMember(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).AddNonMember(@ptrCast(*const IAzApplicationGroup, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_DeleteNonMember(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).DeleteNonMember(@ptrCast(*const IAzApplicationGroup, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_get_Writable(self: *const T, pfProp: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).get_Writable(@ptrCast(*const IAzApplicationGroup, self), pfProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_GetProperty(self: *const T, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).GetProperty(@ptrCast(*const IAzApplicationGroup, self), lPropId, varReserved, pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_SetProperty(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).SetProperty(@ptrCast(*const IAzApplicationGroup, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_AddPropertyItem(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).AddPropertyItem(@ptrCast(*const IAzApplicationGroup, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_DeletePropertyItem(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).DeletePropertyItem(@ptrCast(*const IAzApplicationGroup, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_Submit(self: *const T, lFlags: i32, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).Submit(@ptrCast(*const IAzApplicationGroup, self), lFlags, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_AddMemberName(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).AddMemberName(@ptrCast(*const IAzApplicationGroup, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_DeleteMemberName(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).DeleteMemberName(@ptrCast(*const IAzApplicationGroup, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_AddNonMemberName(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).AddNonMemberName(@ptrCast(*const IAzApplicationGroup, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_DeleteNonMemberName(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).DeleteNonMemberName(@ptrCast(*const IAzApplicationGroup, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_get_MembersName(self: *const T, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).get_MembersName(@ptrCast(*const IAzApplicationGroup, self), pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup_get_NonMembersName(self: *const T, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup.VTable, self.vtable).get_NonMembersName(@ptrCast(*const IAzApplicationGroup, self), pvarProp); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzApplicationGroups_Value = Guid.initString("4ce66ad5-9f3c-469d-a911-b99887a7e685"); pub const IID_IAzApplicationGroups = &IID_IAzApplicationGroups_Value; pub const IAzApplicationGroups = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IAzApplicationGroups, Index: i32, pvarObtPtr: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IAzApplicationGroups, plCount: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IAzApplicationGroups, ppEnumPtr: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroups_get_Item(self: *const T, Index: i32, pvarObtPtr: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroups.VTable, self.vtable).get_Item(@ptrCast(*const IAzApplicationGroups, self), Index, pvarObtPtr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroups_get_Count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroups.VTable, self.vtable).get_Count(@ptrCast(*const IAzApplicationGroups, self), plCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroups_get__NewEnum(self: *const T, ppEnumPtr: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroups.VTable, self.vtable).get__NewEnum(@ptrCast(*const IAzApplicationGroups, self), ppEnumPtr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzRole_Value = Guid.initString("859e0d8d-62d7-41d8-a034-c0cd5d43fdfa"); pub const IID_IAzRole = &IID_IAzRole_Value; pub const IAzRole = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IAzRole, pbstrName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Name: fn( self: *const IAzRole, bstrName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IAzRole, pbstrDescription: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IAzRole, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ApplicationData: fn( self: *const IAzRole, pbstrApplicationData: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ApplicationData: fn( self: *const IAzRole, bstrApplicationData: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddAppMember: fn( self: *const IAzRole, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAppMember: fn( self: *const IAzRole, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddTask: fn( self: *const IAzRole, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteTask: fn( self: *const IAzRole, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddOperation: fn( self: *const IAzRole, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteOperation: fn( self: *const IAzRole, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddMember: fn( self: *const IAzRole, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteMember: fn( self: *const IAzRole, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Writable: fn( self: *const IAzRole, pfProp: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProperty: fn( self: *const IAzRole, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProperty: fn( self: *const IAzRole, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AppMembers: fn( self: *const IAzRole, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Members: fn( self: *const IAzRole, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Operations: fn( self: *const IAzRole, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Tasks: fn( self: *const IAzRole, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPropertyItem: fn( self: *const IAzRole, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePropertyItem: fn( self: *const IAzRole, lPropId: i32, varProp: VARIANT, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Submit: fn( self: *const IAzRole, lFlags: i32, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddMemberName: fn( self: *const IAzRole, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteMemberName: fn( self: *const IAzRole, bstrProp: ?BSTR, varReserved: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MembersName: fn( self: *const IAzRole, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_get_Name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).get_Name(@ptrCast(*const IAzRole, self), pbstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_put_Name(self: *const T, bstrName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).put_Name(@ptrCast(*const IAzRole, self), bstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_get_Description(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).get_Description(@ptrCast(*const IAzRole, self), pbstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).put_Description(@ptrCast(*const IAzRole, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_get_ApplicationData(self: *const T, pbstrApplicationData: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).get_ApplicationData(@ptrCast(*const IAzRole, self), pbstrApplicationData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_put_ApplicationData(self: *const T, bstrApplicationData: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).put_ApplicationData(@ptrCast(*const IAzRole, self), bstrApplicationData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_AddAppMember(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).AddAppMember(@ptrCast(*const IAzRole, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_DeleteAppMember(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).DeleteAppMember(@ptrCast(*const IAzRole, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_AddTask(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).AddTask(@ptrCast(*const IAzRole, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_DeleteTask(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).DeleteTask(@ptrCast(*const IAzRole, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_AddOperation(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).AddOperation(@ptrCast(*const IAzRole, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_DeleteOperation(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).DeleteOperation(@ptrCast(*const IAzRole, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_AddMember(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).AddMember(@ptrCast(*const IAzRole, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_DeleteMember(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).DeleteMember(@ptrCast(*const IAzRole, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_get_Writable(self: *const T, pfProp: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).get_Writable(@ptrCast(*const IAzRole, self), pfProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_GetProperty(self: *const T, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).GetProperty(@ptrCast(*const IAzRole, self), lPropId, varReserved, pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_SetProperty(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).SetProperty(@ptrCast(*const IAzRole, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_get_AppMembers(self: *const T, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).get_AppMembers(@ptrCast(*const IAzRole, self), pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_get_Members(self: *const T, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).get_Members(@ptrCast(*const IAzRole, self), pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_get_Operations(self: *const T, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).get_Operations(@ptrCast(*const IAzRole, self), pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_get_Tasks(self: *const T, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).get_Tasks(@ptrCast(*const IAzRole, self), pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_AddPropertyItem(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).AddPropertyItem(@ptrCast(*const IAzRole, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_DeletePropertyItem(self: *const T, lPropId: i32, varProp: VARIANT, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).DeletePropertyItem(@ptrCast(*const IAzRole, self), lPropId, varProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_Submit(self: *const T, lFlags: i32, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).Submit(@ptrCast(*const IAzRole, self), lFlags, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_AddMemberName(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).AddMemberName(@ptrCast(*const IAzRole, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_DeleteMemberName(self: *const T, bstrProp: ?BSTR, varReserved: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).DeleteMemberName(@ptrCast(*const IAzRole, self), bstrProp, varReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRole_get_MembersName(self: *const T, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRole.VTable, self.vtable).get_MembersName(@ptrCast(*const IAzRole, self), pvarProp); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzRoles_Value = Guid.initString("95e0f119-13b4-4dae-b65f-2f7d60d822e4"); pub const IID_IAzRoles = &IID_IAzRoles_Value; pub const IAzRoles = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IAzRoles, Index: i32, pvarObtPtr: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IAzRoles, plCount: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IAzRoles, ppEnumPtr: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoles_get_Item(self: *const T, Index: i32, pvarObtPtr: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoles.VTable, self.vtable).get_Item(@ptrCast(*const IAzRoles, self), Index, pvarObtPtr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoles_get_Count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoles.VTable, self.vtable).get_Count(@ptrCast(*const IAzRoles, self), plCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoles_get__NewEnum(self: *const T, ppEnumPtr: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoles.VTable, self.vtable).get__NewEnum(@ptrCast(*const IAzRoles, self), ppEnumPtr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzClientContext_Value = Guid.initString("eff1f00b-488a-466d-afd9-a401c5f9eef5"); pub const IID_IAzClientContext = &IID_IAzClientContext_Value; pub const IAzClientContext = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, AccessCheck: fn( self: *const IAzClientContext, bstrObjectName: ?BSTR, varScopeNames: VARIANT, varOperations: VARIANT, varParameterNames: VARIANT, varParameterValues: VARIANT, varInterfaceNames: VARIANT, varInterfaceFlags: VARIANT, varInterfaces: VARIANT, pvarResults: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBusinessRuleString: fn( self: *const IAzClientContext, pbstrBusinessRuleString: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserDn: fn( self: *const IAzClientContext, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserSamCompat: fn( self: *const IAzClientContext, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserDisplay: fn( self: *const IAzClientContext, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserGuid: fn( self: *const IAzClientContext, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserCanonical: fn( self: *const IAzClientContext, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserUpn: fn( self: *const IAzClientContext, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserDnsSamCompat: fn( self: *const IAzClientContext, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProperty: fn( self: *const IAzClientContext, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRoles: fn( self: *const IAzClientContext, bstrScopeName: ?BSTR, pvarRoleNames: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RoleForAccessCheck: fn( self: *const IAzClientContext, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_RoleForAccessCheck: fn( self: *const IAzClientContext, bstrProp: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext_AccessCheck(self: *const T, bstrObjectName: ?BSTR, varScopeNames: VARIANT, varOperations: VARIANT, varParameterNames: VARIANT, varParameterValues: VARIANT, varInterfaceNames: VARIANT, varInterfaceFlags: VARIANT, varInterfaces: VARIANT, pvarResults: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext.VTable, self.vtable).AccessCheck(@ptrCast(*const IAzClientContext, self), bstrObjectName, varScopeNames, varOperations, varParameterNames, varParameterValues, varInterfaceNames, varInterfaceFlags, varInterfaces, pvarResults); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext_GetBusinessRuleString(self: *const T, pbstrBusinessRuleString: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext.VTable, self.vtable).GetBusinessRuleString(@ptrCast(*const IAzClientContext, self), pbstrBusinessRuleString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext_get_UserDn(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext.VTable, self.vtable).get_UserDn(@ptrCast(*const IAzClientContext, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext_get_UserSamCompat(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext.VTable, self.vtable).get_UserSamCompat(@ptrCast(*const IAzClientContext, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext_get_UserDisplay(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext.VTable, self.vtable).get_UserDisplay(@ptrCast(*const IAzClientContext, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext_get_UserGuid(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext.VTable, self.vtable).get_UserGuid(@ptrCast(*const IAzClientContext, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext_get_UserCanonical(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext.VTable, self.vtable).get_UserCanonical(@ptrCast(*const IAzClientContext, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext_get_UserUpn(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext.VTable, self.vtable).get_UserUpn(@ptrCast(*const IAzClientContext, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext_get_UserDnsSamCompat(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext.VTable, self.vtable).get_UserDnsSamCompat(@ptrCast(*const IAzClientContext, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext_GetProperty(self: *const T, lPropId: i32, varReserved: VARIANT, pvarProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext.VTable, self.vtable).GetProperty(@ptrCast(*const IAzClientContext, self), lPropId, varReserved, pvarProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext_GetRoles(self: *const T, bstrScopeName: ?BSTR, pvarRoleNames: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext.VTable, self.vtable).GetRoles(@ptrCast(*const IAzClientContext, self), bstrScopeName, pvarRoleNames); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext_get_RoleForAccessCheck(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext.VTable, self.vtable).get_RoleForAccessCheck(@ptrCast(*const IAzClientContext, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext_put_RoleForAccessCheck(self: *const T, bstrProp: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext.VTable, self.vtable).put_RoleForAccessCheck(@ptrCast(*const IAzClientContext, self), bstrProp); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2008' const IID_IAzClientContext2_Value = Guid.initString("2b0c92b8-208a-488a-8f81-e4edb22111cd"); pub const IID_IAzClientContext2 = &IID_IAzClientContext2_Value; pub const IAzClientContext2 = extern struct { pub const VTable = extern struct { base: IAzClientContext.VTable, GetAssignedScopesPage: fn( self: *const IAzClientContext2, lOptions: i32, PageSize: i32, pvarCursor: ?*VARIANT, pvarScopeNames: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddRoles: fn( self: *const IAzClientContext2, varRoles: VARIANT, bstrScopeName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddApplicationGroups: fn( self: *const IAzClientContext2, varApplicationGroups: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddStringSids: fn( self: *const IAzClientContext2, varStringSids: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LDAPQueryDN: fn( self: *const IAzClientContext2, bstrLDAPQueryDN: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LDAPQueryDN: fn( self: *const IAzClientContext2, pbstrLDAPQueryDN: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IAzClientContext.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext2_GetAssignedScopesPage(self: *const T, lOptions: i32, PageSize: i32, pvarCursor: ?*VARIANT, pvarScopeNames: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext2.VTable, self.vtable).GetAssignedScopesPage(@ptrCast(*const IAzClientContext2, self), lOptions, PageSize, pvarCursor, pvarScopeNames); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext2_AddRoles(self: *const T, varRoles: VARIANT, bstrScopeName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext2.VTable, self.vtable).AddRoles(@ptrCast(*const IAzClientContext2, self), varRoles, bstrScopeName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext2_AddApplicationGroups(self: *const T, varApplicationGroups: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext2.VTable, self.vtable).AddApplicationGroups(@ptrCast(*const IAzClientContext2, self), varApplicationGroups); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext2_AddStringSids(self: *const T, varStringSids: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext2.VTable, self.vtable).AddStringSids(@ptrCast(*const IAzClientContext2, self), varStringSids); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext2_put_LDAPQueryDN(self: *const T, bstrLDAPQueryDN: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext2.VTable, self.vtable).put_LDAPQueryDN(@ptrCast(*const IAzClientContext2, self), bstrLDAPQueryDN); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext2_get_LDAPQueryDN(self: *const T, pbstrLDAPQueryDN: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext2.VTable, self.vtable).get_LDAPQueryDN(@ptrCast(*const IAzClientContext2, self), pbstrLDAPQueryDN); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzBizRuleContext_Value = Guid.initString("e192f17d-d59f-455e-a152-940316cd77b2"); pub const IID_IAzBizRuleContext = &IID_IAzBizRuleContext_Value; pub const IAzBizRuleContext = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BusinessRuleResult: fn( self: *const IAzBizRuleContext, bResult: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BusinessRuleString: fn( self: *const IAzBizRuleContext, bstrBusinessRuleString: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BusinessRuleString: fn( self: *const IAzBizRuleContext, pbstrBusinessRuleString: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetParameter: fn( self: *const IAzBizRuleContext, bstrParameterName: ?BSTR, pvarParameterValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleContext_put_BusinessRuleResult(self: *const T, bResult: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleContext.VTable, self.vtable).put_BusinessRuleResult(@ptrCast(*const IAzBizRuleContext, self), bResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleContext_put_BusinessRuleString(self: *const T, bstrBusinessRuleString: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleContext.VTable, self.vtable).put_BusinessRuleString(@ptrCast(*const IAzBizRuleContext, self), bstrBusinessRuleString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleContext_get_BusinessRuleString(self: *const T, pbstrBusinessRuleString: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleContext.VTable, self.vtable).get_BusinessRuleString(@ptrCast(*const IAzBizRuleContext, self), pbstrBusinessRuleString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleContext_GetParameter(self: *const T, bstrParameterName: ?BSTR, pvarParameterValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleContext.VTable, self.vtable).GetParameter(@ptrCast(*const IAzBizRuleContext, self), bstrParameterName, pvarParameterValue); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzBizRuleParameters_Value = Guid.initString("fc17685f-e25d-4dcd-bae1-276ec9533cb5"); pub const IID_IAzBizRuleParameters = &IID_IAzBizRuleParameters_Value; pub const IAzBizRuleParameters = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, AddParameter: fn( self: *const IAzBizRuleParameters, bstrParameterName: ?BSTR, varParameterValue: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddParameters: fn( self: *const IAzBizRuleParameters, varParameterNames: VARIANT, varParameterValues: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetParameterValue: fn( self: *const IAzBizRuleParameters, bstrParameterName: ?BSTR, pvarParameterValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IAzBizRuleParameters, varParameterName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAll: fn( self: *const IAzBizRuleParameters, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IAzBizRuleParameters, plCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleParameters_AddParameter(self: *const T, bstrParameterName: ?BSTR, varParameterValue: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleParameters.VTable, self.vtable).AddParameter(@ptrCast(*const IAzBizRuleParameters, self), bstrParameterName, varParameterValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleParameters_AddParameters(self: *const T, varParameterNames: VARIANT, varParameterValues: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleParameters.VTable, self.vtable).AddParameters(@ptrCast(*const IAzBizRuleParameters, self), varParameterNames, varParameterValues); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleParameters_GetParameterValue(self: *const T, bstrParameterName: ?BSTR, pvarParameterValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleParameters.VTable, self.vtable).GetParameterValue(@ptrCast(*const IAzBizRuleParameters, self), bstrParameterName, pvarParameterValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleParameters_Remove(self: *const T, varParameterName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleParameters.VTable, self.vtable).Remove(@ptrCast(*const IAzBizRuleParameters, self), varParameterName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleParameters_RemoveAll(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleParameters.VTable, self.vtable).RemoveAll(@ptrCast(*const IAzBizRuleParameters, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleParameters_get_Count(self: *const T, plCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleParameters.VTable, self.vtable).get_Count(@ptrCast(*const IAzBizRuleParameters, self), plCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzBizRuleInterfaces_Value = Guid.initString("e94128c7-e9da-44cc-b0bd-53036f3aab3d"); pub const IID_IAzBizRuleInterfaces = &IID_IAzBizRuleInterfaces_Value; pub const IAzBizRuleInterfaces = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, AddInterface: fn( self: *const IAzBizRuleInterfaces, bstrInterfaceName: ?BSTR, lInterfaceFlag: i32, varInterface: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddInterfaces: fn( self: *const IAzBizRuleInterfaces, varInterfaceNames: VARIANT, varInterfaceFlags: VARIANT, varInterfaces: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInterfaceValue: fn( self: *const IAzBizRuleInterfaces, bstrInterfaceName: ?BSTR, lInterfaceFlag: ?*i32, varInterface: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IAzBizRuleInterfaces, bstrInterfaceName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAll: fn( self: *const IAzBizRuleInterfaces, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IAzBizRuleInterfaces, plCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleInterfaces_AddInterface(self: *const T, bstrInterfaceName: ?BSTR, lInterfaceFlag: i32, varInterface: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleInterfaces.VTable, self.vtable).AddInterface(@ptrCast(*const IAzBizRuleInterfaces, self), bstrInterfaceName, lInterfaceFlag, varInterface); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleInterfaces_AddInterfaces(self: *const T, varInterfaceNames: VARIANT, varInterfaceFlags: VARIANT, varInterfaces: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleInterfaces.VTable, self.vtable).AddInterfaces(@ptrCast(*const IAzBizRuleInterfaces, self), varInterfaceNames, varInterfaceFlags, varInterfaces); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleInterfaces_GetInterfaceValue(self: *const T, bstrInterfaceName: ?BSTR, lInterfaceFlag: ?*i32, varInterface: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleInterfaces.VTable, self.vtable).GetInterfaceValue(@ptrCast(*const IAzBizRuleInterfaces, self), bstrInterfaceName, lInterfaceFlag, varInterface); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleInterfaces_Remove(self: *const T, bstrInterfaceName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleInterfaces.VTable, self.vtable).Remove(@ptrCast(*const IAzBizRuleInterfaces, self), bstrInterfaceName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleInterfaces_RemoveAll(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleInterfaces.VTable, self.vtable).RemoveAll(@ptrCast(*const IAzBizRuleInterfaces, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzBizRuleInterfaces_get_Count(self: *const T, plCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzBizRuleInterfaces.VTable, self.vtable).get_Count(@ptrCast(*const IAzBizRuleInterfaces, self), plCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzClientContext3_Value = Guid.initString("11894fde-1deb-4b4b-8907-6d1cda1f5d4f"); pub const IID_IAzClientContext3 = &IID_IAzClientContext3_Value; pub const IAzClientContext3 = extern struct { pub const VTable = extern struct { base: IAzClientContext2.VTable, AccessCheck2: fn( self: *const IAzClientContext3, bstrObjectName: ?BSTR, bstrScopeName: ?BSTR, lOperation: i32, plResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsInRoleAssignment: fn( self: *const IAzClientContext3, bstrScopeName: ?BSTR, bstrRoleName: ?BSTR, pbIsInRole: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOperations: fn( self: *const IAzClientContext3, bstrScopeName: ?BSTR, ppOperationCollection: ?*?*IAzOperations, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTasks: fn( self: *const IAzClientContext3, bstrScopeName: ?BSTR, ppTaskCollection: ?*?*IAzTasks, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BizRuleParameters: fn( self: *const IAzClientContext3, ppBizRuleParam: ?*?*IAzBizRuleParameters, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BizRuleInterfaces: fn( self: *const IAzClientContext3, ppBizRuleInterfaces: ?*?*IAzBizRuleInterfaces, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGroups: fn( self: *const IAzClientContext3, bstrScopeName: ?BSTR, ulOptions: AZ_PROP_CONSTANTS, pGroupArray: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Sids: fn( self: *const IAzClientContext3, pStringSidArray: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IAzClientContext2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext3_AccessCheck2(self: *const T, bstrObjectName: ?BSTR, bstrScopeName: ?BSTR, lOperation: i32, plResult: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext3.VTable, self.vtable).AccessCheck2(@ptrCast(*const IAzClientContext3, self), bstrObjectName, bstrScopeName, lOperation, plResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext3_IsInRoleAssignment(self: *const T, bstrScopeName: ?BSTR, bstrRoleName: ?BSTR, pbIsInRole: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext3.VTable, self.vtable).IsInRoleAssignment(@ptrCast(*const IAzClientContext3, self), bstrScopeName, bstrRoleName, pbIsInRole); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext3_GetOperations(self: *const T, bstrScopeName: ?BSTR, ppOperationCollection: ?*?*IAzOperations) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext3.VTable, self.vtable).GetOperations(@ptrCast(*const IAzClientContext3, self), bstrScopeName, ppOperationCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext3_GetTasks(self: *const T, bstrScopeName: ?BSTR, ppTaskCollection: ?*?*IAzTasks) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext3.VTable, self.vtable).GetTasks(@ptrCast(*const IAzClientContext3, self), bstrScopeName, ppTaskCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext3_get_BizRuleParameters(self: *const T, ppBizRuleParam: ?*?*IAzBizRuleParameters) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext3.VTable, self.vtable).get_BizRuleParameters(@ptrCast(*const IAzClientContext3, self), ppBizRuleParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext3_get_BizRuleInterfaces(self: *const T, ppBizRuleInterfaces: ?*?*IAzBizRuleInterfaces) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext3.VTable, self.vtable).get_BizRuleInterfaces(@ptrCast(*const IAzClientContext3, self), ppBizRuleInterfaces); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext3_GetGroups(self: *const T, bstrScopeName: ?BSTR, ulOptions: AZ_PROP_CONSTANTS, pGroupArray: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext3.VTable, self.vtable).GetGroups(@ptrCast(*const IAzClientContext3, self), bstrScopeName, ulOptions, pGroupArray); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzClientContext3_get_Sids(self: *const T, pStringSidArray: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzClientContext3.VTable, self.vtable).get_Sids(@ptrCast(*const IAzClientContext3, self), pStringSidArray); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzScope2_Value = Guid.initString("ee9fe8c9-c9f3-40e2-aa12-d1d8599727fd"); pub const IID_IAzScope2 = &IID_IAzScope2_Value; pub const IAzScope2 = extern struct { pub const VTable = extern struct { base: IAzScope.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RoleDefinitions: fn( self: *const IAzScope2, ppRoleDefinitions: ?*?*IAzRoleDefinitions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateRoleDefinition: fn( self: *const IAzScope2, bstrRoleDefinitionName: ?BSTR, ppRoleDefinitions: ?*?*IAzRoleDefinition, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenRoleDefinition: fn( self: *const IAzScope2, bstrRoleDefinitionName: ?BSTR, ppRoleDefinitions: ?*?*IAzRoleDefinition, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteRoleDefinition: fn( self: *const IAzScope2, bstrRoleDefinitionName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RoleAssignments: fn( self: *const IAzScope2, ppRoleAssignments: ?*?*IAzRoleAssignments, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateRoleAssignment: fn( self: *const IAzScope2, bstrRoleAssignmentName: ?BSTR, ppRoleAssignment: ?*?*IAzRoleAssignment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenRoleAssignment: fn( self: *const IAzScope2, bstrRoleAssignmentName: ?BSTR, ppRoleAssignment: ?*?*IAzRoleAssignment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteRoleAssignment: fn( self: *const IAzScope2, bstrRoleAssignmentName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IAzScope.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope2_get_RoleDefinitions(self: *const T, ppRoleDefinitions: ?*?*IAzRoleDefinitions) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope2.VTable, self.vtable).get_RoleDefinitions(@ptrCast(*const IAzScope2, self), ppRoleDefinitions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope2_CreateRoleDefinition(self: *const T, bstrRoleDefinitionName: ?BSTR, ppRoleDefinitions: ?*?*IAzRoleDefinition) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope2.VTable, self.vtable).CreateRoleDefinition(@ptrCast(*const IAzScope2, self), bstrRoleDefinitionName, ppRoleDefinitions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope2_OpenRoleDefinition(self: *const T, bstrRoleDefinitionName: ?BSTR, ppRoleDefinitions: ?*?*IAzRoleDefinition) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope2.VTable, self.vtable).OpenRoleDefinition(@ptrCast(*const IAzScope2, self), bstrRoleDefinitionName, ppRoleDefinitions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope2_DeleteRoleDefinition(self: *const T, bstrRoleDefinitionName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope2.VTable, self.vtable).DeleteRoleDefinition(@ptrCast(*const IAzScope2, self), bstrRoleDefinitionName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope2_get_RoleAssignments(self: *const T, ppRoleAssignments: ?*?*IAzRoleAssignments) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope2.VTable, self.vtable).get_RoleAssignments(@ptrCast(*const IAzScope2, self), ppRoleAssignments); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope2_CreateRoleAssignment(self: *const T, bstrRoleAssignmentName: ?BSTR, ppRoleAssignment: ?*?*IAzRoleAssignment) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope2.VTable, self.vtable).CreateRoleAssignment(@ptrCast(*const IAzScope2, self), bstrRoleAssignmentName, ppRoleAssignment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope2_OpenRoleAssignment(self: *const T, bstrRoleAssignmentName: ?BSTR, ppRoleAssignment: ?*?*IAzRoleAssignment) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope2.VTable, self.vtable).OpenRoleAssignment(@ptrCast(*const IAzScope2, self), bstrRoleAssignmentName, ppRoleAssignment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzScope2_DeleteRoleAssignment(self: *const T, bstrRoleAssignmentName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzScope2.VTable, self.vtable).DeleteRoleAssignment(@ptrCast(*const IAzScope2, self), bstrRoleAssignmentName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzApplication3_Value = Guid.initString("181c845e-7196-4a7d-ac2e-020c0bb7a303"); pub const IID_IAzApplication3 = &IID_IAzApplication3_Value; pub const IAzApplication3 = extern struct { pub const VTable = extern struct { base: IAzApplication2.VTable, ScopeExists: fn( self: *const IAzApplication3, bstrScopeName: ?BSTR, pbExist: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenScope2: fn( self: *const IAzApplication3, bstrScopeName: ?BSTR, ppScope2: ?*?*IAzScope2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateScope2: fn( self: *const IAzApplication3, bstrScopeName: ?BSTR, ppScope2: ?*?*IAzScope2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteScope2: fn( self: *const IAzApplication3, bstrScopeName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RoleDefinitions: fn( self: *const IAzApplication3, ppRoleDefinitions: ?*?*IAzRoleDefinitions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateRoleDefinition: fn( self: *const IAzApplication3, bstrRoleDefinitionName: ?BSTR, ppRoleDefinitions: ?*?*IAzRoleDefinition, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenRoleDefinition: fn( self: *const IAzApplication3, bstrRoleDefinitionName: ?BSTR, ppRoleDefinitions: ?*?*IAzRoleDefinition, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteRoleDefinition: fn( self: *const IAzApplication3, bstrRoleDefinitionName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RoleAssignments: fn( self: *const IAzApplication3, ppRoleAssignments: ?*?*IAzRoleAssignments, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateRoleAssignment: fn( self: *const IAzApplication3, bstrRoleAssignmentName: ?BSTR, ppRoleAssignment: ?*?*IAzRoleAssignment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenRoleAssignment: fn( self: *const IAzApplication3, bstrRoleAssignmentName: ?BSTR, ppRoleAssignment: ?*?*IAzRoleAssignment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteRoleAssignment: fn( self: *const IAzApplication3, bstrRoleAssignmentName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BizRulesEnabled: fn( self: *const IAzApplication3, pbEnabled: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BizRulesEnabled: fn( self: *const IAzApplication3, bEnabled: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IAzApplication2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication3_ScopeExists(self: *const T, bstrScopeName: ?BSTR, pbExist: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication3.VTable, self.vtable).ScopeExists(@ptrCast(*const IAzApplication3, self), bstrScopeName, pbExist); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication3_OpenScope2(self: *const T, bstrScopeName: ?BSTR, ppScope2: ?*?*IAzScope2) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication3.VTable, self.vtable).OpenScope2(@ptrCast(*const IAzApplication3, self), bstrScopeName, ppScope2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication3_CreateScope2(self: *const T, bstrScopeName: ?BSTR, ppScope2: ?*?*IAzScope2) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication3.VTable, self.vtable).CreateScope2(@ptrCast(*const IAzApplication3, self), bstrScopeName, ppScope2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication3_DeleteScope2(self: *const T, bstrScopeName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication3.VTable, self.vtable).DeleteScope2(@ptrCast(*const IAzApplication3, self), bstrScopeName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication3_get_RoleDefinitions(self: *const T, ppRoleDefinitions: ?*?*IAzRoleDefinitions) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication3.VTable, self.vtable).get_RoleDefinitions(@ptrCast(*const IAzApplication3, self), ppRoleDefinitions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication3_CreateRoleDefinition(self: *const T, bstrRoleDefinitionName: ?BSTR, ppRoleDefinitions: ?*?*IAzRoleDefinition) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication3.VTable, self.vtable).CreateRoleDefinition(@ptrCast(*const IAzApplication3, self), bstrRoleDefinitionName, ppRoleDefinitions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication3_OpenRoleDefinition(self: *const T, bstrRoleDefinitionName: ?BSTR, ppRoleDefinitions: ?*?*IAzRoleDefinition) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication3.VTable, self.vtable).OpenRoleDefinition(@ptrCast(*const IAzApplication3, self), bstrRoleDefinitionName, ppRoleDefinitions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication3_DeleteRoleDefinition(self: *const T, bstrRoleDefinitionName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication3.VTable, self.vtable).DeleteRoleDefinition(@ptrCast(*const IAzApplication3, self), bstrRoleDefinitionName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication3_get_RoleAssignments(self: *const T, ppRoleAssignments: ?*?*IAzRoleAssignments) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication3.VTable, self.vtable).get_RoleAssignments(@ptrCast(*const IAzApplication3, self), ppRoleAssignments); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication3_CreateRoleAssignment(self: *const T, bstrRoleAssignmentName: ?BSTR, ppRoleAssignment: ?*?*IAzRoleAssignment) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication3.VTable, self.vtable).CreateRoleAssignment(@ptrCast(*const IAzApplication3, self), bstrRoleAssignmentName, ppRoleAssignment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication3_OpenRoleAssignment(self: *const T, bstrRoleAssignmentName: ?BSTR, ppRoleAssignment: ?*?*IAzRoleAssignment) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication3.VTable, self.vtable).OpenRoleAssignment(@ptrCast(*const IAzApplication3, self), bstrRoleAssignmentName, ppRoleAssignment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication3_DeleteRoleAssignment(self: *const T, bstrRoleAssignmentName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication3.VTable, self.vtable).DeleteRoleAssignment(@ptrCast(*const IAzApplication3, self), bstrRoleAssignmentName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication3_get_BizRulesEnabled(self: *const T, pbEnabled: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication3.VTable, self.vtable).get_BizRulesEnabled(@ptrCast(*const IAzApplication3, self), pbEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplication3_put_BizRulesEnabled(self: *const T, bEnabled: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplication3.VTable, self.vtable).put_BizRulesEnabled(@ptrCast(*const IAzApplication3, self), bEnabled); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzOperation2_Value = Guid.initString("1f5ea01f-44a2-4184-9c48-a75b4dcc8ccc"); pub const IID_IAzOperation2 = &IID_IAzOperation2_Value; pub const IAzOperation2 = extern struct { pub const VTable = extern struct { base: IAzOperation.VTable, RoleAssignments: fn( self: *const IAzOperation2, bstrScopeName: ?BSTR, bRecursive: i16, ppRoleAssignments: ?*?*IAzRoleAssignments, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IAzOperation.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzOperation2_RoleAssignments(self: *const T, bstrScopeName: ?BSTR, bRecursive: i16, ppRoleAssignments: ?*?*IAzRoleAssignments) callconv(.Inline) HRESULT { return @ptrCast(*const IAzOperation2.VTable, self.vtable).RoleAssignments(@ptrCast(*const IAzOperation2, self), bstrScopeName, bRecursive, ppRoleAssignments); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzRoleDefinitions_Value = Guid.initString("881f25a5-d755-4550-957a-d503a3b34001"); pub const IID_IAzRoleDefinitions = &IID_IAzRoleDefinitions_Value; pub const IAzRoleDefinitions = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IAzRoleDefinitions, Index: i32, pvarObtPtr: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IAzRoleDefinitions, plCount: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IAzRoleDefinitions, ppEnumPtr: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoleDefinitions_get_Item(self: *const T, Index: i32, pvarObtPtr: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoleDefinitions.VTable, self.vtable).get_Item(@ptrCast(*const IAzRoleDefinitions, self), Index, pvarObtPtr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoleDefinitions_get_Count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoleDefinitions.VTable, self.vtable).get_Count(@ptrCast(*const IAzRoleDefinitions, self), plCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoleDefinitions_get__NewEnum(self: *const T, ppEnumPtr: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoleDefinitions.VTable, self.vtable).get__NewEnum(@ptrCast(*const IAzRoleDefinitions, self), ppEnumPtr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzRoleDefinition_Value = Guid.initString("d97fcea1-2599-44f1-9fc3-58e9fbe09466"); pub const IID_IAzRoleDefinition = &IID_IAzRoleDefinition_Value; pub const IAzRoleDefinition = extern struct { pub const VTable = extern struct { base: IAzTask.VTable, RoleAssignments: fn( self: *const IAzRoleDefinition, bstrScopeName: ?BSTR, bRecursive: i16, ppRoleAssignments: ?*?*IAzRoleAssignments, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddRoleDefinition: fn( self: *const IAzRoleDefinition, bstrRoleDefinition: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteRoleDefinition: fn( self: *const IAzRoleDefinition, bstrRoleDefinition: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RoleDefinitions: fn( self: *const IAzRoleDefinition, ppRoleDefinitions: ?*?*IAzRoleDefinitions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IAzTask.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoleDefinition_RoleAssignments(self: *const T, bstrScopeName: ?BSTR, bRecursive: i16, ppRoleAssignments: ?*?*IAzRoleAssignments) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoleDefinition.VTable, self.vtable).RoleAssignments(@ptrCast(*const IAzRoleDefinition, self), bstrScopeName, bRecursive, ppRoleAssignments); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoleDefinition_AddRoleDefinition(self: *const T, bstrRoleDefinition: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoleDefinition.VTable, self.vtable).AddRoleDefinition(@ptrCast(*const IAzRoleDefinition, self), bstrRoleDefinition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoleDefinition_DeleteRoleDefinition(self: *const T, bstrRoleDefinition: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoleDefinition.VTable, self.vtable).DeleteRoleDefinition(@ptrCast(*const IAzRoleDefinition, self), bstrRoleDefinition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoleDefinition_get_RoleDefinitions(self: *const T, ppRoleDefinitions: ?*?*IAzRoleDefinitions) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoleDefinition.VTable, self.vtable).get_RoleDefinitions(@ptrCast(*const IAzRoleDefinition, self), ppRoleDefinitions); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzRoleAssignment_Value = Guid.initString("55647d31-0d5a-4fa3-b4ac-2b5f9ad5ab76"); pub const IID_IAzRoleAssignment = &IID_IAzRoleAssignment_Value; pub const IAzRoleAssignment = extern struct { pub const VTable = extern struct { base: IAzRole.VTable, AddRoleDefinition: fn( self: *const IAzRoleAssignment, bstrRoleDefinition: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteRoleDefinition: fn( self: *const IAzRoleAssignment, bstrRoleDefinition: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RoleDefinitions: fn( self: *const IAzRoleAssignment, ppRoleDefinitions: ?*?*IAzRoleDefinitions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Scope: fn( self: *const IAzRoleAssignment, ppScope: ?*?*IAzScope, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IAzRole.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoleAssignment_AddRoleDefinition(self: *const T, bstrRoleDefinition: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoleAssignment.VTable, self.vtable).AddRoleDefinition(@ptrCast(*const IAzRoleAssignment, self), bstrRoleDefinition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoleAssignment_DeleteRoleDefinition(self: *const T, bstrRoleDefinition: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoleAssignment.VTable, self.vtable).DeleteRoleDefinition(@ptrCast(*const IAzRoleAssignment, self), bstrRoleDefinition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoleAssignment_get_RoleDefinitions(self: *const T, ppRoleDefinitions: ?*?*IAzRoleDefinitions) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoleAssignment.VTable, self.vtable).get_RoleDefinitions(@ptrCast(*const IAzRoleAssignment, self), ppRoleDefinitions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoleAssignment_get_Scope(self: *const T, ppScope: ?*?*IAzScope) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoleAssignment.VTable, self.vtable).get_Scope(@ptrCast(*const IAzRoleAssignment, self), ppScope); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzRoleAssignments_Value = Guid.initString("9c80b900-fceb-4d73-a0f4-c83b0bbf2481"); pub const IID_IAzRoleAssignments = &IID_IAzRoleAssignments_Value; pub const IAzRoleAssignments = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IAzRoleAssignments, Index: i32, pvarObtPtr: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IAzRoleAssignments, plCount: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IAzRoleAssignments, ppEnumPtr: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoleAssignments_get_Item(self: *const T, Index: i32, pvarObtPtr: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoleAssignments.VTable, self.vtable).get_Item(@ptrCast(*const IAzRoleAssignments, self), Index, pvarObtPtr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoleAssignments_get_Count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoleAssignments.VTable, self.vtable).get_Count(@ptrCast(*const IAzRoleAssignments, self), plCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzRoleAssignments_get__NewEnum(self: *const T, ppEnumPtr: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAzRoleAssignments.VTable, self.vtable).get__NewEnum(@ptrCast(*const IAzRoleAssignments, self), ppEnumPtr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzPrincipalLocator_Value = Guid.initString("e5c3507d-ad6a-4992-9c7f-74ab480b44cc"); pub const IID_IAzPrincipalLocator = &IID_IAzPrincipalLocator_Value; pub const IAzPrincipalLocator = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NameResolver: fn( self: *const IAzPrincipalLocator, ppNameResolver: ?*?*IAzNameResolver, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ObjectPicker: fn( self: *const IAzPrincipalLocator, ppObjectPicker: ?*?*IAzObjectPicker, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzPrincipalLocator_get_NameResolver(self: *const T, ppNameResolver: ?*?*IAzNameResolver) callconv(.Inline) HRESULT { return @ptrCast(*const IAzPrincipalLocator.VTable, self.vtable).get_NameResolver(@ptrCast(*const IAzPrincipalLocator, self), ppNameResolver); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzPrincipalLocator_get_ObjectPicker(self: *const T, ppObjectPicker: ?*?*IAzObjectPicker) callconv(.Inline) HRESULT { return @ptrCast(*const IAzPrincipalLocator.VTable, self.vtable).get_ObjectPicker(@ptrCast(*const IAzPrincipalLocator, self), ppObjectPicker); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzNameResolver_Value = Guid.initString("504d0f15-73e2-43df-a870-a64f40714f53"); pub const IID_IAzNameResolver = &IID_IAzNameResolver_Value; pub const IAzNameResolver = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, NameFromSid: fn( self: *const IAzNameResolver, bstrSid: ?BSTR, pSidType: ?*i32, pbstrName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NamesFromSids: fn( self: *const IAzNameResolver, vSids: VARIANT, pvSidTypes: ?*VARIANT, pvNames: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzNameResolver_NameFromSid(self: *const T, bstrSid: ?BSTR, pSidType: ?*i32, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzNameResolver.VTable, self.vtable).NameFromSid(@ptrCast(*const IAzNameResolver, self), bstrSid, pSidType, pbstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzNameResolver_NamesFromSids(self: *const T, vSids: VARIANT, pvSidTypes: ?*VARIANT, pvNames: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzNameResolver.VTable, self.vtable).NamesFromSids(@ptrCast(*const IAzNameResolver, self), vSids, pvSidTypes, pvNames); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzObjectPicker_Value = Guid.initString("63130a48-699a-42d8-bf01-c62ac3fb79f9"); pub const IID_IAzObjectPicker = &IID_IAzObjectPicker_Value; pub const IAzObjectPicker = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, GetPrincipals: fn( self: *const IAzObjectPicker, hParentWnd: ?HWND, bstrTitle: ?BSTR, pvSidTypes: ?*VARIANT, pvNames: ?*VARIANT, pvSids: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IAzObjectPicker, pbstrName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzObjectPicker_GetPrincipals(self: *const T, hParentWnd: ?HWND, bstrTitle: ?BSTR, pvSidTypes: ?*VARIANT, pvNames: ?*VARIANT, pvSids: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IAzObjectPicker.VTable, self.vtable).GetPrincipals(@ptrCast(*const IAzObjectPicker, self), hParentWnd, bstrTitle, pvSidTypes, pvNames, pvSids); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzObjectPicker_get_Name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzObjectPicker.VTable, self.vtable).get_Name(@ptrCast(*const IAzObjectPicker, self), pbstrName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzApplicationGroup2_Value = Guid.initString("3f0613fc-b71a-464e-a11d-5b881a56cefa"); pub const IID_IAzApplicationGroup2 = &IID_IAzApplicationGroup2_Value; pub const IAzApplicationGroup2 = extern struct { pub const VTable = extern struct { base: IAzApplicationGroup.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BizRule: fn( self: *const IAzApplicationGroup2, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BizRule: fn( self: *const IAzApplicationGroup2, bstrProp: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BizRuleLanguage: fn( self: *const IAzApplicationGroup2, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BizRuleLanguage: fn( self: *const IAzApplicationGroup2, bstrProp: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BizRuleImportedPath: fn( self: *const IAzApplicationGroup2, pbstrProp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BizRuleImportedPath: fn( self: *const IAzApplicationGroup2, bstrProp: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RoleAssignments: fn( self: *const IAzApplicationGroup2, bstrScopeName: ?BSTR, bRecursive: i16, ppRoleAssignments: ?*?*IAzRoleAssignments, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IAzApplicationGroup.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup2_get_BizRule(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup2.VTable, self.vtable).get_BizRule(@ptrCast(*const IAzApplicationGroup2, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup2_put_BizRule(self: *const T, bstrProp: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup2.VTable, self.vtable).put_BizRule(@ptrCast(*const IAzApplicationGroup2, self), bstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup2_get_BizRuleLanguage(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup2.VTable, self.vtable).get_BizRuleLanguage(@ptrCast(*const IAzApplicationGroup2, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup2_put_BizRuleLanguage(self: *const T, bstrProp: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup2.VTable, self.vtable).put_BizRuleLanguage(@ptrCast(*const IAzApplicationGroup2, self), bstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup2_get_BizRuleImportedPath(self: *const T, pbstrProp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup2.VTable, self.vtable).get_BizRuleImportedPath(@ptrCast(*const IAzApplicationGroup2, self), pbstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup2_put_BizRuleImportedPath(self: *const T, bstrProp: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup2.VTable, self.vtable).put_BizRuleImportedPath(@ptrCast(*const IAzApplicationGroup2, self), bstrProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzApplicationGroup2_RoleAssignments(self: *const T, bstrScopeName: ?BSTR, bRecursive: i16, ppRoleAssignments: ?*?*IAzRoleAssignments) callconv(.Inline) HRESULT { return @ptrCast(*const IAzApplicationGroup2.VTable, self.vtable).RoleAssignments(@ptrCast(*const IAzApplicationGroup2, self), bstrScopeName, bRecursive, ppRoleAssignments); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAzTask2_Value = Guid.initString("03a9a5ee-48c8-4832-9025-aad503c46526"); pub const IID_IAzTask2 = &IID_IAzTask2_Value; pub const IAzTask2 = extern struct { pub const VTable = extern struct { base: IAzTask.VTable, RoleAssignments: fn( self: *const IAzTask2, bstrScopeName: ?BSTR, bRecursive: i16, ppRoleAssignments: ?*?*IAzRoleAssignments, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IAzTask.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAzTask2_RoleAssignments(self: *const T, bstrScopeName: ?BSTR, bRecursive: i16, ppRoleAssignments: ?*?*IAzRoleAssignments) callconv(.Inline) HRESULT { return @ptrCast(*const IAzTask2.VTable, self.vtable).RoleAssignments(@ptrCast(*const IAzTask2, self), bstrScopeName, bRecursive, ppRoleAssignments); } };} pub usingnamespace MethodMixin(@This()); }; pub const AZ_PROP_CONSTANTS = enum(i32) { PROP_NAME = 1, PROP_DESCRIPTION = 2, PROP_WRITABLE = 3, PROP_APPLICATION_DATA = 4, PROP_CHILD_CREATE = 5, MAX_APPLICATION_NAME_LENGTH = 512, MAX_OPERATION_NAME_LENGTH = 64, // MAX_TASK_NAME_LENGTH = 64, this enum value conflicts with MAX_OPERATION_NAME_LENGTH MAX_SCOPE_NAME_LENGTH = 65536, // MAX_GROUP_NAME_LENGTH = 64, this enum value conflicts with MAX_OPERATION_NAME_LENGTH // MAX_ROLE_NAME_LENGTH = 64, this enum value conflicts with MAX_OPERATION_NAME_LENGTH // MAX_NAME_LENGTH = 65536, this enum value conflicts with MAX_SCOPE_NAME_LENGTH MAX_DESCRIPTION_LENGTH = 1024, MAX_APPLICATION_DATA_LENGTH = 4096, // SUBMIT_FLAG_ABORT = 1, this enum value conflicts with PROP_NAME // SUBMIT_FLAG_FLUSH = 2, this enum value conflicts with PROP_DESCRIPTION // MAX_POLICY_URL_LENGTH = 65536, this enum value conflicts with MAX_SCOPE_NAME_LENGTH // AZSTORE_FLAG_CREATE = 1, this enum value conflicts with PROP_NAME // AZSTORE_FLAG_MANAGE_STORE_ONLY = 2, this enum value conflicts with PROP_DESCRIPTION // AZSTORE_FLAG_BATCH_UPDATE = 4, this enum value conflicts with PROP_APPLICATION_DATA AZSTORE_FLAG_AUDIT_IS_CRITICAL = 8, AZSTORE_FORCE_APPLICATION_CLOSE = 16, AZSTORE_NT6_FUNCTION_LEVEL = 32, AZSTORE_FLAG_MANAGE_ONLY_PASSIVE_SUBMIT = 32768, PROP_AZSTORE_DOMAIN_TIMEOUT = 100, AZSTORE_DEFAULT_DOMAIN_TIMEOUT = 15000, PROP_AZSTORE_SCRIPT_ENGINE_TIMEOUT = 101, AZSTORE_MIN_DOMAIN_TIMEOUT = 500, AZSTORE_MIN_SCRIPT_ENGINE_TIMEOUT = 5000, AZSTORE_DEFAULT_SCRIPT_ENGINE_TIMEOUT = 45000, PROP_AZSTORE_MAX_SCRIPT_ENGINES = 102, AZSTORE_DEFAULT_MAX_SCRIPT_ENGINES = 120, PROP_AZSTORE_MAJOR_VERSION = 103, PROP_AZSTORE_MINOR_VERSION = 104, PROP_AZSTORE_TARGET_MACHINE = 105, PROP_AZTORE_IS_ADAM_INSTANCE = 106, PROP_OPERATION_ID = 200, PROP_TASK_OPERATIONS = 300, PROP_TASK_BIZRULE = 301, PROP_TASK_BIZRULE_LANGUAGE = 302, PROP_TASK_TASKS = 303, PROP_TASK_BIZRULE_IMPORTED_PATH = 304, PROP_TASK_IS_ROLE_DEFINITION = 305, // MAX_TASK_BIZRULE_LENGTH = 65536, this enum value conflicts with MAX_SCOPE_NAME_LENGTH // MAX_TASK_BIZRULE_LANGUAGE_LENGTH = 64, this enum value conflicts with MAX_OPERATION_NAME_LENGTH // MAX_TASK_BIZRULE_IMPORTED_PATH_LENGTH = 512, this enum value conflicts with MAX_APPLICATION_NAME_LENGTH // MAX_BIZRULE_STRING = 65536, this enum value conflicts with MAX_SCOPE_NAME_LENGTH PROP_GROUP_TYPE = 400, // GROUPTYPE_LDAP_QUERY = 1, this enum value conflicts with PROP_NAME // GROUPTYPE_BASIC = 2, this enum value conflicts with PROP_DESCRIPTION // GROUPTYPE_BIZRULE = 3, this enum value conflicts with PROP_WRITABLE PROP_GROUP_APP_MEMBERS = 401, PROP_GROUP_APP_NON_MEMBERS = 402, PROP_GROUP_LDAP_QUERY = 403, // MAX_GROUP_LDAP_QUERY_LENGTH = 4096, this enum value conflicts with MAX_APPLICATION_DATA_LENGTH PROP_GROUP_MEMBERS = 404, PROP_GROUP_NON_MEMBERS = 405, PROP_GROUP_MEMBERS_NAME = 406, PROP_GROUP_NON_MEMBERS_NAME = 407, PROP_GROUP_BIZRULE = 408, PROP_GROUP_BIZRULE_LANGUAGE = 409, PROP_GROUP_BIZRULE_IMPORTED_PATH = 410, // MAX_GROUP_BIZRULE_LENGTH = 65536, this enum value conflicts with MAX_SCOPE_NAME_LENGTH // MAX_GROUP_BIZRULE_LANGUAGE_LENGTH = 64, this enum value conflicts with MAX_OPERATION_NAME_LENGTH // MAX_GROUP_BIZRULE_IMPORTED_PATH_LENGTH = 512, this enum value conflicts with MAX_APPLICATION_NAME_LENGTH // PROP_ROLE_APP_MEMBERS = 500, this enum value conflicts with AZSTORE_MIN_DOMAIN_TIMEOUT PROP_ROLE_MEMBERS = 501, PROP_ROLE_OPERATIONS = 502, PROP_ROLE_TASKS = 504, PROP_ROLE_MEMBERS_NAME = 505, PROP_SCOPE_BIZRULES_WRITABLE = 600, PROP_SCOPE_CAN_BE_DELEGATED = 601, PROP_CLIENT_CONTEXT_USER_DN = 700, PROP_CLIENT_CONTEXT_USER_SAM_COMPAT = 701, PROP_CLIENT_CONTEXT_USER_DISPLAY = 702, PROP_CLIENT_CONTEXT_USER_GUID = 703, PROP_CLIENT_CONTEXT_USER_CANONICAL = 704, PROP_CLIENT_CONTEXT_USER_UPN = 705, PROP_CLIENT_CONTEXT_USER_DNS_SAM_COMPAT = 707, PROP_CLIENT_CONTEXT_ROLE_FOR_ACCESS_CHECK = 708, PROP_CLIENT_CONTEXT_LDAP_QUERY_DN = 709, PROP_APPLICATION_AUTHZ_INTERFACE_CLSID = 800, PROP_APPLICATION_VERSION = 801, // MAX_APPLICATION_VERSION_LENGTH = 512, this enum value conflicts with MAX_APPLICATION_NAME_LENGTH PROP_APPLICATION_NAME = 802, PROP_APPLICATION_BIZRULE_ENABLED = 803, PROP_APPLY_STORE_SACL = 900, PROP_GENERATE_AUDITS = 901, PROP_POLICY_ADMINS = 902, PROP_POLICY_READERS = 903, PROP_DELEGATED_POLICY_USERS = 904, PROP_POLICY_ADMINS_NAME = 905, PROP_POLICY_READERS_NAME = 906, PROP_DELEGATED_POLICY_USERS_NAME = 907, // CLIENT_CONTEXT_SKIP_GROUP = 1, this enum value conflicts with PROP_NAME // CLIENT_CONTEXT_SKIP_LDAP_QUERY = 1, this enum value conflicts with PROP_NAME // CLIENT_CONTEXT_GET_GROUP_RECURSIVE = 2, this enum value conflicts with PROP_DESCRIPTION // CLIENT_CONTEXT_GET_GROUPS_STORE_LEVEL_ONLY = 2, this enum value conflicts with PROP_DESCRIPTION }; pub const AZ_PROP_NAME = AZ_PROP_CONSTANTS.PROP_NAME; pub const AZ_PROP_DESCRIPTION = AZ_PROP_CONSTANTS.PROP_DESCRIPTION; pub const AZ_PROP_WRITABLE = AZ_PROP_CONSTANTS.PROP_WRITABLE; pub const AZ_PROP_APPLICATION_DATA = AZ_PROP_CONSTANTS.PROP_APPLICATION_DATA; pub const AZ_PROP_CHILD_CREATE = AZ_PROP_CONSTANTS.PROP_CHILD_CREATE; pub const AZ_MAX_APPLICATION_NAME_LENGTH = AZ_PROP_CONSTANTS.MAX_APPLICATION_NAME_LENGTH; pub const AZ_MAX_OPERATION_NAME_LENGTH = AZ_PROP_CONSTANTS.MAX_OPERATION_NAME_LENGTH; pub const AZ_MAX_TASK_NAME_LENGTH = AZ_PROP_CONSTANTS.MAX_OPERATION_NAME_LENGTH; pub const AZ_MAX_SCOPE_NAME_LENGTH = AZ_PROP_CONSTANTS.MAX_SCOPE_NAME_LENGTH; pub const AZ_MAX_GROUP_NAME_LENGTH = AZ_PROP_CONSTANTS.MAX_OPERATION_NAME_LENGTH; pub const AZ_MAX_ROLE_NAME_LENGTH = AZ_PROP_CONSTANTS.MAX_OPERATION_NAME_LENGTH; pub const AZ_MAX_NAME_LENGTH = AZ_PROP_CONSTANTS.MAX_SCOPE_NAME_LENGTH; pub const AZ_MAX_DESCRIPTION_LENGTH = AZ_PROP_CONSTANTS.MAX_DESCRIPTION_LENGTH; pub const AZ_MAX_APPLICATION_DATA_LENGTH = AZ_PROP_CONSTANTS.MAX_APPLICATION_DATA_LENGTH; pub const AZ_SUBMIT_FLAG_ABORT = AZ_PROP_CONSTANTS.PROP_NAME; pub const AZ_SUBMIT_FLAG_FLUSH = AZ_PROP_CONSTANTS.PROP_DESCRIPTION; pub const AZ_MAX_POLICY_URL_LENGTH = AZ_PROP_CONSTANTS.MAX_SCOPE_NAME_LENGTH; pub const AZ_AZSTORE_FLAG_CREATE = AZ_PROP_CONSTANTS.PROP_NAME; pub const AZ_AZSTORE_FLAG_MANAGE_STORE_ONLY = AZ_PROP_CONSTANTS.PROP_DESCRIPTION; pub const AZ_AZSTORE_FLAG_BATCH_UPDATE = AZ_PROP_CONSTANTS.PROP_APPLICATION_DATA; pub const AZ_AZSTORE_FLAG_AUDIT_IS_CRITICAL = AZ_PROP_CONSTANTS.AZSTORE_FLAG_AUDIT_IS_CRITICAL; pub const AZ_AZSTORE_FORCE_APPLICATION_CLOSE = AZ_PROP_CONSTANTS.AZSTORE_FORCE_APPLICATION_CLOSE; pub const AZ_AZSTORE_NT6_FUNCTION_LEVEL = AZ_PROP_CONSTANTS.AZSTORE_NT6_FUNCTION_LEVEL; pub const AZ_AZSTORE_FLAG_MANAGE_ONLY_PASSIVE_SUBMIT = AZ_PROP_CONSTANTS.AZSTORE_FLAG_MANAGE_ONLY_PASSIVE_SUBMIT; pub const AZ_PROP_AZSTORE_DOMAIN_TIMEOUT = AZ_PROP_CONSTANTS.PROP_AZSTORE_DOMAIN_TIMEOUT; pub const AZ_AZSTORE_DEFAULT_DOMAIN_TIMEOUT = AZ_PROP_CONSTANTS.AZSTORE_DEFAULT_DOMAIN_TIMEOUT; pub const AZ_PROP_AZSTORE_SCRIPT_ENGINE_TIMEOUT = AZ_PROP_CONSTANTS.PROP_AZSTORE_SCRIPT_ENGINE_TIMEOUT; pub const AZ_AZSTORE_MIN_DOMAIN_TIMEOUT = AZ_PROP_CONSTANTS.AZSTORE_MIN_DOMAIN_TIMEOUT; pub const AZ_AZSTORE_MIN_SCRIPT_ENGINE_TIMEOUT = AZ_PROP_CONSTANTS.AZSTORE_MIN_SCRIPT_ENGINE_TIMEOUT; pub const AZ_AZSTORE_DEFAULT_SCRIPT_ENGINE_TIMEOUT = AZ_PROP_CONSTANTS.AZSTORE_DEFAULT_SCRIPT_ENGINE_TIMEOUT; pub const AZ_PROP_AZSTORE_MAX_SCRIPT_ENGINES = AZ_PROP_CONSTANTS.PROP_AZSTORE_MAX_SCRIPT_ENGINES; pub const AZ_AZSTORE_DEFAULT_MAX_SCRIPT_ENGINES = AZ_PROP_CONSTANTS.AZSTORE_DEFAULT_MAX_SCRIPT_ENGINES; pub const AZ_PROP_AZSTORE_MAJOR_VERSION = AZ_PROP_CONSTANTS.PROP_AZSTORE_MAJOR_VERSION; pub const AZ_PROP_AZSTORE_MINOR_VERSION = AZ_PROP_CONSTANTS.PROP_AZSTORE_MINOR_VERSION; pub const AZ_PROP_AZSTORE_TARGET_MACHINE = AZ_PROP_CONSTANTS.PROP_AZSTORE_TARGET_MACHINE; pub const AZ_PROP_AZTORE_IS_ADAM_INSTANCE = AZ_PROP_CONSTANTS.PROP_AZTORE_IS_ADAM_INSTANCE; pub const AZ_PROP_OPERATION_ID = AZ_PROP_CONSTANTS.PROP_OPERATION_ID; pub const AZ_PROP_TASK_OPERATIONS = AZ_PROP_CONSTANTS.PROP_TASK_OPERATIONS; pub const AZ_PROP_TASK_BIZRULE = AZ_PROP_CONSTANTS.PROP_TASK_BIZRULE; pub const AZ_PROP_TASK_BIZRULE_LANGUAGE = AZ_PROP_CONSTANTS.PROP_TASK_BIZRULE_LANGUAGE; pub const AZ_PROP_TASK_TASKS = AZ_PROP_CONSTANTS.PROP_TASK_TASKS; pub const AZ_PROP_TASK_BIZRULE_IMPORTED_PATH = AZ_PROP_CONSTANTS.PROP_TASK_BIZRULE_IMPORTED_PATH; pub const AZ_PROP_TASK_IS_ROLE_DEFINITION = AZ_PROP_CONSTANTS.PROP_TASK_IS_ROLE_DEFINITION; pub const AZ_MAX_TASK_BIZRULE_LENGTH = AZ_PROP_CONSTANTS.MAX_SCOPE_NAME_LENGTH; pub const AZ_MAX_TASK_BIZRULE_LANGUAGE_LENGTH = AZ_PROP_CONSTANTS.MAX_OPERATION_NAME_LENGTH; pub const AZ_MAX_TASK_BIZRULE_IMPORTED_PATH_LENGTH = AZ_PROP_CONSTANTS.MAX_APPLICATION_NAME_LENGTH; pub const AZ_MAX_BIZRULE_STRING = AZ_PROP_CONSTANTS.MAX_SCOPE_NAME_LENGTH; pub const AZ_PROP_GROUP_TYPE = AZ_PROP_CONSTANTS.PROP_GROUP_TYPE; pub const AZ_GROUPTYPE_LDAP_QUERY = AZ_PROP_CONSTANTS.PROP_NAME; pub const AZ_GROUPTYPE_BASIC = AZ_PROP_CONSTANTS.PROP_DESCRIPTION; pub const AZ_GROUPTYPE_BIZRULE = AZ_PROP_CONSTANTS.PROP_WRITABLE; pub const AZ_PROP_GROUP_APP_MEMBERS = AZ_PROP_CONSTANTS.PROP_GROUP_APP_MEMBERS; pub const AZ_PROP_GROUP_APP_NON_MEMBERS = AZ_PROP_CONSTANTS.PROP_GROUP_APP_NON_MEMBERS; pub const AZ_PROP_GROUP_LDAP_QUERY = AZ_PROP_CONSTANTS.PROP_GROUP_LDAP_QUERY; pub const AZ_MAX_GROUP_LDAP_QUERY_LENGTH = AZ_PROP_CONSTANTS.MAX_APPLICATION_DATA_LENGTH; pub const AZ_PROP_GROUP_MEMBERS = AZ_PROP_CONSTANTS.PROP_GROUP_MEMBERS; pub const AZ_PROP_GROUP_NON_MEMBERS = AZ_PROP_CONSTANTS.PROP_GROUP_NON_MEMBERS; pub const AZ_PROP_GROUP_MEMBERS_NAME = AZ_PROP_CONSTANTS.PROP_GROUP_MEMBERS_NAME; pub const AZ_PROP_GROUP_NON_MEMBERS_NAME = AZ_PROP_CONSTANTS.PROP_GROUP_NON_MEMBERS_NAME; pub const AZ_PROP_GROUP_BIZRULE = AZ_PROP_CONSTANTS.PROP_GROUP_BIZRULE; pub const AZ_PROP_GROUP_BIZRULE_LANGUAGE = AZ_PROP_CONSTANTS.PROP_GROUP_BIZRULE_LANGUAGE; pub const AZ_PROP_GROUP_BIZRULE_IMPORTED_PATH = AZ_PROP_CONSTANTS.PROP_GROUP_BIZRULE_IMPORTED_PATH; pub const AZ_MAX_GROUP_BIZRULE_LENGTH = AZ_PROP_CONSTANTS.MAX_SCOPE_NAME_LENGTH; pub const AZ_MAX_GROUP_BIZRULE_LANGUAGE_LENGTH = AZ_PROP_CONSTANTS.MAX_OPERATION_NAME_LENGTH; pub const AZ_MAX_GROUP_BIZRULE_IMPORTED_PATH_LENGTH = AZ_PROP_CONSTANTS.MAX_APPLICATION_NAME_LENGTH; pub const AZ_PROP_ROLE_APP_MEMBERS = AZ_PROP_CONSTANTS.AZSTORE_MIN_DOMAIN_TIMEOUT; pub const AZ_PROP_ROLE_MEMBERS = AZ_PROP_CONSTANTS.PROP_ROLE_MEMBERS; pub const AZ_PROP_ROLE_OPERATIONS = AZ_PROP_CONSTANTS.PROP_ROLE_OPERATIONS; pub const AZ_PROP_ROLE_TASKS = AZ_PROP_CONSTANTS.PROP_ROLE_TASKS; pub const AZ_PROP_ROLE_MEMBERS_NAME = AZ_PROP_CONSTANTS.PROP_ROLE_MEMBERS_NAME; pub const AZ_PROP_SCOPE_BIZRULES_WRITABLE = AZ_PROP_CONSTANTS.PROP_SCOPE_BIZRULES_WRITABLE; pub const AZ_PROP_SCOPE_CAN_BE_DELEGATED = AZ_PROP_CONSTANTS.PROP_SCOPE_CAN_BE_DELEGATED; pub const AZ_PROP_CLIENT_CONTEXT_USER_DN = AZ_PROP_CONSTANTS.PROP_CLIENT_CONTEXT_USER_DN; pub const AZ_PROP_CLIENT_CONTEXT_USER_SAM_COMPAT = AZ_PROP_CONSTANTS.PROP_CLIENT_CONTEXT_USER_SAM_COMPAT; pub const AZ_PROP_CLIENT_CONTEXT_USER_DISPLAY = AZ_PROP_CONSTANTS.PROP_CLIENT_CONTEXT_USER_DISPLAY; pub const AZ_PROP_CLIENT_CONTEXT_USER_GUID = AZ_PROP_CONSTANTS.PROP_CLIENT_CONTEXT_USER_GUID; pub const AZ_PROP_CLIENT_CONTEXT_USER_CANONICAL = AZ_PROP_CONSTANTS.PROP_CLIENT_CONTEXT_USER_CANONICAL; pub const AZ_PROP_CLIENT_CONTEXT_USER_UPN = AZ_PROP_CONSTANTS.PROP_CLIENT_CONTEXT_USER_UPN; pub const AZ_PROP_CLIENT_CONTEXT_USER_DNS_SAM_COMPAT = AZ_PROP_CONSTANTS.PROP_CLIENT_CONTEXT_USER_DNS_SAM_COMPAT; pub const AZ_PROP_CLIENT_CONTEXT_ROLE_FOR_ACCESS_CHECK = AZ_PROP_CONSTANTS.PROP_CLIENT_CONTEXT_ROLE_FOR_ACCESS_CHECK; pub const AZ_PROP_CLIENT_CONTEXT_LDAP_QUERY_DN = AZ_PROP_CONSTANTS.PROP_CLIENT_CONTEXT_LDAP_QUERY_DN; pub const AZ_PROP_APPLICATION_AUTHZ_INTERFACE_CLSID = AZ_PROP_CONSTANTS.PROP_APPLICATION_AUTHZ_INTERFACE_CLSID; pub const AZ_PROP_APPLICATION_VERSION = AZ_PROP_CONSTANTS.PROP_APPLICATION_VERSION; pub const AZ_MAX_APPLICATION_VERSION_LENGTH = AZ_PROP_CONSTANTS.MAX_APPLICATION_NAME_LENGTH; pub const AZ_PROP_APPLICATION_NAME = AZ_PROP_CONSTANTS.PROP_APPLICATION_NAME; pub const AZ_PROP_APPLICATION_BIZRULE_ENABLED = AZ_PROP_CONSTANTS.PROP_APPLICATION_BIZRULE_ENABLED; pub const AZ_PROP_APPLY_STORE_SACL = AZ_PROP_CONSTANTS.PROP_APPLY_STORE_SACL; pub const AZ_PROP_GENERATE_AUDITS = AZ_PROP_CONSTANTS.PROP_GENERATE_AUDITS; pub const AZ_PROP_POLICY_ADMINS = AZ_PROP_CONSTANTS.PROP_POLICY_ADMINS; pub const AZ_PROP_POLICY_READERS = AZ_PROP_CONSTANTS.PROP_POLICY_READERS; pub const AZ_PROP_DELEGATED_POLICY_USERS = AZ_PROP_CONSTANTS.PROP_DELEGATED_POLICY_USERS; pub const AZ_PROP_POLICY_ADMINS_NAME = AZ_PROP_CONSTANTS.PROP_POLICY_ADMINS_NAME; pub const AZ_PROP_POLICY_READERS_NAME = AZ_PROP_CONSTANTS.PROP_POLICY_READERS_NAME; pub const AZ_PROP_DELEGATED_POLICY_USERS_NAME = AZ_PROP_CONSTANTS.PROP_DELEGATED_POLICY_USERS_NAME; pub const AZ_CLIENT_CONTEXT_SKIP_GROUP = AZ_PROP_CONSTANTS.PROP_NAME; pub const AZ_CLIENT_CONTEXT_SKIP_LDAP_QUERY = AZ_PROP_CONSTANTS.PROP_NAME; pub const AZ_CLIENT_CONTEXT_GET_GROUP_RECURSIVE = AZ_PROP_CONSTANTS.PROP_DESCRIPTION; pub const AZ_CLIENT_CONTEXT_GET_GROUPS_STORE_LEVEL_ONLY = AZ_PROP_CONSTANTS.PROP_DESCRIPTION; pub const FN_PROGRESS = fn( pObjectName: ?PWSTR, Status: u32, pInvokeSetting: ?*PROG_INVOKE_SETTING, Args: ?*anyopaque, SecuritySet: BOOL, ) callconv(@import("std").os.windows.WINAPI) void; pub const AUTHZ_ACCESS_CHECK_RESULTS_HANDLE = isize; pub const AUTHZ_CLIENT_CONTEXT_HANDLE = isize; pub const AUTHZ_RESOURCE_MANAGER_HANDLE = isize; pub const AUTHZ_AUDIT_EVENT_HANDLE = *opaque{}; pub const AUTHZ_AUDIT_EVENT_TYPE_HANDLE = isize; pub const AUTHZ_SECURITY_EVENT_PROVIDER_HANDLE = isize; //-------------------------------------------------------------------------------- // Section: Functions (90) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.1.2600' pub extern "AUTHZ" fn AuthzAccessCheck( Flags: AUTHZ_ACCESS_CHECK_FLAGS, hAuthzClientContext: AUTHZ_CLIENT_CONTEXT_HANDLE, pRequest: ?*AUTHZ_ACCESS_REQUEST, hAuditEvent: ?AUTHZ_AUDIT_EVENT_HANDLE, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, OptionalSecurityDescriptorArray: ?[*]?*SECURITY_DESCRIPTOR, OptionalSecurityDescriptorCount: u32, pReply: ?*AUTHZ_ACCESS_REPLY, phAccessCheckResults: ?*isize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "AUTHZ" fn AuthzCachedAccessCheck( Flags: u32, hAccessCheckResults: AUTHZ_ACCESS_CHECK_RESULTS_HANDLE, pRequest: ?*AUTHZ_ACCESS_REQUEST, hAuditEvent: ?AUTHZ_AUDIT_EVENT_HANDLE, pReply: ?*AUTHZ_ACCESS_REPLY, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "AUTHZ" fn AuthzOpenObjectAudit( Flags: u32, hAuthzClientContext: AUTHZ_CLIENT_CONTEXT_HANDLE, pRequest: ?*AUTHZ_ACCESS_REQUEST, hAuditEvent: ?AUTHZ_AUDIT_EVENT_HANDLE, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, OptionalSecurityDescriptorArray: ?[*]?*SECURITY_DESCRIPTOR, OptionalSecurityDescriptorCount: u32, pReply: ?*AUTHZ_ACCESS_REPLY, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "AUTHZ" fn AuthzFreeHandle( hAccessCheckResults: AUTHZ_ACCESS_CHECK_RESULTS_HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "AUTHZ" fn AuthzInitializeResourceManager( Flags: u32, pfnDynamicAccessCheck: ?PFN_AUTHZ_DYNAMIC_ACCESS_CHECK, pfnComputeDynamicGroups: ?PFN_AUTHZ_COMPUTE_DYNAMIC_GROUPS, pfnFreeDynamicGroups: ?PFN_AUTHZ_FREE_DYNAMIC_GROUPS, szResourceManagerName: ?[*:0]const u16, phAuthzResourceManager: ?*AUTHZ_RESOURCE_MANAGER_HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' // This function from dll 'AUTHZ' is being skipped because it has some sort of issue pub fn AuthzInitializeResourceManagerEx() void { @panic("this function is not working"); } // TODO: this type is limited to platform 'windows8.0' pub extern "AUTHZ" fn AuthzInitializeRemoteResourceManager( pRpcInitInfo: ?*AUTHZ_RPC_INIT_INFO_CLIENT, phAuthzResourceManager: ?*AUTHZ_RESOURCE_MANAGER_HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "AUTHZ" fn AuthzFreeResourceManager( hAuthzResourceManager: AUTHZ_RESOURCE_MANAGER_HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "AUTHZ" fn AuthzInitializeContextFromToken( Flags: u32, TokenHandle: ?HANDLE, hAuthzResourceManager: AUTHZ_RESOURCE_MANAGER_HANDLE, pExpirationTime: ?*LARGE_INTEGER, Identifier: LUID, DynamicGroupArgs: ?*anyopaque, phAuthzClientContext: ?*isize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "AUTHZ" fn AuthzInitializeContextFromSid( Flags: u32, UserSid: ?PSID, hAuthzResourceManager: AUTHZ_RESOURCE_MANAGER_HANDLE, pExpirationTime: ?*LARGE_INTEGER, Identifier: LUID, DynamicGroupArgs: ?*anyopaque, phAuthzClientContext: ?*isize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "AUTHZ" fn AuthzInitializeContextFromAuthzContext( Flags: u32, hAuthzClientContext: AUTHZ_CLIENT_CONTEXT_HANDLE, pExpirationTime: ?*LARGE_INTEGER, Identifier: LUID, DynamicGroupArgs: ?*anyopaque, phNewAuthzClientContext: ?*isize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "AUTHZ" fn AuthzInitializeCompoundContext( UserContext: AUTHZ_CLIENT_CONTEXT_HANDLE, DeviceContext: AUTHZ_CLIENT_CONTEXT_HANDLE, phCompoundContext: ?*isize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "AUTHZ" fn AuthzAddSidsToContext( hAuthzClientContext: AUTHZ_CLIENT_CONTEXT_HANDLE, Sids: ?*SID_AND_ATTRIBUTES, SidCount: u32, RestrictedSids: ?*SID_AND_ATTRIBUTES, RestrictedSidCount: u32, phNewAuthzClientContext: ?*isize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "AUTHZ" fn AuthzModifySecurityAttributes( hAuthzClientContext: AUTHZ_CLIENT_CONTEXT_HANDLE, pOperations: ?*AUTHZ_SECURITY_ATTRIBUTE_OPERATION, pAttributes: ?*AUTHZ_SECURITY_ATTRIBUTES_INFORMATION, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "AUTHZ" fn AuthzModifyClaims( hAuthzClientContext: AUTHZ_CLIENT_CONTEXT_HANDLE, ClaimClass: AUTHZ_CONTEXT_INFORMATION_CLASS, pClaimOperations: ?*AUTHZ_SECURITY_ATTRIBUTE_OPERATION, pClaims: ?*AUTHZ_SECURITY_ATTRIBUTES_INFORMATION, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "AUTHZ" fn AuthzModifySids( hAuthzClientContext: AUTHZ_CLIENT_CONTEXT_HANDLE, SidClass: AUTHZ_CONTEXT_INFORMATION_CLASS, pSidOperations: ?*AUTHZ_SID_OPERATION, pSids: ?*TOKEN_GROUPS, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "AUTHZ" fn AuthzSetAppContainerInformation( hAuthzClientContext: AUTHZ_CLIENT_CONTEXT_HANDLE, pAppContainerSid: ?PSID, CapabilityCount: u32, pCapabilitySids: ?[*]SID_AND_ATTRIBUTES, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "AUTHZ" fn AuthzGetInformationFromContext( hAuthzClientContext: AUTHZ_CLIENT_CONTEXT_HANDLE, InfoClass: AUTHZ_CONTEXT_INFORMATION_CLASS, BufferSize: u32, pSizeRequired: ?*u32, Buffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "AUTHZ" fn AuthzFreeContext( hAuthzClientContext: AUTHZ_CLIENT_CONTEXT_HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "AUTHZ" fn AuthzInitializeObjectAccessAuditEvent( Flags: AUTHZ_INITIALIZE_OBJECT_ACCESS_AUDIT_EVENT_FLAGS, hAuditEventType: AUTHZ_AUDIT_EVENT_TYPE_HANDLE, szOperationType: ?PWSTR, szObjectType: ?PWSTR, szObjectName: ?PWSTR, szAdditionalInfo: ?PWSTR, phAuditEvent: ?*isize, dwAdditionalParameterCount: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windowsServer2003' pub extern "AUTHZ" fn AuthzInitializeObjectAccessAuditEvent2( Flags: u32, hAuditEventType: AUTHZ_AUDIT_EVENT_TYPE_HANDLE, szOperationType: ?PWSTR, szObjectType: ?PWSTR, szObjectName: ?PWSTR, szAdditionalInfo: ?PWSTR, szAdditionalInfo2: ?PWSTR, phAuditEvent: ?*isize, dwAdditionalParameterCount: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "AUTHZ" fn AuthzFreeAuditEvent( hAuditEvent: ?AUTHZ_AUDIT_EVENT_HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "AUTHZ" fn AuthzEvaluateSacl( AuthzClientContext: AUTHZ_CLIENT_CONTEXT_HANDLE, pRequest: ?*AUTHZ_ACCESS_REQUEST, Sacl: ?*ACL, GrantedAccess: u32, AccessGranted: BOOL, pbGenerateAudit: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windowsServer2003' pub extern "AUTHZ" fn AuthzInstallSecurityEventSource( dwFlags: u32, pRegistration: ?*AUTHZ_SOURCE_SCHEMA_REGISTRATION, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windowsServer2003' pub extern "AUTHZ" fn AuthzUninstallSecurityEventSource( dwFlags: u32, szEventSourceName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windowsServer2003' pub extern "AUTHZ" fn AuthzEnumerateSecurityEventSources( dwFlags: u32, Buffer: ?*AUTHZ_SOURCE_SCHEMA_REGISTRATION, pdwCount: ?*u32, pdwLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windowsServer2003' pub extern "AUTHZ" fn AuthzRegisterSecurityEventSource( dwFlags: u32, szEventSourceName: ?[*:0]const u16, phEventProvider: ?*isize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windowsServer2003' pub extern "AUTHZ" fn AuthzUnregisterSecurityEventSource( dwFlags: u32, phEventProvider: ?*isize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windowsServer2003' pub extern "AUTHZ" fn AuthzReportSecurityEvent( dwFlags: u32, hEventProvider: AUTHZ_SECURITY_EVENT_PROVIDER_HANDLE, dwAuditId: u32, pUserSid: ?PSID, dwCount: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windowsServer2003' pub extern "AUTHZ" fn AuthzReportSecurityEventFromParams( dwFlags: u32, hEventProvider: AUTHZ_SECURITY_EVENT_PROVIDER_HANDLE, dwAuditId: u32, pUserSid: ?PSID, pParams: ?*AUDIT_PARAMS, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "AUTHZ" fn AuthzRegisterCapChangeNotification( phCapChangeSubscription: ?*?*AUTHZ_CAP_CHANGE_SUBSCRIPTION_HANDLE__, pfnCapChangeCallback: ?LPTHREAD_START_ROUTINE, pCallbackContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "AUTHZ" fn AuthzUnregisterCapChangeNotification( hCapChangeSubscription: ?*AUTHZ_CAP_CHANGE_SUBSCRIPTION_HANDLE__, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "AUTHZ" fn AuthzFreeCentralAccessPolicyCache( ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetEntriesInAclA( cCountOfExplicitEntries: u32, pListOfExplicitEntries: ?[*]EXPLICIT_ACCESS_A, OldAcl: ?*ACL, NewAcl: ?*?*ACL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetEntriesInAclW( cCountOfExplicitEntries: u32, pListOfExplicitEntries: ?[*]EXPLICIT_ACCESS_W, OldAcl: ?*ACL, NewAcl: ?*?*ACL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetExplicitEntriesFromAclA( pacl: ?*ACL, pcCountOfExplicitEntries: ?*u32, pListOfExplicitEntries: ?*?*EXPLICIT_ACCESS_A, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetExplicitEntriesFromAclW( pacl: ?*ACL, pcCountOfExplicitEntries: ?*u32, pListOfExplicitEntries: ?*?*EXPLICIT_ACCESS_W, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetEffectiveRightsFromAclA( pacl: ?*ACL, pTrustee: ?*TRUSTEE_A, pAccessRights: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetEffectiveRightsFromAclW( pacl: ?*ACL, pTrustee: ?*TRUSTEE_W, pAccessRights: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetAuditedPermissionsFromAclA( pacl: ?*ACL, pTrustee: ?*TRUSTEE_A, pSuccessfulAuditedRights: ?*u32, pFailedAuditRights: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetAuditedPermissionsFromAclW( pacl: ?*ACL, pTrustee: ?*TRUSTEE_W, pSuccessfulAuditedRights: ?*u32, pFailedAuditRights: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetNamedSecurityInfoA( pObjectName: ?[*:0]const u8, ObjectType: SE_OBJECT_TYPE, SecurityInfo: OBJECT_SECURITY_INFORMATION, ppsidOwner: ?*?PSID, ppsidGroup: ?*?PSID, ppDacl: ?*?*ACL, ppSacl: ?*?*ACL, ppSecurityDescriptor: ?*?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetNamedSecurityInfoW( pObjectName: ?[*:0]const u16, ObjectType: SE_OBJECT_TYPE, SecurityInfo: OBJECT_SECURITY_INFORMATION, ppsidOwner: ?*?PSID, ppsidGroup: ?*?PSID, ppDacl: ?*?*ACL, ppSacl: ?*?*ACL, ppSecurityDescriptor: ?*?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetSecurityInfo( handle: ?HANDLE, ObjectType: SE_OBJECT_TYPE, SecurityInfo: u32, ppsidOwner: ?*?PSID, ppsidGroup: ?*?PSID, ppDacl: ?*?*ACL, ppSacl: ?*?*ACL, ppSecurityDescriptor: ?*?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetNamedSecurityInfoA( pObjectName: ?PSTR, ObjectType: SE_OBJECT_TYPE, SecurityInfo: OBJECT_SECURITY_INFORMATION, psidOwner: ?PSID, psidGroup: ?PSID, pDacl: ?*ACL, pSacl: ?*ACL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetNamedSecurityInfoW( pObjectName: ?PWSTR, ObjectType: SE_OBJECT_TYPE, SecurityInfo: OBJECT_SECURITY_INFORMATION, psidOwner: ?PSID, psidGroup: ?PSID, pDacl: ?*ACL, pSacl: ?*ACL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetSecurityInfo( handle: ?HANDLE, ObjectType: SE_OBJECT_TYPE, SecurityInfo: u32, psidOwner: ?PSID, psidGroup: ?PSID, pDacl: ?*ACL, pSacl: ?*ACL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetInheritanceSourceA( pObjectName: ?PSTR, ObjectType: SE_OBJECT_TYPE, SecurityInfo: u32, Container: BOOL, pObjectClassGuids: ?[*]?*Guid, GuidCount: u32, pAcl: ?*ACL, pfnArray: ?*FN_OBJECT_MGR_FUNCTIONS, pGenericMapping: ?*GENERIC_MAPPING, pInheritArray: ?*INHERITED_FROMA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetInheritanceSourceW( pObjectName: ?PWSTR, ObjectType: SE_OBJECT_TYPE, SecurityInfo: u32, Container: BOOL, pObjectClassGuids: ?[*]?*Guid, GuidCount: u32, pAcl: ?*ACL, pfnArray: ?*FN_OBJECT_MGR_FUNCTIONS, pGenericMapping: ?*GENERIC_MAPPING, pInheritArray: ?*INHERITED_FROMW, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn FreeInheritedFromArray( pInheritArray: [*]INHERITED_FROMW, AceCnt: u16, pfnArray: ?*FN_OBJECT_MGR_FUNCTIONS, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn TreeResetNamedSecurityInfoA( pObjectName: ?PSTR, ObjectType: SE_OBJECT_TYPE, SecurityInfo: u32, pOwner: ?PSID, pGroup: ?PSID, pDacl: ?*ACL, pSacl: ?*ACL, KeepExplicit: BOOL, fnProgress: ?FN_PROGRESS, ProgressInvokeSetting: PROG_INVOKE_SETTING, Args: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn TreeResetNamedSecurityInfoW( pObjectName: ?PWSTR, ObjectType: SE_OBJECT_TYPE, SecurityInfo: u32, pOwner: ?PSID, pGroup: ?PSID, pDacl: ?*ACL, pSacl: ?*ACL, KeepExplicit: BOOL, fnProgress: ?FN_PROGRESS, ProgressInvokeSetting: PROG_INVOKE_SETTING, Args: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn TreeSetNamedSecurityInfoA( pObjectName: ?PSTR, ObjectType: SE_OBJECT_TYPE, SecurityInfo: u32, pOwner: ?PSID, pGroup: ?PSID, pDacl: ?*ACL, pSacl: ?*ACL, dwAction: TREE_SEC_INFO, fnProgress: ?FN_PROGRESS, ProgressInvokeSetting: PROG_INVOKE_SETTING, Args: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn TreeSetNamedSecurityInfoW( pObjectName: ?PWSTR, ObjectType: SE_OBJECT_TYPE, SecurityInfo: u32, pOwner: ?PSID, pGroup: ?PSID, pDacl: ?*ACL, pSacl: ?*ACL, dwAction: TREE_SEC_INFO, fnProgress: ?FN_PROGRESS, ProgressInvokeSetting: PROG_INVOKE_SETTING, Args: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn BuildSecurityDescriptorA( pOwner: ?*TRUSTEE_A, pGroup: ?*TRUSTEE_A, cCountOfAccessEntries: u32, pListOfAccessEntries: ?[*]EXPLICIT_ACCESS_A, cCountOfAuditEntries: u32, pListOfAuditEntries: ?[*]EXPLICIT_ACCESS_A, pOldSD: ?*SECURITY_DESCRIPTOR, pSizeNewSD: ?*u32, pNewSD: ?*?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn BuildSecurityDescriptorW( pOwner: ?*TRUSTEE_W, pGroup: ?*TRUSTEE_W, cCountOfAccessEntries: u32, pListOfAccessEntries: ?[*]EXPLICIT_ACCESS_W, cCountOfAuditEntries: u32, pListOfAuditEntries: ?[*]EXPLICIT_ACCESS_W, pOldSD: ?*SECURITY_DESCRIPTOR, pSizeNewSD: ?*u32, pNewSD: ?*?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LookupSecurityDescriptorPartsA( ppOwner: ?*?*TRUSTEE_A, ppGroup: ?*?*TRUSTEE_A, pcCountOfAccessEntries: ?*u32, ppListOfAccessEntries: ?*?*EXPLICIT_ACCESS_A, pcCountOfAuditEntries: ?*u32, ppListOfAuditEntries: ?*?*EXPLICIT_ACCESS_A, pSD: ?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LookupSecurityDescriptorPartsW( ppOwner: ?*?*TRUSTEE_W, ppGroup: ?*?*TRUSTEE_W, pcCountOfAccessEntries: ?*u32, ppListOfAccessEntries: ?*?*EXPLICIT_ACCESS_W, pcCountOfAuditEntries: ?*u32, ppListOfAuditEntries: ?*?*EXPLICIT_ACCESS_W, pSD: ?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn BuildExplicitAccessWithNameA( pExplicitAccess: ?*EXPLICIT_ACCESS_A, pTrusteeName: ?PSTR, AccessPermissions: u32, AccessMode: ACCESS_MODE, Inheritance: ACE_FLAGS, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn BuildExplicitAccessWithNameW( pExplicitAccess: ?*EXPLICIT_ACCESS_W, pTrusteeName: ?PWSTR, AccessPermissions: u32, AccessMode: ACCESS_MODE, Inheritance: ACE_FLAGS, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "ADVAPI32" fn BuildImpersonateExplicitAccessWithNameA( pExplicitAccess: ?*EXPLICIT_ACCESS_A, pTrusteeName: ?PSTR, pTrustee: ?*TRUSTEE_A, AccessPermissions: u32, AccessMode: ACCESS_MODE, Inheritance: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "ADVAPI32" fn BuildImpersonateExplicitAccessWithNameW( pExplicitAccess: ?*EXPLICIT_ACCESS_W, pTrusteeName: ?PWSTR, pTrustee: ?*TRUSTEE_W, AccessPermissions: u32, AccessMode: ACCESS_MODE, Inheritance: u32, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn BuildTrusteeWithNameA( pTrustee: ?*TRUSTEE_A, pName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn BuildTrusteeWithNameW( pTrustee: ?*TRUSTEE_W, pName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "ADVAPI32" fn BuildImpersonateTrusteeA( pTrustee: ?*TRUSTEE_A, pImpersonateTrustee: ?*TRUSTEE_A, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "ADVAPI32" fn BuildImpersonateTrusteeW( pTrustee: ?*TRUSTEE_W, pImpersonateTrustee: ?*TRUSTEE_W, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn BuildTrusteeWithSidA( pTrustee: ?*TRUSTEE_A, pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn BuildTrusteeWithSidW( pTrustee: ?*TRUSTEE_W, pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn BuildTrusteeWithObjectsAndSidA( pTrustee: ?*TRUSTEE_A, pObjSid: ?*OBJECTS_AND_SID, pObjectGuid: ?*Guid, pInheritedObjectGuid: ?*Guid, pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn BuildTrusteeWithObjectsAndSidW( pTrustee: ?*TRUSTEE_W, pObjSid: ?*OBJECTS_AND_SID, pObjectGuid: ?*Guid, pInheritedObjectGuid: ?*Guid, pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' // This function from dll 'ADVAPI32' is being skipped because it has some sort of issue pub fn BuildTrusteeWithObjectsAndNameA() void { @panic("this function is not working"); } // TODO: this type is limited to platform 'windows5.1.2600' // This function from dll 'ADVAPI32' is being skipped because it has some sort of issue pub fn BuildTrusteeWithObjectsAndNameW() void { @panic("this function is not working"); } // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetTrusteeNameA( pTrustee: ?*TRUSTEE_A, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetTrusteeNameW( pTrustee: ?*TRUSTEE_W, ) callconv(@import("std").os.windows.WINAPI) ?PWSTR; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetTrusteeTypeA( pTrustee: ?*TRUSTEE_A, ) callconv(@import("std").os.windows.WINAPI) TRUSTEE_TYPE; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetTrusteeTypeW( pTrustee: ?*TRUSTEE_W, ) callconv(@import("std").os.windows.WINAPI) TRUSTEE_TYPE; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetTrusteeFormA( pTrustee: ?*TRUSTEE_A, ) callconv(@import("std").os.windows.WINAPI) TRUSTEE_FORM; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetTrusteeFormW( pTrustee: ?*TRUSTEE_W, ) callconv(@import("std").os.windows.WINAPI) TRUSTEE_FORM; pub extern "ADVAPI32" fn GetMultipleTrusteeOperationA( pTrustee: ?*TRUSTEE_A, ) callconv(@import("std").os.windows.WINAPI) MULTIPLE_TRUSTEE_OPERATION; pub extern "ADVAPI32" fn GetMultipleTrusteeOperationW( pTrustee: ?*TRUSTEE_W, ) callconv(@import("std").os.windows.WINAPI) MULTIPLE_TRUSTEE_OPERATION; pub extern "ADVAPI32" fn GetMultipleTrusteeA( pTrustee: ?*TRUSTEE_A, ) callconv(@import("std").os.windows.WINAPI) ?*TRUSTEE_A; pub extern "ADVAPI32" fn GetMultipleTrusteeW( pTrustee: ?*TRUSTEE_W, ) callconv(@import("std").os.windows.WINAPI) ?*TRUSTEE_W; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ConvertSidToStringSidA( Sid: ?PSID, StringSid: ?*?PSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ConvertSidToStringSidW( Sid: ?PSID, StringSid: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ConvertStringSidToSidA( StringSid: ?[*:0]const u8, Sid: ?*?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ConvertStringSidToSidW( StringSid: ?[*:0]const u16, Sid: ?*?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ConvertStringSecurityDescriptorToSecurityDescriptorA( StringSecurityDescriptor: ?[*:0]const u8, StringSDRevision: u32, SecurityDescriptor: ?*?*SECURITY_DESCRIPTOR, SecurityDescriptorSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ConvertStringSecurityDescriptorToSecurityDescriptorW( StringSecurityDescriptor: ?[*:0]const u16, StringSDRevision: u32, SecurityDescriptor: ?*?*SECURITY_DESCRIPTOR, SecurityDescriptorSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ConvertSecurityDescriptorToStringSecurityDescriptorA( SecurityDescriptor: ?*SECURITY_DESCRIPTOR, RequestedStringSDRevision: u32, SecurityInformation: u32, StringSecurityDescriptor: ?*?PSTR, StringSecurityDescriptorLen: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ConvertSecurityDescriptorToStringSecurityDescriptorW( SecurityDescriptor: ?*SECURITY_DESCRIPTOR, RequestedStringSDRevision: u32, SecurityInformation: u32, StringSecurityDescriptor: ?*?PWSTR, StringSecurityDescriptorLen: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (38) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const OBJECTS_AND_NAME_ = thismodule.OBJECTS_AND_NAME_A; pub const TRUSTEE_ = thismodule.TRUSTEE_A; pub const EXPLICIT_ACCESS_ = thismodule.EXPLICIT_ACCESS_A; pub const ACTRL_ACCESS_ENTRY = thismodule.ACTRL_ACCESS_ENTRYA; pub const ACTRL_ACCESS_ENTRY_LIST = thismodule.ACTRL_ACCESS_ENTRY_LISTA; pub const ACTRL_PROPERTY_ENTRY = thismodule.ACTRL_PROPERTY_ENTRYA; pub const ACTRL_ACCESS = thismodule.ACTRL_ACCESSA; pub const TRUSTEE_ACCESS = thismodule.TRUSTEE_ACCESSA; pub const ACTRL_ACCESS_INFO = thismodule.ACTRL_ACCESS_INFOA; pub const ACTRL_CONTROL_INFO = thismodule.ACTRL_CONTROL_INFOA; pub const INHERITED_FROM = thismodule.INHERITED_FROMA; pub const SetEntriesInAcl = thismodule.SetEntriesInAclA; pub const GetExplicitEntriesFromAcl = thismodule.GetExplicitEntriesFromAclA; pub const GetEffectiveRightsFromAcl = thismodule.GetEffectiveRightsFromAclA; pub const GetAuditedPermissionsFromAcl = thismodule.GetAuditedPermissionsFromAclA; pub const GetNamedSecurityInfo = thismodule.GetNamedSecurityInfoA; pub const SetNamedSecurityInfo = thismodule.SetNamedSecurityInfoA; pub const GetInheritanceSource = thismodule.GetInheritanceSourceA; pub const TreeResetNamedSecurityInfo = thismodule.TreeResetNamedSecurityInfoA; pub const TreeSetNamedSecurityInfo = thismodule.TreeSetNamedSecurityInfoA; pub const BuildSecurityDescriptor = thismodule.BuildSecurityDescriptorA; pub const LookupSecurityDescriptorParts = thismodule.LookupSecurityDescriptorPartsA; pub const BuildExplicitAccessWithName = thismodule.BuildExplicitAccessWithNameA; pub const BuildImpersonateExplicitAccessWithName = thismodule.BuildImpersonateExplicitAccessWithNameA; pub const BuildTrusteeWithName = thismodule.BuildTrusteeWithNameA; pub const BuildImpersonateTrustee = thismodule.BuildImpersonateTrusteeA; pub const BuildTrusteeWithSid = thismodule.BuildTrusteeWithSidA; pub const BuildTrusteeWithObjectsAndSid = thismodule.BuildTrusteeWithObjectsAndSidA; pub const BuildTrusteeWithObjectsAndName = thismodule.BuildTrusteeWithObjectsAndNameA; pub const GetTrusteeName = thismodule.GetTrusteeNameA; pub const GetTrusteeType = thismodule.GetTrusteeTypeA; pub const GetTrusteeForm = thismodule.GetTrusteeFormA; pub const GetMultipleTrusteeOperation = thismodule.GetMultipleTrusteeOperationA; pub const GetMultipleTrustee = thismodule.GetMultipleTrusteeA; pub const ConvertSidToStringSid = thismodule.ConvertSidToStringSidA; pub const ConvertStringSidToSid = thismodule.ConvertStringSidToSidA; pub const ConvertStringSecurityDescriptorToSecurityDescriptor = thismodule.ConvertStringSecurityDescriptorToSecurityDescriptorA; pub const ConvertSecurityDescriptorToStringSecurityDescriptor = thismodule.ConvertSecurityDescriptorToStringSecurityDescriptorA; }, .wide => struct { pub const OBJECTS_AND_NAME_ = thismodule.OBJECTS_AND_NAME_W; pub const TRUSTEE_ = thismodule.TRUSTEE_W; pub const EXPLICIT_ACCESS_ = thismodule.EXPLICIT_ACCESS_W; pub const ACTRL_ACCESS_ENTRY = thismodule.ACTRL_ACCESS_ENTRYW; pub const ACTRL_ACCESS_ENTRY_LIST = thismodule.ACTRL_ACCESS_ENTRY_LISTW; pub const ACTRL_PROPERTY_ENTRY = thismodule.ACTRL_PROPERTY_ENTRYW; pub const ACTRL_ACCESS = thismodule.ACTRL_ACCESSW; pub const TRUSTEE_ACCESS = thismodule.TRUSTEE_ACCESSW; pub const ACTRL_ACCESS_INFO = thismodule.ACTRL_ACCESS_INFOW; pub const ACTRL_CONTROL_INFO = thismodule.ACTRL_CONTROL_INFOW; pub const INHERITED_FROM = thismodule.INHERITED_FROMW; pub const SetEntriesInAcl = thismodule.SetEntriesInAclW; pub const GetExplicitEntriesFromAcl = thismodule.GetExplicitEntriesFromAclW; pub const GetEffectiveRightsFromAcl = thismodule.GetEffectiveRightsFromAclW; pub const GetAuditedPermissionsFromAcl = thismodule.GetAuditedPermissionsFromAclW; pub const GetNamedSecurityInfo = thismodule.GetNamedSecurityInfoW; pub const SetNamedSecurityInfo = thismodule.SetNamedSecurityInfoW; pub const GetInheritanceSource = thismodule.GetInheritanceSourceW; pub const TreeResetNamedSecurityInfo = thismodule.TreeResetNamedSecurityInfoW; pub const TreeSetNamedSecurityInfo = thismodule.TreeSetNamedSecurityInfoW; pub const BuildSecurityDescriptor = thismodule.BuildSecurityDescriptorW; pub const LookupSecurityDescriptorParts = thismodule.LookupSecurityDescriptorPartsW; pub const BuildExplicitAccessWithName = thismodule.BuildExplicitAccessWithNameW; pub const BuildImpersonateExplicitAccessWithName = thismodule.BuildImpersonateExplicitAccessWithNameW; pub const BuildTrusteeWithName = thismodule.BuildTrusteeWithNameW; pub const BuildImpersonateTrustee = thismodule.BuildImpersonateTrusteeW; pub const BuildTrusteeWithSid = thismodule.BuildTrusteeWithSidW; pub const BuildTrusteeWithObjectsAndSid = thismodule.BuildTrusteeWithObjectsAndSidW; pub const BuildTrusteeWithObjectsAndName = thismodule.BuildTrusteeWithObjectsAndNameW; pub const GetTrusteeName = thismodule.GetTrusteeNameW; pub const GetTrusteeType = thismodule.GetTrusteeTypeW; pub const GetTrusteeForm = thismodule.GetTrusteeFormW; pub const GetMultipleTrusteeOperation = thismodule.GetMultipleTrusteeOperationW; pub const GetMultipleTrustee = thismodule.GetMultipleTrusteeW; pub const ConvertSidToStringSid = thismodule.ConvertSidToStringSidW; pub const ConvertStringSidToSid = thismodule.ConvertStringSidToSidW; pub const ConvertStringSecurityDescriptorToSecurityDescriptor = thismodule.ConvertStringSecurityDescriptorToSecurityDescriptorW; pub const ConvertSecurityDescriptorToStringSecurityDescriptor = thismodule.ConvertSecurityDescriptorToStringSecurityDescriptorW; }, .unspecified => if (@import("builtin").is_test) struct { pub const OBJECTS_AND_NAME_ = *opaque{}; pub const TRUSTEE_ = *opaque{}; pub const EXPLICIT_ACCESS_ = *opaque{}; pub const ACTRL_ACCESS_ENTRY = *opaque{}; pub const ACTRL_ACCESS_ENTRY_LIST = *opaque{}; pub const ACTRL_PROPERTY_ENTRY = *opaque{}; pub const ACTRL_ACCESS = *opaque{}; pub const TRUSTEE_ACCESS = *opaque{}; pub const ACTRL_ACCESS_INFO = *opaque{}; pub const ACTRL_CONTROL_INFO = *opaque{}; pub const INHERITED_FROM = *opaque{}; pub const SetEntriesInAcl = *opaque{}; pub const GetExplicitEntriesFromAcl = *opaque{}; pub const GetEffectiveRightsFromAcl = *opaque{}; pub const GetAuditedPermissionsFromAcl = *opaque{}; pub const GetNamedSecurityInfo = *opaque{}; pub const SetNamedSecurityInfo = *opaque{}; pub const GetInheritanceSource = *opaque{}; pub const TreeResetNamedSecurityInfo = *opaque{}; pub const TreeSetNamedSecurityInfo = *opaque{}; pub const BuildSecurityDescriptor = *opaque{}; pub const LookupSecurityDescriptorParts = *opaque{}; pub const BuildExplicitAccessWithName = *opaque{}; pub const BuildImpersonateExplicitAccessWithName = *opaque{}; pub const BuildTrusteeWithName = *opaque{}; pub const BuildImpersonateTrustee = *opaque{}; pub const BuildTrusteeWithSid = *opaque{}; pub const BuildTrusteeWithObjectsAndSid = *opaque{}; pub const BuildTrusteeWithObjectsAndName = *opaque{}; pub const GetTrusteeName = *opaque{}; pub const GetTrusteeType = *opaque{}; pub const GetTrusteeForm = *opaque{}; pub const GetMultipleTrusteeOperation = *opaque{}; pub const GetMultipleTrustee = *opaque{}; pub const ConvertSidToStringSid = *opaque{}; pub const ConvertStringSidToSid = *opaque{}; pub const ConvertStringSecurityDescriptorToSecurityDescriptor = *opaque{}; pub const ConvertSecurityDescriptorToStringSecurityDescriptor = *opaque{}; } else struct { pub const OBJECTS_AND_NAME_ = @compileError("'OBJECTS_AND_NAME_' requires that UNICODE be set to true or false in the root module"); pub const TRUSTEE_ = @compileError("'TRUSTEE_' requires that UNICODE be set to true or false in the root module"); pub const EXPLICIT_ACCESS_ = @compileError("'EXPLICIT_ACCESS_' requires that UNICODE be set to true or false in the root module"); pub const ACTRL_ACCESS_ENTRY = @compileError("'ACTRL_ACCESS_ENTRY' requires that UNICODE be set to true or false in the root module"); pub const ACTRL_ACCESS_ENTRY_LIST = @compileError("'ACTRL_ACCESS_ENTRY_LIST' requires that UNICODE be set to true or false in the root module"); pub const ACTRL_PROPERTY_ENTRY = @compileError("'ACTRL_PROPERTY_ENTRY' requires that UNICODE be set to true or false in the root module"); pub const ACTRL_ACCESS = @compileError("'ACTRL_ACCESS' requires that UNICODE be set to true or false in the root module"); pub const TRUSTEE_ACCESS = @compileError("'TRUSTEE_ACCESS' requires that UNICODE be set to true or false in the root module"); pub const ACTRL_ACCESS_INFO = @compileError("'ACTRL_ACCESS_INFO' requires that UNICODE be set to true or false in the root module"); pub const ACTRL_CONTROL_INFO = @compileError("'ACTRL_CONTROL_INFO' requires that UNICODE be set to true or false in the root module"); pub const INHERITED_FROM = @compileError("'INHERITED_FROM' requires that UNICODE be set to true or false in the root module"); pub const SetEntriesInAcl = @compileError("'SetEntriesInAcl' requires that UNICODE be set to true or false in the root module"); pub const GetExplicitEntriesFromAcl = @compileError("'GetExplicitEntriesFromAcl' requires that UNICODE be set to true or false in the root module"); pub const GetEffectiveRightsFromAcl = @compileError("'GetEffectiveRightsFromAcl' requires that UNICODE be set to true or false in the root module"); pub const GetAuditedPermissionsFromAcl = @compileError("'GetAuditedPermissionsFromAcl' requires that UNICODE be set to true or false in the root module"); pub const GetNamedSecurityInfo = @compileError("'GetNamedSecurityInfo' requires that UNICODE be set to true or false in the root module"); pub const SetNamedSecurityInfo = @compileError("'SetNamedSecurityInfo' requires that UNICODE be set to true or false in the root module"); pub const GetInheritanceSource = @compileError("'GetInheritanceSource' requires that UNICODE be set to true or false in the root module"); pub const TreeResetNamedSecurityInfo = @compileError("'TreeResetNamedSecurityInfo' requires that UNICODE be set to true or false in the root module"); pub const TreeSetNamedSecurityInfo = @compileError("'TreeSetNamedSecurityInfo' requires that UNICODE be set to true or false in the root module"); pub const BuildSecurityDescriptor = @compileError("'BuildSecurityDescriptor' requires that UNICODE be set to true or false in the root module"); pub const LookupSecurityDescriptorParts = @compileError("'LookupSecurityDescriptorParts' requires that UNICODE be set to true or false in the root module"); pub const BuildExplicitAccessWithName = @compileError("'BuildExplicitAccessWithName' requires that UNICODE be set to true or false in the root module"); pub const BuildImpersonateExplicitAccessWithName = @compileError("'BuildImpersonateExplicitAccessWithName' requires that UNICODE be set to true or false in the root module"); pub const BuildTrusteeWithName = @compileError("'BuildTrusteeWithName' requires that UNICODE be set to true or false in the root module"); pub const BuildImpersonateTrustee = @compileError("'BuildImpersonateTrustee' requires that UNICODE be set to true or false in the root module"); pub const BuildTrusteeWithSid = @compileError("'BuildTrusteeWithSid' requires that UNICODE be set to true or false in the root module"); pub const BuildTrusteeWithObjectsAndSid = @compileError("'BuildTrusteeWithObjectsAndSid' requires that UNICODE be set to true or false in the root module"); pub const BuildTrusteeWithObjectsAndName = @compileError("'BuildTrusteeWithObjectsAndName' requires that UNICODE be set to true or false in the root module"); pub const GetTrusteeName = @compileError("'GetTrusteeName' requires that UNICODE be set to true or false in the root module"); pub const GetTrusteeType = @compileError("'GetTrusteeType' requires that UNICODE be set to true or false in the root module"); pub const GetTrusteeForm = @compileError("'GetTrusteeForm' requires that UNICODE be set to true or false in the root module"); pub const GetMultipleTrusteeOperation = @compileError("'GetMultipleTrusteeOperation' requires that UNICODE be set to true or false in the root module"); pub const GetMultipleTrustee = @compileError("'GetMultipleTrustee' requires that UNICODE be set to true or false in the root module"); pub const ConvertSidToStringSid = @compileError("'ConvertSidToStringSid' requires that UNICODE be set to true or false in the root module"); pub const ConvertStringSidToSid = @compileError("'ConvertStringSidToSid' requires that UNICODE be set to true or false in the root module"); pub const ConvertStringSecurityDescriptorToSecurityDescriptor = @compileError("'ConvertStringSecurityDescriptorToSecurityDescriptor' requires that UNICODE be set to true or false in the root module"); pub const ConvertSecurityDescriptorToStringSecurityDescriptor = @compileError("'ConvertSecurityDescriptorToStringSecurityDescriptor' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (26) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const ACE_FLAGS = @import("../security.zig").ACE_FLAGS; const ACE_HEADER = @import("../security.zig").ACE_HEADER; const ACL = @import("../security.zig").ACL; const BOOL = @import("../foundation.zig").BOOL; const BSTR = @import("../foundation.zig").BSTR; const GENERIC_MAPPING = @import("../security.zig").GENERIC_MAPPING; const HANDLE = @import("../foundation.zig").HANDLE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IDispatch = @import("../system/com.zig").IDispatch; const IUnknown = @import("../system/com.zig").IUnknown; const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER; const LPTHREAD_START_ROUTINE = @import("../system/threading.zig").LPTHREAD_START_ROUTINE; const LUID = @import("../foundation.zig").LUID; const OBJECT_SECURITY_INFORMATION = @import("../security.zig").OBJECT_SECURITY_INFORMATION; const OBJECT_TYPE_LIST = @import("../security.zig").OBJECT_TYPE_LIST; const PSID = @import("../foundation.zig").PSID; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const SECURITY_DESCRIPTOR = @import("../security.zig").SECURITY_DESCRIPTOR; const SID = @import("../security.zig").SID; const SID_AND_ATTRIBUTES = @import("../security.zig").SID_AND_ATTRIBUTES; const SYSTEM_AUDIT_OBJECT_ACE_FLAGS = @import("../security.zig").SYSTEM_AUDIT_OBJECT_ACE_FLAGS; const TOKEN_GROUPS = @import("../security.zig").TOKEN_GROUPS; const VARIANT = @import("../system/com.zig").VARIANT; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFN_AUTHZ_DYNAMIC_ACCESS_CHECK")) { _ = PFN_AUTHZ_DYNAMIC_ACCESS_CHECK; } if (@hasDecl(@This(), "PFN_AUTHZ_COMPUTE_DYNAMIC_GROUPS")) { _ = PFN_AUTHZ_COMPUTE_DYNAMIC_GROUPS; } if (@hasDecl(@This(), "PFN_AUTHZ_FREE_DYNAMIC_GROUPS")) { _ = PFN_AUTHZ_FREE_DYNAMIC_GROUPS; } if (@hasDecl(@This(), "PFN_AUTHZ_GET_CENTRAL_ACCESS_POLICY")) { _ = PFN_AUTHZ_GET_CENTRAL_ACCESS_POLICY; } if (@hasDecl(@This(), "PFN_AUTHZ_FREE_CENTRAL_ACCESS_POLICY")) { _ = PFN_AUTHZ_FREE_CENTRAL_ACCESS_POLICY; } if (@hasDecl(@This(), "FN_PROGRESS")) { _ = FN_PROGRESS; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } } //-------------------------------------------------------------------------------- // Section: SubModules (1) //-------------------------------------------------------------------------------- pub const ui = @import("authorization/ui.zig");
win32/security/authorization.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); const Vec2 = tools.Vec2; const Map = tools.Map(u1, 400, 400, true); pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); var map = Map{ .default_tile = 0 }; { var it = std.mem.tokenize(u8, input_text, "\n\r"); while (it.next()) |line| { var i: usize = 0; var p = Vec2{ .x = 0, .y = 0 }; while (i < line.len) { switch (line[i]) { 'e' => { p.x += 1; i += 1; }, 'w' => { p.x -= 1; i += 1; }, 's' => switch (line[i + 1]) { 'e' => { p.x += @mod(p.y, 2); p.y += 1; i += 2; }, 'w' => { p.x -= (1 - @mod(p.y, 2)); p.y += 1; i += 2; }, else => unreachable, }, 'n' => switch (line[i + 1]) { 'e' => { p.x += @mod(p.y, 2); p.y -= 1; i += 2; }, 'w' => { p.x -= (1 - @mod(p.y, 2)); p.y -= 1; i += 2; }, else => unreachable, }, else => unreachable, } } const cur = map.get(p) orelse 0; map.set(p, 1 - cur); } } const ans1 = ans: { var nb: u32 = 0; var it = map.iter(null); while (it.next()) |t| nb += t; break :ans nb; }; const ans2 = ans: { var round: u32 = 0; while (round < 100) : (round += 1) { var map2 = Map{ .default_tile = 0 }; map.growBBox(Vec2{ .x = map.bbox.min.x - 1, .y = map.bbox.min.y - 1 }); map.growBBox(Vec2{ .x = map.bbox.max.x + 1, .y = map.bbox.max.y + 1 }); var it = map.iter(null); while (it.nextEx()) |t| { const neib = blk: { const w = t.left orelse 0; const e = t.right orelse 0; var sw: u1 = 0; var se: u1 = 0; var nw: u1 = 0; var ne: u1 = 0; if (@mod(t.p.y, 2) == 0) { nw = t.up_left orelse 0; ne = t.up orelse 0; sw = t.down_left orelse 0; se = t.down orelse 0; } else { nw = t.up orelse 0; ne = t.up_right orelse 0; sw = t.down orelse 0; se = t.down_right orelse 0; } var nb: u8 = 0; nb += w; nb += e; nb += nw; nb += ne; nb += sw; nb += se; break :blk nb; }; if (t.t.* == 1) { if (neib == 0 or neib > 2) { map2.set(t.p, 0); } else { map2.set(t.p, 1); } } else { if (neib == 2) { map2.set(t.p, 1); } else { map2.set(t.p, 0); } } } map = map2; } var nb: u32 = 0; var it = map.iter(null); while (it.next()) |t| nb += t; break :ans nb; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2020/input_day24.txt", run);
2020/day24.zig
const subo = @import("subo.zig"); const testing = @import("std").testing; fn test__subosi4(a: i32, b: i32) !void { var result_ov: c_int = undefined; var expected_ov: c_int = undefined; var result = subo.__subosi4(a, b, &result_ov); var expected: i32 = simple_subosi4(a, b, &expected_ov); try testing.expectEqual(expected, result); try testing.expectEqual(expected_ov, result_ov); } // 2 cases on evaluating `a-b`: // 1. `a-b` may underflow, iff b>0 && a<0 and a-b < min <=> a<min+b // 2. `a-b` may overflow, iff b<0 && a>0 and a-b > max <=> a>max+b // `-b` evaluation may overflow, iff b==min, but this is handled by the hardware pub fn simple_subosi4(a: i32, b: i32, overflow: *c_int) i32 { overflow.* = 0; const min: i32 = -2147483648; const max: i32 = 2147483647; if (((b > 0) and (a < min + b)) or ((b < 0) and (a > max + b))) overflow.* = 1; return a -% b; } test "subosi3" { // -2^31 <= i32 <= 2^31-1 // 2^31 = 2147483648 // 2^31-1 = 2147483647 const min: i32 = -2147483648; const max: i32 = 2147483647; var i: i32 = 1; while (i < max) : (i *|= 2) { try test__subosi4(i, i); try test__subosi4(-i, -i); try test__subosi4(i, -i); try test__subosi4(-i, i); } // edge cases // 0 - 0 = 0 // MIN - MIN = 0 // MAX - MAX = 0 // 0 - MIN overflow // 0 - MAX = MIN+1 // MIN - 0 = MIN // MAX - 0 = MAX // MIN - MAX overflow // MAX - MIN overflow try test__subosi4(0, 0); try test__subosi4(min, min); try test__subosi4(max, max); try test__subosi4(0, min); try test__subosi4(0, max); try test__subosi4(min, 0); try test__subosi4(max, 0); try test__subosi4(min, max); try test__subosi4(max, min); // derived edge cases // MIN+1 - MIN = 1 // MAX-1 - MAX = -1 // 1 - MIN overflow // -1 - MIN = MAX // -1 - MAX = MIN // +1 - MAX = MIN+2 // MIN - 1 overflow // MIN - -1 = MIN+1 // MAX - 1 = MAX-1 // MAX - -1 overflow try test__subosi4(min + 1, min); try test__subosi4(max - 1, max); try test__subosi4(1, min); try test__subosi4(-1, min); try test__subosi4(-1, max); try test__subosi4(1, max); try test__subosi4(min, 1); try test__subosi4(min, -1); try test__subosi4(max, -1); try test__subosi4(max, 1); }
lib/std/special/compiler_rt/subosi4_test.zig
const std = @import("std"); const mem = std.mem; const net = std.net; const os = std.os; const IO = @import("tigerbeetle-io").IO; const http = @import("http"); const Client = struct { io: IO, sock: os.socket_t, address: std.net.Address, send_buf: []u8, recv_buf: []u8, allocator: mem.Allocator, completion: IO.Completion = undefined, done: bool = false, fn init(allocator: mem.Allocator, address: std.net.Address) !Client { const sock = try os.socket(address.any.family, os.SOCK_STREAM | os.SOCK_CLOEXEC, 0); const send_buf = try allocator.alloc(u8, 8192); const recv_buf = try allocator.alloc(u8, 8192); return Client{ .io = try IO.init(256, 0), .sock = sock, .address = address, .send_buf = send_buf, .recv_buf = recv_buf, .allocator = allocator, }; } pub fn deinit(self: *Client) void { self.allocator.free(self.send_buf); self.allocator.free(self.recv_buf); self.io.deinit(); } pub fn run(self: *Client) !void { self.io.connect(*Client, self, connectCallback, &self.completion, self.sock, self.address); while (!self.done) try self.io.tick(); } fn connectCallback( self: *Client, completion: *IO.Completion, result: IO.ConnectError!void, ) void { var fbs = std.io.fixedBufferStream(self.send_buf); var w = fbs.writer(); std.fmt.format(w, "Hello from client!\n", .{}) catch unreachable; self.io.send( *Client, self, sendCallback, completion, self.sock, fbs.getWritten(), if (std.Target.current.os.tag == .linux) os.MSG_NOSIGNAL else 0, ); } fn sendCallback( self: *Client, completion: *IO.Completion, result: IO.SendError!usize, ) void { const sent = result catch @panic("send error"); std.debug.print("Sent: {s}", .{self.send_buf[0..sent]}); self.io.recv( *Client, self, recvCallback, completion, self.sock, self.recv_buf, if (std.Target.current.os.tag == .linux) os.MSG_NOSIGNAL else 0, ); } fn recvCallback( self: *Client, completion: *IO.Completion, result: IO.RecvError!usize, ) void { const received = result catch @panic("recv error"); std.debug.print("Received: {s}", .{self.recv_buf[0..received]}); self.io.close( *Client, self, closeCallback, completion, self.sock, ); } fn closeCallback( self: *Client, completion: *IO.Completion, result: IO.CloseError!void, ) void { _ = result catch @panic("close error"); self.done = true; } }; pub fn main() anyerror!void { const allocator = std.heap.page_allocator; const address = try std.net.Address.parseIp4("127.0.0.1", 3131); var client = try Client.init(allocator, address); defer client.deinit(); try client.run(); }
examples/tcp_echo_client.zig
const std = @import("std"); const Allocator = std.mem.Allocator; pub const png = @cImport({ @cDefine("LODEPNG_NO_COMPILE_CPP", "1"); @cDefine("LODEPNG_COMPILE_ERROR_TEXT", "1"); // TODO remove libc dependency // @cDefine("LODEPNG_NO_COMPILE_DISK", "1"); // @cDefine("LODEPNG_NO_COMPILE_ALLOCATORS", "1"); @cInclude("lodepng.h"); }); const testing = std.testing; const log = std.log.scoped(.png); /// Control how many pixels are printed when formatting an image. pub const PRINT_PIXELS = 30; pub const Rgb24 = extern struct { r: u8, g: u8, b: u8 }; pub const Gray8 = u8; pub const Rgb_f32 = struct { r: f32, g: f32, b: f32, alpha: f32 = 1.0 }; // TODO enable all types pub const ColorType = enum(c_uint) { rgb24 = png.LCT_RGB, gray8 = png.LCT_GREY, }; pub fn PixelType(t: ColorType) type { return switch (t) { .rgb24 => Rgb24, .gray8 => Gray8, }; } pub fn grayscale(allocator: std.mem.Allocator, width: u32, height: u32) !Image { return Image.init(allocator, width, height, .gray8); } pub const Image = struct { width: u32, height: u32, px: union(ColorType) { rgb24: []Rgb24, gray8: []u8 }, allocator: Allocator, pub fn init(allocator: Allocator, width: u32, height: u32, color_type: ColorType) !Image { const n = @as(usize, width * height); return Image{ .width = width, .height = height, .allocator = allocator, .px = switch (color_type) { .rgb24 => .{ .rgb24 = try allocator.alloc(Rgb24, n) }, .gray8 => .{ .gray8 = try allocator.alloc(Gray8, n) }, }, }; } pub fn deinit(self: Image) void { self.allocator.free(self.raw()); } pub fn raw(self: Image) []u8 { return switch (self.px) { .rgb24 => |px| std.mem.sliceAsBytes(px), .gray8 => |px| std.mem.sliceAsBytes(px), }; } pub fn len(self: Image) usize { return self.width * self.height; } pub fn fromFilePath(allocator: Allocator, file_path: []const u8) !Image { var img: Image = undefined; // TODO: use lodepng_inspect to get the image size and handle allocations ourselves img.allocator = std.heap.c_allocator; var buffer: [*c]u8 = undefined; var resolved_path = try std.fs.path.resolve(allocator, &[_][]const u8{file_path}); defer allocator.free(resolved_path); var resolved_pathZ: []u8 = try allocator.dupeZ(u8, resolved_path); defer allocator.free(resolved_pathZ); // TODO: handle different color encoding try check(png.lodepng_decode24_file( &buffer, &img.width, &img.height, @ptrCast([*c]const u8, resolved_pathZ), )); std.debug.assert(buffer != null); img.px = .{ .rgb24 = @ptrCast([*]Rgb24, buffer.?)[0..img.len()] }; return img; } fn lodeBitDepth(self: Image) c_uint { _ = self; return 8; } pub fn writeToFilePath(self: Image, file_path: []const u8) !void { var resolved_path = try std.fs.path.resolve(testing.allocator, &[_][]const u8{file_path}); defer testing.allocator.free(resolved_path); var resolved_pathZ: []u8 = try testing.allocator.dupeZ(u8, resolved_path); defer testing.allocator.free(resolved_pathZ); // Write image data try check(png.lodepng_encode_file( @ptrCast([*c]const u8, resolved_pathZ), self.raw().ptr, @intCast(c_uint, self.width), @intCast(c_uint, self.height), @enumToInt(self.px), self.lodeBitDepth(), )); log.info("Wrote full image {s}", .{resolved_pathZ}); return; } // TODO: does it make sense to use f32 here ? shouldn't we stick with pub const Iterator = struct { image: Image, i: usize, fn u8_to_f32(value: u8) f32 { return @intToFloat(f32, value) / 255.0; } pub fn next(self: *Iterator) ?Rgb_f32 { if (self.i >= self.image.width * self.image.height) return null; const px_f32 = switch (self.image.px) { .rgb24 => |pixels| blk: { const px = pixels[self.i]; break :blk Rgb_f32{ .r = u8_to_f32(px.r), .g = u8_to_f32(px.g), .b = u8_to_f32(px.b) }; }, .gray8 => |pixels| blk: { const gray = u8_to_f32(pixels[self.i]); break :blk Rgb_f32{ .r = gray, .g = gray, .b = gray }; }, }; self.i += 1; return px_f32; } }; pub fn iterator(self: Image) Iterator { return .{ .image = self, .i = 0 }; } pub fn format( self: *const Image, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = fmt; _ = options; try std.fmt.format(writer, "Image ({s}){}x{}: (...{any}...)", .{ @tagName(self.px), self.width, self.height, self.raw()[200 .. 200 + PRINT_PIXELS] }); } }; pub fn check(err: c_uint) !void { if (err != 0) { log.err("Error {s}({})", .{ png.lodepng_error_text(err), err }); return error.PngError; } } pub fn img_eq(output: Image, reference: Image) bool { const same_dim = (output.width == reference.width) and (output.height == reference.height); if (!same_dim) return false; const same_len = output.raw().len == reference.raw().len; if (!same_len) return false; var i: usize = 0; while (i < output.raw().len) : (i += 1) { if (output.raw()[i] != reference.raw()[i]) return false; } return true; } test "read/write/read" { var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var base = try Image.fromFilePath(testing.allocator, "resources/hw1_resources/cinque_terre_small.png"); defer base.deinit(); try tmp.dir.writeFile("out.png", "hello"); var tmp_img = try tmp.dir.realpathAlloc(testing.allocator, "out.png"); log.warn("will write image ({}x{}) to {s}", .{ base.width, base.height, tmp_img }); defer testing.allocator.free(tmp_img); <<<<<<< HEAD <<<<<<< HEAD try base.writePngToFile(tmp_img); ======= try base.writeToFilePath(tmp_img); >>>>>>> bb5c855 (fixup! use lodepng instead of libpng / zigimg) ======= try base.writePngToFilePath(tmp_img); >>>>>>> c1e9b13 (move from zigimg to png.zig and lodepng) var loaded = try Image.fromFilePath(testing.allocator, tmp_img); defer loaded.deinit(); try testing.expectEqualSlices(u8, base.raw(), loaded.raw()); try testing.expect(img_eq(base, loaded)); }
CS344/src/png.zig
pub const c = @cImport({ @cInclude("SFML/System.h"); }); pub fn sleep(time: Time) void { c.sfSleep(time.internal); } pub const InputStream = struct { readFn: fn (*InputStream, []u8) anyerror!i64, seekFn: fn (*InputStream, i64) anyerror!i64, tellFn: fn (*InputStream) anyerror!i64, getSizeFn: fn (*InputStream) anyerror!i64, /// Creates an sfInputStream instance based on provided stream. **Important:** `stream` pointer is assumed to be /// valid as long as CSFML wants to use it. pub fn toCSFML(stream: *InputStream) c.sfInputStream { return .{ .read = inputStreamRead, .seek = inputStreamSeek, .tell = inputStreamTell, .getSize = inputStreamGetSize, .userData = stream, }; } fn inputStreamRead(data: *c_void, size: c.sfInt64, user_data: *c_void) callconv(.C) c.sfInt64 { const self = @ptrCast(*InputStream, user_data); return self.readFn(self, @ptrCast([*]u8, data)[0..size]) catch -1; } fn inputStreamSeek(position: c.sfInt64, user_data: *c_void) callconv(.C) c.sfInt64 { const self = @ptrCast(*InputStream, user_data); return self.seekFn(self, @intCast(i64, position)) catch -1; } fn inputStreamTell(user_data: *c_void) callconv(.C) c.sfInt64 { const self = @ptrCast(*InputStream, user_data); return self.tellFn(self) catch -1; } fn inputStreamGetSize(user_data: *c_void) callconv(.C) c.sfInt64 { const self = @ptrCast(*InputStream, user_data); return self.getSizeFn(self) catch -1; } }; pub const Mutex = struct { internal: *c.sfMutex, pub fn create() !Mutex { return Mutex{ .internal = c.sfMutex_create() orelse return error.SfmlError }; } pub fn destroy(self: *Mutex) void { c.sfMutex_destroy(self.internal); } pub fn lock(self: *Mutex) void { c.sfMutex_lock(self.internal); } pub fn unlock(self: *Mutex) void { c.sfMutex_unlock(self.internal); } }; pub const Thread = struct { internal: *c.sfThread, pub fn create(func: fn (?*c_void) callconv(.C) void, user_data: ?*c_void) !Thread { return Thread{ .internal = c.sfThread_create(func, user_data) orelse return error.SfmlError, }; } pub fn destroy(self: *Thread) void { c.sfThread_destroy(self.internal); } pub fn launch(self: *Thread) void { c.sfThread_launch(self.internal); } pub fn wait(self: *Thread) void { c.sfThread_wait(self.internal); } pub fn terminate(self: *Thread) void { c.sfThread_terminate(self.internal); } }; pub const Time = struct { pub fn zero() Time { return .{ .internal = c.sfTime_Zero }; } internal: c.sfTime, pub fn seconds(amount: f32) Time { return .{ .internal = c.sfSeconds(amount) }; } pub fn milliseconds(amount: i32) Time { return .{ .internal = c.sfMilliseconds(@intCast(c.sfInt32, amount)) }; } pub fn microseconds(amount: i64) Time { return .{ .internal = c.sfMicroseconds(@intCast(c.sfInt64, amount)) }; } pub fn asSeconds(time: Time) f32 { return @floatCast(f32, c.sfTime_asSeconds(time.internal)); } pub fn asMilliseconds(time: Time) i32 { return @intCast(i32, c.sfTime_asMilliseconds(time.internal)); } pub fn asMicroseconds(time: Time) i64 { return @intCast(i64, c.sfTime_asMicroseconds(time.internal)); } }; pub const Clock = struct { internal: *c.sfClock, pub fn create() !Clock { return Clock{ .internal = c.sfClock_create() orelse return error.SfmlError }; } pub fn destroy(self: *Clock) void { c.sfClock_destroy(self.internal); } pub fn copy(self: *const Clock) !Clock { return Clock{ .internal = c.sfClock_copy(self.internal) orelse return error.SfmlError }; } pub fn getElapsedTime(self: *const Clock) Time { return .{ .internal = c.sfClock_getElapsedTime(self.internal) }; } pub fn restart(self: *Clock) Time { return .{ .internal = c.sfClock_restart(self.internal) }; } }; pub const Vector2i = c.sfVector2i; pub const Vector2u = c.sfVector2u; pub const Vector2f = c.sfVector2f;
src/system.zig
const std = @import("std"); const trait = std.meta.trait; pub const api = @import("api.zig"); pub const build_util = @import("build_util.zig"); pub const hot_reload = @import("hot_reload.zig"); pub const audio_io = @import("audio_io.zig"); pub const helper = @import("helper.zig"); pub const Info = struct { /// The unique ID of the VST Plugin id: i32, /// The version of the VST Plugin version: [4]u8, /// The name of the VST Plugin name: []const u8 = "", /// The vendor of the VST Plugin vendor: []const u8 = "", /// The amount of audio outputs /// The initial delay in samples until the plugin produces output. delay: usize = 0, flags: []const api.Plugin.Flag, category: api.Plugin.Category = .Unknown, /// The layout of the input buffers this plugin accepts. input: audio_io.IOLayout, /// The layout of the output buffers this plugin accepts. output: audio_io.IOLayout, fn versionToI32(self: Info) i32 { const v = self.version; return (@as(i32, v[0]) << 24) | (@as(i32, v[1]) << 16) | (@as(i32, v[2]) << 8) | @as(i32, v[3]); } }; pub const EmbedInfo = struct { effect: api.AEffect, host_callback: api.HostCallback, // TODO I'm not happy with this yet. It feels kinda clunky. custom_ref: ?*c_void = null, pub fn query( self: *EmbedInfo, code: api.Codes.PluginToHost, index: i32, value: isize, ptr: ?*c_void, opt: f32, ) isize { return self.queryRaw(code.toInt(), index, value, ptr, opt); } pub fn queryRaw( self: *EmbedInfo, opcode: i32, index: i32, value: isize, ptr: ?*c_void, opt: f32, ) isize { return self.host_callback(&self.effect, opcode, index, value, ptr, opt); } fn setCustomRef(self: *EmbedInfo, ptr: anytype) void { self.custom_ref = @ptrCast(*c_void, ptr); } fn clearCustomRef(self: *EmbedInfo) void { self.custom_ref = null; } fn getCustomRef(self: *EmbedInfo, comptime T: type) ?*T { if (self.custom_ref) |ptr| { return @ptrCast(*T, @alignCast(@alignOf(T), ptr)); } return null; } }; pub fn VstPlugin(comptime info_arg: Info, comptime T: type) type { return struct { pub const Inner = T; pub const info = info_arg; const Self = @This(); var log_allocator = std.heap.page_allocator; var external_write_log: ?hot_reload.HotReloadLog = null; inner: T, allocator: *std.mem.Allocator, /// TODO Remove the dummy argument once https://github.com/ziglang/zig/issues/5380 /// gets fixed pub fn generateExports(comptime dummy: void) void { comptime std.debug.assert(@TypeOf(VSTPluginMain) == api.PluginMain); @export(VSTPluginMain, .{ .name = "VSTPluginMain", .linkage = .Strong, }); comptime std.debug.assert(@TypeOf(VSTHotReloadInit) == hot_reload.HotReloadInit); @export(VSTHotReloadInit, .{ .name = "VSTHotReloadInit", .linkage = .Strong, }); comptime std.debug.assert(@TypeOf(VSTHotReloadDeinit) == hot_reload.HotReloadDeinit); @export(VSTHotReloadDeinit, .{ .name = "VSTHotReloadDeinit", .linkage = .Strong, }); comptime std.debug.assert(@TypeOf(VSTHotReloadUpdate) == hot_reload.HotReloadUpdate); @export(VSTHotReloadUpdate, .{ .name = "VSTHotReloadUpdate", .linkage = .Strong, }); } /// This will set up a log handler, which you should probably do /// when you make use of hot reloads. pub fn generateTopLevelHandlers() type { // TODO How do we handle logging in standalone mode? return struct { pub fn log( comptime level: std.log.Level, comptime scope: @TypeOf(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { if (external_write_log) |log_fn| { const data = std.fmt.allocPrint(log_allocator, format, args) catch return; defer log_allocator.free(data); log_fn(data.ptr, data.len); } } }; } fn VSTHotReloadInit(embed_info: *EmbedInfo, log_fn: hot_reload.HotReloadLog) callconv(.Cold) bool { external_write_log = log_fn; embed_info.effect = initAEffect(); var self = init(std.heap.page_allocator, embed_info) catch return false; return true; } fn VSTHotReloadDeinit(embed_info: *EmbedInfo) callconv(.Cold) void { var self = embed_info.getCustomRef(Self) orelse return; self.deinit(); } fn VSTHotReloadUpdate(embed_info: *EmbedInfo, log_fn: hot_reload.HotReloadLog) callconv(.Cold) bool { external_write_log = log_fn; const old_effect = embed_info.*.effect; embed_info.effect = initAEffect(); var self = init(std.heap.page_allocator, embed_info) catch return false; // TODO Find out which properties can be updated. Especially, what // about num_params? Since the hot reload feature is only // intended for development we might be able to get away with // pre-defining a huge amount of parameters and just have // the majority of them be unused and labelled as such. // If that works: Are we able to tell the host to reload the // parameters? If I add a new one I want its name to show up // in the DAW. const new_effect = embed_info.effect; if (old_effect.version != new_effect.version) { std.log.warn(.zig_vst, "You can't change the plugin version between hot reloads\n", .{}); } if (old_effect.flags != new_effect.flags) { std.log.warn(.zig_vst, "You can't change the plugin flags between hot reloads\n", .{}); } if (old_effect.unique_id != new_effect.unique_id) { std.log.warn(.zig_vst, "You can't change the plugin unique_id between hot reloads\n", .{}); } if (old_effect.initial_delay != new_effect.initial_delay) { std.log.warn(.zig_vst, "You can't change the plugin initial_delay between hot reloads\n", .{}); } if (old_effect.num_inputs != new_effect.num_inputs or old_effect.num_outputs != new_effect.num_outputs) { // TODO Find out if this works _ = embed_info.query(.IOChanged, 0, 0, null, 0); } return true; } fn VSTPluginMain(callback: api.HostCallback) callconv(.C) ?*api.AEffect { var allocator = std.heap.page_allocator; // TODO Maybe the VSTPluginMain should not initialize the inner // value. Otherwise it always gets called, even when the // VST host is just reading basic information. var embed_info = allocator.create(EmbedInfo) catch return null; embed_info.host_callback = callback; embed_info.effect = initAEffect(); var self = init(allocator, embed_info) catch return null; return &embed_info.effect; } fn initAEffect() api.AEffect { return .{ .dispatcher = dispatcherCallback, .setParameter = setParameterCallback, .getParameter = getParameterCallback, .processReplacing = processReplacingCallback, .processReplacingF64 = processReplacingCallbackF64, .num_programs = 0, .num_params = 0, .num_inputs = info.input.len, .num_outputs = info.output.len, .flags = api.Plugin.Flag.toBitmask(info.flags), .initial_delay = info.delay, .unique_id = info.id, .version = info.versionToI32(), }; } fn init(allocator: *std.mem.Allocator, embed_info: *EmbedInfo) !*Self { var self = try allocator.create(Self); embed_info.setCustomRef(self); self.allocator = allocator; var effect = &embed_info.effect; effect.dispatcher = dispatcherCallback; effect.setParameter = setParameterCallback; effect.getParameter = getParameterCallback; effect.processReplacing = processReplacingCallback; effect.processReplacingF64 = processReplacingCallbackF64; const type_info = @typeInfo(@TypeOf(T.create)).Fn; const returns_error = comptime trait.is(.ErrorUnion)(type_info.return_type.?); const takes_allocator = comptime blk_takes_allocator: { const args = type_info.args; break :blk_takes_allocator args.len == 2 and args[1].arg_type == *std.mem.Allocator; }; if (!takes_allocator and !returns_error) { T.create(&self.inner); } else if (takes_allocator and !returns_error) { T.create(&self.inner, allocator); } else if (!takes_allocator and returns_error) { try T.create(&self.inner); } else if (takes_allocator and returns_error) { try T.create(&self.inner, allocator); } return self; } fn deinit(self: *Self) void { if (comptime trait.hasFn("deinit")(T)) { T.deinit(&self.inner); } self.allocator.destroy(self); } fn fromEffectPtr(effect: *api.AEffect) ?*Self { const embed_info = @fieldParentPtr(EmbedInfo, "effect", effect); return embed_info.getCustomRef(Self); } fn dispatcherCallback(effect: *api.AEffect, opcode: i32, index: i32, value: isize, ptr: ?*c_void, opt: f32) callconv(.C) isize { const self = fromEffectPtr(effect) orelse unreachable; const code = api.Codes.HostToPlugin.fromInt(opcode) catch return -1; switch (code) { .Initialize => {}, .Shutdown => self.deinit(), .GetProductName => setData(ptr.?, info.name, api.ProductNameMaxLength), .GetVendorName => setData(ptr.?, info.vendor, api.VendorNameMaxLength), .GetCategory => return info.category.toI32(), .GetApiVersion => return 2400, .GetTailSize => return 0, .SetSampleRate => {}, .SetBufferSize => {}, .StateChange => {}, .GetInputInfo => { std.log.debug(.zig_vst, "GetInputInfo\n", .{}); }, .GetOutputInfo => { std.log.debug(.zig_vst, "GetOutputInfo\n", .{}); }, else => {}, } return 0; } fn setParameterCallback(effect: *api.AEffect, index: i32, parameter: f32) callconv(.C) void {} fn getParameterCallback(effect: *api.AEffect, index: i32) callconv(.C) f32 { return 0; } fn processReplacingCallback(effect: *api.AEffect, inputs: [*][*]f32, outputs: [*][*]f32, sample_frames: i32) callconv(.C) void { const frames = @intCast(usize, sample_frames); var input = audio_io.AudioBuffer(info.input, f32).fromRaw(inputs, sample_frames); var output = audio_io.AudioBuffer(info.output, f32).fromRaw(outputs, sample_frames); const self = fromEffectPtr(effect) orelse return; self.inner.process(&input, &output); } fn processReplacingCallbackF64(effect: *api.AEffect, inputs: [*][*]f64, outputs: [*][*]f64, sample_frames: i32) callconv(.C) void {} }; } /// Copy data to the given location. The max_length parameter should include 1 /// byte for a null character. So if you pass a max_length of 64 a maximum of /// 63 bytes will be copied from the data. /// The indices from data.len until max_length will be filled with zeroes. fn setData(ptr: *c_void, data: []const u8, max_length: usize) void { const buf_ptr = @ptrCast([*]u8, ptr); const copy_len = std.math.min(max_length - 1, data.len); @memcpy(buf_ptr, data.ptr, copy_len); std.mem.set(u8, buf_ptr[copy_len..max_length], 0); } test "setData" { var raw_data = [_]u8{0xaa} ** 20; var c_ptr = @ptrCast(*c_void, &raw_data); setData(c_ptr, "Hello World!", 15); const correct = "Hello World!" ++ [_]u8{0} ** 3 ++ [_]u8{0xaa} ** 5; std.testing.expect(std.mem.eql(u8, &raw_data, correct)); std.mem.set(u8, &raw_data, 0xaa); setData(c_ptr, "This is a very long string. Too long, in fact!", 20); const correct2 = "This is a very long" ++ [_]u8{0}; std.testing.expectEqual(20, correct2.len); std.testing.expect(std.mem.eql(u8, &raw_data, correct2)); }
src/main.zig
const rl = @import("raylib"); const rlm = @import("raylib-math"); const MAX_BUILDINGS = 100; pub fn main() anyerror!void { // Initialization //-------------------------------------------------------------------------------------- const screenWidth = 800; const screenHeight = 450; rl.InitWindow(screenWidth, screenHeight, "raylib-zig [core] example - 2d camera"); var player = rl.Rectangle { .x = 400, .y = 280, .width = 40, .height = 40 }; var buildings: [MAX_BUILDINGS]rl.Rectangle = undefined; var buildColors: [MAX_BUILDINGS]rl.Color = undefined; var spacing: i32 = 0; for (buildings) |_, i| { buildings[i].width = @intToFloat(f32, rl.GetRandomValue(50, 200)); buildings[i].height = @intToFloat(f32, rl.GetRandomValue(100, 800)); buildings[i].y = screenHeight - 130 - buildings[i].height; buildings[i].x = @intToFloat(f32, -6000 + spacing); spacing += @floatToInt(i32, buildings[i].width); buildColors[i] = rl.Color { .r = @intCast(u8, rl.GetRandomValue(200, 240)), .g = @intCast(u8, rl.GetRandomValue(200, 240)), .b = @intCast(u8, rl.GetRandomValue(200, 250)), .a = 255 }; } var camera = rl.Camera2D { .target = rl.Vector2 { .x = player.x + 20, .y = player.y + 20 }, .offset = rl.Vector2 { .x = screenWidth/2, .y = screenHeight/2 }, .rotation = 0, .zoom = 1, }; rl.SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop while (!rl.WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- // Player movement if (rl.IsKeyDown(rl.KeyboardKey.KEY_RIGHT)) { player.x += 2; } else if (rl.IsKeyDown(rl.KeyboardKey.KEY_LEFT)) { player.x -= 2; } // Camera target follows player camera.target = rl.Vector2 { .x = player.x + 20, .y = player.y + 20 }; // Camera rotation controls if (rl.IsKeyDown(rl.KeyboardKey.KEY_A)) { camera.rotation -= 1; } else if (rl.IsKeyDown(rl.KeyboardKey.KEY_S)) { camera.rotation += 1; } // Limit camera rotation to 80 degrees (-40 to 40) camera.rotation = rlm.Clamp(camera.rotation, -40, 40); // Camera zoom controls camera.zoom += rl.GetMouseWheelMove() * 0.05; camera.zoom = rlm.Clamp(camera.zoom, 0.1, 3.0); // Camera reset (zoom and rotation) if (rl.IsKeyPressed(rl.KeyboardKey.KEY_R)) { camera.zoom = 1.0; camera.rotation = 0.0; } //---------------------------------------------------------------------------------- // Draw //---------------------------------------------------------------------------------- rl.BeginDrawing(); rl.ClearBackground(rl.RAYWHITE); camera.Begin(); rl.DrawRectangle(-6000, 320, 13000, 8000, rl.DARKGRAY); for (buildings) |building, i| { rl.DrawRectangleRec(building, buildColors[i]); } rl.DrawRectangleRec(player, rl.RED); rl.DrawLine(@floatToInt(c_int, camera.target.x), -screenHeight*10, @floatToInt(c_int, camera.target.x), screenHeight*10, rl.GREEN); rl.DrawLine(-screenWidth*10, @floatToInt(c_int, camera.target.y), screenWidth*10, @floatToInt(c_int, camera.target.y), rl.GREEN); camera.End(); rl.DrawText("SCREEN AREA", 640, 10, 20, rl.RED); rl.DrawRectangle(0, 0, screenWidth, 5, rl.RED); rl.DrawRectangle(0, 5, 5, screenHeight - 10, rl.RED); rl.DrawRectangle(screenWidth - 5, 5, 5, screenHeight - 10, rl.RED); rl.DrawRectangle(0, screenHeight - 5, screenWidth, 5, rl.RED); rl.DrawRectangle( 10, 10, 250, 113, rl.Fade(rl.SKYBLUE, 0.5)); rl.DrawRectangleLines( 10, 10, 250, 113, rl.BLUE); rl.DrawText("Free 2d camera controls:", 20, 20, 10, rl.BLACK); rl.DrawText("- Right/Left to move Offset", 40, 40, 10, rl.DARKGRAY); rl.DrawText("- Mouse Wheel to Zoom in-out", 40, 60, 10, rl.DARKGRAY); rl.DrawText("- A / S to Rotate", 40, 80, 10, rl.DARKGRAY); rl.DrawText("- R to reset Zoom and Rotation", 40, 100, 10, rl.DARKGRAY); rl.EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization //-------------------------------------------------------------------------------------- rl.CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- }
examples/core/2d_camera.zig
const std = @import("std"); const utils = @import("utils.zig"); const vector = @import("vector.zig"); const Vec4 = vector.Vec4; const Mat4 = @import("matrix.zig").Mat4; const Shape = @import("shape.zig").Shape; const initPoint = vector.initPoint; const initVector = vector.initVector; pub const Ray = struct { const Self = @This(); origin: Vec4, direction: Vec4, pub fn init(origin: Vec4, direction: Vec4) Self { return Self{ .origin = origin, .direction = direction, }; } pub fn position(self: Self, t: f64) Vec4 { return self.origin.add(self.direction.scale(t)); } pub fn transform(self: Self, mat: Mat4) Self { return Self{ .origin = mat.multVec(self.origin), .direction = mat.multVec(self.direction), }; } }; test "creating and querying a ray" { const origin = initPoint(1, 2, 3); const direction = initVector(4, 5, 6); const r = Ray.init(origin, direction); try std.testing.expect(r.origin.eql(origin)); try std.testing.expect(r.direction.eql(direction)); } test "computing a point from a distance" { const r = Ray.init(initPoint(2, 3, 4), initVector(1, 0, 0)); try std.testing.expect(r.position(0).eql(initPoint(2, 3, 4))); try std.testing.expect(r.position(1).eql(initPoint(3, 3, 4))); try std.testing.expect(r.position(-1).eql(initPoint(1, 3, 4))); try std.testing.expect(r.position(2.5).eql(initPoint(4.5, 3, 4))); } pub const Intersection = struct { t: f64, object: Shape, }; pub const Intersections = struct { const Self = @This(); allocator: std.mem.Allocator, list: std.ArrayList(Intersection), pub fn init(allocator: std.mem.Allocator) Self { return .{ .allocator = allocator, .list = std.ArrayList(Intersection).init(allocator), }; } pub fn hit(self: Self) ?Intersection { std.sort.sort(Intersection, self.list.items, {}, lessThanIntersection); const first_hit = for (self.list.items) |intersection| { if (intersection.t >= 0) break intersection; } else null; return first_hit; } pub fn deinit(self: *Self) void { self.list.deinit(); } pub fn lessThanIntersection(context: void, a: Intersection, b: Intersection) bool { _ = context; return a.t < b.t; } }; const alloc = std.testing.allocator; test "The hit, when all intersections have positive t" { const s = Shape{ .geo = .{ .sphere = .{} } }; var xs = Intersections.init(alloc); defer xs.deinit(); const is1 = Intersection{ .t = 1, .object = s }; try xs.list.append(is1); const is2 = Intersection{ .t = 2, .object = s }; try xs.list.append(is2); try std.testing.expectEqual(is1, xs.hit().?); } test "The hit, when some intersections have negative t" { const s = Shape{ .geo = .{ .sphere = .{} } }; var xs = Intersections.init(alloc); defer xs.deinit(); const is1 = Intersection{ .t = -1, .object = s }; try xs.list.append(is1); const is2 = Intersection{ .t = 1, .object = s }; try xs.list.append(is2); try std.testing.expectEqual(is2, xs.hit().?); } test "The hit, when all intersections have negative t" { const s = Shape{ .geo = .{ .sphere = .{} } }; var xs = Intersections.init(alloc); defer xs.deinit(); const is1 = Intersection{ .t = -2, .object = s }; try xs.list.append(is1); const is2 = Intersection{ .t = -1, .object = s }; try xs.list.append(is2); try std.testing.expect(xs.hit() == null); } test "The hit is always the lowest nonnegative intersection" { const s = Shape{ .geo = .{ .sphere = .{} } }; var xs = Intersections.init(alloc); defer xs.deinit(); const is1 = Intersection{ .t = 5, .object = s }; try xs.list.append(is1); const is2 = Intersection{ .t = 7, .object = s }; try xs.list.append(is2); const is3 = Intersection{ .t = -3, .object = s }; try xs.list.append(is3); const is4 = Intersection{ .t = 2, .object = s }; try xs.list.append(is4); try std.testing.expectEqual(is4, xs.hit().?); } test "Translating a ray" { const r = Ray.init(initPoint(1, 2, 3), initVector(0, 1, 0)); const m = Mat4.identity().translate(3, 4, 5); const r2 = r.transform(m); try std.testing.expect(r2.origin.eql(initPoint(4, 6, 8))); try std.testing.expect(r2.direction.eql(initVector(0, 1, 0))); } test "Scaling a ray" { const r = Ray.init(initPoint(1, 2, 3), initVector(0, 1, 0)); const m = Mat4.identity().scale(2, 3, 4); const r2 = r.transform(m); try std.testing.expect(r2.origin.eql(initPoint(2, 6, 12))); try std.testing.expect(r2.direction.eql(initVector(0, 3, 0))); }
ray.zig
const std = @import("std"); const builtin = @import("builtin"); const CrossTarget = std.zig.CrossTarget; pub fn build(b: *std.build.Builder) !void { b.setPreferredReleaseMode(.ReleaseFast); const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const lib_only: bool = b.option(bool, "lib-only", "Only compile the library") orelse false; const skip_lib: bool = b.option(bool, "skip-lib", "Skip compiling the library") orelse false; const wasm: bool = b.option(bool, "wasm", "Compile the wasm library") orelse false; const vendored_pcre: bool = b.option(bool, "vendored-pcre", "Use vendored pcre (for non-Windows platforms)") orelse true; // Compile pcre const pcre = b.addStaticLibrary("pcre", null); pcre.setTarget(target); pcre.linkLibC(); pcre.addIncludeDir(pcreIncludeDir); pcre.addCSourceFiles(&pcreSources, &buildOptions); // Main build step if (!lib_only and !wasm) { const fastfec_cli = b.addExecutable("fastfec", null); fastfec_cli.setTarget(target); fastfec_cli.setBuildMode(mode); fastfec_cli.install(); // Add curl fastfec_cli.linkLibC(); if (builtin.os.tag == .windows) { fastfec_cli.linkSystemLibrary("ws2_32"); fastfec_cli.linkSystemLibrary("advapi32"); fastfec_cli.linkSystemLibrary("crypt32"); fastfec_cli.linkSystemLibrary("libcurl"); fastfec_cli.linkSystemLibraryName("zlib"); fastfec_cli.linkSystemLibrary("pcre"); } else { fastfec_cli.linkSystemLibrary("curl"); if (vendored_pcre) { fastfec_cli.addIncludeDir(pcreIncludeDir); fastfec_cli.linkLibrary(pcre); } else { fastfec_cli.linkSystemLibrary("libpcre"); } } fastfec_cli.addCSourceFiles(&libSources, &buildOptions); fastfec_cli.addCSourceFiles(&.{ "src/urlopen.c", "src/main.c", }, &buildOptions); } if (!wasm and !skip_lib) { // Library build step const fastfec_lib = b.addSharedLibrary("fastfec", null, .unversioned); fastfec_lib.setTarget(target); fastfec_lib.setBuildMode(mode); fastfec_lib.install(); fastfec_lib.linkLibC(); if (builtin.os.tag == .windows) { fastfec_lib.linkSystemLibrary("pcre"); } else { if (vendored_pcre) { fastfec_lib.addIncludeDir(pcreIncludeDir); fastfec_lib.linkLibrary(pcre); } else { fastfec_lib.linkSystemLibrary("libpcre"); } } fastfec_lib.addCSourceFiles(&libSources, &buildOptions); } else if (wasm) { // Wasm library build step const fastfec_wasm = b.addSharedLibrary("fastfec", null, .unversioned); const wasm_target = CrossTarget{ .cpu_arch = .wasm32, .os_tag = .wasi }; fastfec_wasm.setTarget(wasm_target); // Update pcre target for wasm pcre.setTarget(wasm_target); fastfec_wasm.setBuildMode(mode); fastfec_wasm.install(); fastfec_wasm.linkLibC(); if (vendored_pcre) { fastfec_wasm.addIncludeDir(pcreIncludeDir); fastfec_wasm.linkLibrary(pcre); } else { fastfec_wasm.linkSystemLibrary("libpcre"); } fastfec_wasm.addCSourceFiles(&libSources, &buildOptions); fastfec_wasm.addCSourceFile("src/wasm.c", &buildOptions); } // Test step var prev_test_step: ?*std.build.Step = null; for (tests) |test_file| { const base_file = std.fs.path.basename(test_file); const subtest_exe = b.addExecutable(base_file, null); subtest_exe.linkLibC(); subtest_exe.addCSourceFiles(&testIncludes, &buildOptions); subtest_exe.addCSourceFile(test_file, &buildOptions); // Link PCRE if (builtin.os.tag == .windows) { subtest_exe.linkSystemLibrary("pcre"); } else { if (vendored_pcre) { subtest_exe.addIncludeDir(pcreIncludeDir); subtest_exe.linkLibrary(pcre); } else { subtest_exe.linkSystemLibrary("libpcre"); } } const subtest_cmd = subtest_exe.run(); if (prev_test_step != null) { subtest_cmd.step.dependOn(prev_test_step.?); } prev_test_step = &subtest_cmd.step; } const test_steps = prev_test_step.?; const test_step = b.step("test", "Run unit tests"); test_step.dependOn(test_steps); } const libSources = [_][]const u8{ "src/buffer.c", "src/memory.c", "src/encoding.c", "src/csv.c", "src/writer.c", "src/fec.c", }; const pcreSources = [_][]const u8{ "deps/pcre/pcre_chartables.c", "deps/pcre/pcre_byte_order.c", "deps/pcre/pcre_compile.c", "deps/pcre/pcre_config.c", "deps/pcre/pcre_dfa_exec.c", "deps/pcre/pcre_exec.c", "deps/pcre/pcre_fullinfo.c", "deps/pcre/pcre_get.c", "deps/pcre/pcre_globals.c", "deps/pcre/pcre_jit_compile.c", "deps/pcre/pcre_maketables.c", "deps/pcre/pcre_newline.c", "deps/pcre/pcre_ord2utf8.c", "deps/pcre/pcre_refcount.c", "deps/pcre/pcre_string_utils.c", "deps/pcre/pcre_study.c", "deps/pcre/pcre_tables.c", "deps/pcre/pcre_ucd.c", "deps/pcre/pcre_valid_utf8.c", "deps/pcre/pcre_version.c", "deps/pcre/pcre_xclass.c", }; const pcreIncludeDir = "deps/pcre"; const tests = [_][]const u8{ "src/buffer_test.c", "src/csv_test.c", "src/writer_test.c" }; const testIncludes = [_][]const u8{ "src/buffer.c", "src/memory.c", "src/encoding.c", "src/csv.c", "src/writer.c", }; const buildOptions = [_][]const u8{ "-std=c11", "-pedantic", "-Wall", "-W", "-Wno-missing-field-initializers", };
build.zig
const std = @import("std"); const Surface = @import("Surface.zig"); const Adapter = @import("Adapter.zig"); const PowerPreference = @import("enums.zig").PowerPreference; const Interface = @This(); /// The type erased pointer to the Interface implementation ptr: *anyopaque, vtable: *const VTable, pub const VTable = struct { reference: fn (ptr: *anyopaque) void, release: fn (ptr: *anyopaque) void, requestAdapter: fn requestAdapter( ptr: *anyopaque, options: *const RequestAdapterOptions, callback: *RequestAdapterCallback, ) void, }; pub inline fn reference(interface: Interface) void { interface.vtable.reference(interface.ptr); } pub inline fn release(interface: Interface) void { interface.vtable.release(interface.ptr); } pub const RequestAdapterOptions = struct { power_preference: PowerPreference, force_fallback_adapter: bool = false, /// Only respected by native WebGPU implementations. compatible_surface: ?Surface = null, }; pub const RequestAdapterErrorCode = error{ Unavailable, Error, Unknown, }; pub const RequestAdapterError = struct { message: []const u8, code: RequestAdapterErrorCode, }; pub const RequestAdapterResponseTag = enum { adapter, err, }; pub const RequestAdapterResponse = union(RequestAdapterResponseTag) { adapter: Adapter, err: RequestAdapterError, }; pub fn requestAdapter( interface: Interface, options: *const RequestAdapterOptions, callback: *RequestAdapterCallback, ) void { interface.vtable.requestAdapter(interface.ptr, options, callback); } pub const RequestAdapterCallback = struct { type_erased_ctx: *anyopaque, type_erased_callback: fn (ctx: *anyopaque, response: RequestAdapterResponse) callconv(.Inline) void, pub fn init( comptime Context: type, ctx: Context, comptime callback: fn (ctx: Context, response: RequestAdapterResponse) void, ) RequestAdapterCallback { const erased = (struct { pub inline fn erased(type_erased_ctx: *anyopaque, response: RequestAdapterResponse) void { callback(if (Context == void) {} else @ptrCast(Context, @alignCast(std.meta.alignment(Context), type_erased_ctx)), response); } }).erased; return .{ .type_erased_ctx = if (Context == void) undefined else ctx, .type_erased_callback = erased, }; } }; /// A helper which invokes requestAdapter and blocks until the adapter is recieved. pub fn waitForAdapter(interface: Interface, options: *const RequestAdapterOptions) RequestAdapterResponse { var response: RequestAdapterResponse = undefined; var callback = RequestAdapterCallback.init(*RequestAdapterResponse, &response, (struct { pub fn callback(ctx: *RequestAdapterResponse, callback_response: RequestAdapterResponse) void { ctx.* = callback_response; } }).callback); interface.requestAdapter(options, &callback); // TODO: FUTURE: Once crbug.com/dawn/1122 is fixed, we should process events here otherwise our // callback would not be invoked: //c.wgpuInstanceProcessEvents(interface.instance) return response; } test { _ = VTable; _ = reference; _ = release; _ = RequestAdapterOptions; _ = RequestAdapterErrorCode; _ = RequestAdapterError; _ = RequestAdapterResponse; _ = requestAdapter; _ = waitForAdapter; }
gpu/src/Interface.zig
const std = @import("std"); const builtin = @import("builtin"); const mem = std.mem; const meta = std.meta; /// Provides generic hashing for any eligible type. /// Only hashes `key` itself, pointers are not followed. pub fn autoHash(hasher: var, key: var) void { const Key = @typeOf(key); switch (@typeInfo(Key)) { .NoReturn, .Opaque, .Undefined, .ArgTuple, .Void, .Null, .BoundFn, .ComptimeFloat, .ComptimeInt, .Type, .EnumLiteral, .Frame, => @compileError("cannot hash this type"), // Help the optimizer see that hashing an int is easy by inlining! // TODO Check if the situation is better after #561 is resolved. .Int => @inlineCall(hasher.update, std.mem.asBytes(&key)), .Float => |info| autoHash(hasher, @bitCast(@IntType(false, info.bits), key)), .Bool => autoHash(hasher, @boolToInt(key)), .Enum => autoHash(hasher, @enumToInt(key)), .ErrorSet => autoHash(hasher, @errorToInt(key)), .AnyFrame, .Fn => autoHash(hasher, @ptrToInt(key)), .Pointer => |info| switch (info.size) { builtin.TypeInfo.Pointer.Size.One, builtin.TypeInfo.Pointer.Size.Many, builtin.TypeInfo.Pointer.Size.C, => autoHash(hasher, @ptrToInt(key)), builtin.TypeInfo.Pointer.Size.Slice => { autoHash(hasher, key.ptr); autoHash(hasher, key.len); }, }, .Optional => if (key) |k| autoHash(hasher, k), .Array => { // TODO detect via a trait when Key has no padding bits to // hash it as an array of bytes. // Otherwise, hash every element. for (key) |element| { autoHash(hasher, element); } }, .Vector => |info| { if (info.child.bit_count % 8 == 0) { // If there's no unused bits in the child type, we can just hash // this as an array of bytes. hasher.update(mem.asBytes(&key)); } else { // Otherwise, hash every element. // TODO remove the copy to an array once field access is done. const array: [info.len]info.child = key; comptime var i: u32 = 0; inline while (i < info.len) : (i += 1) { autoHash(hasher, array[i]); } } }, .Struct => |info| { // TODO detect via a trait when Key has no padding bits to // hash it as an array of bytes. // Otherwise, hash every field. inline for (info.fields) |field| { // We reuse the hash of the previous field as the seed for the // next one so that they're dependant. autoHash(hasher, @field(key, field.name)); } }, .Union => |info| blk: { if (info.tag_type) |tag_type| { const tag = meta.activeTag(key); const s = autoHash(hasher, tag); inline for (info.fields) |field| { const enum_field = field.enum_field.?; if (enum_field.value == @enumToInt(tag)) { autoHash(hasher, @field(key, enum_field.name)); // TODO use a labelled break when it does not crash the compiler. // break :blk; return; } } unreachable; } else @compileError("cannot hash untagged union type: " ++ @typeName(Key) ++ ", provide your own hash function"); }, .ErrorUnion => blk: { const payload = key catch |err| { autoHash(hasher, err); break :blk; }; autoHash(hasher, payload); }, } } const testing = std.testing; const Wyhash = std.hash.Wyhash; fn testAutoHash(key: var) u64 { // Any hash could be used here, for testing autoHash. var hasher = Wyhash.init(0); autoHash(&hasher, key); return hasher.final(); } test "autoHash slice" { // Allocate one array dynamically so that we're assured it is not merged // with the other by the optimization passes. const array1 = try std.heap.direct_allocator.create([6]u32); defer std.heap.direct_allocator.destroy(array1); array1.* = [_]u32{ 1, 2, 3, 4, 5, 6 }; const array2 = [_]u32{ 1, 2, 3, 4, 5, 6 }; const a = array1[0..]; const b = array2[0..]; const c = array1[0..3]; testing.expect(testAutoHash(a) == testAutoHash(a)); testing.expect(testAutoHash(a) != testAutoHash(array1)); testing.expect(testAutoHash(a) != testAutoHash(b)); testing.expect(testAutoHash(a) != testAutoHash(c)); } test "testAutoHash optional" { const a: ?u32 = 123; const b: ?u32 = null; testing.expectEqual(testAutoHash(a), testAutoHash(u32(123))); testing.expect(testAutoHash(a) != testAutoHash(b)); testing.expectEqual(testAutoHash(b), 0); } test "testAutoHash array" { const a = [_]u32{ 1, 2, 3 }; const h = testAutoHash(a); var hasher = Wyhash.init(0); autoHash(&hasher, u32(1)); autoHash(&hasher, u32(2)); autoHash(&hasher, u32(3)); testing.expectEqual(h, hasher.final()); } test "testAutoHash struct" { const Foo = struct { a: u32 = 1, b: u32 = 2, c: u32 = 3, }; const f = Foo{}; const h = testAutoHash(f); var hasher = Wyhash.init(0); autoHash(&hasher, u32(1)); autoHash(&hasher, u32(2)); autoHash(&hasher, u32(3)); testing.expectEqual(h, hasher.final()); } test "testAutoHash union" { const Foo = union(enum) { A: u32, B: f32, C: u32, }; const a = Foo{ .A = 18 }; var b = Foo{ .B = 12.34 }; const c = Foo{ .C = 18 }; testing.expect(testAutoHash(a) == testAutoHash(a)); testing.expect(testAutoHash(a) != testAutoHash(b)); testing.expect(testAutoHash(a) != testAutoHash(c)); b = Foo{ .A = 18 }; testing.expect(testAutoHash(a) == testAutoHash(b)); } test "testAutoHash vector" { const a: @Vector(4, u32) = [_]u32{ 1, 2, 3, 4 }; const b: @Vector(4, u32) = [_]u32{ 1, 2, 3, 5 }; const c: @Vector(4, u31) = [_]u31{ 1, 2, 3, 4 }; testing.expect(testAutoHash(a) == testAutoHash(a)); testing.expect(testAutoHash(a) != testAutoHash(b)); testing.expect(testAutoHash(a) != testAutoHash(c)); } test "testAutoHash error union" { const Errors = error{Test}; const Foo = struct { a: u32 = 1, b: u32 = 2, c: u32 = 3, }; const f = Foo{}; const g: Errors!Foo = Errors.Test; testing.expect(testAutoHash(f) != testAutoHash(g)); testing.expect(testAutoHash(f) == testAutoHash(Foo{})); testing.expect(testAutoHash(g) == testAutoHash(Errors.Test)); }
std/hash/auto_hash.zig
const std = @import("std"); const utils = @import("utils"); const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const print = utils.print; const Values = struct { all_digits: [10]u8, output: [4]u8, }; fn readInput(arena: *ArenaAllocator, lines_it: *utils.FileLineIterator) anyerror![]Values { var values = try std.ArrayList(Values).initCapacity(&arena.allocator, 4096); while (lines_it.next()) |line| { var signals = std.mem.tokenize(u8, line, " |"); var v: Values = undefined; for (v.all_digits) |*digit| { digit.* = parseSignals(signals.next().?); } for (v.output) |*digit| { digit.* = parseSignals(signals.next().?); } try values.append(v); } print("File ok :) Number of inputs: {d}", .{values.items.len}); return values.items; } fn parseSignals(signals: []const u8) u8 { var res: u8 = 0; for (signals) |signal| { switch (signal) { 'a' => res |= 1, 'b' => res |= 2, 'c' => res |= 4, 'd' => res |= 8, 'e' => res |= 16, 'f' => res |= 32, 'g' => res |= 64, else => unreachable, } } return res; } fn mapDigits(scrambled: [10]u8) [10]u8 { var d = std.mem.zeroes([10]u8); for (scrambled) |digit| { if (@popCount(u8, digit) == 2) { d[1] = digit; } } for (scrambled) |digit| { if (@popCount(u8, digit) == 4) { d[4] = digit; } } for (scrambled) |digit| { if (@popCount(u8, digit) == 3) { d[7] = digit; } } for (scrambled) |digit| { if (@popCount(u8, digit) == 7) { d[8] = digit; } } for (scrambled) |digit| { if (@popCount(u8, digit) == 5 and digit & d[1] == d[1]) { d[3] = digit; } } for (scrambled) |digit| { if (@popCount(u8, digit) == 6 and digit & d[4] == d[4]) { d[9] = digit; } } for (scrambled) |digit| { if (@popCount(u8, digit) == 6 and digit & d[7] == d[7] and digit != d[9]) { d[0] = digit; } } for (scrambled) |digit| { if (@popCount(u8, digit) == 6 and digit != d[9] and digit != d[0]) { d[6] = digit; } } for (scrambled) |digit| { if (@popCount(u8, digit) == 5 and @popCount(u8, digit & d[6]) == 5) { d[5] = digit; } } for (scrambled) |digit| { if (@popCount(u8, digit) == 5 and digit != d[5] and digit != d[3]) { d[2] = digit; } } return d; } fn part1(all_values: []Values) i32 { var occurences: i32 = 0; for (all_values) |values| { const d = mapDigits(values.all_digits); for (values.output) |o| { if (o == d[1] or o == d[4] or o == d[7] or o == d[8]) { occurences += 1; } } } return occurences; } fn part2(all_values: []Values) i32 { var sum: i32 = 0; for (all_values) |values| { const mapped = mapDigits(values.all_digits); var res: i32 = 0; for (values.output) |o| { for (mapped) |d, i| { if (d == o) { res *= 10; res += @intCast(i32, i); } } } sum += res; } return sum; } pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var lines_it = try utils.iterateLinesInFile(&arena.allocator, "input.txt"); defer lines_it.deinit(); const input = try readInput(&arena, &lines_it); const part1_result = part1(input); print("Part 1: {d}", .{part1_result}); const part2_result = part2(input); print("Part 2: {d}", .{part2_result}); }
day8/src/main.zig
const std = @import("std"); const expect = std.testing.expect; pub const Vec3 = Vector3(f32); pub const Point3 = Vector3(f32); pub const Color = Vector3(f32); fn Vector3(comptime T: type) type { return struct { const Self = @This(); x: T, y: T, z: T, pub const zero = Vec3.initAll(0); pub fn init(x: T, y: T, z: T) Self { return Self{ .x = x, .y = y, .z = z }; } pub fn initAll(x: T) Self { return Self.init(x, x, x); } pub fn random(r: *std.rand.Random) Self { return Self.init(r.float(T), r.float(T), r.float(T)); } // Vector arithmetic pub fn add(a: Self, b: Self) Self { return Self.init(a.x + b.x, a.y + b.y, a.z + b.z); } pub fn sub(a: Self, b: Self) Self { return Self.init(a.x - b.x, a.y - b.y, a.z - b.z); } pub fn dot(a: Self, b: Self) T { return a.x * b.x + a.y * b.y + a.z * b.z; } pub fn cross(a: Self, b: Self) Self { return Self.init( a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x, ); } /// Component-wise multiplication pub fn mul(a: Self, b: Self) Self { return Self.init(a.x * b.x, a.y * b.y, a.z * b.z); } // Scalar arithmetic pub fn scale(a: Self, b: T) Self { return Self.init(a.x * b, a.y * b, a.z * b); } pub fn div(a: Self, b: T) Self { return a.scale(@as(T, 1) / b); } pub fn len2(a: Self) T { return dot(a, a); } pub fn len(a: Self) T { return @sqrt(len2(a)); } pub fn normalize(a: Self) Self { return a.div(len(a)); } pub fn neg(a: Self) Self { return a.scale(@as(T, -1)); } pub fn sqrt(a: Self) Self { return Self.init(@sqrt(a.x), @sqrt(a.y), @sqrt(a.z)); } pub fn eql(a: Self, b: Self) bool { return std.meta.eql(a, b); } pub fn approxEqAbs(a: Self, b: Self, eps: T) bool { return std.math.approxEqAbs(T, a.x, b.x, eps) and std.math.approxEqAbs(T, a.y, b.y, eps) and std.math.approxEqAbs(T, a.z, b.z, eps); } /// Reflects vector `v` around the normal vector `n`. pub fn reflect(v: Self, n: Self) Self { return v.sub(n.scale(2 * v.dot(n))); } pub fn refract(v: Self, n: Self, eta: f32) Self { const cos_theta = @minimum(-v.dot(n), 1); // Perpendicular and parallel parts of the refracted vector. const perp = v.add(n.scale(cos_theta)).scale(eta); const par = n.scale(-@sqrt(@fabs(1 - perp.len2()))); return perp.add(par); } pub fn lerp(a: Self, b: Self, t: f32) Self { return a.scale(1.0 - t).add(b.scale(t)); } pub const red = Self.init(1, 0, 0); pub const green = Self.init(0, 1, 0); pub const blue = Self.init(0, 0, 1); pub const white = Self.init(1, 1, 1); pub const black = Self.init(0, 0, 0); }; } test "add" { const a = Vec3.init(1, 2, 3); const b = Vec3.init(4, 5, 6); try expect(a.add(b).eql(Vec3.init(5, 7, 9))); } test "sub" { const a = Vec3.init(1, 2, 3); const b = Vec3.init(4, 5, 6); try expect(a.sub(b).eql(Vec3.init(-3, -3, -3))); } test "dot" { const a = Vec3.init(1, 2, 3); const b = Vec3.init(4, 5, 6); try expect(a.dot(b) == 32); } test "cross" { const a = Vec3.init(1, 2, 3); const b = Vec3.init(4, 5, 6); try expect(a.cross(b).eql(Vec3.init(-3, 6, -3))); } test "scale" { const a = Vec3.init(1, 2, 3); const b = 10.0; try expect(a.scale(b).eql(Vec3.init(10, 20, 30))); } test "norm" { const a = Vec3.init(1, 2, 3); try expect(a.len() == @sqrt(14.0)); } test "normalize" { const a = Vec3.init(10, 0, 0); try expect(a.normalize().eql(Vec3.init(1, 0, 0))); }
src/vec.zig
const std = @import("std"); const SDL = @import("sdl2"); const target_os = @import("builtin").os; pub fn main() !void { if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_EVENTS | SDL.SDL_INIT_AUDIO) < 0) sdlPanic(); defer SDL.SDL_Quit(); var window = SDL.SDL_CreateWindow( "SDL.zig Basic Demo", SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED, 640, 480, SDL.SDL_WINDOW_SHOWN, ) orelse sdlPanic(); defer _ = SDL.SDL_DestroyWindow(window); var renderer = SDL.SDL_CreateRenderer(window, -1, SDL.SDL_RENDERER_ACCELERATED) orelse sdlPanic(); defer _ = SDL.SDL_DestroyRenderer(renderer); const vertices = [_]SDL.SDL_Vertex{ .{ .position = .{ .x = 400, .y = 150 }, .color = .{ .r = 255, .g = 0, .b = 0, .a = 255 }, }, .{ .position = .{ .x = 350, .y = 200 }, .color = .{ .r = 0, .g = 0, .b = 255, .a = 255 }, }, .{ .position = .{ .x = 450, .y = 200 }, .color = .{ .r = 0, .g = 255, .b = 0, .a = 255 }, }, }; mainLoop: while (true) { var ev: SDL.SDL_Event = undefined; while (SDL.SDL_PollEvent(&ev) != 0) { switch (ev.type) { SDL.SDL_QUIT => break :mainLoop, SDL.SDL_KEYDOWN => { switch (ev.key.keysym.scancode) { SDL.SDL_SCANCODE_ESCAPE => break :mainLoop, else => std.log.info("key pressed: {}\n", .{ev.key.keysym.scancode}), } }, else => {}, } } _ = SDL.SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0xFF); _ = SDL.SDL_RenderClear(renderer); _ = SDL.SDL_SetRenderDrawColor(renderer, 0xF7, 0xA4, 0x1D, 0xFF); _ = SDL.SDL_RenderDrawRect(renderer, &SDL.SDL_Rect{ .x = 270, .y = 215, .w = 100, .h = 50, }); if (target_os.tag != .linux) { // Ubuntu CI doesn't have this function available yet _ = SDL.SDL_RenderGeometry( renderer, null, &vertices, 3, null, 0, ); } SDL.SDL_RenderPresent(renderer); } } fn sdlPanic() noreturn { const str = @as(?[*:0]const u8, SDL.SDL_GetError()) orelse "unknown error"; @panic(std.mem.sliceTo(str, 0)); }
examples/native.zig
const std = @import("std"); const RingBuffer = @import("ring_buffer.zig").RingBuffer; const Message = @import("Message.zig"); const fd_t = std.os.fd_t; const Buffer = @This(); pub const Error = error{BufferFull}; bytes: RingBuffer(u8, 4096), fds: RingBuffer(fd_t, 512), pub fn init() Buffer { return .{ .bytes = RingBuffer(u8, 4096).init(), .fds = RingBuffer(fd_t, 512).init(), }; } pub fn getMessage(buf: *Buffer) ?Message { if (buf.bytes.readableLength() < 8) return null; const id = @bitCast(u32, [4]u8{ buf.bytes.data[buf.bytes.tail +% 0], buf.bytes.data[buf.bytes.tail +% 1], buf.bytes.data[buf.bytes.tail +% 2], buf.bytes.data[buf.bytes.tail +% 3], }); const op_len = @bitCast(u32, [4]u8{ buf.bytes.data[buf.bytes.tail +% 4], buf.bytes.data[buf.bytes.tail +% 5], buf.bytes.data[buf.bytes.tail +% 6], buf.bytes.data[buf.bytes.tail +% 7], }); const op = @intCast(u16, op_len & 0xffff); const len = @intCast(u12, op_len >> 16); if (buf.bytes.readableLength() < len) return null; buf.bytes.ensureContiguous(len); const data = buf.bytes.readableSlices()[0][8..len]; buf.bytes.tail +%= len; return Message{ .id = id, .op = op, .data = data, }; } pub fn putInt(buf: *Buffer, int: i32) Error!void { try buf.bytes.appendSlice(std.mem.asBytes(&int)); } pub fn putUInt(buf: *Buffer, uint: u32) Error!void { try buf.putInt(@bitCast(i32, uint)); } pub fn putFixed(buf: *Buffer, fixed: f64) Error!void { try buf.putInt(@floatToInt(i32, fixed * 256)); } pub fn putString(buf: *Buffer, string: ?[]const u8) Error!void { if (string) |_string| { const len = @intCast(u32, _string.len) + 1; const padded = (len + 3) / 4 * 4; const zeroes = [4]u8{ 0, 0, 0, 0 }; try buf.putUInt(len); try buf.bytes.appendSlice(_string); try buf.bytes.appendSlice(zeroes[0 .. padded - len + 1]); } else { try buf.putUInt(0); } } pub fn putArray(buf: *Buffer, array: ?[]const u8) Error!void { if (array) |_array| { const len = @intCast(u32, _array.len); const padded = (len + 3) / 4 * 4; const zeroes = [4]u8{ 0, 0, 0, 0 }; try buf.putUInt(len); try buf.bytes.appendSlice(_array); try buf.bytes.appendSlice(zeroes[0 .. padded - len]); } else { try buf.putUInt(0); } } pub fn putFd(buf: *Buffer, fd: fd_t) Error!void { try buf.fds.append(fd); } test "Buffer" { std.testing.refAllDecls(Buffer); }
src/common/Buffer.zig
const std = @import("std"); const Image = @import("image.zig").Image; const printError = @import("../application/print_error.zig").printError; const Chunk = struct { length: u32, chunk_type: [4]u8, chunk_data: []u8, crc: u32, pub fn read(reader: anytype, allocator: std.mem.Allocator) !Chunk { var chunk: Chunk = undefined; chunk.length = try reader.readIntBig(u32); _ = try reader.readAll(chunk.chunk_type[0..]); chunk.chunk_data = allocator.alloc(u8, chunk.length) catch unreachable; _ = try reader.readAll(chunk.chunk_data); chunk.crc = try reader.readIntBig(u32); return chunk; } }; const IHDRImageHeader = struct { width: i32, height: i32, bit_depth: u8, color_type: u8, compression_method: u8, filter_method: u8, interlace_method: u8, pub fn read(reader: anytype) !IHDRImageHeader { var header: IHDRImageHeader = undefined; header.width = try reader.readIntBig(i32); header.height = try reader.readIntBig(i32); header.bit_depth = try reader.readByte(); header.color_type = try reader.readByte(); header.compression_method = try reader.readByte(); header.filter_method = try reader.readByte(); header.interlace_method = try reader.readByte(); return header; } }; pub fn check_header(reader: anytype) !bool { const png_signature = [_]u8{ 137, 80, 78, 71, 13, 10, 26, 10 }; return try reader.isBytes(&png_signature); } // Without header // Use check_header to read and check png file signature pub fn parse(reader: anytype, allocator: std.mem.Allocator) !Image { var ihdr_chunk: Chunk = try Chunk.read(reader, allocator); defer allocator.free(ihdr_chunk.chunk_data); var fbs: std.io.FixedBufferStream([]const u8) = undefined; fbs.buffer = ihdr_chunk.chunk_data; fbs.pos = 0; const image_header: IHDRImageHeader = try IHDRImageHeader.read(fbs.reader()); var image: Image = undefined; image.width = @intCast(usize, image_header.width); image.height = @intCast(usize, image_header.height); image.data = allocator.alloc(u8, image.width * image.height * 4) catch unreachable; while (true) { var chunk: Chunk = Chunk.read(reader, allocator) catch break; defer allocator.free(chunk.chunk_data); if (std.mem.eql(u8, chunk.chunk_type[0..], "IEND")) break; if (std.mem.eql(u8, chunk.chunk_type[0..], "IDAT")) { var data_stream = std.io.fixedBufferStream(chunk.chunk_data); var zlib_stream = try std.compress.zlib.zlibStream(allocator, data_stream.reader()); defer zlib_stream.deinit(); var deflated_data = try zlib_stream.reader().readAllAlloc(allocator, std.math.maxInt(usize)); defer allocator.free(deflated_data); const scanline_size: usize = image.width * 4 + 1; const bpp: usize = 4; var y: usize = 0; while (y < image.height) : (y += 1) { const filter: u8 = deflated_data[y * scanline_size]; var scanline: []const u8 = deflated_data[y * scanline_size + 1 .. (y + 1) * scanline_size]; switch (filter) { 0 => { // None std.mem.copy(u8, image.data[y * image.width * 4 ..], scanline); }, 1 => { // Sub for (scanline) |_, x| { const prev: u8 = if (x - bpp < 0) 0 else image.data[y * image.width * 4 + x - bpp]; image.data[y * image.width * 4 + x] = scanline[x] +% prev; } }, 2 => { // Up for (scanline) |_, x| { const prev: u8 = if (y == 0) 0 else image.data[(y - 1) * image.width * 4 + x]; image.data[y * image.width * 4 + x] = scanline[x] +% prev; } }, 3 => { // Average for (scanline) |_, x| { const prev: i32 = if (y == 0) 0 else @intCast(i32, image.data[(y - 1) * image.width * 4 + x]); const prev_x: i32 = if (x - bpp < 0) 0 else @intCast(i32, image.data[y * image.width * 4 + x - bpp]); image.data[y * image.width * 4 + x] = @intCast(u8, @mod(@intCast(i32, scanline[x]) + @divFloor(prev_x + prev, 2), 256)); } }, 4 => { // Paeth for (scanline) |_, x| { const prev_y: u8 = if (y == 0) 0 else image.data[(y - 1) * image.width * 4 + x]; const prev_x: u8 = if (x - bpp < 0) 0 else image.data[y * image.width * 4 + x - bpp]; const prev_x_y: u8 = if (x - bpp < 0 or y == 0) 0 else image.data[(y - 1) * image.width * 4 + x - bpp]; image.data[y * image.width * 4 + x] = scanline[x] +% paethPredictor(prev_x, prev_y, prev_x_y); } }, else => { printError("PNG", "Unknown png filter"); }, } } } } return image; } fn paethPredictor(left: u8, above: u8, upper_left: u8) u8 { const initial_estimate: i32 = @intCast(i32, left) + @intCast(i32, above) - @intCast(i32, upper_left); const distance_left: i32 = std.math.absInt(initial_estimate - left) catch unreachable; const distance_above: i32 = std.math.absInt(initial_estimate - above) catch unreachable; const distance_upper_left: i32 = std.math.absInt(initial_estimate - upper_left) catch unreachable; // return nearest // breaking ties in order: left, above, upper left if (distance_left <= distance_above and distance_left <= distance_upper_left) { return left; } else { return if (distance_above <= distance_upper_left) above else upper_left; } }
src/image/png.zig
//-------------------------------------------------------------------------------- // Section: Types (15) //-------------------------------------------------------------------------------- // TODO: this type has a FreeFunc 'HcsCloseOperation', what can Zig do with this information? pub const HCS_OPERATION = isize; // TODO: this type has a FreeFunc 'HcsCloseComputeSystem', what can Zig do with this information? pub const HCS_SYSTEM = isize; // TODO: this type has a FreeFunc 'HcsCloseProcess', what can Zig do with this information? pub const HCS_PROCESS = isize; pub const HCS_OPERATION_TYPE = enum(i32) { None = -1, Enumerate = 0, Create = 1, Start = 2, Shutdown = 3, Pause = 4, Resume = 5, Save = 6, Terminate = 7, Modify = 8, GetProperties = 9, CreateProcess = 10, SignalProcess = 11, GetProcessInfo = 12, GetProcessProperties = 13, ModifyProcess = 14, Crash = 15, }; pub const HcsOperationTypeNone = HCS_OPERATION_TYPE.None; pub const HcsOperationTypeEnumerate = HCS_OPERATION_TYPE.Enumerate; pub const HcsOperationTypeCreate = HCS_OPERATION_TYPE.Create; pub const HcsOperationTypeStart = HCS_OPERATION_TYPE.Start; pub const HcsOperationTypeShutdown = HCS_OPERATION_TYPE.Shutdown; pub const HcsOperationTypePause = HCS_OPERATION_TYPE.Pause; pub const HcsOperationTypeResume = HCS_OPERATION_TYPE.Resume; pub const HcsOperationTypeSave = HCS_OPERATION_TYPE.Save; pub const HcsOperationTypeTerminate = HCS_OPERATION_TYPE.Terminate; pub const HcsOperationTypeModify = HCS_OPERATION_TYPE.Modify; pub const HcsOperationTypeGetProperties = HCS_OPERATION_TYPE.GetProperties; pub const HcsOperationTypeCreateProcess = HCS_OPERATION_TYPE.CreateProcess; pub const HcsOperationTypeSignalProcess = HCS_OPERATION_TYPE.SignalProcess; pub const HcsOperationTypeGetProcessInfo = HCS_OPERATION_TYPE.GetProcessInfo; pub const HcsOperationTypeGetProcessProperties = HCS_OPERATION_TYPE.GetProcessProperties; pub const HcsOperationTypeModifyProcess = HCS_OPERATION_TYPE.ModifyProcess; pub const HcsOperationTypeCrash = HCS_OPERATION_TYPE.Crash; pub const HCS_OPERATION_COMPLETION = fn( operation: HCS_OPERATION, context: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const HCS_EVENT_TYPE = enum(i32) { Invalid = 0, SystemExited = 1, SystemCrashInitiated = 2, SystemCrashReport = 3, SystemRdpEnhancedModeStateChanged = 4, SystemSiloJobCreated = 5, SystemGuestConnectionClosed = 6, ProcessExited = 65536, OperationCallback = 16777216, ServiceDisconnect = 33554432, }; pub const HcsEventInvalid = HCS_EVENT_TYPE.Invalid; pub const HcsEventSystemExited = HCS_EVENT_TYPE.SystemExited; pub const HcsEventSystemCrashInitiated = HCS_EVENT_TYPE.SystemCrashInitiated; pub const HcsEventSystemCrashReport = HCS_EVENT_TYPE.SystemCrashReport; pub const HcsEventSystemRdpEnhancedModeStateChanged = HCS_EVENT_TYPE.SystemRdpEnhancedModeStateChanged; pub const HcsEventSystemSiloJobCreated = HCS_EVENT_TYPE.SystemSiloJobCreated; pub const HcsEventSystemGuestConnectionClosed = HCS_EVENT_TYPE.SystemGuestConnectionClosed; pub const HcsEventProcessExited = HCS_EVENT_TYPE.ProcessExited; pub const HcsEventOperationCallback = HCS_EVENT_TYPE.OperationCallback; pub const HcsEventServiceDisconnect = HCS_EVENT_TYPE.ServiceDisconnect; pub const HCS_EVENT = extern struct { Type: HCS_EVENT_TYPE, EventData: ?[*:0]const u16, Operation: HCS_OPERATION, }; pub const HCS_EVENT_OPTIONS = enum(u32) { None = 0, EnableOperationCallbacks = 1, _, pub fn initFlags(o: struct { None: u1 = 0, EnableOperationCallbacks: u1 = 0, }) HCS_EVENT_OPTIONS { return @intToEnum(HCS_EVENT_OPTIONS, (if (o.None == 1) @enumToInt(HCS_EVENT_OPTIONS.None) else 0) | (if (o.EnableOperationCallbacks == 1) @enumToInt(HCS_EVENT_OPTIONS.EnableOperationCallbacks) else 0) ); } }; pub const HcsEventOptionNone = HCS_EVENT_OPTIONS.None; pub const HcsEventOptionEnableOperationCallbacks = HCS_EVENT_OPTIONS.EnableOperationCallbacks; pub const HCS_EVENT_CALLBACK = fn( event: ?*HCS_EVENT, context: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const HCS_NOTIFICATION_FLAGS = enum(i32) { Success = 0, Failure = -2147483648, }; pub const HcsNotificationFlagSuccess = HCS_NOTIFICATION_FLAGS.Success; pub const HcsNotificationFlagFailure = HCS_NOTIFICATION_FLAGS.Failure; pub const HCS_NOTIFICATIONS = enum(i32) { Invalid = 0, SystemExited = 1, SystemCreateCompleted = 2, SystemStartCompleted = 3, SystemPauseCompleted = 4, SystemResumeCompleted = 5, SystemCrashReport = 6, SystemSiloJobCreated = 7, SystemSaveCompleted = 8, SystemRdpEnhancedModeStateChanged = 9, SystemShutdownFailed = 10, // SystemShutdownCompleted = 10, this enum value conflicts with SystemShutdownFailed SystemGetPropertiesCompleted = 11, SystemModifyCompleted = 12, SystemCrashInitiated = 13, SystemGuestConnectionClosed = 14, SystemOperationCompletion = 15, SystemPassThru = 16, ProcessExited = 65536, ServiceDisconnect = 16777216, FlagsReserved = -268435456, }; pub const HcsNotificationInvalid = HCS_NOTIFICATIONS.Invalid; pub const HcsNotificationSystemExited = HCS_NOTIFICATIONS.SystemExited; pub const HcsNotificationSystemCreateCompleted = HCS_NOTIFICATIONS.SystemCreateCompleted; pub const HcsNotificationSystemStartCompleted = HCS_NOTIFICATIONS.SystemStartCompleted; pub const HcsNotificationSystemPauseCompleted = HCS_NOTIFICATIONS.SystemPauseCompleted; pub const HcsNotificationSystemResumeCompleted = HCS_NOTIFICATIONS.SystemResumeCompleted; pub const HcsNotificationSystemCrashReport = HCS_NOTIFICATIONS.SystemCrashReport; pub const HcsNotificationSystemSiloJobCreated = HCS_NOTIFICATIONS.SystemSiloJobCreated; pub const HcsNotificationSystemSaveCompleted = HCS_NOTIFICATIONS.SystemSaveCompleted; pub const HcsNotificationSystemRdpEnhancedModeStateChanged = HCS_NOTIFICATIONS.SystemRdpEnhancedModeStateChanged; pub const HcsNotificationSystemShutdownFailed = HCS_NOTIFICATIONS.SystemShutdownFailed; pub const HcsNotificationSystemShutdownCompleted = HCS_NOTIFICATIONS.SystemShutdownFailed; pub const HcsNotificationSystemGetPropertiesCompleted = HCS_NOTIFICATIONS.SystemGetPropertiesCompleted; pub const HcsNotificationSystemModifyCompleted = HCS_NOTIFICATIONS.SystemModifyCompleted; pub const HcsNotificationSystemCrashInitiated = HCS_NOTIFICATIONS.SystemCrashInitiated; pub const HcsNotificationSystemGuestConnectionClosed = HCS_NOTIFICATIONS.SystemGuestConnectionClosed; pub const HcsNotificationSystemOperationCompletion = HCS_NOTIFICATIONS.SystemOperationCompletion; pub const HcsNotificationSystemPassThru = HCS_NOTIFICATIONS.SystemPassThru; pub const HcsNotificationProcessExited = HCS_NOTIFICATIONS.ProcessExited; pub const HcsNotificationServiceDisconnect = HCS_NOTIFICATIONS.ServiceDisconnect; pub const HcsNotificationFlagsReserved = HCS_NOTIFICATIONS.FlagsReserved; pub const HCS_NOTIFICATION_CALLBACK = fn( notificationType: u32, context: ?*anyopaque, notificationStatus: HRESULT, notificationData: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) void; pub const HCS_PROCESS_INFORMATION = extern struct { ProcessId: u32, Reserved: u32, StdInput: ?HANDLE, StdOutput: ?HANDLE, StdError: ?HANDLE, }; pub const HCS_CREATE_OPTIONS = enum(i32) { @"1" = 65536, }; pub const HcsCreateOptions_1 = HCS_CREATE_OPTIONS.@"1"; pub const HCS_CREATE_OPTIONS_1 = extern struct { Version: HCS_CREATE_OPTIONS, UserToken: ?HANDLE, SecurityDescriptor: ?*SECURITY_DESCRIPTOR, CallbackOptions: HCS_EVENT_OPTIONS, CallbackContext: ?*anyopaque, Callback: ?HCS_EVENT_CALLBACK, }; //-------------------------------------------------------------------------------- // Section: Functions (64) //-------------------------------------------------------------------------------- pub extern "computecore" fn HcsEnumerateComputeSystems( query: ?[*:0]const u16, operation: HCS_OPERATION, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsEnumerateComputeSystemsInNamespace( idNamespace: ?[*:0]const u16, query: ?[*:0]const u16, operation: HCS_OPERATION, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsCreateOperation( context: ?*const anyopaque, callback: ?HCS_OPERATION_COMPLETION, ) callconv(@import("std").os.windows.WINAPI) HCS_OPERATION; pub extern "computecore" fn HcsCloseOperation( operation: HCS_OPERATION, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "computecore" fn HcsGetOperationContext( operation: HCS_OPERATION, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "computecore" fn HcsSetOperationContext( operation: HCS_OPERATION, context: ?*const anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsGetComputeSystemFromOperation( operation: HCS_OPERATION, ) callconv(@import("std").os.windows.WINAPI) HCS_SYSTEM; pub extern "computecore" fn HcsGetProcessFromOperation( operation: HCS_OPERATION, ) callconv(@import("std").os.windows.WINAPI) HCS_PROCESS; pub extern "computecore" fn HcsGetOperationType( operation: HCS_OPERATION, ) callconv(@import("std").os.windows.WINAPI) HCS_OPERATION_TYPE; pub extern "computecore" fn HcsGetOperationId( operation: HCS_OPERATION, ) callconv(@import("std").os.windows.WINAPI) u64; pub extern "computecore" fn HcsGetOperationResult( operation: HCS_OPERATION, resultDocument: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsGetOperationResultAndProcessInfo( operation: HCS_OPERATION, processInformation: ?*HCS_PROCESS_INFORMATION, resultDocument: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsGetProcessorCompatibilityFromSavedState( RuntimeFileName: ?[*:0]const u16, ProcessorFeaturesString: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsWaitForOperationResult( operation: HCS_OPERATION, timeoutMs: u32, resultDocument: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsWaitForOperationResultAndProcessInfo( operation: HCS_OPERATION, timeoutMs: u32, processInformation: ?*HCS_PROCESS_INFORMATION, resultDocument: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsSetOperationCallback( operation: HCS_OPERATION, context: ?*const anyopaque, callback: ?HCS_OPERATION_COMPLETION, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsCancelOperation( operation: HCS_OPERATION, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsCreateComputeSystem( id: ?[*:0]const u16, configuration: ?[*:0]const u16, operation: HCS_OPERATION, securityDescriptor: ?*const SECURITY_DESCRIPTOR, computeSystem: ?*HCS_SYSTEM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsCreateComputeSystemInNamespace( idNamespace: ?[*:0]const u16, id: ?[*:0]const u16, configuration: ?[*:0]const u16, operation: HCS_OPERATION, options: ?*const HCS_CREATE_OPTIONS, computeSystem: ?*HCS_SYSTEM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsOpenComputeSystem( id: ?[*:0]const u16, requestedAccess: u32, computeSystem: ?*HCS_SYSTEM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsOpenComputeSystemInNamespace( idNamespace: ?[*:0]const u16, id: ?[*:0]const u16, requestedAccess: u32, computeSystem: ?*HCS_SYSTEM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsCloseComputeSystem( computeSystem: HCS_SYSTEM, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "computecore" fn HcsStartComputeSystem( computeSystem: HCS_SYSTEM, operation: HCS_OPERATION, options: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsShutDownComputeSystem( computeSystem: HCS_SYSTEM, operation: HCS_OPERATION, options: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsTerminateComputeSystem( computeSystem: HCS_SYSTEM, operation: HCS_OPERATION, options: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsCrashComputeSystem( computeSystem: HCS_SYSTEM, operation: HCS_OPERATION, options: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsPauseComputeSystem( computeSystem: HCS_SYSTEM, operation: HCS_OPERATION, options: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsResumeComputeSystem( computeSystem: HCS_SYSTEM, operation: HCS_OPERATION, options: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsSaveComputeSystem( computeSystem: HCS_SYSTEM, operation: HCS_OPERATION, options: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsGetComputeSystemProperties( computeSystem: HCS_SYSTEM, operation: HCS_OPERATION, propertyQuery: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsModifyComputeSystem( computeSystem: HCS_SYSTEM, operation: HCS_OPERATION, configuration: ?[*:0]const u16, identity: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsWaitForComputeSystemExit( computeSystem: HCS_SYSTEM, timeoutMs: u32, result: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsSetComputeSystemCallback( computeSystem: HCS_SYSTEM, callbackOptions: HCS_EVENT_OPTIONS, context: ?*const anyopaque, callback: ?HCS_EVENT_CALLBACK, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsCreateProcess( computeSystem: HCS_SYSTEM, processParameters: ?[*:0]const u16, operation: HCS_OPERATION, securityDescriptor: ?*const SECURITY_DESCRIPTOR, process: ?*HCS_PROCESS, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsOpenProcess( computeSystem: HCS_SYSTEM, processId: u32, requestedAccess: u32, process: ?*HCS_PROCESS, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsCloseProcess( process: HCS_PROCESS, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "computecore" fn HcsTerminateProcess( process: HCS_PROCESS, operation: HCS_OPERATION, options: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsSignalProcess( process: HCS_PROCESS, operation: HCS_OPERATION, options: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsGetProcessInfo( process: HCS_PROCESS, operation: HCS_OPERATION, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsGetProcessProperties( process: HCS_PROCESS, operation: HCS_OPERATION, propertyQuery: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsModifyProcess( process: HCS_PROCESS, operation: HCS_OPERATION, settings: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsSetProcessCallback( process: HCS_PROCESS, callbackOptions: HCS_EVENT_OPTIONS, context: ?*anyopaque, callback: ?HCS_EVENT_CALLBACK, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsWaitForProcessExit( computeSystem: HCS_PROCESS, timeoutMs: u32, result: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsGetServiceProperties( propertyQuery: ?[*:0]const u16, result: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsModifyServiceSettings( settings: ?[*:0]const u16, result: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsSubmitWerReport( settings: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsCreateEmptyGuestStateFile( guestStateFilePath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsCreateEmptyRuntimeStateFile( runtimeStateFilePath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsGrantVmAccess( vmId: ?[*:0]const u16, filePath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsRevokeVmAccess( vmId: ?[*:0]const u16, filePath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsGrantVmGroupAccess( filePath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computecore" fn HcsRevokeVmGroupAccess( filePath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computestorage" fn HcsImportLayer( layerPath: ?[*:0]const u16, sourceFolderPath: ?[*:0]const u16, layerData: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computestorage" fn HcsExportLayer( layerPath: ?[*:0]const u16, exportFolderPath: ?[*:0]const u16, layerData: ?[*:0]const u16, options: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computestorage" fn HcsExportLegacyWritableLayer( writableLayerMountPath: ?[*:0]const u16, writableLayerFolderPath: ?[*:0]const u16, exportFolderPath: ?[*:0]const u16, layerData: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computestorage" fn HcsDestroyLayer( layerPath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computestorage" fn HcsSetupBaseOSLayer( layerPath: ?[*:0]const u16, vhdHandle: ?HANDLE, options: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computestorage" fn HcsInitializeWritableLayer( writableLayerPath: ?[*:0]const u16, layerData: ?[*:0]const u16, options: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computestorage" fn HcsInitializeLegacyWritableLayer( writableLayerMountPath: ?[*:0]const u16, writableLayerFolderPath: ?[*:0]const u16, layerData: ?[*:0]const u16, options: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computestorage" fn HcsAttachLayerStorageFilter( layerPath: ?[*:0]const u16, layerData: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computestorage" fn HcsDetachLayerStorageFilter( layerPath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computestorage" fn HcsFormatWritableLayerVhd( vhdHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computestorage" fn HcsGetLayerVhdMountPath( vhdHandle: ?HANDLE, mountPath: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "computestorage" fn HcsSetupBaseOSVolume( layerPath: ?[*:0]const u16, volumePath: ?[*:0]const u16, options: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (4) //-------------------------------------------------------------------------------- const HANDLE = @import("../foundation.zig").HANDLE; const HRESULT = @import("../foundation.zig").HRESULT; const PWSTR = @import("../foundation.zig").PWSTR; const SECURITY_DESCRIPTOR = @import("../security.zig").SECURITY_DESCRIPTOR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "HCS_OPERATION_COMPLETION")) { _ = HCS_OPERATION_COMPLETION; } if (@hasDecl(@This(), "HCS_EVENT_CALLBACK")) { _ = HCS_EVENT_CALLBACK; } if (@hasDecl(@This(), "HCS_NOTIFICATION_CALLBACK")) { _ = HCS_NOTIFICATION_CALLBACK; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/system/host_compute_system.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); const Vec2 = tools.Vec2; const Fabric = tools.Map(u8, 1024, 1024, false); pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { var fabric = Fabric{ .default_tile = 0 }; { var it = std.mem.tokenize(u8, input, "\n\r"); while (it.next()) |line| { const fields = tools.match_pattern("#{} @ {},{}: {}x{}", line) orelse unreachable; //const patchId = fields[0].imm; const pos = Vec2{ .x = @intCast(i32, fields[1].imm), .y = @intCast(i32, fields[2].imm) }; const size = Vec2{ .x = @intCast(i32, fields[3].imm) - 1, .y = @intCast(i32, fields[4].imm) - 1 }; const patch = tools.BBox{ .min = pos, .max = Vec2.add(pos, size), }; fabric.fillIncrement(1, patch); } } // part1 const ans1 = overlaps: { var count: usize = 0; var it = fabric.iter(null); while (it.next()) |tile| { if (tile > 1) count += 1; } break :overlaps count; }; // part2 //var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); //defer arena.deinit(); const ans2 = goodpatch: { var it = std.mem.tokenize(u8, input, "\n\r"); while (it.next()) |line| { const fields = tools.match_pattern("#{} @ {},{}: {}x{}", line) orelse unreachable; const patchId = fields[0].imm; const pos = Vec2{ .x = @intCast(i32, fields[1].imm), .y = @intCast(i32, fields[2].imm) }; const size = Vec2{ .x = @intCast(i32, fields[3].imm) - 1, .y = @intCast(i32, fields[4].imm) - 1 }; const patch = tools.BBox{ .min = pos, .max = Vec2.add(pos, size), }; var isbad = false; var it2 = fabric.iter(patch); while (it2.next()) |tile| { assert(tile >= 1); if (tile > 1) { isbad = true; break; } } if (!isbad) break :goodpatch patchId; } unreachable; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2018/input_day03.txt", run);
2018/day03.zig
const sdl = @import("sdl.zig"); const SDL_RWops = sdl.SDL_RWops; pub const SDL_IMAGE_MAJOR_VERSION = 2; pub const SDL_IMAGE_MINOR_VERSION = 0; pub const SDL_IMAGE_PATCHLEVEL = 4; pub fn SDL_IMAGE_VERSION(vers: *sdl.SDL_version) void { vers.major = SDL_IMAGE_MAJOR_VERSION; vers.minor = SDL_IMAGE_MINOR_VERSION; vers.patch = SDL_IMAGE_PATCHLEVEL; } pub const SDL_IMAGE_COMPILEDVERSION = SDL_VERSIONNUM(SDL_IMAGE_MAJOR_VERSION, SDL_IMAGE_MINOR_VERSION, SDL_IMAGE_PATCHLEVEL); pub fn SDL_IMAGE_VERSION_ATLEAST(X: anytype, Y: anytype, Z: anytype) bool { return (SDL_IMAGE_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z)); } pub extern fn IMG_Linked_Version(void) callconv(.C) *const sdl.SDL_version; pub const IMG_InitFlags = extern enum { IMG_INIT_JPG = 0x00000001, IMG_INIT_PNG = 0x00000002, IMG_INIT_TIF = 0x00000004, IMG_INIT_WEBP = 0x00000008 }; pub const IMG_INIT_JPG = @enumToInt(IMG_InitFlags.IMG_INIT_JPG); pub const IMG_INIT_PNG = @enumToInt(IMG_InitFlags.IMG_INIT_PNG); pub const IMG_INIT_TIF = @enumToInt(IMG_InitFlags.IMG_INIT_TIF); pub const IMG_INIT_WEBP = @enumToInt(IMG_InitFlags.IMG_INIT_WEBP); pub extern fn IMG_Init(flags: c_int) c_int; pub extern fn IMG_Quit() void; pub extern fn IMG_LoadTyped_RW(src: *SDL_RWops, freesrc: c_int, type: [*:0]const u8) ?*sdl.SDL_Surface; pub extern fn IMG_Load(file: [*:0]const u8) ?*sdl.SDL_Surface; pub extern fn IMG_Load_RW(src: *SDL_RWops, freesrc: c_int) ?*sdl.SDL_Surface; pub extern fn IMG_LoadTexture(renderer: *sdl.SDL_Renderer, file: [*:0]const u8) ?*sdl.SDL_Texture; pub extern fn IMG_LoadTexture_RW(renderer: *sdl.SDL_Renderer, src: *SDL_RWops, freesrc: c_int) ?*sdl.SDL_Texture; pub extern fn IMG_LoadTextureTyped_RW(renderer: *sdl.SDL_Renderer, src: *SDL_RWops, freesrc: c_int, type: [*:0]const u8) ?*sdl.SDL_Texture; pub extern fn IMG_isICO(src: *SDL_RWops) c_int; pub extern fn IMG_isCUR(src: *SDL_RWops) c_int; pub extern fn IMG_isBMP(src: *SDL_RWops) c_int; pub extern fn IMG_isGIF(src: *SDL_RWops) c_int; pub extern fn IMG_isJPG(src: *SDL_RWops) c_int; pub extern fn IMG_isLBM(src: *SDL_RWops) c_int; pub extern fn IMG_isPCX(src: *SDL_RWops) c_int; pub extern fn IMG_isPNG(src: *SDL_RWops) c_int; pub extern fn IMG_isPNM(src: *SDL_RWops) c_int; pub extern fn IMG_isSVG(src: *SDL_RWops) c_int; pub extern fn IMG_isTIF(src: *SDL_RWops) c_int; pub extern fn IMG_isXCF(src: *SDL_RWops) c_int; pub extern fn IMG_isXPM(src: *SDL_RWops) c_int; pub extern fn IMG_isXV(src: *SDL_RWops) c_int; pub extern fn IMG_isWEBP(src: *SDL_RWops) c_int; pub extern fn IMG_LoadICO_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadCUR_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadBMP_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadGIF_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadJPG_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadLBM_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadPCX_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadPNG_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadPNM_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadSVG_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadTGA_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadTIF_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadXCF_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadXPM_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadXV_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_LoadWEBP_RW(src: *SDL_RWops) ?*sdl.SDL_Surface; pub extern fn IMG_ReadXPMFromArray(xpm: [*]const [*:0]const u8) ?*sdl.SDL_Surface; pub extern fn IMG_SavePNG(surface: *sdl.SDL_Surface, file: [*:0]const u8) c_int; pub extern fn IMG_SavePNG_RW(surface: *sdl.SDL_Surface, dst: *sdl.SDL_RWops, freedst: c_int) c_int; pub extern fn IMG_SaveJPG(surface: *sdl.SDL_Surface, file: [*:0]const u8, quality: c_int) c_int; pub extern fn IMG_SaveJPG_RW(surface: *sdl.SDL_Surface, dst: *sdl.SDL_RWops, freedst: c_int, quality: c_int) c_int; pub const IMG_SetError = sdl.SDL_SetError; pub const IMG_GetError = sdl.SDL_GetError;
src/binding/sdl_image.zig
const std = @import("std"); const Blo = @import("blo.zig").Blo; const process = std.process; const mem = std.mem; const fs = std.fs; const io = std.io; const log = std.log; const help_output = \\Usage: blo [OPTION]... [FILE]... \\With no FILE, read standard input. \\ \\Options: \\-n, --number prints number of lines \\-i, --info prints the file info (size, mime, modification, etc) \\-e, --show-end prints <end> after file \\-a, --ascii uses ascii chars to print info and lines delimiter \\-c, --no-color disable printing colored output \\-h, --help display this help and exit \\ \\Examples: \\blo test.txt prints the test.txt content \\blo copy standard input to output ; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = arena.allocator(); const args = try process.argsAlloc(allocator); var files = std.ArrayList([]u8).init(allocator); defer { files.deinit(); process.argsFree(allocator, args); arena.deinit(); } // zig fmt: off var config = Blo.Config{ .highlight = true, .ascii_chars = false, .colors = true, .show_end = false, .line_number = false, .info = false }; // zig fmt: on for (args[1..]) |arg| { if (arg.len > 1 and arg[0] == '-') { if (mem.eql(u8, arg, "-a") or mem.eql(u8, arg, "--ascii")) { config.ascii_chars = true; } else if (mem.eql(u8, arg, "-c") or mem.eql(u8, arg, "--no-color")) { config.colors = false; } else if (mem.eql(u8, arg, "-e") or mem.eql(u8, arg, "--show-end")) { config.show_end = true; } else if (mem.eql(u8, arg, "-n") or mem.eql(u8, arg, "--number")) { config.line_number = true; } else if (mem.eql(u8, arg, "-i") or mem.eql(u8, arg, "--info")) { config.info = true; } else if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) { log.info(help_output, .{}); return; } else { log.err("unkown option {s}", .{arg}); return; } } else { try files.append(arg); } } const stdout = io.getStdOut(); const stdin = io.getStdIn(); if (files.items.len == 0) { while (true) { var buf: [1024]u8 = undefined; if (try stdin.reader().readUntilDelimiterOrEof(&buf, '\n')) |line| { try stdout.writer().print("{s}\n", .{line}); } else break; } } else { const blo = Blo.init(allocator, io.getStdOut(), config); for (files.items) |file, index| { blo.printFile(file) catch |err| { log.err("{s}", .{@errorName(err)}); return; }; if (index < files.items.len - 1) { try blo.write("\n\n"); } } } }
src/main.zig
const std = @import("std"); const Rect = @import("./ui.zig").Rect; const math = std.math; const RowLayoutMode = enum { RowFlex, RowFixed, RowFixedArray }; const LayoutOptions = struct { spacing: f32, vert_pad: f32, hori_pad: f32, }; /// Layout. pub const Layout = struct { /// Parent region (egual to region's body). /// TODO Rename to just `space` or `region` /// or `area`. parent: Rect, /// Cursor region through the parent region available. cursor: struct { x: f32, y: f32 }, indent: f32 = 0, is_first_on_row: bool = true, is_bigger_than_parent: bool = false, spacing: f32 = 5, height: f32, row_mode: union(RowLayoutMode) { RowFlex: void, RowFixed: f32, RowFixedArray: []const f32, } = .RowFlex, /// Maximum number of column allowed. column_threshold: i32 = 1, /// The number of column currently filled. /// Will never be bigger than the threshold. column_filled: i32 = 0, const Self = @This(); pub fn new(parent: Rect, height: f32, spacing: f32) Self { return .{ .parent = parent, .spacing = spacing, .cursor = .{ .x = parent.x, .y = parent.y }, .height = height, }; } /// Return the layout total width according to /// current indentation. fn layout_width(self: *const Self) f32 { const padded_parent = self.parent.add_padding(self.indent, 0); return padded_parent.w; } pub fn reset(self: *Self) void { self.column_filled = 0; if (!self.is_first_on_row) self.add_row(); } fn add_row(self: *Self) void { self.column_filled = 0; self.cursor.x = self.parent.x; self.cursor.y += self.height + self.spacing; self.is_first_on_row = true; } /// TODO: Fix remaining_width... fn cast_width(self: *Self, w: f32) f32 { if (w >= 0 and w <= 1) { const percent = math.max(0, w); const total_width = self.layout_width(); // const remaining_width = total_width - self.cursor.x; var width = total_width * percent; // const count = self.column_threshold - self.column_filled; // if (count == 1 and width >= remaining_width) width = remaining_width; return width; } return w; } /// Allocate new space for widget. pub fn allocate_space(self: *Self, min: ?f32) Rect { const available_count = self.column_threshold - self.column_filled; if (available_count == 0) self.add_row(); var widget_width: f32 = undefined; switch (self.row_mode) { .RowFlex => { const column_threshold = @intToFloat(f32, self.column_threshold); widget_width = (self.layout_width() - self.spacing) * (1 / column_threshold); }, .RowFixed => |w| { widget_width = self.cast_width(w) - self.spacing; }, .RowFixedArray => |widths| { const index = @intCast(usize, math.max(0, self.column_filled)); widget_width = self.cast_width(widths[index]) - self.spacing; }, } if (min) |min_width| { widget_width = math.max(min_width, widget_width); } defer { self.cursor.x += widget_width + self.spacing; self.column_filled += 1; self.is_first_on_row = false; self.is_bigger_than_parent = self.cursor.y > (self.parent.y + self.parent.h); } return Rect{ .x = self.cursor.x + self.indent, .y = self.cursor.y, .w = widget_width, .h = self.height, }; } };
src/layout.zig
const std = @import("std"); const aoc = @import("aoc-lib.zig"); test "examples" { try aoc.assertEq(@as(usize, 2), part1(aoc.test1file)); try aoc.assertEq(@as(usize, 1), part2(aoc.test1file)); try aoc.assertEq(@as(usize, 454), part1(aoc.inputfile)); try aoc.assertEq(@as(usize, 649), part2(aoc.inputfile)); } fn part1(inp: anytype) usize { var lit = std.mem.split(u8, inp, "\n"); var c: usize = 0; while (lit.next()) |line| { if (line.len == 0) { break; } var fit = std.mem.tokenize(u8, line, "- :"); const n1 = std.fmt.parseInt(i64, fit.next().?, 10) catch unreachable; const n2 = std.fmt.parseInt(i64, fit.next().?, 10) catch unreachable; const ch = (fit.next().?)[0]; const str = fit.next().?; var cc: i64 = 0; for (str) |tch| { if (tch == ch) { cc += 1; } } if (cc >= n1 and cc <= n2) { c += 1; } } return c; } fn part2(inp: anytype) usize { var lit = std.mem.split(u8, inp, "\n"); var c: usize = 0; while (lit.next()) |line| { if (line.len == 0) { break; } var fit = std.mem.tokenize(u8, line, "- :"); const n1 = std.fmt.parseUnsigned(usize, fit.next().?, 10) catch unreachable; const n2 = std.fmt.parseUnsigned(usize, fit.next().?, 10) catch unreachable; const ch = (fit.next().?)[0]; const str = fit.next().?; var cc: i64 = 0; for (str) |tch| { if (tch == ch) { cc += 1; } } const first = str[n1 - 1] == ch; const second = str[n2 - 1] == ch; if ((first or second) and !(first and second)) { c += 1; } } return c; } fn day02(inp: []const u8, bench: bool) anyerror!void { var p1 = part1(inp); var p2 = part2(inp); if (!bench) { try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 }); } } pub fn main() anyerror!void { try aoc.benchme(aoc.input(), day02); }
2020/02/aoc.zig
const aoc = @import("../aoc.zig"); const std = @import("std"); const Fold = union(enum) { x: u16, y: u16 }; pub fn run(problem: *aoc.Problem) !aoc.Solution { var dots = blk: { var dots = std.AutoHashMap(aoc.Coord2D, void).init(problem.allocator); const group = problem.group().?; var tokens = std.mem.tokenize(u8, group, "\n,"); while (tokens.next()) |x_str| { const y_str = tokens.next().?; try dots.put(aoc.Coord2D.init(.{ try std.fmt.parseInt(u16, x_str, 10), try std.fmt.parseInt(u16, y_str, 10), }), {}); } break :blk dots; }; defer dots.deinit(); var folds = blk: { var folds = std.ArrayList(Fold).init(problem.allocator); const group = problem.group().?; var tokens = std.mem.tokenize(u8, group, "fold ang=\n"); while (tokens.next()) |dir| { const line = try std.fmt.parseInt(u16, tokens.next().?, 10); try folds.append(switch (dir[0]) { 'x' => Fold{ .x = line }, 'y' => Fold{ .y = line }, else => unreachable }); } break :blk folds; }; defer folds.deinit(); var one_fold_dot_count: usize = undefined; var screen_size: aoc.Coord2D = undefined; for (folds.items) |fold, idx| { switch (fold) { .x => |x| screen_size.x = x, .y => |y| screen_size.y = y, } var next_dots = std.AutoHashMap(aoc.Coord2D, void).init(problem.allocator); var iter = dots.keyIterator(); while (iter.next()) |coord| { const x = if (std.meta.activeTag(fold) == .x and coord.x > fold.x) 2*fold.x - coord.x else coord.x; const y = if (std.meta.activeTag(fold) == .y and coord.y > fold.y) 2*fold.y - coord.y else coord.y; try next_dots.put(aoc.Coord2D.init(.{x, y}), {}); } dots.deinit(); dots = next_dots; if (idx == 0) { one_fold_dot_count = dots.count(); } } var code = std.ArrayList(u8).init(problem.allocator); defer code.deinit(); var coord = aoc.Coord2D.init(.{0, 0}); while (coord.y < screen_size.y) : ({ coord.x = 0; coord.y += 1; }) { while (coord.x < screen_size.x) : (coord.x += 1) { try code.append(if (dots.contains(coord)) '#' else '.'); } try code.append('\n'); } return problem.solution(one_fold_dot_count, code.items); }
src/main/zig/2021/day13.zig
const std = @import("std"); const utils = @import("utils"); const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const print = utils.print; fn readInput(arena: *ArenaAllocator, lines_it: *utils.FileLineIterator) anyerror![][]u8 { var lines = try std.ArrayList([]u8).initCapacity(&arena.allocator, 4096); while (lines_it.next()) |line| { try lines.append(line); } print("File ok :) Number of inputs: {d}", .{lines.items.len}); return lines.items; } const Result = struct { part1: i32, part2: i64 }; fn part1And2(arena: *ArenaAllocator, lines: [][]u8) anyerror!Result { var stack = try std.ArrayList(u8).initCapacity(&arena.allocator, 4096); var corrupt_score_sum: i32 = 0; var incomplete_scores = try std.ArrayList(i64).initCapacity(&arena.allocator, 4096); for (lines) |line| { stack.clearRetainingCapacity(); var corrupt_score: i32 = 0; for (line) |chr| { if (chr == '(' or chr == '[' or chr == '{' or chr == '<') { try stack.append(chr); } else if (chr == ')' or chr == ']' or chr == '}' or chr == '>') { const opening = stack.pop(); if (corrupt_score == 0) { if (chr == ')' and opening != '(') corrupt_score = 3; if (chr == ']' and opening != '[') corrupt_score = 57; if (chr == '}' and opening != '{') corrupt_score = 1197; if (chr == '>' and opening != '<') corrupt_score = 25137; } } else { unreachable; } } corrupt_score_sum += corrupt_score; if (corrupt_score == 0) { var incomplete_score: i64 = 0; while (stack.popOrNull()) |chr| { const chr_score: i32 = switch (chr) { '(' => 1, '[' => 2, '{' => 3, '<' => 4, else => unreachable, }; incomplete_score *= 5; incomplete_score += chr_score; } try incomplete_scores.append(incomplete_score); } } std.sort.sort(i64, incomplete_scores.items, {}, comptime std.sort.desc(i64)); const incomplete_score_middle = incomplete_scores.items[incomplete_scores.items.len / 2]; return Result{ .part1 = corrupt_score_sum, .part2 = incomplete_score_middle, }; } pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var lines_it = try utils.iterateLinesInFile(&arena.allocator, "input.txt"); defer lines_it.deinit(); const input = try readInput(&arena, &lines_it); const result = try part1And2(&arena, input); print("Part 1: {d}", .{result.part1}); print("Part 2: {d}", .{result.part2}); }
day10/src/main.zig
const std = @import("std"); const gen = @import("gen.zig"); const base = @import("base.zig"); const logic = @import("logic.zig"); const RADIX = 10; const MAX_LIST_LEN = 32; pub fn validNameList( cal: *const base.Cal, raw_nlist: ?*const base.NameList, ) bool { const nlist = raw_nlist orelse return true; const months = gen.listLen([*:0]u8, nlist.*.month_list); if (months != cal.*.common_month_max and months != cal.*.leap_month_max) { return false; } if (months >= MAX_LIST_LEN) { return false; } const weekdays = gen.listLen([*:0]u8, nlist.*.weekday_list); if (weekdays != cal.*.week.length or weekdays >= MAX_LIST_LEN) { return false; } const eras = gen.listLen([*:0]u8, nlist.*.era_list); if (eras != 2 or eras >= MAX_LIST_LEN) { //Reconsider for calendars with regnal era return false; } if (cal.*.intercalary_list) |ic_list| { const ic_count = gen.listLen(base.Intercalary, ic_list); if ((ic_count * 2 + weekdays) >= MAX_LIST_LEN) { return false; } if ((ic_count * 2 + months) >= MAX_LIST_LEN) { return false; } if (nlist.*.intercalary_list) |nic_list| { if (gen.listLen([*:0]u8, nic_list) != ic_count) { return false; } } else { return false; } if (nlist.*.alt_intercalary_list) |alt_nic_list| { if (gen.listLen([*:0]u8, alt_nic_list) != ic_count) { return false; } } } else { if (nlist.*.intercalary_list) |_| { return false; } if (nlist.*.alt_intercalary_list) |_| { return false; } } return true; } const Flag = enum(u8) { pad_none = '-', pad_space = '_', pad_zero = '0', absolute_value = '|', fn getChar(self: Flag) ?u8 { return switch (self) { .pad_space => ' ', .pad_zero => '0', else => null, }; } }; const Sequence = enum(u8) { percent = '%', weekday_name = 'A', month_name = 'B', day_of_month = 'd', calendar_name = 'f', day_of_year = 'j', month_number = 'm', newline = 'n', era_name = 'q', tab = 't', weekday_number = 'u', year = 'Y', fn isChar(self: Sequence) bool { return switch (self) { .percent, .newline, .tab => true, else => false, }; } fn isNumeric(self: Sequence) bool { return switch (self) { .day_of_month, .day_of_year, .month_number, .weekday_number, .year => true, else => false, }; } fn isName(self: Sequence) bool { return switch (self) { .weekday_name, .month_name, .calendar_name, .era_name => true, else => false, }; } fn canBeIntercalary(self: Sequence) bool { return switch (self) { .weekday_name, .month_name => true, else => false, }; } fn defaultPaddingWidth(self: Sequence) u8 { return switch (self) { .day_of_month => 2, .day_of_year => 3, .month_number => 2, else => 0, }; } }; const State = enum(u8) { start, end, spec_prefix, spec_width, spec_flag, spec_seq, copy, fn afterStart(c: u8) State { return switch (c) { '%' => State.spec_prefix, 0 => State.end, else => State.copy, }; } fn afterPrefixOrFlag(c: u8) base.Err!State { if (gen.validInEnum(Flag, c)) { return State.spec_flag; } else if (std.ascii.isDigit(c)) { //Check digit after flag because '0' is a flag. return State.spec_width; } else if (gen.validInEnum(Sequence, c)) { return State.spec_seq; } else { return base.Err.InvalidSequence; } } fn afterWidth(c: u8) base.Err!State { if (std.ascii.isDigit(c)) { return State.spec_width; } else if (gen.validInEnum(Sequence, c)) { return State.spec_seq; } else { return base.Err.InvalidSequence; } } fn next(self: State, c: u8) base.Err!State { return switch (self) { .start, .copy, .spec_seq => afterStart(c), .end => base.Err.BeyondEndState, .spec_prefix, .spec_flag => afterPrefixOrFlag(c), .spec_width => afterWidth(c), }; } }; const Specifier = struct { pad_width: usize = 0, absolute_value: bool = false, seq: Sequence = Sequence.percent, pad_flag: ?Flag = null, fn getPadChar(self: Specifier) ?u8 { if (self.pad_flag) |pf| { return pf.getChar(); } else { return '0'; } } fn getPadWidth(self: Specifier) usize { if (self.pad_flag) |pf| { if (pf == Flag.pad_none) { return 0; } else { return self.pad_width; } } else { return self.seq.defaultPaddingWidth(); } } fn toStdFmtOptions(self: Specifier) std.fmt.FormatOptions { var res = std.fmt.FormatOptions{}; const width = self.getPadWidth(); if (width > 0) { res.width = width; if (self.getPadChar()) |fill| { res.fill = fill; } } return res; } fn writePadding(self: Specifier, name: [*:0]const u8, writer: anytype) !void { const name_len = std.mem.len(name); const pad_width = self.getPadWidth(); if (self.getPadChar()) |c| { if (pad_width > name_len) { try writer.writeByteNTimes(c, pad_width - name_len); } } } fn readPadding(self: Specifier, ps: anytype) !u8 { const pad_char = self.getPadChar() orelse ' '; const pad_width = self.getPadWidth(); if (pad_width > 0) { var c = pad_char; while (c == pad_char) { c = try ps.*.reader().readByte(); } return c; } else { return ps.*.reader().readByte(); } } }; fn checkInt(comptime T: type, negative: bool, n: u32) base.Err!T { if (negative) { return base.Err.InvalidDate; } if (n > std.math.maxInt(T)) { return base.Err.Overflow; } return @intCast(T, n); } fn readUnsignedInt(comptime T: type, start_c: u8, ps: anytype) !T { var n: T = 0; var put_back = true; var read_digit = false; var c = start_c; while (std.ascii.isDigit(c)) { const digit = try std.fmt.charToDigit(c, RADIX); n = try std.math.mul(T, n, RADIX); n = try std.math.add(T, n, digit); read_digit = true; c = ps.*.reader().readByte() catch |err| err_blk: { if (err == error.EndOfStream) { put_back = false; break :err_blk 0; } else { return err; } }; } if (put_back) { try ps.*.putBackByte(c); } if (!read_digit) { return base.Err.DateNotFound; } return n; } fn readNameInArr(arr: []?[*:0]u8, ps: anytype) !usize { if (arr.len >= MAX_LIST_LEN) { return base.Err.InvalidNameList; } var done = std.bit_set.IntegerBitSet(MAX_LIST_LEN).initEmpty(); var matches = std.bit_set.IntegerBitSet(MAX_LIST_LEN).initEmpty(); var match_i: usize = 0; while (match_i < arr.len) : (match_i += 1) { if (arr[match_i] != null) { matches.set(match_i); } } var name_i: usize = 0; var res_i: usize = 0; var last_c: ?u8 = null; while (matches.count() > done.count()) : (name_i += 1) { const c = ps.*.reader().readByte() catch |err| { if (err == error.EndOfStream) { last_c = null; break; } else { return err; } }; match_i = 0; while (match_i < arr.len) : (match_i += 1) { if (matches.isSet(match_i) and !done.isSet(match_i)) { if (arr[match_i]) |name| { const nc = name[name_i]; if (nc == 0) { done.set(match_i); } else { if (nc == c) { res_i = match_i; } else { matches.unset(match_i); } } } } } last_c = c; } if (last_c) |c| { try ps.*.putBackByte(c); } if (matches.count() < 1) { return base.Err.InvalidDate; } return res_i; } const DateData = struct { year_abs: ?u32 = null, month: ?u8 = null, day_of_month: ?u8 = null, day_of_year: ?u16 = null, day_of_week: ?u8 = null, after_epoch: ?bool = null, fn setYmdi(self: DateData, mjd: i32, cal: *const base.Cal) base.Err!DateData { if (self.year_abs) |_| { return self; } else { var raw_y: i32 = 0; var raw_m: u8 = 0; var raw_d: u8 = 0; try logic.mjdToYmd(mjd, cal, &raw_y, &raw_m, &raw_d); var dd = self; dd.month = raw_m; dd.day_of_month = raw_d; dd.after_epoch = raw_y > 0; dd.year_abs = @intCast(u32, if (raw_y > 0) raw_y else -raw_y); return dd; } } fn setFields(self: DateData, spec: Specifier, mjd: i32, cal: *const base.Cal) base.Err!DateData { return switch (spec.seq) { .percent, .tab, .calendar_name, .newline => self, .weekday_name, .weekday_number => weekday: { if (self.day_of_week) |_| { break :weekday self; } else { var dd = self; const weekday = try logic.mjdToDayOfWeek(mjd, cal); dd.day_of_week = weekday; if (weekday == 0) { break :weekday dd.setYmdi(mjd, cal); } else { break :weekday dd; } } }, .day_of_year => doy: { if (self.day_of_year) |_| { break :doy self; } else { var dd = self; dd.day_of_year = try logic.mjdToDayOfYear(mjd, cal); break :doy dd; } }, else => try self.setYmdi(mjd, cal), }; } fn writeNumber(self: DateData, spec: Specifier, writer: anytype) !void { const n = switch (spec.seq) { .day_of_month => @intCast(i32, self.day_of_month orelse unreachable), .day_of_year => @intCast(i32, self.day_of_year orelse unreachable), .month_number => @intCast(i32, self.month orelse unreachable), .weekday_number => @intCast(i32, self.day_of_week orelse unreachable), .year => year: { const after_epoch = self.after_epoch orelse unreachable; const y = @intCast(i32, self.year_abs orelse unreachable); if (after_epoch) { break :year y; } else { break :year -y; } }, else => unreachable, }; const x = if (spec.absolute_value and n < 0) -n else n; const opt = spec.toStdFmtOptions(); const case = std.fmt.Case.lower; if (x >= 0) { const abs = @intCast(u32, x); //Force the + sign to be omitted try std.fmt.formatInt(abs, RADIX, case, opt, writer); } else { try std.fmt.formatInt(n, RADIX, case, opt, writer); } } fn toIcName( self: DateData, cal: *const base.Cal, nlist: *const base.NameList, ) base.Err![*:0]const u8 { const y = self.year_abs orelse return base.Err.DateNotFound; const m = self.month orelse unreachable; const d = self.day_of_month orelse unreachable; const raw_ic = gen.seekIc(m, d, cal); const ic = raw_ic orelse return base.Err.BadCalendar; const use_alt = ic.era_start_alt_name and y == 0 and ic.day_of_year == gen.yearLen(false, cal); const raw_list = if (use_alt) nlist.*.alt_intercalary_list else nlist.*.intercalary_list; const list = raw_list orelse return base.Err.InvalidNameList; return list[ic.name_i] orelse base.Err.InvalidNameList; } fn writeName( self: DateData, spec: Specifier, cal: *const base.Cal, nlist: *const base.NameList, writer: anytype, ) !void { const name = switch (spec.seq) { .weekday_name => weekday: { const day_of_week = self.day_of_week orelse unreachable; if (day_of_week == @enumToInt(base.Weekday7.NoWeekday)) { break :weekday try self.toIcName(cal, nlist); } else { const i = @intCast(usize, day_of_week - 1); break :weekday nlist.*.weekday_list[i] orelse return base.Err.InvalidNameList; } }, .month_name => month: { const m = self.month orelse unreachable; if (m == 0) { break :month try self.toIcName(cal, nlist); } else { const i = @intCast(usize, m - 1); break :month nlist.*.month_list[i] orelse return base.Err.InvalidNameList; } }, .calendar_name => nlist.*.calendar_name, .era_name => era: { const after_epoch = self.after_epoch orelse unreachable; const era_idx: usize = if (after_epoch) 1 else 0; const era_list = nlist.*.era_list; break :era era_list[era_idx] orelse return base.Err.InvalidNameList; }, else => unreachable, }; try spec.writePadding(name, writer); var name_i: u32 = 0; while (name[name_i] != 0) { const name_c = name[name_i]; const count = std.unicode.utf8ByteSequenceLength(name_c) catch { return base.Err.InvalidUtf8; }; const next_name_i = name_i + count; _ = try writer.write(name[name_i..next_name_i]); name_i = next_name_i; } } fn readNumber(self: DateData, spec: Specifier, ps: anytype) !DateData { var c = try spec.readPadding(ps); const negative = (c == '-'); if (negative) { if (spec.absolute_value) { try ps.*.putBackByte(c); return self; } c = ps.*.reader().readByte() catch |err| { if (err == error.EndOfStream) { return self; } else { return err; } }; } const n = try readUnsignedInt(u32, c, ps); var dd = self; switch (spec.seq) { .weekday_number => { dd.day_of_week = try checkInt(u8, negative, n); }, .day_of_month => { dd.day_of_month = try checkInt(u8, negative, n); }, .day_of_year => { dd.day_of_year = try checkInt(u16, negative, n); }, .month_number => { dd.month = try checkInt(u8, negative, n); }, .year => { dd.year_abs = n; if (negative or n == 0) { dd.after_epoch = false; } else if (!spec.absolute_value) { dd.after_epoch = true; } }, else => unreachable, } return dd; } fn setIntercalary( self: DateData, cal: *const base.Cal, raw_name_i: usize, ic_count: usize, ) !DateData { const ic_name_i = raw_name_i % ic_count; const alt_name = raw_name_i >= ic_count; if (cal.*.intercalary_list) |ic_list| { var i: usize = 0; while (ic_list[i]) |ic| : (i += 1) { if (ic.name_i == ic_name_i) { var res = self; res.day_of_week = 0; res.month = ic.month; res.day_of_month = ic.day; if (alt_name) { if (ic.era_start_alt_name) { res.year_abs = if (cal.*.year0) 0 else 1; res.after_epoch = false; } } return res; } } } return base.Err.DateNotFound; } fn readName( self: DateData, spec: Specifier, cal: *const base.Cal, nlist: *const base.NameList, ps: anytype, ) !DateData { var name_arr: [MAX_LIST_LEN]?[*:0]u8 = undefined; var i: usize = 0; switch (spec.seq) { .calendar_name => { name_arr[0] = nlist.*.calendar_name; i = 1; }, .era_name => { while (i < 2) : (i += 1) { name_arr[i] = nlist.*.era_list[i]; } }, .weekday_name => { while (i < cal.*.week.length) : (i += 1) { name_arr[i] = nlist.*.weekday_list[i]; } }, .month_name => { if (cal.*.common_month_max != cal.*.leap_month_max) { return base.Err.BadCalendar; } while (i < cal.*.common_month_max) : (i += 1) { name_arr[i] = nlist.*.month_list[i]; } }, else => unreachable, } var ic_count: usize = 0; if (cal.*.intercalary_list) |ic_list| { if (spec.seq.canBeIntercalary()) { ic_count = gen.listLen(base.Intercalary, ic_list); if (nlist.*.intercalary_list) |nic_list| { const boundary_i = i; while ((i - boundary_i) < ic_count) : (i += 1) { name_arr[i] = nic_list[i - boundary_i]; } } if (nlist.*.alt_intercalary_list) |alt_nic_list| { const boundary_i = i; while ((i - boundary_i) < ic_count) : (i += 1) { name_arr[i] = alt_nic_list[i - boundary_i]; } } } } const match_i = try readNameInArr(name_arr[0..i], ps); var res = self; switch (spec.seq) { .calendar_name => {}, .era_name => { res.after_epoch = (match_i > 0); }, .weekday_name => { if (match_i < cal.*.week.length) { res.day_of_week = (@intCast(u8, match_i) + 1); } else if (ic_count > 0) { const ic_i = (match_i - cal.*.week.length); res = try self.setIntercalary(cal, ic_i, ic_count); } }, .month_name => { if (match_i < cal.*.common_month_max) { res.month = (@intCast(u8, match_i) + 1); } else if (ic_count > 0) { const ic_i = (match_i - cal.*.common_month_max); res = try self.setIntercalary(cal, ic_i, ic_count); } }, else => unreachable, } return res; } fn toMjd(self: DateData, cal: *const base.Cal) base.Err!i32 { const after_epoch = self.after_epoch orelse true; const year_abs = self.year_abs orelse return base.Err.DateNotFound; if (year_abs > std.math.maxInt(i32)) { return base.Err.Overflow; } const y = if (after_epoch) @intCast(i32, year_abs) else -@intCast(i32, year_abs); if (self.day_of_year) |day_of_year| { return logic.mjdFromDayOfYear(cal, y, day_of_year); } else { const month = self.month orelse return base.Err.DateNotFound; const day_of_month = self.day_of_month orelse return base.Err.DateNotFound; return logic.mjdFromYmd(cal, y, month, day_of_month); } } }; fn writeCopy(c: u8, fmt_reader: anytype, writer: anytype) !void { const count = std.unicode.utf8ByteSequenceLength(c) catch { return base.Err.InvalidUtf8; }; if (count > 4) { unreachable; } var buf: [4]u8 = undefined; buf[0] = c; const read_bytes = try fmt_reader.read(buf[1..count]); if (read_bytes != (count - 1)) { return base.Err.InvalidSequence; } _ = try writer.write(buf[0..count]); } fn doPrefix() void {} fn doSpecWidth(c: u8, spec: *Specifier) void { spec.*.pad_width = (spec.*.pad_width * RADIX) + (c - '0'); } fn doFlag(c: u8, spec: *Specifier) void { const f = @intToEnum(Flag, c); if (f == Flag.absolute_value) { spec.*.absolute_value = true; } else { spec.*.pad_flag = f; } } fn writeChar(spec: Specifier, writer: anytype) !void { const ch: u8 = switch (spec.seq) { .percent => '%', .newline => '\n', .tab => '\t', else => unreachable, }; try writer.writeByte(ch); } fn readCopy(c: u8, reader: anytype) !void { const count = std.unicode.utf8ByteSequenceLength(c) catch { return base.Err.InvalidUtf8; }; if (count > 4) { unreachable; } var buf: [4]u8 = undefined; const read_bytes = try reader.read(buf[0..count]); if (read_bytes != count) { return base.Err.InvalidSequence; } if (buf[0] != c) { //Caused by digit after numeric sequence return base.Err.InvalidSequence; } } pub fn formatW( mjd: i32, cal: *const base.Cal, raw_nlist: ?*const base.NameList, fmt: []const u8, writer: anytype, ) !void { if (!validNameList(cal, raw_nlist)) { return base.Err.InvalidNameList; } var s = State.start; var fmt_reader = std.io.fixedBufferStream(fmt).reader(); var spec = Specifier{}; var dd = DateData{}; while (true) { const c = fmt_reader.readByte() catch |err| { if (err == error.EndOfStream) { break; } else { return err; } }; s = try s.next(c); switch (s) { .copy => try writeCopy(c, fmt_reader, writer), .spec_prefix => doPrefix(), .spec_width => doSpecWidth(c, &spec), .spec_flag => doFlag(c, &spec), .spec_seq => { spec.seq = @intToEnum(Sequence, c); if (spec.seq.isChar()) { try writeChar(spec, writer); } else if (spec.seq.isNumeric()) { dd = try dd.setFields(spec, mjd, cal); try dd.writeNumber(spec, writer); } else if (spec.seq.isName()) { const nlist = raw_nlist orelse return base.Err.NullNameList; dd = try dd.setFields(spec, mjd, cal); try dd.writeName(spec, cal, nlist, writer); } else { return base.Err.InvalidSequence; } spec = Specifier{}; }, .end => break, .start => return base.Err.InvalidSequence, } } writer.writeByte(0) catch return base.Err.FailedToInsertNullCharacter; } pub fn format( mjd: i32, cal: *const base.Cal, raw_nlist: ?*const base.NameList, fmt: []const u8, raw_buf: ?[]u8, ) !c_int { if (raw_buf) |buf| { if (buf.len > 0) { var bufWriter = std.io.fixedBufferStream(buf); formatW(mjd, cal, raw_nlist, fmt, bufWriter.writer()) catch |err| { if (err == error.NoSpaceLeft or err == base.Err.FailedToInsertNullCharacter) { buf[buf.len - 1] = 0; } return format(mjd, cal, raw_nlist, fmt, null); }; const res = try bufWriter.getPos(); return @intCast(c_int, res) - 1; } } var counter = std.io.countingWriter(std.io.null_writer); try formatW(mjd, cal, raw_nlist, fmt, counter.writer()); return @intCast(c_int, counter.bytes_written) - 1; } pub fn parseR( cal: *const base.Cal, raw_nlist: ?*const base.NameList, fmt: []const u8, raw_reader: anytype, mjd_res: *i32, ) !usize { if (!validNameList(cal, raw_nlist)) { return base.Err.InvalidNameList; } var s = State.start; var fmt_reader = std.io.fixedBufferStream(fmt).reader(); var spec = Specifier{}; var dd = DateData{}; var ps = std.io.peekStream(1, raw_reader); while (true) { const c = fmt_reader.readByte() catch |err| { if (err == error.EndOfStream) { break; } else { return err; } }; const prev_s = s; s = try s.next(c); if (prev_s == State.spec_seq) { if (s == State.spec_prefix) { return base.Err.DateNotFound; //Ambiguous } if (s == State.copy and std.ascii.isDigit(c)) { return base.Err.DateNotFound; //Ambiguous } } switch (s) { .copy => try readCopy(c, ps.reader()), .spec_prefix => doPrefix(), .spec_width => doSpecWidth(c, &spec), .spec_flag => doFlag(c, &spec), .spec_seq => { spec.seq = @intToEnum(Sequence, c); if (spec.seq.isChar()) { try ps.reader().skipBytes(1, .{ .buf_size = 1 }); } else if (spec.seq.isNumeric()) { dd = try dd.readNumber(spec, &ps); } else if (spec.seq.isName()) { const nlist = raw_nlist orelse return base.Err.NullNameList; dd = try dd.readName(spec, cal, nlist, &ps); } else { return base.Err.InvalidSequence; } spec = Specifier{}; }, .end => break, .start => return base.Err.InvalidSequence, } } mjd_res.* = try dd.toMjd(cal); return ps.fifo.readableLength(); } pub fn parse( cal: *const base.Cal, raw_nlist: ?*const base.NameList, fmt: []const u8, buf: []const u8, mjd_res: *i32, ) !c_int { var fbs = std.io.fixedBufferStream(buf); const off = try parseR(cal, raw_nlist, fmt, fbs.reader(), mjd_res); const pos = try fbs.getPos(); if (pos > std.math.maxInt(c_int)) { return base.Err.Overflow; } return @intCast(c_int, pos) - @intCast(c_int, off); }
src/format.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const assert = std.debug.assert; const print = std.debug.print; const input = @embedFile("../input/day07.txt"); const Content = struct { count: usize, color: []const u8, pub fn init(string: []const u8) !Content { var s = std.mem.tokenize(string, " "); const count = try std.fmt.parseUnsigned(usize, s.next().?, 10); var color = s.rest(); const i = std.mem.indexOf(u8, color, " bag").?; var self = Content{ .count = count, .color = color[0..i], }; return self; } }; const Bag = struct { color: []const u8, content: ArrayList(Content), pub fn init(allocator: *Allocator, string: []const u8) !Bag { var s = std.mem.split(string, " bags contain "); var self = Bag{ .color = s.next().?, .content = ArrayList(Content).init(allocator), }; var content = s.next().?; if (!std.mem.eql(u8, content, "no other bags.")) { s = std.mem.split(content, ", "); while (s.next()) |c| { try self.content.append(try Content.init(c)); } } return self; } pub fn deinit(self: *Bag) void { self.content.deinit(); } }; var bags: ArrayList(Bag) = undefined; fn initBags(allocator: *Allocator, string: []const u8) !void { var lines = std.mem.split(string, "\n"); bags = ArrayList(Bag).init(allocator); while (lines.next()) |line| { try bags.append(try Bag.init(allocator, line)); } } pub fn findBag(color: []const u8) ?usize { for (bags.items) |bag, i| { if (std.mem.eql(u8, bag.color, color)) { return i; } } return null; } pub fn canContainShinyGoldBag(i: usize) bool { for (bags.items[i].content.items) |item| { if (std.mem.eql(u8, item.color, "shiny gold")) { return true; } if (findBag(item.color)) |j| { if (canContainShinyGoldBag(j)) { return true; } } } return false; } pub fn countContainingBags(i: usize) usize { var sum: usize = 0; for (bags.items[i].content.items) |item| { if (findBag(item.color)) |j| { sum += item.count + item.count * countContainingBags(j); } } return sum; } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = &gpa.allocator; try initBags(allocator, input); var count: usize = 0; for (bags.items) |_, i| { if (canContainShinyGoldBag(i)) { count += 1; } } print("part1: {}\n", .{count}); if (findBag("shiny gold")) |shiny_gold| { print("part2: {}\n", .{countContainingBags(shiny_gold)}); } } const example_part1 = \\light red bags contain 1 bright white bag, 2 muted yellow bags. \\dark orange bags contain 3 bright white bags, 4 muted yellow bags. \\bright white bags contain 1 shiny gold bag. \\muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. \\shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. \\dark olive bags contain 3 faded blue bags, 4 dotted black bags. \\vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. \\faded blue bags contain no other bags. \\dotted black bags contain no other bags. ; test "part1 example" { try initBags(std.testing.allocator, example_part1); defer { for (bags.items) |*bag| { bag.deinit(); } bags.deinit(); } var count: usize = 0; for (bags.items) |_, i| { if (canContainShinyGoldBag(i)) { count += 1; } } std.testing.expect(count == 4); } const example_part2 = \\shiny gold bags contain 2 dark red bags. \\dark red bags contain 2 dark orange bags. \\dark orange bags contain 2 dark yellow bags. \\dark yellow bags contain 2 dark green bags. \\dark green bags contain 2 dark blue bags. \\dark blue bags contain 2 dark violet bags. \\dark violet bags contain no other bags. ; test "part2 example" { try initBags(std.testing.allocator, example_part2); defer { for (bags.items) |*bag| { bag.deinit(); } bags.deinit(); } var shiny_gold = findBag("shiny gold").?; std.testing.expect(countContainingBags(shiny_gold) == 126); }
src/day07.zig
export var vector_table linksection(".vector_table") = packed struct { initial_sp: u32 = model.memory.ram.stack_bottom, reset: EntryPoint = reset, system_exceptions: [14]EntryPoint = [1]EntryPoint{exception} ** 14, interrupts: [model.number_of_peripherals]EntryPoint = [1]EntryPoint{exception} ** model.number_of_peripherals, const EntryPoint = fn () callconv(.C) noreturn; }{}; fn reset() callconv(.C) noreturn { model.memory.ram.prepare(); Uart.prepare(); Timers[0].prepare(); Terminal.reset(); Terminal.attribute(Terminal.background_green); Terminal.clearScreen(); Terminal.move(1, 1); log("https://github.com/markfirmware/zig-vector-table is running on a microbit!", .{}); var status_line_number: u32 = 2; if (Ficr.isQemu()) { Terminal.attribute(Terminal.foreground_magenta); log("actually qemu -M microbit (zig build qemu)", .{}); log("the emulated timer can be slower than a real one", .{}); log(" and also slightly erratic (due to running on a shared host)", .{}); Terminal.attribute(Terminal.foreground_black); status_line_number += 3; Terminal.move(status_line_number, 1); log("waiting for timer ...", .{}); } var t = TimeKeeper.ofMilliseconds(1000); var i: u32 = 0; while (true) { Uart.update(); if (t.isFinishedThenReset()) { i += 1; Terminal.move(status_line_number, 1); log("up and running for {} seconds!", .{i}); } } } fn exception() callconv(.C) noreturn { const ipsr_interrupt_program_status_register = asm ("mrs %[ipsr_interrupt_program_status_register], ipsr" : [ipsr_interrupt_program_status_register] "=r" (-> usize) ); const isr_number = ipsr_interrupt_program_status_register & 0xff; panicf("arm exception ipsr.isr_number {}", .{isr_number}); } pub fn panic(message: []const u8, trace: ?*std.builtin.StackTrace) noreturn { _ = trace; panicf("panic(): {s}", .{message}); } fn hangf(comptime fmt: []const u8, args: anytype) noreturn { log(fmt, args); Uart.drainTx(); while (true) {} } fn panicf(comptime fmt: []const u8, args: anytype) noreturn { @setCold(true); log("\npanicf(): " ++ fmt, args); hangf("panic completed", .{}); } const Ficr = struct { pub fn deviceId() u64 { return @as(u64, contents[0x64 / 4]) << 32 | contents[0x60 / 4]; } pub fn isQemu() bool { return deviceId() == 0x1234567800000003; } pub const contents = @intToPtr(*[64]u32, 0x10000000); }; const Gpio = struct { const p = Peripheral.at(0x50000000); pub const registers = struct { pub const out = p.typedRegisterGroup(0x504, 0x508, 0x50c, Pins); pub const in = p.typedRegister(0x510, Pins); pub const direction = p.typedRegisterGroup(0x514, 0x518, 0x51c, Pins); pub const config = p.typedRegisterArray(32, 0x700, Config); pub const Config = packed struct { output_connected: u1, input_disconnected: u1, pull: enum(u2) { disabled, down, up = 3 }, unused1: u4 = 0, drive: enum(u3) { s0s1, h0s1, s0h1, h0h1, d0s1, d0h1, s0d1, h0d1 }, unused2: u5 = 0, sense: enum(u2) { disabled, high = 2, low }, unused3: u14 = 0, }; }; }; const Peripheral = struct { fn at(base: u32) type { assert(base == 0xe000e000 or base == 0x50000000 or base & 0xfffe0fff == 0x40000000); return struct { const peripheral_id = base >> 12 & 0x1f; fn mmio(address: u32, comptime T: type) *align(4) volatile T { return @intToPtr(*align(4) volatile T, address); } fn event(offset: u32) Event { var e: Event = undefined; e.address = base + offset; return e; } fn typedRegister(offset: u32, comptime the_layout: type) type { return struct { pub const layout = the_layout; pub noinline fn read() layout { return mmio(base + offset, layout).*; } pub noinline fn write(x: layout) void { mmio(base + offset, layout).* = x; } }; } fn register(offset: u32) type { return typedRegister(offset, u32); } fn registerGroup(offsets: RegisterGroup) type { return typedRegisterGroup(offsets, u32); } fn typedRegisterGroup(offsets: RegisterGroup, comptime T: type) type { assert(offsets.read == offsets.write); assert(offsets.set == offsets.write + 4); assert(offsets.clear == offsets.set + 4); return struct { pub fn read() T { return typedRegister(offsets.read, T).read(); } pub fn write(x: T) void { typedRegister(offsets.write, T).write(x); } pub fn set(x: T) void { typedRegister(offsets.set, T).write(x); } pub fn clear(x: T) void { typedRegister(offsets.clear, T).write(x); } }; } fn Register(comptime T: type) type { return struct { address: u32, pub noinline fn read(self: @This()) T { return mmio(self.address, T).*; } pub noinline fn write(self: @This(), x: T) void { mmio(self.address, T).* = x; } }; } fn typedRegisterArray(comptime length: u32, offset: u32, comptime T: type) [length]Register(T) { return addressedArray(length, offset, 4, Register(T)); } fn registerArray(comptime length: u32, offset: u32) [length]Register(u32) { return addressedArray(length, offset, 4, Register(u32)); } fn registerArrayDelta(comptime length: u32, offset: u32, delta: u32) [length]Register(u32) { return addressedArray(length, offset, delta, Register(u32)); } fn shorts(comptime EventsType: type, comptime TasksType: type, event2: EventsType.enums, task2: TasksType.enums) type { _ = event2; _ = task2; return struct { fn enable(pairs: []struct { event: EventsType.enums, task: TasksType.enums }) void { _ = pairs; } }; } fn task(offset: u32) Task { var t: Task = undefined; t.address = base + offset; return t; } fn addressedArray(comptime length: u32, offset: u32, delta: u32, comptime T: type) [length]T { var t: [length]T = undefined; var i: u32 = 0; while (i < length) : (i += 1) { t[i].address = base + offset + i * delta; } return t; } fn eventArray(comptime length: u32, offset: u32) [length]Event { return addressedArray(length, offset, 4, Event); } fn taskArray(comptime length: u32, offset: u32) [length]Task { return addressedArray(length, offset, 4, Task); } fn taskArrayDelta(comptime length: u32, offset: u32, delta: u32) [length]Task { return addressedArray(length, offset, delta, Task); } const Event = struct { address: u32, pub fn clearEvent(self: Event) void { mmio(self.address, u32).* = 0; } pub fn eventOccurred(self: Event) bool { return mmio(self.address, u32).* == 1; } }; const RegisterGroup = struct { read: u32, write: u32, set: u32, clear: u32, }; const Task = struct { address: u32, pub fn doTask(self: Task) void { mmio(self.address, u32).* = 1; } }; }; } }; pub const Pins = packed struct { i2c_scl: u1 = 0, ring2: u1 = 0, ring1: u1 = 0, ring0: u1 = 0, led_cathodes: u9 = 0, led_anodes: u3 = 0, unused1: u1 = 0, button_a: u1 = 0, unused2: u6 = 0, target_txd: u1 = 0, target_rxd: u1 = 0, button_b: u1 = 0, unused3: u3 = 0, i2c_sda: u1 = 0, unused4: u1 = 0, pub const of = struct { pub const i2c_scl = Pins{ .i2c_scl = 1 }; pub const ring2 = Pins{ .ring2 = 1 }; pub const ring1 = Pins{ .ring1 = 1 }; pub const ring0 = Pins{ .ring0 = 1 }; pub const led_anodes = Pins{ .led_anodes = 0x7 }; pub const led_cathodes = Pins{ .led_cathodes = 0x1ff }; pub const leds = led_anodes.maskUnion(led_cathodes); pub const button_a = Pins{ .button_a = 1 }; pub const target_txd = Pins{ .target_txd = 1 }; pub const target_rxd = Pins{ .target_rxd = 1 }; pub const button_b = Pins{ .button_b = 1 }; pub const i2c_sda = Pins{ .i2c_sda = 1 }; }; pub fn clear(self: Pins) void { Gpio.registers.out.clear(self); } pub fn config(self: Pins, the_config: Gpio.registers.Config) void { var i: u32 = 0; while (i < self.width()) : (i += 1) { Gpio.registers.config[self.bitPosition(i)].write(the_config); } } pub fn connectI2c(self: Pins) void { self.config(.{ .output_connected = 0, .input_disconnected = 0, .pull = .disabled, .drive = .s0d1, .sense = .disabled }); } pub fn connectInput(self: Pins) void { self.config(.{ .output_connected = 0, .input_disconnected = 0, .pull = .disabled, .drive = .s0s1, .sense = .disabled }); } pub fn connectIo(self: Pins) void { self.config(.{ .output_connected = 1, .input_disconnected = 0, .pull = .disabled, .drive = .s0s1, .sense = .disabled }); } pub fn connectOutput(self: Pins) void { self.config(.{ .output_connected = 1, .input_disconnected = 1, .pull = .disabled, .drive = .s0s1, .sense = .disabled }); } pub fn directionClear(self: @This()) void { Gpio.registers.direction.clear(self); } pub fn directionSet(self: @This()) void { Gpio.registers.direction.set(self); } pub fn mask(self: Pins) u32 { assert(@sizeOf(Pins) == 4); return @bitCast(u32, self); } pub fn maskUnion(self: Pins, other: Pins) Pins { return @bitCast(Pins, self.mask() | other.mask()); } pub fn outRead(self: Pins) u32 { return (@bitCast(u32, Gpio.registers.out.read()) & self.mask()) >> self.bitPosition(0); } fn bitPosition(self: Pins, i: u32) u5 { return @truncate(u5, @ctz(u32, self.mask()) + i); } pub fn read(self: Pins) u32 { return (@bitCast(u32, Gpio.registers.in.read()) & self.mask()) >> self.bitPosition(0); } pub fn set(self: Pins) void { Gpio.registers.out.set(self); } fn width(self: Pins) u32 { return 32 - @clz(u32, self.mask()) - @ctz(u32, self.mask()); } pub fn write(self: Pins, x: u32) void { var new = Gpio.registers.out.read().mask() & ~self.mask(); new |= (x << self.bitPosition(0)) & self.mask(); Gpio.registers.out.write(@bitCast(Pins, new)); } pub fn writeWholeMask(self: Pins) void { Gpio.registers.out.write(self); } }; pub const Terminal = struct { pub fn attribute(n: u32) void { pair(n, 0, "m"); } pub fn clearScreen() void { pair(2, 0, "J"); } pub fn hideCursor() void { Uart.writeText(csi ++ "?25l"); } pub fn line(comptime fmt: []const u8, args: anytype) void { print(fmt, args); pair(0, 0, "K"); Uart.writeText("\n"); } pub fn move(row: u32, column: u32) void { pair(row, column, "H"); } pub fn pair(a: u32, b: u32, letter: []const u8) void { if (a <= 1 and b <= 1) { print("{s}{s}", .{ csi, letter }); } else if (b <= 1) { print("{s}{}{s}", .{ csi, a, letter }); } else if (a <= 1) { print("{s};{}{s}", .{ csi, b, letter }); } else { print("{s}{};{}{s}", .{ csi, a, b, letter }); } } pub fn requestCursorPosition() void { Uart.writeText(csi ++ "6n"); } pub fn requestDeviceCode() void { Uart.writeText(csi ++ "c"); } pub fn reset() void { Uart.writeText("\x1bc"); } pub fn restoreCursorAndAttributes() void { Uart.writeText("\x1b8"); } pub fn saveCursorAndAttributes() void { Uart.writeText("\x1b7"); } pub fn setLineWrap(enabled: bool) void { pair(0, 0, if (enabled) "7h" else "7l"); } pub fn setScrollingRegion(top: u32, bottom: u32) void { pair(top, bottom, "r"); } pub fn showCursor() void { Uart.writeText(csi ++ "?25h"); } const csi = "\x1b["; const background_green = 42; const background_yellow = 43; const foreground_black = 30; const foreground_magenta = 35; const print = Uart.print; var height: u32 = 24; var width: u32 = 80; }; pub const TimeKeeper = struct { duration: u32, max_elapsed: u32, start_time: u32, fn capture(self: *TimeKeeper) u32 { _ = self; Timers[0].tasks.capture[0].doTask(); return Timers[0].registers.capture_compare[0].read(); } fn elapsed(self: *TimeKeeper) u32 { return self.capture() -% self.start_time; } fn ofMilliseconds(ms: u32) TimeKeeper { var t: TimeKeeper = undefined; t.prepare(1000 * ms); return t; } fn prepare(self: *TimeKeeper, duration: u32) void { self.duration = duration; self.max_elapsed = 0; self.reset(); } fn isFinishedThenReset(self: *TimeKeeper) bool { const since = self.elapsed(); if (since >= self.duration) { if (since > self.max_elapsed) { self.max_elapsed = since; } self.reset(); return true; } else { return false; } } fn reset(self: *TimeKeeper) void { self.start_time = self.capture(); } fn wait(self: *TimeKeeper) void { while (!self.isFinishedThenReset()) {} } pub fn delay(duration: u32) void { var time_keeper: TimeKeeper = undefined; time_keeper.prepare(duration); time_keeper.wait(); } }; pub const Timers = [_]@TypeOf(Timer(0x40008000)){ Timer(0x40008000), Timer(0x40009000), Timer(0x4000a000) }; fn Timer(base: u32) type { return struct { const max_width = if (base == 0x40008000) @as(u32, 32) else 16; const p = Peripheral.at(base); pub const tasks = struct { pub const start = p.task(0x000); pub const stop = p.task(0x004); pub const count = p.task(0x008); pub const clear = p.task(0x00c); pub const capture = p.taskArray(4, 0x040); }; pub const events = struct { pub const compare = p.eventArray(4, 0x140); }; pub const registers = struct { pub const shorts = p.register(0x200); pub const interrupts = p.registerSetClear(0x304, 0x308); pub const mode = p.register(0x504); pub const bit_mode = p.register(0x508); pub const prescaler = p.register(0x510); pub const capture_compare = p.registerArray(4, 0x540); }; pub fn captureAndRead() u32 { tasks.capture[0].doTask(); return registers.capture_compare[0].read(); } pub fn prepare() void { registers.mode.write(0x0); registers.bit_mode.write(if (base == 0x40008000) @as(u32, 0x3) else 0x0); registers.prescaler.write(if (base == 0x40008000) @as(u32, 4) else 9); tasks.start.doTask(); const now = captureAndRead(); var i: u32 = 0; while (captureAndRead() == now) : (i += 1) { if (i == 1000) { panicf("timer 0x{x} is not responding", .{base}); } } } }; } const Uart = struct { const p = Peripheral.at(0x40002000); pub const tasks = struct { pub const start_rx = p.task(0x000); pub const stop_rx = p.task(0x004); pub const start_tx = p.task(0x008); pub const stop_tx = p.task(0x00c); }; pub const events = struct { pub const cts = p.event(0x100); pub const not_cts = p.event(0x104); pub const rx_ready = p.event(0x108); pub const tx_ready = p.event(0x11c); pub const error_detected = p.event(0x124); pub const rx_timeout = p.event(0x144); }; pub const registers = struct { pub const interrupts = p.registerGroup(.{ .read = 0x300, .write = 0x300, .set = 0x304, .clear = 0x308 }); pub const error_source = p.register(0x480); pub const enable = p.register(0x500); pub const pin_select_rts = p.register(0x508); pub const pin_select_txd = p.register(0x50c); pub const pin_select_cts = p.register(0x510); pub const pin_select_rxd = p.register(0x514); pub const rxd = p.register(0x518); pub const txd = p.register(0x51c); pub const baud_rate = p.register(0x524); }; const Instance = struct { pub fn write(context: *Instance, buffer: []const u8) Error!usize { _ = context; Uart.writeText(buffer); return buffer.len; } const Error = error{UartError}; const Writer = std.io.Writer(*Instance, Instance.Error, Instance.write); const writer = Writer{ .context = &instance }; var instance = Instance{}; }; var tx_busy: bool = undefined; var tx_queue: [3]u8 = undefined; var tx_queue_read: usize = undefined; var tx_queue_write: usize = undefined; var updater: ?fn () void = undefined; pub fn drainTx() void { while (tx_queue_read != tx_queue_write) { loadTxd(); } } pub fn prepare() void { Pins.of.target_txd.connectOutput(); registers.pin_select_rxd.write(Pins.of.target_rxd.bitPosition(0)); registers.pin_select_txd.write(Pins.of.target_txd.bitPosition(0)); registers.enable.write(0x04); tasks.start_rx.doTask(); tasks.start_tx.doTask(); } pub fn isReadByteReady() bool { return events.rx_ready.eventOccurred(); } pub fn print(comptime fmt: []const u8, args: anytype) void { std.fmt.format(Instance.writer, fmt, args) catch {}; } pub fn loadTxd() void { if (tx_queue_read != tx_queue_write and (!tx_busy or events.tx_ready.eventOccurred())) { events.tx_ready.clearEvent(); registers.txd.write(tx_queue[tx_queue_read]); tx_queue_read = (tx_queue_read + 1) % tx_queue.len; tx_busy = true; if (updater) |an_updater| { an_updater(); } } } pub fn log(comptime fmt: []const u8, args: anytype) void { print(fmt ++ "\n", args); } pub fn writeText(buffer: []const u8) void { for (buffer) |c| { switch (c) { '\n' => { writeByteBlocking('\r'); writeByteBlocking('\n'); }, else => writeByteBlocking(c), } } } pub fn setUpdater(new_updater: fn () void) void { updater = new_updater; } pub fn update() void { loadTxd(); } pub fn writeByteBlocking(byte: u8) void { const next = (tx_queue_write + 1) % tx_queue.len; while (next == tx_queue_read) { loadTxd(); } tx_queue[tx_queue_write] = byte; tx_queue_write = next; loadTxd(); } pub fn readByte() u8 { events.rx_ready.clearEvent(); return @truncate(u8, registers.rxd.read()); } }; const assert = std.debug.assert; const log = Uart.log; const model = @import("system_model.zig"); const std = @import("std");
main.zig
const Texture = @import("Texture.zig"); const Buffer = @import("Buffer.zig"); const RenderBundle = @import("RenderBundle.zig"); const BindGroup = @import("BindGroup.zig"); const RenderPipeline = @import("RenderPipeline.zig"); const IndexFormat = @import("enums.zig").IndexFormat; const RenderBundleEncoder = @This(); /// The type erased pointer to the RenderBundleEncoder implementation /// Equal to c.WGPURenderBundleEncoder for NativeInstance. ptr: *anyopaque, vtable: *const VTable, pub const VTable = struct { reference: fn (ptr: *anyopaque) void, release: fn (ptr: *anyopaque) void, draw: fn ( ptr: *anyopaque, vertex_count: u32, instance_count: u32, first_vertex: u32, first_instance: u32, ) void, drawIndexed: fn ( ptr: *anyopaque, index_count: u32, instance_count: u32, first_index: u32, base_vertex: i32, first_instance: u32, ) void, drawIndexedIndirect: fn (ptr: *anyopaque, indirect_buffer: Buffer, indirect_offset: u64) void, drawIndirect: fn (ptr: *anyopaque, indirect_buffer: Buffer, indirect_offset: u64) void, finish: fn (ptr: *anyopaque, descriptor: *const RenderBundle.Descriptor) RenderBundle, insertDebugMarker: fn (ptr: *anyopaque, marker_label: [*:0]const u8) void, popDebugGroup: fn (ptr: *anyopaque) void, pushDebugGroup: fn (ptr: *anyopaque, group_label: [*:0]const u8) void, setBindGroup: fn (ptr: *anyopaque, group_index: u32, group: BindGroup, dynamic_offsets: []u32) void, setIndexBuffer: fn (ptr: *anyopaque, buffer: Buffer, format: IndexFormat, offset: u64, size: u64) void, setLabel: fn (ptr: *anyopaque, label: [:0]const u8) void, setPipeline: fn (ptr: *anyopaque, pipeline: RenderPipeline) void, setVertexBuffer: fn (ptr: *anyopaque, slot: u32, buffer: Buffer, offset: u64, size: u64) void, }; pub inline fn reference(enc: RenderBundleEncoder) void { enc.vtable.reference(enc.ptr); } pub inline fn release(enc: RenderBundleEncoder) void { enc.vtable.release(enc.ptr); } pub inline fn draw( enc: RenderBundleEncoder, vertex_count: u32, instance_count: u32, first_vertex: u32, first_instance: u32, ) void { enc.vtable.draw(enc.ptr, vertex_count, instance_count, first_vertex, first_instance); } pub inline fn drawIndexed( enc: RenderBundleEncoder, index_count: u32, instance_count: u32, first_index: u32, base_vertex: i32, first_instance: u32, ) void { enc.vtable.drawIndexed(enc.ptr, index_count, instance_count, first_index, base_vertex, first_instance); } pub inline fn drawIndexedIndirect(enc: RenderBundleEncoder, indirect_buffer: Buffer, indirect_offset: u64) void { enc.vtable.drawIndexedIndirect(enc.ptr, indirect_buffer, indirect_offset); } pub inline fn drawIndirect(enc: RenderBundleEncoder, indirect_buffer: Buffer, indirect_offset: u64) void { enc.vtable.drawIndirect(enc.ptr, indirect_buffer, indirect_offset); } pub inline fn finish(enc: RenderBundleEncoder, descriptor: *const RenderBundle.Descriptor) RenderBundle { return enc.vtable.finish(enc.ptr, descriptor); } pub inline fn insertDebugMarker(enc: RenderBundleEncoder, marker_label: [*:0]const u8) void { enc.vtable.insertDebugMarker(enc.ptr, marker_label); } pub inline fn popDebugGroup(enc: RenderBundleEncoder) void { enc.vtable.popDebugGroup(enc.ptr); } pub inline fn pushDebugGroup(enc: RenderBundleEncoder, group_label: [*:0]const u8) void { enc.vtable.pushDebugGroup(enc.ptr, group_label); } pub inline fn setBindGroup( enc: RenderBundleEncoder, group_index: u32, group: BindGroup, dynamic_offsets: []u32, ) void { enc.vtable.setBindGroup(enc.ptr, group_index, group, dynamic_offsets); } pub inline fn setIndexBuffer( enc: RenderBundleEncoder, buffer: Buffer, format: IndexFormat, offset: u64, size: u64, ) void { enc.vtable.setIndexBuffer(enc.ptr, buffer, format, offset, size); } pub inline fn setLabel(enc: RenderBundleEncoder, label: [:0]const u8) void { enc.vtable.setLabel(enc.ptr, label); } pub inline fn setPipeline(enc: RenderBundleEncoder, pipeline: RenderPipeline) void { enc.vtable.setPipeline(enc.ptr, pipeline); } pub inline fn setVertexBuffer( enc: RenderBundleEncoder, slot: u32, buffer: Buffer, offset: u64, size: u64, ) void { enc.vtable.setVertexBuffer(enc.ptr, slot, buffer, offset, size); } pub const Descriptor = struct { label: ?[*:0]const u8 = null, color_formats: []Texture.Format, depth_stencil_format: Texture.Format, sample_count: u32, depth_read_only: bool, stencil_read_only: bool, }; test { _ = VTable; _ = reference; _ = release; _ = draw; _ = drawIndexed; _ = drawIndexedIndirect; _ = drawIndirect; _ = finish; _ = insertDebugMarker; _ = popDebugGroup; _ = pushDebugGroup; _ = setBindGroup; _ = setIndexBuffer; _ = setLabel; _ = setPipeline; _ = setVertexBuffer; _ = Descriptor; }
gpu/src/RenderBundleEncoder.zig
const std = @import("std"); /// An entry in a ini file. Each line that contains non-whitespace text can /// be categorized into a record type. pub const Record = union(enum) { /// A section heading enclosed in `[` and `]`. The brackets are not included. section: [:0]const u8, /// A line that contains a key-value pair separated by `=`. /// Both key and value have the excess whitespace trimmed. /// Both key and value allow escaping with C string syntax. property: KeyValue, /// A line that is either escaped as a C string or contains no `=` enumeration: [:0]const u8, }; pub const KeyValue = struct { key: [:0]const u8, value: [:0]const u8, }; const whitespace = " \r\t\x00"; /// WARNING: /// This function is not a general purpose function but /// requires to be executed on slices of the line_buffer *after* /// the NUL terminator appendix. /// This function will override the character after the slice end, /// so make sure there is one available! fn insertNulTerminator(slice: []const u8) [:0]const u8 { const mut_ptr = @intToPtr([*]u8, @ptrToInt(slice.ptr)); mut_ptr[slice.len] = 0; return mut_ptr[0..slice.len :0]; } pub fn Parser(comptime Reader: type) type { return struct { const Self = @This(); line_buffer: std.ArrayList(u8), reader: Reader, pub fn deinit(self: *Self) void { self.line_buffer.deinit(); self.* = undefined; } pub fn next(self: *Self) !?Record { while (true) { self.reader.readUntilDelimiterArrayList(&self.line_buffer, '\n', 4096) catch |err| switch (err) { error.EndOfStream => { if (self.line_buffer.items.len == 0) return null; }, else => |e| return e, }; try self.line_buffer.append(0); // append guaranteed space for sentinel const line = if (std.mem.indexOfAny(u8, self.line_buffer.items, ";#")) |index| std.mem.trim(u8, self.line_buffer.items[0..index], whitespace) else std.mem.trim(u8, self.line_buffer.items, whitespace); if (line.len == 0) continue; if (std.mem.startsWith(u8, line, "[") and std.mem.endsWith(u8, line, "]")) { return Record{ .section = insertNulTerminator(line[1 .. line.len - 1]) }; } if (std.mem.indexOfScalar(u8, line, '=')) |index| { return Record{ .property = KeyValue{ // note: the key *might* replace the '=' in the slice with 0! .key = insertNulTerminator(std.mem.trim(u8, line[0..index], whitespace)), .value = insertNulTerminator(std.mem.trim(u8, line[index + 1 ..], whitespace)), }, }; } return Record{ .enumeration = insertNulTerminator(line) }; } } }; } /// Returns a new parser that can read the ini structure pub fn parse(allocator: *std.mem.Allocator, reader: anytype) Parser(@TypeOf(reader)) { return Parser(@TypeOf(reader)){ .line_buffer = std.ArrayList(u8).init(allocator), .reader = reader, }; }
src/ini.zig
const std = @import("std"); const arrayIt = @import("src/arrayIterator.zig").iterator; const iterator = @import("src/iterator.zig").iterator; const enumerateIt = @import("src/enumerate.zig").iterator; const TypeId = @import("builtin").TypeId; const mem = std.mem; const info = @import("src/info.zig"); pub fn init(obj: var) info.getType(@TypeOf(obj)) { return info.initType(@TypeOf(obj), obj); } pub fn range(start: var, stop: @TypeOf(start), step: @TypeOf(start)) iterator(@TypeOf(start), enumerateIt(@TypeOf(start))) { return iterator(@TypeOf(start), enumerateIt(@TypeOf(start))){ .nextIt = enumerateIt(@TypeOf(start)).init(start, stop, step) }; } test "Basic Lazy" { var obj = [_]i32{ 0, 1, 2 }; const result = [_]i32{ 0, 2 }; var buf: [2]i32 = undefined; std.debug.assert(std.mem.eql(i32, init(obj[0..]).where(even).toArray(buf[0..]), result[0..])); // Longer format var it = init(obj[0..]).where(even); var i: usize = 0; while (it.next()) |nxt| { std.debug.assert(nxt == result[i]); i += 1; } std.debug.assert(i == 2); std.debug.assert(it.contains(2)); std.debug.assert(it.next().? == 0); var stringBuf: [3]u8 = undefined; std.debug.assert(std.mem.eql(u8, init(obj[0..]).select(u8, toDigitChar).toArray(stringBuf[0..]), "012")); } fn pow(val: i32) i32 { return val * val; } test "Readme-Tests" { const warn = std.debug.warn; const assert = std.debug.assert; var it = range(@as(i32, 0), 100, 1); var whereIt = it.where(even); var selectIt = whereIt.select(i32, pow); var outBuf: [100]i32 = undefined; _ = range(@as(i32, 0), 100, 2).toArray(outBuf[0..]); var i: usize = 0; if (selectIt.next()) |next| { assert(next == pow(outBuf[i])); i += 1; } while (selectIt.next()) |next| { assert(next == pow(outBuf[i])); i += 1; } selectIt.reset(); var buf: [100]i32 = undefined; var array = selectIt.toArray(buf[0..]); i = 0; while (i < array.len) : (i += 1) { assert(array[i] == pow(outBuf[i])); } } test "Basic Concat" { var obj1 = [_]i32{ 0, 1, 2, }; var obj2 = [_]i32{ 3, 4, 5, 6, }; var i: i32 = 0; var it = init(obj1[0..]).concat(&init(obj2[0..])); while (it.next()) |next| { std.debug.assert(next == i); i += 1; } } test "Basic Cast" { var obj = [_]i32{ 0, 1, 2 }; const result = [_]u8{ 0, 1, 2 }; var buf: [3]u8 = undefined; std.debug.assert(std.mem.eql(u8, init(obj[0..]).cast(u8).toArray(buf[0..]), result[0..])); } fn selectManyTest(arr: []const i32) []const i32 { return arr; } test "Select Many" { var obj = [_][]const i32{ ([_]i32{ 0, 1 })[0..], ([_]i32{ 2, 3 })[0..], ([_]i32{ 4, 5 })[0..] }; var i: i32 = 0; var it = init(obj[0..]).selectMany(i32, selectManyTest); while (it.next()) |next| { std.debug.assert(i == next); i += 1; } } test "Reverse" { var buf: [100]i32 = undefined; var obj = [_]i32{ 9, 4, 54, 23, 1 }; var result = [_]i32{ 1, 23, 54, 4, 9 }; std.debug.assert(std.mem.eql(i32, init(obj[0..]).reverse(buf[0..]).toArray(buf[25..]), result[0..])); } test "Sorting" { var buf: [100]i32 = undefined; var obj = [_]i32{ 9, 4, 54, 23, 1 }; var result = [_]i32{ 1, 4, 9, 23, 54 }; std.debug.assert(std.mem.eql(i32, init(obj[0..]).orderByAscending(i32, orderBySimple, buf[0..]).toArray(buf[25..]), result[0..])); } test "Basic Lazy_List" { //var list = std.ArrayList(i32).init(std.debug.global_allocator); //defer list.deinit(); //try list.append(1); //try list.append(2); //try list.append(3); //const result = [_]i32 { 2 }; //const buf: [1]i32 = undefined; //std.debug.assert(std.mem.eql(i32, init(list).where(even).toArray(buf[0..]), result[0..])); } fn orderBySimple(a: i32) i32 { return a; } fn orderByEven(val: i32, other: i32) bool { const evenVal = @rem(val, 2) == 0; const evenOther = @rem(val, 2) == 0; if (evenVal) { if (!evenOther) return true; return val < other; } else { if (evenOther) return false; return val < other; } } fn toDigitChar(val: i32) u8 { return @intCast(u8, val) + '0'; } fn even(val: i32) bool { return @rem(val, 2) == 0; }
index.zig