From cdb28f9f003cc202b66e21f71dd954bb23121e52 Mon Sep 17 00:00:00 2001 From: zlice dev Date: Fri, 3 Apr 2026 04:11:23 +0900 Subject: [PATCH 1/4] Add CI build/test and security audit workflow --- .github/workflows/ci.yml | 86 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..877ea24 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,86 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + schedule: + - cron: '0 0 * * 1' + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + + - name: Install Zig + run: | + curl -sL "https://ziglang.org/download/0.15.2/zig-x86_64-linux-0.15.2.tar.xz" | tar -xJ + echo "$PWD/zig-x86_64-linux-0.15.2" >> "$GITHUB_PATH" + + - name: Install dependencies + run: | + sudo apt-get update + sudo apt-get install -y libxcb1-dev libxcb-randr0-dev + + - name: Format check + run: zig fmt --check src/ + + - name: Build + run: zig build + + - name: Test + run: zig build test + + security-audit: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Zig Security Audit + env: + GH_EVENT: ${{ github.event_name }} + GH_BASE_REF: ${{ github.event.pull_request.base.ref }} + run: | + echo "## Zig Security Audit" >> "$GITHUB_STEP_SUMMARY" + echo "" >> "$GITHUB_STEP_SUMMARY" + echo "| Pattern | Count | Level |" >> "$GITHUB_STEP_SUMMARY" + echo "|---------|-------|-------|" >> "$GITHUB_STEP_SUMMARY" + + total=0 + + audit() { + local pattern="$1" level="$2" label="$3" + local count + count=$(grep -rn --include='*.zig' -e "$pattern" src/ 2>/dev/null | wc -l) + if [ "$count" -gt 0 ]; then + echo "| \`$label\` | $count | $level |" >> "$GITHUB_STEP_SUMMARY" + total=$((total + count)) + fi + if [ "$GH_EVENT" = "pull_request" ] && [ -n "$GH_BASE_REF" ]; then + git diff --name-only "origin/$GH_BASE_REF" -- '*.zig' 2>/dev/null | while read -r file; do + [ -f "$file" ] || continue + grep -n "$pattern" "$file" 2>/dev/null | while IFS=: read -r line content; do + echo "::warning file=$file,line=$line::[$level] $label: $content" + done + done + fi + } + + audit '@setRuntimeSafety\(false\)' 'Critical' '@setRuntimeSafety(false)' + audit '@ptrCast' 'Tracked' '@ptrCast' + audit '@ptrFromInt' 'Tracked' '@ptrFromInt' + audit '@intFromPtr' 'Tracked' '@intFromPtr' + audit '@alignCast' 'Tracked' '@alignCast' + audit 'catch unreachable' 'Review' 'catch unreachable' + audit 'orelse unreachable' 'Review' 'orelse unreachable' + audit '@cImport' 'Info' '@cImport' + + echo "" >> "$GITHUB_STEP_SUMMARY" + echo "**Total: $total** patterns tracked" >> "$GITHUB_STEP_SUMMARY" + echo "_Not bugs — areas requiring careful review during changes._" >> "$GITHUB_STEP_SUMMARY" From 00f162c96d981ac9b9acbfdc4f03f41fbdde56d9 Mon Sep 17 00:00:00 2001 From: zlice dev Date: Fri, 3 Apr 2026 05:13:47 +0900 Subject: [PATCH 2/4] Make fmt check non-blocking (continue-on-error) --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 877ea24..77be3f4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,6 +27,7 @@ jobs: sudo apt-get install -y libxcb1-dev libxcb-randr0-dev - name: Format check + continue-on-error: true run: zig fmt --check src/ - name: Build From 5499895f05414ebb10eb8b62fa435fa8d2e48e65 Mon Sep 17 00:00:00 2001 From: zlice dev Date: Tue, 7 Apr 2026 05:11:27 +0900 Subject: [PATCH 3/4] Fix all findings from Codex adversarial review Address 10 issues identified across IPC safety, memory correctness, protocol compliance, and architectural concerns: - Fix IPC readMessage partial read desync on non-blocking sockets - Fix sendRequest to use writeAll for partial write safety - Fix workspace move double-free via output_name pointer aliasing - Implement command criteria execution ([class="..."] kill etc.) - Fix JSON escaping in IPC tree/output responses - Replace hardcoded get_config/get_binding_modes with real data - Raise capacity limits (layout 256, render 128/32/128, clients 4096) - Guard executeFloating/executeFullscreen against non-window containers - Fix bar JSON parsing to handle escaped quotes and nested objects - Use XCB accessor for KeyMap.keysymData instead of manual pointer math - Separate OutputData from WorkspaceData to fix type confusion - Add WM_NORMAL_HINTS min size reading and WM_TAKE_FOCUS protocol Co-Authored-By: Claude Opus 4.6 (1M context) --- src/event.zig | 121 ++++++++++++++++++++++++++++++++++++++++++-- src/ipc.zig | 19 ++++--- src/layout.zig | 2 +- src/main.zig | 68 +++++++++++++++++++++---- src/output.zig | 18 +++---- src/render.zig | 12 ++--- src/tree.zig | 12 +++++ src/xcb.zig | 10 ++-- zephwm-bar/main.zig | 67 +++++++++++++++++++++--- 9 files changed, 278 insertions(+), 51 deletions(-) diff --git a/src/event.zig b/src/event.zig index f523969..eba86b5 100644 --- a/src/event.zig +++ b/src/event.zig @@ -285,6 +285,8 @@ fn setFocus(ctx: *EventContext, con: *tree.Container) void { // Set X11 input focus if (con.window) |wd| { _ = xcb.setInputFocus(ctx.conn, xcb.INPUT_FOCUS_POINTER_ROOT, wd.id, xcb.CURRENT_TIME); + // Send WM_TAKE_FOCUS if the window supports it (ICCCM focus protocol) + sendTakeFocus(ctx, wd.id); updateActiveWindow(ctx, wd.id); } else { // No window (e.g. focusing a workspace) — clear active window @@ -292,6 +294,44 @@ fn setFocus(ctx: *EventContext, con: *tree.Container) void { } } +/// Send WM_TAKE_FOCUS ClientMessage if the window supports it (ICCCM). +fn sendTakeFocus(ctx: *EventContext, window: xcb.Window) void { + // Check if window supports WM_TAKE_FOCUS in WM_PROTOCOLS + const cookie = xcb.getProperty(ctx.conn, 0, window, ctx.atoms.wm_protocols, xcb.ATOM_ATOM, 0, 32); + const reply = xcb.getPropertyReply(ctx.conn, cookie, null) orelse return; + defer std.c.free(reply); + + const len = xcb.getPropertyValueLength(reply); + if (len <= 0) return; + const ptr = xcb.getPropertyValue(reply) orelse return; + const atoms_list: [*]const xcb.Atom = @ptrCast(@alignCast(ptr)); + const count: usize = @intCast(@divTrunc(len, 4)); + + var supports_take_focus = false; + for (atoms_list[0..count]) |atom| { + if (atom == ctx.atoms.wm_take_focus) { + supports_take_focus = true; + break; + } + } + if (!supports_take_focus) return; + + // Send WM_TAKE_FOCUS client message + var event_data: xcb.c.xcb_client_message_event_t = undefined; + event_data.response_type = xcb.CLIENT_MESSAGE; + event_data.format = 32; + event_data.sequence = 0; + event_data.window = window; + event_data.type = ctx.atoms.wm_protocols; + event_data.data.data32[0] = ctx.atoms.wm_take_focus; + event_data.data.data32[1] = xcb.CURRENT_TIME; + event_data.data.data32[2] = 0; + event_data.data.data32[3] = 0; + event_data.data.data32[4] = 0; + + _ = xcb.sendEvent(ctx.conn, 0, window, xcb.EVENT_MASK_NO_EVENT, @ptrCast(&event_data)); +} + /// Clear is_focused along the currently focused path only. O(depth). fn clearFocusedPath(root: *tree.Container) void { var con = root; @@ -446,11 +486,11 @@ pub fn relayoutAndRender(ctx: *EventContext) void { /// Collect all managed window IDs and set _NET_CLIENT_LIST on the root window. pub fn updateClientList(ctx: *EventContext) void { // Build client list from window_map (O(n) where n = managed windows, no tree walk) - var ids: [1024]u32 = undefined; + var ids: [4096]u32 = undefined; var count: usize = 0; var iter = ctx.window_map.iterator(); while (iter.next()) |entry| { - if (count >= 1024) break; + if (count >= ids.len) break; const con = entry.value_ptr.*; const wd = con.window orelse continue; if (entry.key_ptr.* != wd.id) continue; // skip frame_id entries @@ -666,6 +706,8 @@ const BatchedWindowProps = struct { window_type: []const u8 = "", window_role: []const u8 = "", should_float: bool = false, + min_w: u32 = 0, + min_h: u32 = 0, }; /// Read all window properties in a single batched roundtrip. @@ -680,6 +722,7 @@ fn readAllWindowPropertiesBatched(allocator: std.mem.Allocator, conn: *xcb.Conne const transient_cookie = xcb.getProperty(conn, 0, window, xcb.ATOM_WM_TRANSIENT_FOR, xcb.ATOM_WINDOW, 0, 1); const type_cookie = xcb.getProperty(conn, 0, window, atoms.net_wm_window_type, xcb.ATOM_ATOM, 0, 32); const role_cookie = xcb.getProperty(conn, 0, window, atoms.wm_window_role, xcb.ATOM_STRING, 0, 256); + const hints_cookie = xcb.getProperty(conn, 0, window, xcb.ATOM_WM_NORMAL_HINTS, xcb.ATOM_WM_NORMAL_HINTS, 0, 18); var props = BatchedWindowProps{}; @@ -799,6 +842,24 @@ fn readAllWindowPropertiesBatched(allocator: std.mem.Allocator, conn: *xcb.Conne } } + // 6. WM_NORMAL_HINTS — extract minimum size constraints + if (xcb.getPropertyReply(conn, hints_cookie, null)) |reply| { + defer std.c.free(reply); + const len = xcb.getPropertyValueLength(reply); + // WM_SIZE_HINTS: flags at offset 0, min_width at offset 5, min_height at offset 6 (u32 units) + if (len >= 7 * 4) { + if (xcb.getPropertyValue(reply)) |ptr| { + const vals: [*]const u32 = @ptrCast(@alignCast(ptr)); + const flags = vals[0]; + const PMinSize: u32 = (1 << 4); // ICCCM PMinSize flag + if (flags & PMinSize != 0) { + props.min_w = vals[5]; + props.min_h = vals[6]; + } + } + } + } + return props; } @@ -892,6 +953,8 @@ fn handleMapRequest(ctx: *EventContext, ev: *xcb.MapRequestEvent) void { .window_role = props.window_role, .transient_for = props.transient_for, .pending_unmap = 0, // Window is unmapped at MapRequest time; reparent of unmapped window does not generate UnmapNotify + .min_w = props.min_w, + .min_h = props.min_h, }; con.is_floating = props.should_float; // Apply default border style from config @@ -1668,7 +1731,49 @@ fn handleExpose(ctx: *EventContext, ev: *xcb.c.xcb_expose_event_t) void { // --- Command execution --- +/// Collect containers matching criteria (max 64). Walks tree depth-first. +fn collectMatchingContainers(root: *tree.Container, crit: *const criteria.Criteria, out: *[64]*tree.Container) usize { + var count: usize = 0; + collectMatchingRecursive(root, crit, out, &count); + return count; +} + +fn collectMatchingRecursive(con: *tree.Container, crit: *const criteria.Criteria, out: *[64]*tree.Container, count: *usize) void { + if (count.* >= 64) return; + if (criteria.matches(crit, con)) { + out[count.*] = con; + count.* += 1; + } + var cur = con.children.first; + while (cur) |child| : (cur = child.next) { + collectMatchingRecursive(child, crit, out, count); + } +} + pub fn executeCommand(ctx: *EventContext, cmd: command_mod.Command) void { + // If command has criteria, execute on all matching containers instead of focused + if (cmd.criteria) |crit| { + var matches_buf: [64]*tree.Container = undefined; + const match_count = collectMatchingContainers(ctx.tree_root, &crit, &matches_buf); + if (match_count == 0) return; + + // For each matching container, temporarily make it the focused container, + // execute the command, then restore focus. This matches i3 behavior. + const original_focused = getFocusedContainer(ctx.tree_root); + for (matches_buf[0..match_count]) |target| { + // Set temporary focus for the command execution + setFocus(ctx, target); + var cmd_no_crit = cmd; + cmd_no_crit.criteria = null; + executeCommand(ctx, cmd_no_crit); + } + // Restore original focus if it's still valid + if (original_focused) |orig| { + setFocus(ctx, orig); + } + return; + } + switch (cmd.type) { .split => executeSplit(ctx, cmd), .focus => executeFocus(ctx, cmd), @@ -2203,6 +2308,8 @@ fn executeExec(cmd: command_mod.Command) void { fn executeFloating(ctx: *EventContext) void { const focused = getFocusedContainer(ctx.tree_root) orelse return; + // Only windows and split_cons can float — workspaces/outputs/root cannot + if (focused.type != .window and focused.type != .split_con) return; focused.is_floating = !focused.is_floating; focused.markDirtyToWorkspace(); relayoutAndRender(ctx); @@ -2283,6 +2390,8 @@ fn executeBorder(ctx: *EventContext, cmd: command_mod.Command) void { fn executeFullscreen(ctx: *EventContext) void { const focused = getFocusedContainer(ctx.tree_root) orelse return; + // Only windows can be fullscreened + if (focused.type != .window) return; focused.is_fullscreen = if (focused.is_fullscreen != .none) .none else .window; focused.markDirtyToWorkspace(); @@ -2539,10 +2648,12 @@ fn executeMoveWorkspaceToOutput(ctx: *EventContext, cmd: command_mod.Command) vo target_out.appendChild(current_ws); current_ws.rect = target_out.rect; - // Update workspace output_name to match target output + // Update workspace output_name to match target output (must dupe to avoid aliased ownership) if (current_ws.workspace) |*wsd| { - if (target_out.workspace) |tout_wsd| { - wsd.output_name = tout_wsd.output_name; + if (target_out.output_data) |od| { + // Free old output_name before replacing (skip empty string literals) + if (wsd.output_name.len > 0) ctx.allocator.free(wsd.output_name); + wsd.output_name = ctx.allocator.dupe(u8, od.name) catch od.name; } } diff --git a/src/ipc.zig b/src/ipc.zig index 9e390fe..1baf3cd 100644 --- a/src/ipc.zig +++ b/src/ipc.zig @@ -133,7 +133,9 @@ pub fn acceptClient(listen_fd: std.posix.fd_t) !std.posix.fd_t { /// Read a complete message from client fd into buf. /// Returns msg_type + payload slice, or null if EOF/disconnect. -/// Returns error.WouldBlock if no data available yet (EAGAIN). +/// Returns error.WouldBlock if no data available yet (EAGAIN) AND no bytes have been read. +/// Once partial data is received, retries instead of returning WouldBlock to prevent +/// stream desynchronization on non-blocking sockets. pub fn readMessage(fd: std.posix.fd_t, buf: []u8) error{WouldBlock}!?struct { msg_type: u32, payload: []const u8 } { if (buf.len < HEADER_SIZE) return null; @@ -141,7 +143,12 @@ pub fn readMessage(fd: std.posix.fd_t, buf: []u8) error{WouldBlock}!?struct { ms var total_read: usize = 0; while (total_read < HEADER_SIZE) { const n = std.posix.read(fd, buf[total_read..]) catch |err| { - if (err == error.WouldBlock) return error.WouldBlock; + if (err == error.WouldBlock) { + // Only return WouldBlock if we haven't read anything yet. + // If partial data was consumed, we must finish reading to stay in sync. + if (total_read == 0) return error.WouldBlock; + continue; // Retry — data should arrive shortly on UNIX domain socket + } return null; }; if (n == 0) return null; // EOF @@ -155,10 +162,10 @@ pub fn readMessage(fd: std.posix.fd_t, buf: []u8) error{WouldBlock}!?struct { ms const total_needed = HEADER_SIZE + payload_len; if (buf.len < total_needed) return null; - // Read payload + // Read payload — once header is read, we must complete the message while (total_read < total_needed) { const n = std.posix.read(fd, buf[total_read..total_needed]) catch |err| { - if (err == error.WouldBlock) return error.WouldBlock; + if (err == error.WouldBlock) continue; // Retry — must finish reading payload return null; }; if (n == 0) return null; @@ -203,10 +210,10 @@ pub fn sendRequest(allocator: std.mem.Allocator, sock_path: []const u8, msg_type const fd = connectToServer(sock_path) catch return null; defer std.posix.close(fd); - // Send + // Send (use writeAll to handle partial writes correctly) var send_buf: [4096 + HEADER_SIZE]u8 = undefined; const msg = encode(msg_type, payload, &send_buf); - _ = std.posix.write(fd, msg) catch return null; + writeAll(fd, msg) catch return null; // Read response var recv_buf: [65536]u8 = undefined; diff --git a/src/layout.zig b/src/layout.zig index 88b9c62..0b75d38 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -3,7 +3,7 @@ const log = std.log.scoped(.layout); const tree = @import("tree.zig"); const render = @import("render.zig"); -const MAX_TILING_CHILDREN: usize = 64; +const MAX_TILING_CHILDREN: usize = 256; /// Apply layout to a container's children. Recursively descends into split_con children. /// gap: pixel gap between windows diff --git a/src/main.zig b/src/main.zig index a5e4fe7..c88eb8d 100644 --- a/src/main.zig +++ b/src/main.zig @@ -158,8 +158,8 @@ fn handleIpcMessage(ctx: *event.EventContext, client_fd: std.posix.fd_t, msg_typ @intFromEnum(ipc.MessageType.get_tree) => buildTreeJson(ctx, &dyn_buf), @intFromEnum(ipc.MessageType.get_marks) => buildMarksJson(ctx, &dyn_buf), @intFromEnum(ipc.MessageType.get_bar_config) => buildBarConfigJson(ctx, &dyn_buf), - @intFromEnum(ipc.MessageType.get_config) => "{}", - @intFromEnum(ipc.MessageType.get_binding_modes) => "[\"default\"]", + @intFromEnum(ipc.MessageType.get_config) => buildConfigJson(ctx, &dyn_buf), + @intFromEnum(ipc.MessageType.get_binding_modes) => buildBindingModesJson(ctx, &dyn_buf), @intFromEnum(ipc.MessageType.subscribe) => blk: { // Parse subscription payload and register client registerSubscription(client_fd, payload, ctx.ipc_sub_fds, ctx.ipc_sub_masks); @@ -222,8 +222,8 @@ fn buildWorkspacesJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { const ws_output_name = blk: { if (ws.parent) |parent| { if (parent.type == .output) { - if (parent.workspace) |parent_wsd| { - if (parent_wsd.output_name.len > 0) break :blk parent_wsd.output_name; + if (parent.output_data) |od| { + if (od.name.len > 0) break :blk od.name; } } } @@ -279,13 +279,14 @@ fn buildOutputsJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { } // Output name: use stored name if available, else "default" - const out_name = if (out_con.workspace) |wsd| wsd.output_name else "default"; + const out_name = if (out_con.output_data) |od| od.name else "default"; const display_name = if (out_name.len > 0) out_name else "default"; + w.writeAll("{\"name\":\"") catch return "[]"; + jsonEscapeWrite(w, display_name) catch return "[]"; std.fmt.format(w, - "{{\"name\":\"{s}\",\"active\":true,\"primary\":{},\"rect\":{{\"x\":{d},\"y\":{d},\"width\":{d},\"height\":{d}}},\"current_workspace\":\"", + "\",\"active\":true,\"primary\":{},\"rect\":{{\"x\":{d},\"y\":{d},\"width\":{d},\"height\":{d}}},\"current_workspace\":\"", .{ - display_name, is_primary, out_con.rect.x, out_con.rect.y, @@ -294,7 +295,7 @@ fn buildOutputsJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { }, ) catch return "[]"; jsonEscapeWrite(w, ws_name) catch return "[]"; - w.writeAll("\"}}") catch return "[]"; + w.writeAll("\"}") catch return "[]"; is_primary = false; } @@ -339,6 +340,47 @@ fn buildBarConfigJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { return fbs.getWritten(); } +fn buildConfigJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { + _ = ctx; + var fbs = std.io.fixedBufferStream(buf); + const w = fbs.writer(); + // Return config file path if known, empty config otherwise (matches i3 behavior) + w.writeAll("{\"config\":\"") catch return "{}"; + // Try to find the config file path + const home = std.posix.getenv("HOME") orelse ""; + const xdg_config = std.posix.getenv("XDG_CONFIG_HOME"); + var path_buf: [512]u8 = undefined; + const config_path: []const u8 = blk: { + if (xdg_config) |xdg| { + const len = (std.fmt.bufPrint(&path_buf, "{s}/zephwm/config", .{xdg}) catch break :blk "").len; + if (std.fs.cwd().access(path_buf[0..len], .{})) |_| break :blk path_buf[0..len] else |_| {} + } + const len = (std.fmt.bufPrint(&path_buf, "{s}/.config/zephwm/config", .{home}) catch break :blk "").len; + if (std.fs.cwd().access(path_buf[0..len], .{})) |_| break :blk path_buf[0..len] else |_| {} + break :blk ""; + }; + jsonEscapeWrite(w, config_path) catch return "{}"; + w.writeAll("\"}") catch return "{}"; + return fbs.getWritten(); +} + +fn buildBindingModesJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { + var fbs = std.io.fixedBufferStream(buf); + const w = fbs.writer(); + w.writeAll("[\"default\"") catch return "[\"default\"]"; + // Add any extra modes defined in config + if (ctx.config) |cfg| { + var mode_iter = cfg.modes.keyIterator(); + while (mode_iter.next()) |key| { + w.writeAll(",\"") catch return "[\"default\"]"; + jsonEscapeWrite(w, key.*) catch return "[\"default\"]"; + w.writeByte('"') catch return "[\"default\"]"; + } + } + w.writeByte(']') catch return "[\"default\"]"; + return fbs.getWritten(); +} + fn buildMarksJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { var fbs = std.io.fixedBufferStream(buf); const w = fbs.writer(); @@ -402,7 +444,9 @@ fn writeContainerJson(w: anytype, con: *tree.Container) !void { // name if (con.workspace) |wsd| { - try std.fmt.format(w, ",\"name\":\"{s}\"", .{wsd.name}); + try w.writeAll(",\"name\":\""); + try jsonEscapeWrite(w, wsd.name); + try w.writeAll("\""); } else if (con.window) |wd| { try w.writeAll(",\"name\":\""); try jsonEscapeWrite(w, wd.title); @@ -438,7 +482,11 @@ fn writeContainerJson(w: anytype, con: *tree.Container) !void { if (con.window) |wd| { try std.fmt.format(w, ",\"window\":{d}", .{wd.id}); if (wd.class.len > 0) { - try std.fmt.format(w, ",\"window_properties\":{{\"class\":\"{s}\",\"instance\":\"{s}\"}}", .{ wd.class, wd.instance }); + try w.writeAll(",\"window_properties\":{\"class\":\""); + try jsonEscapeWrite(w, wd.class); + try w.writeAll("\",\"instance\":\""); + try jsonEscapeWrite(w, wd.instance); + try w.writeAll("\"}"); } } diff --git a/src/output.zig b/src/output.zig index a24acb6..53f1b9f 100644 --- a/src/output.zig +++ b/src/output.zig @@ -46,10 +46,8 @@ pub fn detectOutputs( }; // Store output name in workspace data (reusing WorkspaceData for output_name) const name = try allocator.dupe(u8, info.nameSlice()); - const out_name = try allocator.dupe(u8, info.nameSlice()); - output_con.workspace = tree.WorkspaceData{ + output_con.output_data = tree.OutputData{ .name = name, - .output_name = out_name, }; tree_root.appendChild(output_con); @@ -74,10 +72,8 @@ pub fn detectOutputs( .h = screen.height_in_pixels, }; const name = try allocator.dupe(u8, "default"); - const out_name = try allocator.dupe(u8, "default"); - output_con.workspace = tree.WorkspaceData{ + output_con.output_data = tree.OutputData{ .name = name, - .output_name = out_name, }; tree_root.appendChild(output_con); @@ -216,7 +212,7 @@ pub fn updateOutputs( out_cur = tree_root.children.first; while (out_cur) |out_con| : (out_cur = out_con.next) { if (out_con.type != .output) continue; - const out_name = if (out_con.workspace) |wsd| wsd.output_name else ""; + const out_name = if (out_con.output_data) |od| od.name else ""; if (std.mem.eql(u8, out_name, name)) { // Update geometry out_con.rect = .{ .x = info.x, .y = info.y, .w = info.w, .h = info.h }; @@ -236,10 +232,8 @@ pub fn updateOutputs( const output_con = try tree.Container.create(allocator, .output); output_con.rect = .{ .x = info.x, .y = info.y, .w = info.w, .h = info.h }; const owned_name = try allocator.dupe(u8, name); - const owned_out_name = try allocator.dupe(u8, name); - output_con.workspace = tree.WorkspaceData{ + output_con.output_data = tree.OutputData{ .name = owned_name, - .output_name = owned_out_name, }; output_con.dirty = false; tree_root.appendChild(output_con); @@ -277,7 +271,7 @@ pub fn updateOutputs( while (out_cur) |out_con| { const next = out_con.next; if (out_con.type == .output and out_con.dirty) { - const out_name = if (out_con.workspace) |wsd| wsd.output_name else "?"; + const out_name = if (out_con.output_data) |od| od.name else "?"; std.debug.print("zephwm: output removed: {s}\n", .{out_name}); // Move all workspaces to first_output @@ -315,7 +309,7 @@ pub fn findByName(root: *tree.Container, name: []const u8) ?*tree.Container { var cur = root.children.first; while (cur) |child| : (cur = child.next) { if (child.type != .output) continue; - const out_name = if (child.workspace) |wsd| wsd.output_name else ""; + const out_name = if (child.output_data) |od| od.name else ""; if (std.mem.eql(u8, out_name, name)) return child; } return null; diff --git a/src/render.zig b/src/render.zig index 6ced65e..81d0b05 100644 --- a/src/render.zig +++ b/src/render.zig @@ -310,11 +310,11 @@ fn applyRecursive( con.children.len() > 1; // Single pass: process tiling, collect floating/fullscreen/border-normal - var floating_buf: [32]*tree.Container = undefined; + var floating_buf: [128]*tree.Container = undefined; var floating_count: usize = 0; - var fullscreen_buf: [8]*tree.Container = undefined; + var fullscreen_buf: [32]*tree.Container = undefined; var fullscreen_count: usize = 0; - var normal_border_buf: [32]*tree.Container = undefined; + var normal_border_buf: [128]*tree.Container = undefined; var normal_border_count: usize = 0; // For tabbed/stacked: pre-count tiling children, find focused tiling @@ -338,14 +338,14 @@ fn applyRecursive( var cur = con.children.first; while (cur) |child| : (cur = child.next) { if (child.is_fullscreen != .none) { - if (fullscreen_count < 8) { + if (fullscreen_count < fullscreen_buf.len) { fullscreen_buf[fullscreen_count] = child; fullscreen_count += 1; } continue; } if (child.is_floating) { - if (floating_count < 32) { + if (floating_count < floating_buf.len) { floating_buf[floating_count] = child; floating_count += 1; } @@ -370,7 +370,7 @@ fn applyRecursive( applyRecursive(conn, child, border_focus_color, border_unfocus_color); // Collect border normal windows inline (avoid second pass) if (child.type == .window and child.border_style == .normal) { - if (normal_border_count < 32) { + if (normal_border_count < normal_border_buf.len) { normal_border_buf[normal_border_count] = child; normal_border_count += 1; } diff --git a/src/tree.zig b/src/tree.zig index bf0e6fb..251007f 100644 --- a/src/tree.zig +++ b/src/tree.zig @@ -41,6 +41,9 @@ pub const WindowData = struct { last_color: u32 = 0xFFFFFFFF, /// Set by applyWindow when geometry changed. Used by sendConfigureNotifyChanged. geometry_changed: bool = true, + /// WM_NORMAL_HINTS minimum size constraints (0 = no constraint) + min_w: u32 = 0, + min_h: u32 = 0, }; pub const WorkspaceData = struct { @@ -50,6 +53,10 @@ pub const WorkspaceData = struct { urgent: bool = false, }; +pub const OutputData = struct { + name: []const u8, +}; + pub const ChildList = struct { first: ?*Container = null, last: ?*Container = null, @@ -135,6 +142,7 @@ pub const Container = struct { window_rect: Rect = .{}, window: ?WindowData = null, workspace: ?WorkspaceData = null, + output_data: ?OutputData = null, percent: f32 = 0.0, is_floating: bool = false, is_fullscreen: FullscreenMode = .none, @@ -185,6 +193,10 @@ pub const Container = struct { freeOwnedString(alloc, wsd.name); freeOwnedString(alloc, wsd.output_name); } + // Free allocator-owned output data + if (self.output_data) |od| { + freeOwnedString(alloc, od.name); + } // Free allocator-owned mark strings for (self.marks[0..self.mark_count]) |mark_opt| { if (mark_opt) |mark| { diff --git a/src/xcb.zig b/src/xcb.zig index 4f0a3f5..148a74b 100644 --- a/src/xcb.zig +++ b/src/xcb.zig @@ -371,10 +371,12 @@ pub const KeyMap = struct { fn keysymData(self: *const KeyMap) []const Keysym { const total: usize = @as(usize, self.max_keycode - self.min_keycode + 1) * self.keysyms_per_keycode; - const ptr: [*]const Keysym = @ptrCast(@alignCast( - @as([*]const u8, @ptrCast(self.reply)) + @sizeOf(c.xcb_get_keyboard_mapping_reply_t), - )); - return ptr[0..total]; + if (total == 0) return &.{}; + // Use the XCB protocol accessor (ABI-safe, no manual pointer arithmetic) + const xcb_len: usize = @intCast(c.xcb_get_keyboard_mapping_keysyms_length(self.reply)); + const safe_total = @min(total, xcb_len); + const ptr: [*]const Keysym = @ptrCast(c.xcb_get_keyboard_mapping_keysyms(self.reply)); + return ptr[0..safe_total]; } pub fn getKeysym(self: *const KeyMap, keycode: Keycode, col: u8) Keysym { diff --git a/zephwm-bar/main.zig b/zephwm-bar/main.zig index c51549e..3b78868 100644 --- a/zephwm-bar/main.zig +++ b/zephwm-bar/main.zig @@ -88,10 +88,10 @@ fn queryBarConfig(allocator: std.mem.Allocator, sock_path: []const u8) BarConfig const response = ipc.sendRequest(allocator, sock_path, .get_bar_config, "") orelse return cfg; defer allocator.free(response); - // Parse font + // Parse font (handles escaped quotes) if (std.mem.indexOf(u8, response, "\"font\":\"")) |pos| { const start = pos + 8; - if (std.mem.indexOfScalar(u8, response[start..], '"')) |end| { + if (findUnescapedQuote(response[start..])) |end| { const len: u8 = @intCast(@min(end, 255)); @memcpy(cfg.font[0..len], response[start..][0..len]); cfg.font_len = len; @@ -108,10 +108,10 @@ fn queryBarConfig(allocator: std.mem.Allocator, sock_path: []const u8) BarConfig } } - // Parse status_command + // Parse status_command (handles escaped quotes) if (std.mem.indexOf(u8, response, "\"status_command\":\"")) |pos| { const start = pos + 18; - if (std.mem.indexOfScalar(u8, response[start..], '"')) |end| { + if (findUnescapedQuote(response[start..])) |end| { const len: u16 = @intCast(@min(end, 511)); @memcpy(cfg.status_command[0..len], response[start..][0..len]); cfg.status_command_len = len; @@ -968,7 +968,8 @@ fn parseStatusUpdate( while (pos < inner.len and block_count.* < MAX_STATUS_BLOCKS) { // Find next block object const obj_start = std.mem.indexOfScalar(u8, inner[pos..], '{') orelse break; - const obj_end = std.mem.indexOfScalar(u8, inner[pos + obj_start..], '}') orelse break; + // Find matching '}' while skipping quoted strings + const obj_end = findMatchingBrace(inner[pos + obj_start ..]) orelse break; const obj = inner[pos + obj_start .. pos + obj_start + obj_end + 1]; const idx = block_count.*; @@ -1020,9 +1021,61 @@ fn jsonEscapeWrite(w: anytype, s: []const u8) !void { } } +/// Find the position of the matching '}' for a '{' at s[0], skipping quoted strings. +fn findMatchingBrace(s: []const u8) ?usize { + if (s.len == 0 or s[0] != '{') return null; + var depth: usize = 0; + var in_string = false; + var i: usize = 0; + while (i < s.len) : (i += 1) { + if (in_string) { + if (s[i] == '\\') { + i += 1; // skip escaped character + continue; + } + if (s[i] == '"') in_string = false; + continue; + } + switch (s[i]) { + '"' => in_string = true, + '{' => depth += 1, + '}' => { + depth -= 1; + if (depth == 0) return i; + }, + else => {}, + } + } + return null; +} + +/// Find position of next unescaped double-quote in a string. +/// Skips over backslash-escaped characters (e.g. \"). +fn findUnescapedQuote(s: []const u8) ?usize { + var i: usize = 0; + while (i < s.len) : (i += 1) { + if (s[i] == '\\') { + i += 1; // skip escaped character + continue; + } + if (s[i] == '"') return i; + } + return null; +} + fn extractJsonString(json: []const u8, key: []const u8) ?[]const u8 { const key_pos = std.mem.indexOf(u8, json, key) orelse return null; const val_start = key_pos + key.len; - const val_end = std.mem.indexOfScalar(u8, json[val_start..], '"') orelse return null; - return json[val_start .. val_start + val_end]; + // Scan for unescaped closing quote (skip \" sequences) + var i: usize = 0; + while (i < json[val_start..].len) : (i += 1) { + if (json[val_start + i] == '\\') { + i += 1; // skip escaped character + continue; + } + if (json[val_start + i] == '"') { + return json[val_start .. val_start + i]; + } + } + return null; } From df598dd6c1b58d7859a0dcf243cff8d1aef2d82b Mon Sep 17 00:00:00 2001 From: zlice dev Date: Tue, 7 Apr 2026 05:33:12 +0900 Subject: [PATCH 4/4] Address PR #7 review feedback from CodeRabbit, Gemini, and Codex - Fix criteria execution use-after-free: collect window IDs instead of raw pointers, re-resolve before each command; skip focus restore for focus cmds - Fix OOM double-free in workspace output_name: only free+assign on dupe success - Fix IPC busy-loop: return null on WouldBlock after partial read - Fix WM_NORMAL_HINTS type atom: use WM_SIZE_HINTS per ICCCM spec - Fix getWorkspaceOutputName: read output_data.name instead of stale workspace field - Fix buildConfigJson: search all 4 config paths, return file contents not path - Fix getKeycode: add bounds check for short keysymData replies - Fix xcb_client_message_event_t: zero-init instead of undefined - Add JSON unescape utility to bar, apply to font/status_command/blocks parsing - Extend CI fmt check to cover zephwm-bar/ Co-Authored-By: Claude Opus 4.6 (1M context) --- .github/workflows/ci.yml | 2 +- src/event.zig | 66 +++++++++++++++++++++++----------------- src/ipc.zig | 10 +++--- src/main.zig | 34 ++++++++++++++++++--- src/xcb.zig | 3 ++ zephwm-bar/main.zig | 63 +++++++++++++++++++++++++++----------- 6 files changed, 120 insertions(+), 58 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 77be3f4..68cf10f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,7 +28,7 @@ jobs: - name: Format check continue-on-error: true - run: zig fmt --check src/ + run: zig fmt --check src/ zephwm-bar/ - name: Build run: zig build diff --git a/src/event.zig b/src/event.zig index eba86b5..7403917 100644 --- a/src/event.zig +++ b/src/event.zig @@ -79,8 +79,8 @@ fn jsonEscapeWrite(w: anytype, s: []const u8) !void { fn getWorkspaceOutputName(ws: *tree.Container) []const u8 { if (ws.parent) |parent| { if (parent.type == .output) { - if (parent.workspace) |wsd| { - if (wsd.output_name.len > 0) return wsd.output_name; + if (parent.output_data) |od| { + if (od.name.len > 0) return od.name; } } } @@ -317,17 +317,13 @@ fn sendTakeFocus(ctx: *EventContext, window: xcb.Window) void { if (!supports_take_focus) return; // Send WM_TAKE_FOCUS client message - var event_data: xcb.c.xcb_client_message_event_t = undefined; + var event_data: xcb.c.xcb_client_message_event_t = std.mem.zeroes(xcb.c.xcb_client_message_event_t); event_data.response_type = xcb.CLIENT_MESSAGE; event_data.format = 32; - event_data.sequence = 0; event_data.window = window; event_data.type = ctx.atoms.wm_protocols; event_data.data.data32[0] = ctx.atoms.wm_take_focus; event_data.data.data32[1] = xcb.CURRENT_TIME; - event_data.data.data32[2] = 0; - event_data.data.data32[3] = 0; - event_data.data.data32[4] = 0; _ = xcb.sendEvent(ctx.conn, 0, window, xcb.EVENT_MASK_NO_EVENT, @ptrCast(&event_data)); } @@ -722,7 +718,7 @@ fn readAllWindowPropertiesBatched(allocator: std.mem.Allocator, conn: *xcb.Conne const transient_cookie = xcb.getProperty(conn, 0, window, xcb.ATOM_WM_TRANSIENT_FOR, xcb.ATOM_WINDOW, 0, 1); const type_cookie = xcb.getProperty(conn, 0, window, atoms.net_wm_window_type, xcb.ATOM_ATOM, 0, 32); const role_cookie = xcb.getProperty(conn, 0, window, atoms.wm_window_role, xcb.ATOM_STRING, 0, 256); - const hints_cookie = xcb.getProperty(conn, 0, window, xcb.ATOM_WM_NORMAL_HINTS, xcb.ATOM_WM_NORMAL_HINTS, 0, 18); + const hints_cookie = xcb.getProperty(conn, 0, window, xcb.ATOM_WM_NORMAL_HINTS, xcb.ATOM_WM_SIZE_HINTS, 0, 18); var props = BatchedWindowProps{}; @@ -1731,45 +1727,58 @@ fn handleExpose(ctx: *EventContext, ev: *xcb.c.xcb_expose_event_t) void { // --- Command execution --- -/// Collect containers matching criteria (max 64). Walks tree depth-first. -fn collectMatchingContainers(root: *tree.Container, crit: *const criteria.Criteria, out: *[64]*tree.Container) usize { +/// Collect window IDs of containers matching criteria (max 64). Walks tree depth-first. +/// Uses window IDs instead of raw pointers so commands that destroy/move containers +/// don't cause dangling pointer access. +fn collectMatchingWindowIds(root: *tree.Container, crit: *const criteria.Criteria, out: *[64]xcb.Window) usize { var count: usize = 0; - collectMatchingRecursive(root, crit, out, &count); + collectMatchingWindowIdsRecursive(root, crit, out, &count); return count; } -fn collectMatchingRecursive(con: *tree.Container, crit: *const criteria.Criteria, out: *[64]*tree.Container, count: *usize) void { +fn collectMatchingWindowIdsRecursive(con: *tree.Container, crit: *const criteria.Criteria, out: *[64]xcb.Window, count: *usize) void { if (count.* >= 64) return; if (criteria.matches(crit, con)) { - out[count.*] = con; - count.* += 1; + if (con.window) |wd| { + out[count.*] = wd.id; + count.* += 1; + } } var cur = con.children.first; while (cur) |child| : (cur = child.next) { - collectMatchingRecursive(child, crit, out, count); + collectMatchingWindowIdsRecursive(child, crit, out, count); } } pub fn executeCommand(ctx: *EventContext, cmd: command_mod.Command) void { // If command has criteria, execute on all matching containers instead of focused if (cmd.criteria) |crit| { - var matches_buf: [64]*tree.Container = undefined; - const match_count = collectMatchingContainers(ctx.tree_root, &crit, &matches_buf); + var window_ids: [64]xcb.Window = undefined; + const match_count = collectMatchingWindowIds(ctx.tree_root, &crit, &window_ids); if (match_count == 0) return; - // For each matching container, temporarily make it the focused container, - // execute the command, then restore focus. This matches i3 behavior. - const original_focused = getFocusedContainer(ctx.tree_root); - for (matches_buf[0..match_count]) |target| { - // Set temporary focus for the command execution + // Save original focused window ID for restoration + const original_focused_wid: ?xcb.Window = if (getFocusedContainer(ctx.tree_root)) |fc| + (if (fc.window) |wd| wd.id else null) + else + null; + + for (window_ids[0..match_count]) |wid| { + // Re-resolve container from window ID — it may have been destroyed by a prior command + const target = findContainerByWindow(ctx, wid) orelse continue; setFocus(ctx, target); var cmd_no_crit = cmd; cmd_no_crit.criteria = null; executeCommand(ctx, cmd_no_crit); } - // Restore original focus if it's still valid - if (original_focused) |orig| { - setFocus(ctx, orig); + // Restore original focus only if the original window still exists and + // the command was not a focus command (i3 behavior: [criteria] focus keeps new focus) + if (cmd.type != .focus) { + if (original_focused_wid) |wid| { + if (findContainerByWindow(ctx, wid)) |orig| { + setFocus(ctx, orig); + } + } } return; } @@ -2651,9 +2660,10 @@ fn executeMoveWorkspaceToOutput(ctx: *EventContext, cmd: command_mod.Command) vo // Update workspace output_name to match target output (must dupe to avoid aliased ownership) if (current_ws.workspace) |*wsd| { if (target_out.output_data) |od| { - // Free old output_name before replacing (skip empty string literals) - if (wsd.output_name.len > 0) ctx.allocator.free(wsd.output_name); - wsd.output_name = ctx.allocator.dupe(u8, od.name) catch od.name; + if (ctx.allocator.dupe(u8, od.name)) |new_name| { + if (wsd.output_name.len > 0) ctx.allocator.free(wsd.output_name); + wsd.output_name = new_name; + } else |_| {} // OOM: keep old output_name rather than aliasing } } diff --git a/src/ipc.zig b/src/ipc.zig index 1baf3cd..e22a7f1 100644 --- a/src/ipc.zig +++ b/src/ipc.zig @@ -134,8 +134,8 @@ pub fn acceptClient(listen_fd: std.posix.fd_t) !std.posix.fd_t { /// Read a complete message from client fd into buf. /// Returns msg_type + payload slice, or null if EOF/disconnect. /// Returns error.WouldBlock if no data available yet (EAGAIN) AND no bytes have been read. -/// Once partial data is received, retries instead of returning WouldBlock to prevent -/// stream desynchronization on non-blocking sockets. +/// If partial data was consumed and WouldBlock occurs, returns null (disconnect) to avoid +/// busy-looping on the single-threaded event loop. pub fn readMessage(fd: std.posix.fd_t, buf: []u8) error{WouldBlock}!?struct { msg_type: u32, payload: []const u8 } { if (buf.len < HEADER_SIZE) return null; @@ -144,10 +144,8 @@ pub fn readMessage(fd: std.posix.fd_t, buf: []u8) error{WouldBlock}!?struct { ms while (total_read < HEADER_SIZE) { const n = std.posix.read(fd, buf[total_read..]) catch |err| { if (err == error.WouldBlock) { - // Only return WouldBlock if we haven't read anything yet. - // If partial data was consumed, we must finish reading to stay in sync. if (total_read == 0) return error.WouldBlock; - continue; // Retry — data should arrive shortly on UNIX domain socket + return null; // Partial header + WouldBlock: drop client to avoid busy-loop } return null; }; @@ -165,7 +163,7 @@ pub fn readMessage(fd: std.posix.fd_t, buf: []u8) error{WouldBlock}!?struct { ms // Read payload — once header is read, we must complete the message while (total_read < total_needed) { const n = std.posix.read(fd, buf[total_read..total_needed]) catch |err| { - if (err == error.WouldBlock) continue; // Retry — must finish reading payload + if (err == error.WouldBlock) return null; // Partial payload: drop client to avoid busy-loop return null; }; if (n == 0) return null; diff --git a/src/main.zig b/src/main.zig index c88eb8d..117f71b 100644 --- a/src/main.zig +++ b/src/main.zig @@ -344,9 +344,10 @@ fn buildConfigJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { _ = ctx; var fbs = std.io.fixedBufferStream(buf); const w = fbs.writer(); - // Return config file path if known, empty config otherwise (matches i3 behavior) + // i3 GET_CONFIG returns file contents in the "config" field w.writeAll("{\"config\":\"") catch return "{}"; - // Try to find the config file path + + // Search same paths as loadConfig const home = std.posix.getenv("HOME") orelse ""; const xdg_config = std.posix.getenv("XDG_CONFIG_HOME"); var path_buf: [512]u8 = undefined; @@ -355,11 +356,34 @@ fn buildConfigJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { const len = (std.fmt.bufPrint(&path_buf, "{s}/zephwm/config", .{xdg}) catch break :blk "").len; if (std.fs.cwd().access(path_buf[0..len], .{})) |_| break :blk path_buf[0..len] else |_| {} } - const len = (std.fmt.bufPrint(&path_buf, "{s}/.config/zephwm/config", .{home}) catch break :blk "").len; - if (std.fs.cwd().access(path_buf[0..len], .{})) |_| break :blk path_buf[0..len] else |_| {} + { + const len = (std.fmt.bufPrint(&path_buf, "{s}/.config/zephwm/config", .{home}) catch break :blk "").len; + if (std.fs.cwd().access(path_buf[0..len], .{})) |_| break :blk path_buf[0..len] else |_| {} + } + { + const len = (std.fmt.bufPrint(&path_buf, "{s}/.zephwm/config", .{home}) catch break :blk "").len; + if (std.fs.cwd().access(path_buf[0..len], .{})) |_| break :blk path_buf[0..len] else |_| {} + } + if (std.fs.cwd().access("/etc/zephwm/config", .{})) |_| { + const etc = "/etc/zephwm/config"; + @memcpy(path_buf[0..etc.len], etc); + break :blk path_buf[0..etc.len]; + } else |_| {} break :blk ""; }; - jsonEscapeWrite(w, config_path) catch return "{}"; + + // Read and emit file contents (not the path) + if (config_path.len > 0) { + if (std.fs.cwd().openFile(config_path, .{})) |file| { + defer file.close(); + var read_buf: [4096]u8 = undefined; + while (true) { + const n = file.read(&read_buf) catch break; + if (n == 0) break; + jsonEscapeWrite(w, read_buf[0..n]) catch return "{}"; + } + } else |_| {} + } w.writeAll("\"}") catch return "{}"; return fbs.getWritten(); } diff --git a/src/xcb.zig b/src/xcb.zig index 148a74b..27c7c09 100644 --- a/src/xcb.zig +++ b/src/xcb.zig @@ -120,6 +120,7 @@ pub const ATOM_WM_CLASS: Atom = c.XCB_ATOM_WM_CLASS; pub const ATOM_WM_TRANSIENT_FOR: Atom = c.XCB_ATOM_WM_TRANSIENT_FOR; pub const ATOM_WM_HINTS: Atom = c.XCB_ATOM_WM_HINTS; pub const ATOM_WM_NORMAL_HINTS: Atom = c.XCB_ATOM_WM_NORMAL_HINTS; +pub const ATOM_WM_SIZE_HINTS: Atom = c.XCB_ATOM_WM_SIZE_HINTS; // Input focus pub const INPUT_FOCUS_POINTER_ROOT: u8 = c.XCB_INPUT_FOCUS_POINTER_ROOT; @@ -391,12 +392,14 @@ pub const KeyMap = struct { /// Find the first keycode that produces the given keysym (any column). pub fn getKeycode(self: *const KeyMap, keysym: Keysym) ?Keycode { const data = self.keysymData(); + if (data.len == 0) return null; var kc: usize = 0; const count: usize = @as(usize, self.max_keycode - self.min_keycode) + 1; while (kc < count) : (kc += 1) { const base = kc * self.keysyms_per_keycode; var col: usize = 0; while (col < self.keysyms_per_keycode) : (col += 1) { + if (base + col >= data.len) break; if (data[base + col] == keysym) { return @intCast(kc + self.min_keycode); } diff --git a/zephwm-bar/main.zig b/zephwm-bar/main.zig index 3b78868..8c8de90 100644 --- a/zephwm-bar/main.zig +++ b/zephwm-bar/main.zig @@ -88,12 +88,12 @@ fn queryBarConfig(allocator: std.mem.Allocator, sock_path: []const u8) BarConfig const response = ipc.sendRequest(allocator, sock_path, .get_bar_config, "") orelse return cfg; defer allocator.free(response); - // Parse font (handles escaped quotes) + // Parse font (handles escaped quotes, then unescape) if (std.mem.indexOf(u8, response, "\"font\":\"")) |pos| { const start = pos + 8; if (findUnescapedQuote(response[start..])) |end| { - const len: u8 = @intCast(@min(end, 255)); - @memcpy(cfg.font[0..len], response[start..][0..len]); + const raw = response[start..][0..end]; + const len: u8 = @intCast(unescapeJsonString(&cfg.font, raw)); cfg.font_len = len; } } @@ -108,12 +108,12 @@ fn queryBarConfig(allocator: std.mem.Allocator, sock_path: []const u8) BarConfig } } - // Parse status_command (handles escaped quotes) + // Parse status_command (handles escaped quotes, then unescape) if (std.mem.indexOf(u8, response, "\"status_command\":\"")) |pos| { const start = pos + 18; if (findUnescapedQuote(response[start..])) |end| { - const len: u16 = @intCast(@min(end, 511)); - @memcpy(cfg.status_command[0..len], response[start..][0..len]); + const raw = response[start..][0..end]; + const len: u16 = @intCast(unescapeJsonString(&cfg.status_command, raw)); cfg.status_command_len = len; } } @@ -975,23 +975,17 @@ fn parseStatusUpdate( const idx = block_count.*; blocks[idx] = .{}; - // Extract full_text + // Extract full_text (unescape JSON escapes) if (extractJsonString(obj, "\"full_text\":\"")) |ft| { - const copy_len = @min(ft.len, @as(usize, 256)); - @memcpy(blocks[idx].full_text[0..copy_len], ft[0..copy_len]); - blocks[idx].full_text_len = @intCast(copy_len); + blocks[idx].full_text_len = @intCast(unescapeJsonString(&blocks[idx].full_text, ft)); } - // Extract name + // Extract name (unescape JSON escapes) if (extractJsonString(obj, "\"name\":\"")) |nm| { - const copy_len = @min(nm.len, @as(usize, 64)); - @memcpy(blocks[idx].name[0..copy_len], nm[0..copy_len]); - blocks[idx].name_len = @intCast(copy_len); + blocks[idx].name_len = @intCast(unescapeJsonString(&blocks[idx].name, nm)); } - // Extract instance + // Extract instance (unescape JSON escapes) if (extractJsonString(obj, "\"instance\":\"")) |inst| { - const copy_len = @min(inst.len, @as(usize, 64)); - @memcpy(blocks[idx].instance[0..copy_len], inst[0..copy_len]); - blocks[idx].instance_len = @intCast(copy_len); + blocks[idx].instance_len = @intCast(unescapeJsonString(&blocks[idx].instance, inst)); } block_count.* += 1; @@ -1079,3 +1073,36 @@ fn extractJsonString(json: []const u8, key: []const u8) ?[]const u8 { } return null; } + +/// Unescape JSON string escape sequences in-place into a destination buffer. +/// Handles: \" \\ \/ \b \f \n \r \t. Returns the unescaped length. +fn unescapeJsonString(dst: []u8, src: []const u8) usize { + var si: usize = 0; + var di: usize = 0; + while (si < src.len and di < dst.len) { + if (src[si] == '\\' and si + 1 < src.len) { + const next = src[si + 1]; + const replacement: ?u8 = switch (next) { + '"' => '"', + '\\' => '\\', + '/' => '/', + 'b' => 0x08, + 'f' => 0x0C, + 'n' => '\n', + 'r' => '\r', + 't' => '\t', + else => null, + }; + if (replacement) |ch| { + dst[di] = ch; + di += 1; + si += 2; + continue; + } + } + dst[di] = src[si]; + di += 1; + si += 1; + } + return di; +}