Something went wrong. Try again.
MPRIS for Zig: a media player's side of the D-Bus remote control interfaces, on mdbus and zig-dbus-service.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What an MPRIS server must do with whatever a peer calls it with.//!//! Anything on the session bus may call a media player: a desktop's media//! keys, `playerctl`, a widget, or something that means harm. So each call//! here is input nobody wrote, dispatched to a real `Server` whose player//! is played by the test, in a state the input also chooses. Whatever//! arrives, the server answers, frees what it allocated, and answers with//! something that can be sent; and what it passes on to the player is what//! the MPRIS specification allows -- a position inside the track, a volume//! that is a volume -- since the player is an application that trusts it.//!//! The target is an ordinary test as well as a fuzz target. Without//! `--fuzz` it runs the seeds `tools/fuzz_corpus.zig` makes -- a call to//! every method and property of the four interfaces, and calls the server//! must refuse -- so `zig build test` checks the same property on real//! calls, and that each seed is answered the way it should be. `zig build fuzz --fuzz` hands it//! to Zig's fuzzer, and `zig build fuzz-run` mutates the same seeds with the//! loop in `tools/fuzz.zig`.
const builtin = @import("builtin");const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;const testing = std.testing;const Smith = std.testing.Smith;
const mdbus = @import("mdbus");const dbus = @import("dbus_service");const mpris = @import("mpris");const corpus = @import("fuzz_corpus");
const Encoder = dbus.Encoder;const Server = mpris.Server;
/// The allocator and the `Io` the target runs against.////// Under `zig build test` they are the testing ones, and a leak is a/// failure. `tools/fuzz.zig` cannot name those -- it is not a test build --/// so it sets its own: a checked allocator, and the `Io` it runs on.pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined;pub var io: Io = if (builtin.is_test) testing.io else undefined;
/// The tracks and playlists the player's state is made of.const tracks = [_]mpris.Metadata{ .{ .trackid = "/org/example/track/1", .length_us = 180_000_000, .title = "One", .artists = &.{"Artist"}, .album = "Album", .track_number = 1, .user_rating = 1 }, .{ .trackid = "/org/example/track/2", .length_us = 240_000_000, .title = "Two" }, // A stream: no length, so no end to seek past. .{ .trackid = "/org/example/track/3", .title = "Radio" },};const playlists = [_]mpris.Playlist{ .{ .id = "/org/example/playlist/1", .name = "Favorites" }, .{ .id = "/org/example/playlist/2", .name = "Later", .icon = "file:///icon.png" },};
/// The player, played by the test: it describes a state the input chose,/// and checks that every command it is given is one the specification/// allows.const Fixture = struct { state: mpris.State, /// What was wrong with a command, if one was. wrong: ?[]const u8 = null,
fn from(context: *anyopaque) *Fixture { return @ptrCast(@alignCast(context)); }
fn snapshot(context: *anyopaque, _: Allocator, out: *mpris.State) anyerror!void { out.* = from(context).state; }
fn noop(_: *anyopaque) void {}
fn setPosition(context: *anyopaque, position_us: i64) void { const self = from(context); if (position_us < 0) self.wrong = "a negative position"; if (self.state.metadata.length_us) |len| if (position_us > len) { self.wrong = "a position past the end of the track"; }; }
fn setVolume(context: *anyopaque, volume: f64) void { if (!(volume >= 0) or !std.math.isFinite(volume)) from(context).wrong = "a volume that is not one"; }
fn checkPath(context: *anyopaque, id: []const u8) void { if (!mdbus.wire.validObjectPath(id)) from(context).wrong = "an id that is not an object path"; }
fn openUri(_: *anyopaque, _: []const u8) void {} fn setLoopStatus(_: *anyopaque, _: mpris.LoopStatus) void {} fn setShuffle(_: *anyopaque, _: bool) void {}
fn player(self: *Fixture) Server.Player { return .{ .context = self, .snapshot = snapshot, .raise = noop, .quit = noop, .next = noop, .previous = noop, .play = noop, .pause = noop, .play_pause = noop, .stop = noop, .set_position = setPosition, .open_uri = openUri, .set_loop_status = setLoopStatus, .set_shuffle = setShuffle, .set_volume = setVolume, .go_to = checkPath, .activate_playlist = checkPath, }; }};
/// A state for the player, from a byte of flags and a byte of position.fn stateFrom(flags: u8, position: u8) mpris.State { const track = tracks[flags % tracks.len]; return .{ .playback_status = if (flags & 4 != 0) .Playing else if (flags & 8 != 0) .Paused else .Stopped, .loop_status = .None, .shuffle = flags & 16 != 0, .volume = 0.5, // Somewhere in the track: its start, middle or end, or past a // stream's start. .position_us = if (track.length_us) |len| @divTrunc(len * position, 255) else @as(i64, position) * 1_000_000, .metadata = track, .can_go_next = true, .can_go_previous = true, .can_play = true, .can_pause = true, .can_seek = flags & 32 != 0, .tracks = if (flags & 64 != 0) &tracks else &.{}, .playlists = if (flags & 128 != 0) &playlists else &.{}, .active_playlist = if (flags & 128 != 0) playlists[0] else null, };}
/// What a call is answered with, as a test of the seeds: whether it was a/// return value.const Answer = enum { ok, failure, ignored };
/// Two bytes choosing the player's state before the call and two after it/// -- a byte of flags and a byte of position, each -- then a method call/// from a peer, as its parts: path, interface, member and/// signature, then its arguments -- as zig-dbus-service's target takes one,/// each part picked from the corpus's lists or, from 0xf0 up, a name of its/// own, and the arguments made to fit the signature by `Values`. The call/// is encoded as the bus would deliver it and parsed again, dispatched to a/// `Server`, and its reply encoded and parsed again as the service would/// send it. The player checks every command it is given. Then the state/// changes, and the server works out what to tell the bus.fn callProperty(input: []const u8) !Answer { var values: Values = .{ .in = input }; var fixture: Fixture = .{ .state = stateFrom(values.byte(), values.byte()) }; const after = stateFrom(values.byte(), values.byte()); var parts: [4][]const u8 = undefined; const lists = [_][]const []const u8{ &corpus.paths, &corpus.interfaces, &corpus.members, &corpus.signatures }; for (&parts, lists) |*part, list| part.* = values.name(list);
var body: Encoder = .init(backing); defer body.deinit(); values.all(&body, parts[3], 0) catch |err| switch (err) { error.OutOfMemory => return err, else => return .ignored, }; const call = mdbus.wire.encodeMessage(backing, .{ .message_type = .method_call, .path = parts[0], .interface = if (parts[1].len == 0) null else parts[1], .member = parts[2], .destination = "org.mpris.MediaPlayer2.fuzz", .signature = parts[3], }, 7, body.bytes(), 0) catch |err| switch (err) { error.OutOfMemory => return err, else => return .ignored, }; var message = mdbus.wire.parseMessage(backing, call, &.{}) catch |err| { backing.free(call); if (err == error.OutOfMemory) return err; return .ignored; }; defer message.deinit();
// The server never touches its connection until `start` or `run`, // neither of which a dispatched call needs. var connection: mdbus.Connection = undefined; const server = try Server.create(backing, io, &connection, .{ .name = "fuzz", .identity = "Fuzz", .desktop_entry = "fuzz", .supported_uri_schemes = &.{ "file", "https" }, .supported_mime_types = &.{"audio/flac"}, }, fixture.player()); defer server.destroy(); try server.update();
const reply = try server.service.dispatcher.dispatch(&message); defer reply.deinit(backing); if (fixture.wrong) |what| { std.debug.print("{s}.{s} gave the player {s}\n", .{ parts[1], parts[2], what }); return error.PlayerMisled; }
const encoded = switch (reply) { .ok => |ok| mdbus.wire.encodeMessage(backing, .{ .message_type = .method_return, .reply_serial = message.header.serial, .destination = message.header.sender, .signature = ok.signature, }, 1, ok.body, 0), .failure => |f| blk: { var description: Encoder = .init(backing); defer description.deinit(); description.string(f.description) catch |err| { if (err != error.OutOfMemory) std.debug.print("error description is not text: {t}\n{s}\n", .{ err, f.description }); return err; }; break :blk mdbus.wire.encodeMessage(backing, .{ .message_type = .error_reply, .error_name = f.name, .reply_serial = message.header.serial, .destination = message.header.sender, .signature = "s", }, 1, description.bytes(), 0); }, } catch |err| { if (err != error.OutOfMemory) std.debug.print("the reply cannot be sent: {t}\n", .{err}); return err; }; var sent = try mdbus.wire.parseMessage(backing, encoded, &.{}); sent.deinit();
// And the state changing under it, as the player's does: the next // snapshot, diffed against this one. fixture.state = after; try server.update();
return switch (reply) { .ok => .ok, .failure => .failure, };}
/// Values read from fuzz input, to fit a signature. Past the end of the/// input every value is zero or empty, so every call is complete.const Values = struct { in: []const u8,
/// Deep enough for anything a real call has, and a bound on a variant /// that holds a variant. const max_depth = 8;
fn byte(v: *Values) u8 { if (v.in.len == 0) return 0; defer v.in = v.in[1..]; return v.in[0]; }
fn int(v: *Values, comptime T: type) T { var b: [@sizeOf(T)]u8 = @splat(0); const n = @min(b.len, v.in.len); @memcpy(b[0..n], v.in[0..n]); v.in = v.in[n..]; return std.mem.readInt(T, &b, .little); }
/// A byte of length and that many bytes. fn bytes(v: *Values) []const u8 { const len: usize = @min(v.byte(), v.in.len); defer v.in = v.in[len..]; return v.in[0..len]; }
/// One of `list`, or from 0xf0 up a name of its own. fn name(v: *Values, list: []const []const u8) []const u8 { const pick = v.byte(); return if (pick < 0xf0) list[pick % list.len] else v.bytes(); }
/// Every complete type in `sig`, one after another. fn all(v: *Values, enc: *Encoder, sig: []const u8, depth: usize) !void { var i: usize = 0; while (i < sig.len) i = try v.one(enc, sig, i, depth); }
/// The complete type at `sig[i]`, returning where the next begins. fn one(v: *Values, enc: *Encoder, sig: []const u8, i: usize, depth: usize) anyerror!usize { if (depth > max_depth) return error.TooDeep; switch (sig[i]) { 'y' => try enc.byte(v.byte()), 'b' => try enc.boolean(v.byte() & 1 != 0), 'n' => try enc.int16(v.int(i16)), 'q' => try enc.uint16(v.int(u16)), 'i' => try enc.int32(v.int(i32)), 'u' => try enc.uint32(v.int(u32)), 'x' => try enc.int64(v.int(i64)), 't' => try enc.uint64(v.int(u64)), 'd' => try enc.double(@bitCast(v.int(u64))), 's' => try enc.string(v.bytes()), 'o' => try enc.objectPath(v.name(&corpus.paths)), 'g' => try enc.signature(v.name(&corpus.signatures)), 'v' => { const inner = v.name(&corpus.signatures); try enc.variantSignature(inner); try v.all(enc, inner, depth + 1); }, 'a' => { if (i + 1 >= sig.len) return error.InvalidSignature; const end = try typeEnd(sig, i + 1); const array = try enc.beginArray(sig[i + 1]); for (0..v.byte() % 5) |_| { if (sig[i + 1] == '{') { try enc.dictEntryAlignment(); const key = try v.one(enc, sig, i + 2, depth + 1); _ = try v.one(enc, sig, key, depth + 1); } else _ = try v.one(enc, sig, i + 1, depth + 1); } try enc.endArray(array); return end; }, '(' => { try enc.structAlignment(); var j = i + 1; while (j < sig.len and sig[j] != ')') j = try v.one(enc, sig, j, depth + 1); if (j >= sig.len) return error.InvalidSignature; return j + 1; }, else => return error.InvalidSignature, } return i + 1; }
/// Where the complete type at `sig[i]` ends. fn typeEnd(sig: []const u8, i: usize) error{InvalidSignature}!usize { if (i >= sig.len) return error.InvalidSignature; switch (sig[i]) { 'a' => return typeEnd(sig, i + 1), '(', '{' => { const close: u8 = if (sig[i] == '(') ')' else '}'; var j = i + 1; while (j < sig.len and sig[j] != close) j = try typeEnd(sig, j); if (j >= sig.len) return error.InvalidSignature; return j + 1; }, else => return i + 1, } }};
test "fuzz method calls" { // Every seed is answered as it should be -- or the server is not being // reached the way the corpus says, and it is shallower than it looks -- // and none is refused before it is dispatched. for (corpus.calls, 0..) |seed, i| { const got = try callProperty(seed); if (got != .ok) std.debug.print("call seed {d} was answered {t}\n", .{ i, got }); try testing.expectEqual(Answer.ok, got); } for (corpus.refusals, 0..) |seed, i| { const got = try callProperty(seed); if (got != .failure) std.debug.print("refusal seed {d} was answered {t}\n", .{ i, got }); try testing.expectEqual(Answer.failure, got); } try testing.fuzz({}, fuzzCalls, .{ .corpus = &smith_seeds });}
test "every seed survives running out of memory at any allocation" { // Each seed again, with each of its allocations failing in turn: the // server has to give up with `OutOfMemory` rather than carry on as if // nothing happened, and free everything on the way out, which is only // ever tested by an allocation failing. // // `checkAllAllocationFailures` counts allocations and not resizes, and // whether a list grows in place depends on what the heap looks like // after the run before; it then sees a different count each time and // calls that nondeterministic. So nothing grows in place here. const no_growing: Allocator = .{ .ptr = testing.allocator.ptr, .vtable = &.{ .alloc = testing.allocator.vtable.alloc, .resize = Allocator.noResize, .remap = Allocator.noRemap, .free = testing.allocator.vtable.free, } }; for (corpus.calls ++ corpus.refusals) |seed| { try testing.checkAllAllocationFailures(no_growing, callWith, .{seed}); }}
fn callWith(allocator: Allocator, input: []const u8) !void { const saved = backing; backing = allocator; defer backing = saved; _ = try callProperty(input);}
/// Every seed, as `Smith` reads one through `fuzzCalls`: `slice` takes four/// bytes of little-endian length first, so a seed handed over bare is read/// as a length of millions and comes out empty.const smith_seeds = blk: { const seeds = corpus.calls ++ corpus.refusals; var out: [seeds.len][]const u8 = undefined; for (seeds, &out) |seed, *o| { const framed = std.mem.toBytes(std.mem.nativeToLittle(u32, seed.len)) ++ seed[0..seed.len].*; o.* = &framed; } break :blk out;};
fn fuzzCalls(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; _ = try callProperty(buffer[0..smith.slice(&buffer)]);}
// -- the table -----------------------------------------------------------------
/// A target, as `tools/fuzz.zig` drives it.pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, /// Inputs worth mutating, which stand in for the coverage feedback a /// real fuzzer would have. corpus: []const []const u8, /// The buffer this target reads its input into. `Smith.slice` yields /// an *empty* slice for a length larger than that, not a truncated /// one, so a generator that does not know it feeds the target nothing. content_max: usize,};
fn Driven(comptime one: fn (void, *Smith) anyerror!void) type { return struct { fn run(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return one({}, &smith); } };}
pub const all = [_]Target{ .{ .name = "calls", .run = Driven(fuzzCalls).run, .corpus = &(corpus.calls ++ corpus.refusals), .content_max = 4096 },};