Debian Codegraph @

src/asahi/lib/wrap.c

raw
1 /*
2 * Copyright 2021-2022 Alyssa Rosenzweig
3 * SPDX-License-Identifier: MIT
4 */
5 #include <assert.h>
6 #include <dlfcn.h>
7 #include <inttypes.h>
8 #include <stdint.h>
9 #include <stdio.h>
10 #include <unistd.h>
11
12 #include <IOKit/IODataQueueClient.h>
13 #include <IOKit/IOKitLib.h>
14 #include <mach/mach.h>
15
16 #include "util/compiler.h"
17 #include "util/u_hexdump.h"
18 #include "decode.h"
19 #include "dyld_interpose.h"
20 #include "util.h"
21
22 #define HANDLE(x) (x ^ (1 << 29))
23
24 /*
25 * This section contains the minimal set of definitions to trace the macOS
26 * (IOKit) interface to the AGX accelerator.
27 * They are not used under Linux.
28 *
29 * Information is this file was originally determined independently. More
30 * recently, names have been augmented via the oob_timestamp code sample from
31 * Project Zero [1]
32 *
33 * [1] https://bugs.chromium.org/p/project-zero/issues/detail?id=1986
34 */
35
36 #define AGX_SERVICE_TYPE 0x100005
37
38 enum agx_selector {
39 AGX_SELECTOR_GET_GLOBAL_IDS = 0x6,
40 AGX_SELECTOR_SET_API = 0x7,
41 AGX_SELECTOR_CREATE_COMMAND_QUEUE = 0x8,
42 AGX_SELECTOR_FREE_COMMAND_QUEUE = 0x9,
43 AGX_SELECTOR_ALLOCATE_MEM = 0xA,
44 AGX_SELECTOR_FREE_MEM = 0xB,
45 AGX_SELECTOR_CREATE_SHMEM = 0xF,
46 AGX_SELECTOR_FREE_SHMEM = 0x10,
47 AGX_SELECTOR_CREATE_NOTIFICATION_QUEUE = 0x11,
48 AGX_SELECTOR_FREE_NOTIFICATION_QUEUE = 0x12,
49 AGX_SELECTOR_SUBMIT_COMMAND_BUFFERS = 0x1E,
50 AGX_SELECTOR_GET_VERSION = 0x2A,
51 AGX_NUM_SELECTORS = 0x33
52 };
53
54 struct IOAccelCommandQueueSubmitArgs_Command {
55 uint32_t command_buffer_shmem_id;
56 uint32_t segment_list_shmem_id;
57 uint64_t unk1B; // 0, new in 12.x
58 uint64_t notify_1;
59 uint64_t notify_2;
60 uint32_t unk2;
61 uint32_t unk3;
62 } __attribute__((packed));
63
64 struct agx_allocate_resource_resp {
65 /* Returned GPU virtual address */
66 uint64_t gpu_va;
67
68 /* Returned CPU virtual address */
69 uint64_t cpu;
70
71 uint32_t unk4[3];
72
73 /* Handle used to identify the resource in the segment list */
74 uint32_t handle;
75
76 /* Size of the root resource from which we are allocated. If this is not a
77 * suballocation, this is equal to the size.
78 */
79 uint64_t root_size;
80
81 /* Globally unique identifier for the resource, shown in Instruments */
82 uint32_t guid;
83
84 uint32_t unk11[7];
85
86 /* Maximum size of the suballocation. For a suballocation, this equals:
87 *
88 * sub_size = root_size - (sub_cpu - root_cpu)
89 *
90 * For root allocations, this equals the size.
91 */
92 uint64_t sub_size;
93 } __attribute__((packed));
94
95 /*
96 * Wrap IOKit entrypoints to intercept communication between the AGX kernel
97 * extension and userspace clients. IOKit prototypes are public from the IOKit
98 * source release.
99 */
100
101 mach_port_t metal_connection = 0;
102
103 struct agxdecode_ctx *decode_ctx = NULL;
104
105 kern_return_t
106 wrap_Method(mach_port_t connection, uint32_t selector, const uint64_t *input,
107 uint32_t inputCnt, const void *inputStruct, size_t inputStructCnt,
108 uint64_t *output, uint32_t *outputCnt, void *outputStruct,
109 size_t *outputStructCntP)
110 {
111 if (!decode_ctx) {
112 decode_ctx = agxdecode_new_context(0);
113 }
114
115 /* Heuristic guess which connection is Metal, skip over I/O from everything
116 * else. This is technically wrong but it works in practice, and reduces the
117 * surface area we need to wrap.
118 */
119 if (selector == AGX_SELECTOR_SET_API) {
120 metal_connection = connection;
121 } else if (metal_connection != connection) {
122 return IOConnectCallMethod(connection, selector, input, inputCnt,
123 inputStruct, inputStructCnt, output, outputCnt,
124 outputStruct, outputStructCntP);
125 }
126
127 printf("Selector %u, %X, %X\n", selector, connection, metal_connection);
128
129 /* Check the arguments make sense */
130 assert((input != NULL) == (inputCnt != 0));
131 assert((inputStruct != NULL) == (inputStructCnt != 0));
132 assert((output != NULL) == (outputCnt != 0));
133 assert((outputStruct != NULL) == (outputStructCntP != 0));
134
135 /* Dump inputs */
136 switch (selector) {
137 case AGX_SELECTOR_SET_API:
138 assert(input == NULL && output == NULL && outputStruct == NULL);
139 assert(inputStruct != NULL && inputStructCnt == 16);
140 assert(((uint8_t *)inputStruct)[15] == 0x0);
141
142 printf("%X: SET_API(%s)\n", connection, (const char *)inputStruct);
143 break;
144
145 case AGX_SELECTOR_SUBMIT_COMMAND_BUFFERS: {
146 assert(output == NULL && outputStruct == NULL);
147 // assert(inputCnt == 1);
148
149 printf("%X: SUBMIT_COMMAND_BUFFERS command queue id:%llx %p\n",
150 connection, input[0], inputStruct);
151
152 u_hexdump(stdout, inputStruct, inputStructCnt, true);
153 const struct IOAccelCommandQueueSubmitArgs_Command *cmds =
154 (void *)(inputStruct + 0);
155
156 // for (unsigned i = 0; i < hdr->count; ++i) {
157 const struct IOAccelCommandQueueSubmitArgs_Command *req = &cmds[0];
158 agxdecode_cmdstream(decode_ctx, HANDLE(req->command_buffer_shmem_id),
159 HANDLE(req->segment_list_shmem_id), true);
160 // }
161
162 agxdecode_next_frame();
163 FALLTHROUGH;
164 }
165
166 default:
167 printf("%X: call %X (out %p, %zu)", connection, selector,
168 outputStructCntP, outputStructCntP ? *outputStructCntP : 0);
169
170 for (uint64_t u = 0; u < inputCnt; ++u)
171 printf(" %llx", input[u]);
172
173 if (inputStructCnt) {
174 printf(", struct:\n");
175 u_hexdump(stdout, inputStruct, inputStructCnt, true);
176 } else {
177 printf("\n");
178 }
179
180 break;
181 }
182
183 /* Invoke the real method */
184 kern_return_t ret = IOConnectCallMethod(
185 connection, selector, input, inputCnt, inputStruct, inputStructCnt,
186 output, outputCnt, outputStruct, outputStructCntP);
187
188 if (ret != 0)
189 printf("return %u\n", ret);
190
191 /* Track allocations for later analysis (dumping, disassembly, etc) */
192 switch (selector) {
193 case AGX_SELECTOR_CREATE_SHMEM: {
194 assert(inputCnt == 2);
195 assert((*outputStructCntP) == 0x10);
196 uint64_t *inp = (uint64_t *)input;
197
198 uint8_t type = inp[1];
199
200 assert(type <= 2);
201 if (type == 2)
202 printf("(cmdbuf with error reporting)\n");
203
204 uint64_t *ptr = (uint64_t *)outputStruct;
205 uint32_t *words = (uint32_t *)(ptr + 1);
206
207 /* Construct a synthetic GEM handle for the shmem */
208 agxdecode_track_alloc(decode_ctx, &(struct agx_bo){
209 .handle = HANDLE(words[1]),
210 ._map = (void *)*ptr,
211 .size = words[0],
212 });
213
214 break;
215 }
216
217 case AGX_SELECTOR_ALLOCATE_MEM: {
218 assert((*outputStructCntP) == 0x50);
219 const struct agx_allocate_resource_req *req = inputStruct;
220 struct agx_allocate_resource_resp *resp = outputStruct;
221
222 struct agx_va *va = malloc(sizeof(struct agx_va));
223 va->addr = resp->gpu_va;
224 va->size_B = resp->sub_size;
225
226 agxdecode_track_alloc(decode_ctx, &(struct agx_bo){
227 .size = resp->sub_size,
228 .handle = resp->handle,
229 .va = va,
230 ._map = (void *)resp->cpu,
231 });
232
233 break;
234 }
235
236 case AGX_SELECTOR_FREE_MEM: {
237 assert(inputCnt == 1);
238 assert(inputStruct == NULL);
239 assert(output == NULL);
240 assert(outputStruct == NULL);
241
242 agxdecode_track_free(decode_ctx, &(struct agx_bo){.handle = input[0]});
243
244 break;
245 }
246
247 case AGX_SELECTOR_FREE_SHMEM: {
248 assert(inputCnt == 1);
249 assert(inputStruct == NULL);
250 assert(output == NULL);
251 assert(outputStruct == NULL);
252
253 agxdecode_track_free(decode_ctx,
254 &(struct agx_bo){.handle = HANDLE(input[0])});
255
256 break;
257 }
258
259 default:
260 /* Dump the outputs */
261 if (outputCnt) {
262 printf("%u scalars: ", *outputCnt);
263
264 for (uint64_t u = 0; u < *outputCnt; ++u)
265 printf("%llx ", output[u]);
266
267 printf("\n");
268 }
269
270 if (outputStructCntP) {
271 printf(" struct\n");
272 u_hexdump(stdout, outputStruct, *outputStructCntP, true);
273
274 if (selector == 2) {
275 /* Dump linked buffer as well */
276 void **o = outputStruct;
277 u_hexdump(stdout, *o, 64, true);
278 }
279 }
280
281 printf("\n");
282 break;
283 }
284
285 return ret;
286 }
287
288 kern_return_t
289 wrap_AsyncMethod(mach_port_t connection, uint32_t selector,
290 mach_port_t wakePort, uint64_t *reference,
291 uint32_t referenceCnt, const uint64_t *input,
292 uint32_t inputCnt, const void *inputStruct,
293 size_t inputStructCnt, uint64_t *output, uint32_t *outputCnt,
294 void *outputStruct, size_t *outputStructCntP)
295 {
296 /* Check the arguments make sense */
297 assert((input != NULL) == (inputCnt != 0));
298 assert((inputStruct != NULL) == (inputStructCnt != 0));
299 assert((output != NULL) == (outputCnt != 0));
300 assert((outputStruct != NULL) == (outputStructCntP != 0));
301
302 printf("%X: call %X, wake port %X (out %p, %zu)", connection, selector,
303 wakePort, outputStructCntP, outputStructCntP ? *outputStructCntP : 0);
304
305 for (uint64_t u = 0; u < inputCnt; ++u)
306 printf(" %llx", input[u]);
307
308 if (inputStructCnt) {
309 printf(", struct:\n");
310 u_hexdump(stdout, inputStruct, inputStructCnt, true);
311 } else {
312 printf("\n");
313 }
314
315 printf(", references: ");
316 for (unsigned i = 0; i < referenceCnt; ++i)
317 printf(" %llx", reference[i]);
318 printf("\n");
319
320 kern_return_t ret = IOConnectCallAsyncMethod(
321 connection, selector, wakePort, reference, referenceCnt, input, inputCnt,
322 inputStruct, inputStructCnt, output, outputCnt, outputStruct,
323 outputStructCntP);
324
325 printf("return %u", ret);
326
327 if (outputCnt) {
328 printf("%u scalars: ", *outputCnt);
329
330 for (uint64_t u = 0; u < *outputCnt; ++u)
331 printf("%llx ", output[u]);
332
333 printf("\n");
334 }
335
336 if (outputStructCntP) {
337 printf(" struct\n");
338 u_hexdump(stdout, outputStruct, *outputStructCntP, true);
339
340 if (selector == 2) {
341 /* Dump linked buffer as well */
342 void **o = outputStruct;
343 u_hexdump(stdout, *o, 64, true);
344 }
345 }
346
347 printf("\n");
348 return ret;
349 }
350
351 kern_return_t
352 wrap_StructMethod(mach_port_t connection, uint32_t selector,
353 const void *inputStruct, size_t inputStructCnt,
354 void *outputStruct, size_t *outputStructCntP)
355 {
356 return wrap_Method(connection, selector, NULL, 0, inputStruct,
357 inputStructCnt, NULL, NULL, outputStruct,
358 outputStructCntP);
359 }
360
361 kern_return_t
362 wrap_AsyncStructMethod(mach_port_t connection, uint32_t selector,
363 mach_port_t wakePort, uint64_t *reference,
364 uint32_t referenceCnt, const void *inputStruct,
365 size_t inputStructCnt, void *outputStruct,
366 size_t *outputStructCnt)
367 {
368 return wrap_AsyncMethod(connection, selector, wakePort, reference,
369 referenceCnt, NULL, 0, inputStruct, inputStructCnt,
370 NULL, NULL, outputStruct, outputStructCnt);
371 }
372
373 kern_return_t
374 wrap_ScalarMethod(mach_port_t connection, uint32_t selector,
375 const uint64_t *input, uint32_t inputCnt, uint64_t *output,
376 uint32_t *outputCnt)
377 {
378 return wrap_Method(connection, selector, input, inputCnt, NULL, 0, output,
379 outputCnt, NULL, NULL);
380 }
381
382 kern_return_t
383 wrap_AsyncScalarMethod(mach_port_t connection, uint32_t selector,
384 mach_port_t wakePort, uint64_t *reference,
385 uint32_t referenceCnt, const uint64_t *input,
386 uint32_t inputCnt, uint64_t *output, uint32_t *outputCnt)
387 {
388 return wrap_AsyncMethod(connection, selector, wakePort, reference,
389 referenceCnt, input, inputCnt, NULL, 0, output,
390 outputCnt, NULL, NULL);
391 }
392
393 mach_port_t
394 wrap_DataQueueAllocateNotificationPort()
395 {
396 mach_port_t ret = IODataQueueAllocateNotificationPort();
397 printf("Allocated notif port %X\n", ret);
398 return ret;
399 }
400
401 kern_return_t
402 wrap_SetNotificationPort(io_connect_t connect, uint32_t type, mach_port_t port,
403 uintptr_t reference)
404 {
405 printf(
406 "Set noficiation port connect=%X, type=%X, port=%X, reference=%" PRIx64
407 "\n",
408 connect, type, port, (uint64_t)reference);
409
410 return IOConnectSetNotificationPort(connect, type, port, reference);
411 }
412
413 IOReturn
414 wrap_DataQueueWaitForAvailableData(IODataQueueMemory *dataQueue,
415 mach_port_t notificationPort)
416 {
417 printf("Waiting for data queue at notif port %X\n", notificationPort);
418 IOReturn ret = IODataQueueWaitForAvailableData(dataQueue, notificationPort);
419 printf("ret=%X\n", ret);
420 return ret;
421 }
422
423 IODataQueueEntry *
424 wrap_DataQueuePeek(IODataQueueMemory *dataQueue)
425 {
426 printf("Peeking data queue\n");
427 return IODataQueuePeek(dataQueue);
428 }
429
430 IOReturn
431 wrap_DataQueueDequeue(IODataQueueMemory *dataQueue, void *data,
432 uint32_t *dataSize)
433 {
434 printf("Dequeueing (dataQueue=%p, data=%p, buffer %u)\n", dataQueue, data,
435 *dataSize);
436 IOReturn ret = IODataQueueDequeue(dataQueue, data, dataSize);
437 printf("Return \"%s\", got %u bytes\n", mach_error_string(ret), *dataSize);
438
439 uint8_t *data8 = data;
440 for (unsigned i = 0; i < *dataSize; ++i) {
441 printf("%02X ", data8[i]);
442 }
443 printf("\n");
444
445 return ret;
446 }
447
448 DYLD_INTERPOSE(wrap_Method, IOConnectCallMethod);
449 DYLD_INTERPOSE(wrap_AsyncMethod, IOConnectCallAsyncMethod);
450 DYLD_INTERPOSE(wrap_StructMethod, IOConnectCallStructMethod);
451 DYLD_INTERPOSE(wrap_AsyncStructMethod, IOConnectCallAsyncStructMethod);
452 DYLD_INTERPOSE(wrap_ScalarMethod, IOConnectCallScalarMethod);
453 DYLD_INTERPOSE(wrap_AsyncScalarMethod, IOConnectCallAsyncScalarMethod);
454 DYLD_INTERPOSE(wrap_SetNotificationPort, IOConnectSetNotificationPort);
455 DYLD_INTERPOSE(wrap_DataQueueAllocateNotificationPort,
456 IODataQueueAllocateNotificationPort);
457 DYLD_INTERPOSE(wrap_DataQueueWaitForAvailableData,
458 IODataQueueWaitForAvailableData);
459 DYLD_INTERPOSE(wrap_DataQueuePeek, IODataQueuePeek);
460 DYLD_INTERPOSE(wrap_DataQueueDequeue, IODataQueueDequeue);