1// Copyright 2016 The Fuchsia Authors. All rights reserved.
2//
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5
6#include <stddef.h>
7#include <unistd.h>
8
9#include <zircon/process.h>
10#include <zircon/syscalls.h>
11#include <zircon/syscalls/debug.h>
12#include <zircon/syscalls/exception.h>
13#include <zircon/syscalls/object.h>
14#include <zircon/syscalls/port.h>
15
16#include <runtime/thread.h>
17#include <unittest/unittest.h>
18
19#include "register-set.h"
20#include "thread-functions/thread-functions.h"
21
22static const char kThreadName[] = "test-thread";
23
24static const unsigned kExceptionPortKey = 42u;
25
26// We have to poll a thread's state as there is no way to wait for it to
27// transition states. Wait this amount of time. Generally the thread won't
28// take very long so this is a compromise between polling too frequently and
29// waiting too long.
30constexpr zx_duration_t THREAD_BLOCKED_WAIT_DURATION = ZX_MSEC(1);
31
32static bool get_koid(zx_handle_t handle, zx_koid_t* koid) {
33    zx_info_handle_basic_t info;
34    size_t records_read;
35    ASSERT_EQ(zx_object_get_info(
36                  handle, ZX_INFO_HANDLE_BASIC, &info, sizeof(info),
37                  &records_read, NULL),
38              ZX_OK);
39    ASSERT_EQ(records_read, 1u);
40    *koid = info.koid;
41    return true;
42}
43
44static bool check_reported_pid_and_tid(zx_handle_t thread,
45                                       zx_port_packet_t* packet) {
46    zx_koid_t pid;
47    zx_koid_t tid;
48    if (!get_koid(zx_process_self(), &pid))
49        return false;
50    if (!get_koid(thread, &tid))
51        return false;
52    EXPECT_EQ(packet->exception.pid, pid);
53    EXPECT_EQ(packet->exception.tid, tid);
54    return true;
55}
56
57static bool get_thread_info(zx_handle_t thread, zx_info_thread_t* info) {
58    return zx_object_get_info(thread, ZX_INFO_THREAD, info, sizeof(*info), NULL, NULL) == ZX_OK;
59}
60
61// Suspend the given thread and block until it reaches the suspended state. The suspend token
62// is written to the output parameter.
63static bool suspend_thread_synchronous(zx_handle_t thread, zx_handle_t* suspend_token) {
64    ASSERT_EQ(zx_task_suspend_token(thread, suspend_token), ZX_OK);
65
66    zx_signals_t observed = 0u;
67    ASSERT_EQ(zx_object_wait_one(thread, ZX_THREAD_SUSPENDED, ZX_TIME_INFINITE, &observed), ZX_OK);
68
69    return true;
70}
71
72// Resume the given thread and block until it reaches the running state.
73static bool resume_thread_synchronous(zx_handle_t thread, zx_handle_t suspend_token) {
74    ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
75
76    zx_signals_t observed = 0u;
77    ASSERT_EQ(zx_object_wait_one(thread, ZX_THREAD_RUNNING, ZX_TIME_INFINITE, &observed), ZX_OK);
78
79    return true;
80}
81
82// Updates the thread state to advance over a software breakpoint instruction, assuming the
83// breakpoint was just hit. This does not resume the thread, only updates its state.
84static bool advance_over_breakpoint(zx_handle_t thread) {
85#if defined(__aarch64__)
86    // Advance 4 bytes to the next instruction after the debug break.
87    zx_thread_state_general_regs regs;
88    ASSERT_EQ(zx_thread_read_state(thread, ZX_THREAD_STATE_GENERAL_REGS, &regs, sizeof(regs)),
89              ZX_OK);
90    regs.pc += 4;
91    ASSERT_EQ(zx_thread_write_state(thread, ZX_THREAD_STATE_GENERAL_REGS, &regs, sizeof(regs)),
92              ZX_OK);
93#elif defined(__x86_64__)
94// x86 sets the instruction pointer to the following instruction so needs no update.
95#else
96#error Not supported on this platform.
97#endif
98    return true;
99}
100
101// Waits for the exception type excp_type, ignoring exceptions of type ignore_type (these will
102// just resume the thread), and issues errors for anything else.
103static bool wait_thread_excp_type(zx_handle_t thread, zx_handle_t eport, uint32_t excp_type,
104                                  uint32_t ignore_type) {
105    zx_port_packet_t packet;
106    while (true) {
107        ASSERT_EQ(zx_port_wait(eport, ZX_TIME_INFINITE, &packet), ZX_OK);
108        ASSERT_EQ(packet.key, kExceptionPortKey);
109        if (packet.type != ignore_type) {
110            ASSERT_EQ(packet.type, excp_type);
111            break;
112        } else {
113            ASSERT_EQ(zx_task_resume_from_exception(thread, eport, 0), ZX_OK);
114        }
115    }
116    return true;
117}
118
119static bool start_thread(zxr_thread_entry_t entry, void* arg,
120                         zxr_thread_t* thread_out, zx_handle_t* thread_h) {
121    // TODO: Don't leak these when the thread dies.
122    const size_t stack_size = 256u << 10;
123    zx_handle_t thread_stack_vmo = ZX_HANDLE_INVALID;
124    ASSERT_EQ(zx_vmo_create(stack_size, 0, &thread_stack_vmo), ZX_OK);
125    ASSERT_NE(thread_stack_vmo, ZX_HANDLE_INVALID);
126
127    uintptr_t stack = 0u;
128    ASSERT_EQ(zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE,
129                          0, thread_stack_vmo, 0, stack_size, &stack),
130              ZX_OK);
131    ASSERT_EQ(zx_handle_close(thread_stack_vmo), ZX_OK);
132
133    ASSERT_EQ(zxr_thread_create(zx_process_self(), "test_thread", false,
134                                thread_out),
135              ZX_OK);
136
137    if (thread_h) {
138        ASSERT_EQ(zx_handle_duplicate(zxr_thread_get_handle(thread_out), ZX_RIGHT_SAME_RIGHTS,
139                                      thread_h),
140                  ZX_OK);
141    }
142    ASSERT_EQ(zxr_thread_start(thread_out, stack, stack_size, entry, arg),
143              ZX_OK);
144    return true;
145}
146
147static bool start_and_kill_thread(zxr_thread_entry_t entry, void* arg) {
148    zxr_thread_t thread;
149    zx_handle_t thread_h;
150    ASSERT_TRUE(start_thread(entry, arg, &thread, &thread_h));
151    zx_nanosleep(zx_deadline_after(ZX_MSEC(100)));
152    ASSERT_EQ(zx_task_kill(thread_h), ZX_OK);
153    ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED,
154                                 ZX_TIME_INFINITE, NULL),
155              ZX_OK);
156    zxr_thread_destroy(&thread);
157    ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
158    return true;
159}
160
161static bool set_debugger_exception_port(zx_handle_t* eport_out) {
162    ASSERT_EQ(zx_port_create(0, eport_out), ZX_OK);
163    zx_handle_t self = zx_process_self();
164    ASSERT_EQ(zx_task_bind_exception_port(self, *eport_out, kExceptionPortKey,
165                                          ZX_EXCEPTION_PORT_DEBUGGER),
166              ZX_OK);
167    return true;
168}
169
170static void clear_debugger_exception_port() {
171    zx_handle_t self = zx_process_self();
172    zx_task_bind_exception_port(self, ZX_HANDLE_INVALID, kExceptionPortKey,
173                                ZX_EXCEPTION_PORT_DEBUGGER);
174}
175
176// Wait for |thread| to enter blocked state |reason|.
177// We wait forever and let Unittest's watchdog handle errors.
178
179static bool wait_thread_blocked(zx_handle_t thread, uint32_t reason) {
180    while (true) {
181        zx_info_thread_t info;
182        ASSERT_TRUE(get_thread_info(thread, &info));
183        if (info.state == reason)
184            break;
185        zx_nanosleep(zx_deadline_after(THREAD_BLOCKED_WAIT_DURATION));
186    }
187    return true;
188}
189
190static bool test_basics() {
191    BEGIN_TEST;
192    zxr_thread_t thread;
193    zx_handle_t thread_h;
194    ASSERT_TRUE(start_thread(threads_test_sleep_fn, (void*)zx_deadline_after(ZX_MSEC(100)),
195                             &thread, &thread_h));
196    ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL),
197              ZX_OK);
198    ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
199    END_TEST;
200}
201
202static bool test_detach() {
203    BEGIN_TEST;
204    zxr_thread_t thread;
205    zx_handle_t event;
206    ASSERT_EQ(zx_event_create(0, &event), ZX_OK);
207
208    zx_handle_t thread_h;
209    ASSERT_TRUE(start_thread(threads_test_wait_detach_fn, &event, &thread, &thread_h));
210    // We're not detached yet
211    ASSERT_FALSE(zxr_thread_detached(&thread));
212
213    ASSERT_EQ(zxr_thread_detach(&thread), ZX_OK);
214    ASSERT_TRUE(zxr_thread_detached(&thread));
215
216    // Tell thread to exit
217    ASSERT_EQ(zx_object_signal(event, 0, ZX_USER_SIGNAL_0), ZX_OK);
218
219    // Wait for thread to exit
220    ASSERT_EQ(zx_object_wait_one(thread_h,
221                                 ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL),
222              ZX_OK);
223
224    ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
225
226    END_TEST;
227}
228
229static bool test_long_name_succeeds() {
230    BEGIN_TEST;
231    // Creating a thread with a super long name should succeed.
232    static const char long_name[] =
233        "0123456789012345678901234567890123456789"
234        "0123456789012345678901234567890123456789";
235    ASSERT_GT(strlen(long_name), (size_t)ZX_MAX_NAME_LEN - 1,
236              "too short to truncate");
237
238    zxr_thread_t thread;
239    ASSERT_EQ(zxr_thread_create(zx_process_self(), long_name, false, &thread),
240              ZX_OK);
241    zxr_thread_destroy(&thread);
242    END_TEST;
243}
244
245// zx_thread_start() is not supposed to be usable for creating a
246// process's first thread.  That's what zx_process_start() is for.
247// Check that zx_thread_start() returns an error in this case.
248static bool test_thread_start_on_initial_thread() {
249    BEGIN_TEST;
250
251    static const char kProcessName[] = "test-proc-thread1";
252    zx_handle_t process;
253    zx_handle_t vmar;
254    zx_handle_t thread;
255    ASSERT_EQ(zx_process_create(zx_job_default(), kProcessName, sizeof(kProcessName) - 1,
256                                0, &process, &vmar),
257              ZX_OK);
258    ASSERT_EQ(zx_thread_create(process, kThreadName, sizeof(kThreadName) - 1,
259                               0, &thread),
260              ZX_OK);
261    ASSERT_EQ(zx_thread_start(thread, 1, 1, 1, 1), ZX_ERR_BAD_STATE);
262
263    ASSERT_EQ(zx_handle_close(thread), ZX_OK);
264    ASSERT_EQ(zx_handle_close(vmar), ZX_OK);
265    ASSERT_EQ(zx_handle_close(process), ZX_OK);
266
267    END_TEST;
268}
269
270// Test that we don't get an assertion failure (and kernel panic) if we
271// pass a zero instruction pointer when starting a thread (in this case via
272// zx_process_start()).
273static bool test_thread_start_with_zero_instruction_pointer() {
274    BEGIN_TEST;
275
276    static const char kProcessName[] = "test-proc-thread2";
277    zx_handle_t process;
278    zx_handle_t vmar;
279    zx_handle_t thread;
280    ASSERT_EQ(zx_process_create(zx_job_default(), kProcessName, sizeof(kProcessName) - 1,
281                                0, &process, &vmar),
282              ZX_OK);
283    ASSERT_EQ(zx_thread_create(process, kThreadName, sizeof(kThreadName) - 1,
284                               0, &thread),
285              ZX_OK);
286
287    REGISTER_CRASH(process);
288    ASSERT_EQ(zx_process_start(process, thread, 0, 0, thread, 0), ZX_OK);
289
290    zx_signals_t signals;
291    EXPECT_EQ(zx_object_wait_one(
292                  process, ZX_TASK_TERMINATED, ZX_TIME_INFINITE, &signals),
293              ZX_OK);
294    signals &= ZX_TASK_TERMINATED;
295    EXPECT_EQ(signals, ZX_TASK_TERMINATED);
296
297    ASSERT_EQ(zx_handle_close(process), ZX_OK);
298    ASSERT_EQ(zx_handle_close(vmar), ZX_OK);
299
300    END_TEST;
301}
302
303static bool test_kill_busy_thread() {
304    BEGIN_TEST;
305
306    ASSERT_TRUE(start_and_kill_thread(threads_test_busy_fn, NULL));
307
308    END_TEST;
309}
310
311static bool test_kill_sleep_thread() {
312    BEGIN_TEST;
313
314    ASSERT_TRUE(start_and_kill_thread(threads_test_infinite_sleep_fn, NULL));
315
316    END_TEST;
317}
318
319static bool test_kill_wait_thread() {
320    BEGIN_TEST;
321
322    zx_handle_t event;
323    ASSERT_EQ(zx_event_create(0, &event), ZX_OK);
324    ASSERT_TRUE(start_and_kill_thread(threads_test_infinite_wait_fn, &event));
325    ASSERT_EQ(zx_handle_close(event), ZX_OK);
326
327    END_TEST;
328}
329
330static bool test_bad_state_nonstarted_thread() {
331    BEGIN_TEST;
332
333    // Perform a bunch of apis against non started threads (in the INITIAL STATE).
334    zx_handle_t thread;
335
336    ASSERT_EQ(zx_thread_create(zx_process_self(), "thread", 5, 0, &thread), ZX_OK);
337    ASSERT_EQ(zx_task_resume(thread, 0), ZX_ERR_BAD_STATE);
338    ASSERT_EQ(zx_task_resume(thread, 0), ZX_ERR_BAD_STATE);
339    ASSERT_EQ(zx_handle_close(thread), ZX_OK);
340
341    ASSERT_EQ(zx_thread_create(zx_process_self(), "thread", 5, 0, &thread), ZX_OK);
342    ASSERT_EQ(zx_task_resume(thread, 0), ZX_ERR_BAD_STATE);
343    zx_handle_t suspend_token = ZX_HANDLE_INVALID;
344    ASSERT_EQ(zx_task_suspend_token(thread, &suspend_token), ZX_ERR_BAD_STATE);
345    ASSERT_EQ(zx_handle_close(thread), ZX_OK);
346
347    ASSERT_EQ(zx_thread_create(zx_process_self(), "thread", 5, 0, &thread), ZX_OK);
348    ASSERT_EQ(zx_task_kill(thread), ZX_OK);
349    ASSERT_EQ(zx_task_kill(thread), ZX_OK);
350    ASSERT_EQ(zx_handle_close(thread), ZX_OK);
351
352    ASSERT_EQ(zx_thread_create(zx_process_self(), "thread", 5, 0, &thread), ZX_OK);
353    ASSERT_EQ(zx_task_kill(thread), ZX_OK);
354    ASSERT_EQ(zx_task_resume(thread, 0), ZX_ERR_BAD_STATE);
355    ASSERT_EQ(zx_handle_close(thread), ZX_OK);
356
357    ASSERT_EQ(zx_thread_create(zx_process_self(), "thread", 5, 0, &thread), ZX_OK);
358    ASSERT_EQ(zx_task_kill(thread), ZX_OK);
359    ASSERT_EQ(zx_task_suspend_token(thread, &suspend_token), ZX_ERR_BAD_STATE);
360    ASSERT_EQ(zx_handle_close(thread), ZX_OK);
361
362    END_TEST;
363}
364
365// Arguments for self_killing_fn().
366struct self_killing_thread_args {
367    zxr_thread_t thread; // Used for the thread to kill itself.
368    uint32_t test_value; // Used for testing what the thread does.
369};
370
371__NO_SAFESTACK static void self_killing_fn(void* arg) {
372    self_killing_thread_args* args = static_cast<self_killing_thread_args*>(arg);
373    // Kill the current thread.
374    zx_task_kill(zxr_thread_get_handle(&args->thread));
375    // We should not reach here -- the syscall should not have returned.
376    args->test_value = 999;
377    zx_thread_exit();
378}
379
380// This tests that the zx_task_kill() syscall does not return when a thread
381// uses it to kill itself.
382static bool test_thread_kills_itself() {
383    BEGIN_TEST;
384
385    self_killing_thread_args args;
386    args.test_value = 111;
387    zx_handle_t thread_handle;
388    ASSERT_TRUE(start_thread(self_killing_fn, &args, &args.thread, &thread_handle));
389    ASSERT_EQ(zx_object_wait_one(thread_handle, ZX_THREAD_TERMINATED,
390                                 ZX_TIME_INFINITE, NULL),
391              ZX_OK);
392    ASSERT_EQ(zx_handle_close(thread_handle), ZX_OK);
393    // Check that the thread did not continue execution and modify test_value.
394    ASSERT_EQ(args.test_value, 111u);
395    // We have to destroy the thread afterwards to clean up its internal
396    // handle, since it did not properly exit.
397    zxr_thread_destroy(&args.thread);
398
399    END_TEST;
400}
401
402static bool test_info_task_stats_fails() {
403    BEGIN_TEST;
404    // Spin up a thread.
405    zxr_thread_t thread;
406    zx_handle_t thandle;
407    ASSERT_TRUE(start_thread(threads_test_sleep_fn, (void*)zx_deadline_after(ZX_MSEC(100)), &thread,
408                             &thandle));
409    ASSERT_EQ(zx_object_wait_one(thandle,
410                                 ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL),
411              ZX_OK);
412
413    // Ensure that task_stats doesn't work on it.
414    zx_info_task_stats_t info;
415    EXPECT_NE(zx_object_get_info(thandle, ZX_INFO_TASK_STATS,
416                                 &info, sizeof(info), NULL, NULL),
417              ZX_OK,
418              "Just added thread support to info_task_status?");
419    // If so, replace this with a real test; see example in process.cpp.
420
421    ASSERT_EQ(zx_handle_close(thandle), ZX_OK);
422    END_TEST;
423}
424
425static bool test_resume_suspended() {
426    BEGIN_TEST;
427
428    zx_handle_t event;
429    zxr_thread_t thread;
430    zx_handle_t thread_h;
431
432    ASSERT_EQ(zx_event_create(0, &event), ZX_OK);
433    ASSERT_TRUE(start_thread(threads_test_wait_fn, &event, &thread, &thread_h));
434
435    // threads_test_wait_fn() uses zx_object_wait_one() so we watch for that.
436    ASSERT_TRUE(wait_thread_blocked(thread_h, ZX_THREAD_STATE_BLOCKED_WAIT_ONE));
437
438    zx_handle_t suspend_token = ZX_HANDLE_INVALID;
439    ASSERT_EQ(zx_task_suspend_token(thread_h, &suspend_token), ZX_OK);
440    ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
441
442    // The thread should still be blocked on the event when it wakes up.
443    // It needs to run for a bit to transition from suspended back to blocked
444    // so we need to wait for it.
445    ASSERT_TRUE(wait_thread_blocked(thread_h, ZX_THREAD_STATE_BLOCKED_WAIT_ONE));
446
447    // Check that signaling the event while suspended results in the expected behavior.
448    suspend_token = ZX_HANDLE_INVALID;
449    ASSERT_TRUE(suspend_thread_synchronous(thread_h, &suspend_token));
450
451    // Verify thread is suspended.
452    zx_info_thread_t info;
453    ASSERT_TRUE(get_thread_info(thread_h, &info));
454    ASSERT_EQ(info.state, ZX_THREAD_STATE_SUSPENDED);
455    ASSERT_EQ(info.wait_exception_port_type, ZX_EXCEPTION_PORT_TYPE_NONE);
456
457    // Resuming the thread should mark the thread as blocked again.
458    ASSERT_TRUE(resume_thread_synchronous(thread_h, suspend_token));
459
460    ASSERT_TRUE(wait_thread_blocked(thread_h, ZX_THREAD_STATE_BLOCKED_WAIT_ONE));
461
462    // When the thread is suspended the signaling should not take effect.
463    suspend_token = ZX_HANDLE_INVALID;
464    ASSERT_TRUE(suspend_thread_synchronous(thread_h, &suspend_token));
465    ASSERT_EQ(zx_object_signal(event, 0, ZX_USER_SIGNAL_0), ZX_OK);
466    ASSERT_EQ(zx_object_wait_one(event, ZX_USER_SIGNAL_1, zx_deadline_after(ZX_MSEC(100)), NULL), ZX_ERR_TIMED_OUT);
467
468    ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
469
470    ASSERT_EQ(zx_object_wait_one(event, ZX_USER_SIGNAL_1, ZX_TIME_INFINITE, NULL), ZX_OK);
471
472    ASSERT_EQ(zx_object_wait_one(
473                  thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL),
474              ZX_OK);
475
476    ASSERT_EQ(zx_handle_close(event), ZX_OK);
477    ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
478
479    END_TEST;
480}
481
482static bool test_suspend_sleeping() {
483    BEGIN_TEST;
484
485    const zx_time_t sleep_deadline = zx_deadline_after(ZX_MSEC(100));
486    zxr_thread_t thread;
487
488    zx_handle_t thread_h;
489    ASSERT_TRUE(start_thread(threads_test_sleep_fn, (void*)sleep_deadline, &thread, &thread_h));
490
491    zx_nanosleep(sleep_deadline - ZX_MSEC(50));
492
493    // Suspend the thread.
494    zx_handle_t suspend_token = ZX_HANDLE_INVALID;
495    zx_status_t status = zx_task_suspend_token(thread_h, &suspend_token);
496    if (status != ZX_OK) {
497        ASSERT_EQ(status, ZX_ERR_BAD_STATE);
498        // This might happen if the thread exits before we tried suspending it
499        // (due to e.g. a long context-switch away).  The system is too loaded
500        // and so we might not have a chance at success here without a massive
501        // sleep duration.
502        zx_info_thread_t info;
503        ASSERT_EQ(zx_object_get_info(thread_h, ZX_INFO_THREAD,
504                                     &info, sizeof(info), NULL, NULL),
505                  ZX_OK);
506        ASSERT_EQ(info.state, ZX_THREAD_STATE_DEAD);
507        ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
508        // Early bail from the test, since we hit a possible race from an
509        // overloaded machine.
510        END_TEST;
511    }
512    ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_SUSPENDED, ZX_TIME_INFINITE, NULL), ZX_OK);
513    ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
514
515    // Wait for the sleep to finish
516    ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL),
517              ZX_OK);
518
519    const zx_time_t now = zx_clock_get_monotonic();
520    ASSERT_GE(now, sleep_deadline, "thread did not sleep long enough");
521
522    ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
523    END_TEST;
524}
525
526static bool test_suspend_channel_call() {
527    BEGIN_TEST;
528
529    zxr_thread_t thread;
530
531    zx_handle_t channel;
532    channel_call_suspend_test_arg thread_arg;
533    ASSERT_EQ(zx_channel_create(0, &thread_arg.channel, &channel), ZX_OK);
534    thread_arg.call_status = ZX_ERR_BAD_STATE;
535
536    zx_handle_t thread_h;
537    ASSERT_TRUE(start_thread(threads_test_channel_call_fn, &thread_arg, &thread, &thread_h));
538
539    // Wait for the thread to send a channel call before suspending it
540    ASSERT_EQ(zx_object_wait_one(channel, ZX_CHANNEL_READABLE, ZX_TIME_INFINITE, NULL),
541              ZX_OK);
542
543    // Suspend the thread.
544    zx_handle_t suspend_token = ZX_HANDLE_INVALID;
545    ASSERT_TRUE(suspend_thread_synchronous(thread_h, &suspend_token));
546
547    // Read the message
548    uint8_t buf[9];
549    uint32_t actual_bytes;
550    ASSERT_EQ(zx_channel_read(channel, 0, buf, NULL, sizeof(buf), 0, &actual_bytes, NULL),
551              ZX_OK);
552    ASSERT_EQ(actual_bytes, sizeof(buf));
553    ASSERT_EQ(memcmp(buf + sizeof(zx_txid_t), "abcdefghi" + sizeof(zx_txid_t), sizeof(buf) - sizeof(zx_txid_t)), 0);
554
555    // Write a reply
556    buf[8] = 'j';
557    ASSERT_EQ(zx_channel_write(channel, 0, buf, sizeof(buf), NULL, 0), ZX_OK);
558
559    // Make sure the remote channel didn't get signaled
560    EXPECT_EQ(zx_object_wait_one(thread_arg.channel, ZX_CHANNEL_READABLE, 0, NULL),
561              ZX_ERR_TIMED_OUT);
562
563    // Make sure we can't read from the remote channel (the message should have
564    // been reserved for the other thread, even though it is suspended).
565    EXPECT_EQ(zx_channel_read(thread_arg.channel, 0, buf, NULL, sizeof(buf), 0,
566                              &actual_bytes, NULL),
567              ZX_ERR_SHOULD_WAIT);
568
569    // Wake the suspended thread
570    ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
571
572    // Wait for the thread to finish
573    ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL),
574              ZX_OK);
575    EXPECT_EQ(thread_arg.call_status, ZX_OK);
576
577    ASSERT_EQ(zx_handle_close(channel), ZX_OK);
578    ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
579
580    END_TEST;
581}
582
583static bool test_suspend_port_call() {
584    BEGIN_TEST;
585
586    zxr_thread_t thread;
587    zx_handle_t port[2];
588    ASSERT_EQ(zx_port_create(0, &port[0]), ZX_OK);
589    ASSERT_EQ(zx_port_create(0, &port[1]), ZX_OK);
590
591    zx_handle_t thread_h;
592    ASSERT_TRUE(start_thread(threads_test_port_fn, port, &thread, &thread_h));
593
594    zx_nanosleep(zx_deadline_after(ZX_MSEC(100)));
595    zx_handle_t suspend_token = ZX_HANDLE_INVALID;
596    ASSERT_EQ(zx_task_suspend_token(thread_h, &suspend_token), ZX_OK);
597
598    zx_port_packet_t packet1 = {100ull, ZX_PKT_TYPE_USER, 0u, {}};
599    zx_port_packet_t packet2 = {300ull, ZX_PKT_TYPE_USER, 0u, {}};
600
601    ASSERT_EQ(zx_port_queue(port[0], &packet1), ZX_OK);
602    ASSERT_EQ(zx_port_queue(port[0], &packet2), ZX_OK);
603
604    zx_port_packet_t packet;
605    ASSERT_EQ(zx_port_wait(port[1], zx_deadline_after(ZX_MSEC(100)), &packet), ZX_ERR_TIMED_OUT);
606
607    ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
608
609    ASSERT_EQ(zx_port_wait(port[1], ZX_TIME_INFINITE, &packet), ZX_OK);
610    EXPECT_EQ(packet.key, 105ull);
611
612    ASSERT_EQ(zx_port_wait(port[0], ZX_TIME_INFINITE, &packet), ZX_OK);
613    EXPECT_EQ(packet.key, 300ull);
614
615    ASSERT_EQ(zx_object_wait_one(
616                  thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL),
617              ZX_OK);
618
619    ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
620    ASSERT_EQ(zx_handle_close(port[0]), ZX_OK);
621    ASSERT_EQ(zx_handle_close(port[1]), ZX_OK);
622
623    END_TEST;
624}
625
626struct test_writing_thread_arg {
627    volatile int v;
628};
629
630__NO_SAFESTACK static void test_writing_thread_fn(void* arg_) {
631    test_writing_thread_arg* arg = static_cast<test_writing_thread_arg*>(arg_);
632    while (true) {
633        arg->v = 1;
634    }
635    __builtin_trap();
636}
637
638static bool test_suspend_stops_thread() {
639    BEGIN_TEST;
640
641    zxr_thread_t thread;
642
643    test_writing_thread_arg arg = {.v = 0};
644    zx_handle_t thread_h;
645    ASSERT_TRUE(start_thread(test_writing_thread_fn, &arg, &thread, &thread_h));
646
647    while (arg.v != 1) {
648        zx_nanosleep(0);
649    }
650
651    zx_handle_t suspend_token = ZX_HANDLE_INVALID;
652    ASSERT_EQ(zx_task_suspend_token(thread_h, &suspend_token), ZX_OK);
653    while (arg.v != 2) {
654        arg.v = 2;
655        // Give the thread a chance to clobber the value
656        zx_nanosleep(zx_deadline_after(ZX_MSEC(50)));
657    }
658    ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
659    while (arg.v != 1) {
660        zx_nanosleep(0);
661    }
662
663    // Clean up.
664    ASSERT_EQ(zx_task_kill(thread_h), ZX_OK);
665    // Wait for the thread termination to complete.  We should do this so
666    // that any later tests which use set_debugger_exception_port() do not
667    // receive an ZX_EXCP_THREAD_EXITING event.
668    ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED,
669                                 ZX_TIME_INFINITE, NULL),
670              ZX_OK);
671    ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
672
673    END_TEST;
674}
675
676static bool test_suspend_multiple() {
677    BEGIN_TEST;
678
679    // TODO(brettw) ZX-1072 Fix this test and enable. Currently suspend tokens
680    // and exception resumption don't interact well and resuming from an
681    // exception will resume the thread, even if there is an open suspend
682    // token.
683
684    zx_handle_t event;
685    zxr_thread_t thread;
686    zx_handle_t thread_h;
687
688    ASSERT_EQ(zx_event_create(0, &event), ZX_OK);
689    ASSERT_TRUE(start_thread(threads_test_wait_break_infinite_sleep_fn, &event, &thread,
690                             &thread_h));
691
692    // The thread will now be blocked on the event. Wake it up and catch the trap (undefined
693    // exception).
694    zx_handle_t exception_port = ZX_HANDLE_INVALID;
695    ASSERT_TRUE(set_debugger_exception_port(&exception_port));
696    ASSERT_EQ(zx_object_signal(event, 0, ZX_USER_SIGNAL_0), ZX_OK);
697    ASSERT_TRUE(wait_thread_excp_type(thread_h, exception_port, ZX_EXCP_SW_BREAKPOINT,
698                                      ZX_EXCP_THREAD_STARTING));
699
700    // The thread should now be blocked on a debugger exception.
701    ASSERT_TRUE(wait_thread_blocked(thread_h, ZX_THREAD_STATE_BLOCKED_EXCEPTION));
702    zx_info_thread_t info;
703    ASSERT_TRUE(get_thread_info(thread_h, &info));
704    ASSERT_EQ(info.wait_exception_port_type, ZX_EXCEPTION_PORT_TYPE_DEBUGGER);
705
706    advance_over_breakpoint(thread_h);
707
708    // Suspend twice (on top of the existing exception). Don't use the synchronous suspend since
709    // suspends don't escape out of exception handling, unlike blocking
710    // syscalls where suspend will escape out of them.
711    zx_handle_t suspend_token1 = ZX_HANDLE_INVALID;
712    ASSERT_EQ(zx_task_suspend_token(thread_h, &suspend_token1), ZX_OK);
713    zx_handle_t suspend_token2 = ZX_HANDLE_INVALID;
714    ASSERT_EQ(zx_task_suspend_token(thread_h, &suspend_token2), ZX_OK);
715
716    // Resume one token, it should remain blocked.
717    ASSERT_EQ(zx_handle_close(suspend_token1), ZX_OK);
718    ASSERT_TRUE(get_thread_info(thread_h, &info));
719    // Note: If this check is flaky, it's failing. It should not transition out of the blocked
720    // state, but if it does so, it will do so asynchronously which might cause
721    // nondeterministic failures.
722    ASSERT_EQ(info.state, ZX_THREAD_STATE_BLOCKED_EXCEPTION);
723
724    // Resume from the exception with invalid options.
725    ASSERT_EQ(zx_task_resume_from_exception(thread_h, exception_port, 23), ZX_ERR_INVALID_ARGS);
726
727    // Resume the exception. It should be SUSPENDED now that the exception is complete (one could
728    // argue that it could still be BLOCKED also, but it's not in the current implementation).
729    // The transition to SUSPENDED happens asynchronously unlike some of the exception states.
730    ASSERT_EQ(zx_task_resume_from_exception(thread_h, exception_port, 0), ZX_OK);
731    zx_signals_t observed = 0u;
732    ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_SUSPENDED, ZX_TIME_INFINITE, &observed),
733              ZX_OK);
734
735    ASSERT_TRUE(get_thread_info(thread_h, &info));
736    ASSERT_EQ(info.state, ZX_THREAD_STATE_SUSPENDED);
737
738    // 2nd resume, should be running or sleeping after this.
739    ASSERT_TRUE(resume_thread_synchronous(thread_h, suspend_token2));
740    ASSERT_TRUE(get_thread_info(thread_h, &info));
741    ASSERT_TRUE(info.state == ZX_THREAD_STATE_RUNNING || info.state == ZX_THREAD_STATE_BLOCKED_SLEEPING);
742
743    // Clean up.
744    clear_debugger_exception_port();
745    ASSERT_EQ(zx_task_kill(thread_h), ZX_OK);
746    ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
747
748    END_TEST;
749}
750
751// This tests for a bug in which killing a suspended thread causes the
752// thread to be resumed and execute more instructions in userland.
753static bool test_kill_suspended_thread() {
754    BEGIN_TEST;
755
756    zxr_thread_t thread;
757    test_writing_thread_arg arg = {.v = 0};
758    zx_handle_t thread_h;
759    ASSERT_TRUE(start_thread(test_writing_thread_fn, &arg, &thread, &thread_h));
760
761    // Wait until the thread has started and has modified arg.v.
762    while (arg.v != 1) {
763        zx_nanosleep(0);
764    }
765
766    zx_handle_t suspend_token = ZX_HANDLE_INVALID;
767    ASSERT_TRUE(suspend_thread_synchronous(thread_h, &suspend_token));
768
769    // Attach to debugger port so we can see ZX_EXCP_THREAD_EXITING.
770    zx_handle_t eport;
771    ASSERT_TRUE(set_debugger_exception_port(&eport));
772
773    // Reset the test memory location.
774    arg.v = 100;
775    ASSERT_EQ(zx_task_kill(thread_h), ZX_OK);
776    // Wait for the thread termination to complete.
777    ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED,
778                                 ZX_TIME_INFINITE, NULL),
779              ZX_OK);
780    // Check for the bug.  The thread should not have resumed execution and
781    // so should not have modified arg.v.
782    EXPECT_EQ(arg.v, 100);
783
784    // Check that the thread is reported as exiting and not as resumed.
785    ASSERT_TRUE(wait_thread_excp_type(thread_h, eport, ZX_EXCP_THREAD_EXITING, 0));
786
787    // Clean up.
788    clear_debugger_exception_port();
789    ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
790    ASSERT_EQ(zx_handle_close(eport), ZX_OK);
791    ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
792
793    END_TEST;
794}
795
796static bool port_wait_for_signal_once(zx_handle_t port, zx_handle_t thread,
797                                      zx_time_t deadline, zx_signals_t mask,
798                                      zx_port_packet_t* packet) {
799    ASSERT_EQ(zx_object_wait_async(thread, port, 0u, mask,
800                                   ZX_WAIT_ASYNC_ONCE),
801              ZX_OK);
802    ASSERT_EQ(zx_port_wait(port, deadline, packet), ZX_OK);
803    ASSERT_EQ(packet->type, ZX_PKT_TYPE_SIGNAL_ONE);
804    return true;
805}
806
807static bool port_wait_for_signal_repeating(zx_handle_t port,
808                                           zx_time_t deadline,
809                                           zx_port_packet_t* packet) {
810    ASSERT_EQ(zx_port_wait(port, deadline, packet), ZX_OK);
811    ASSERT_EQ(packet->type, ZX_PKT_TYPE_SIGNAL_REP);
812    return true;
813}
814
815// Test signal delivery of suspended threads via async wait.
816static bool test_suspend_wait_async_signal_delivery_worker(bool use_repeating) {
817    zx_handle_t event;
818    zx_handle_t port;
819    zxr_thread_t thread;
820    zx_handle_t thread_h;
821    const zx_signals_t run_susp_mask = ZX_THREAD_RUNNING | ZX_THREAD_SUSPENDED;
822
823    ASSERT_EQ(zx_event_create(0, &event), ZX_OK);
824    ASSERT_TRUE(start_thread(threads_test_wait_fn, &event, &thread, &thread_h));
825
826    ASSERT_EQ(zx_port_create(0, &port), ZX_OK);
827    if (use_repeating) {
828        ASSERT_EQ(zx_object_wait_async(thread_h, port, 0u, run_susp_mask,
829                                       ZX_WAIT_ASYNC_REPEATING),
830                  ZX_OK);
831    }
832
833    zx_port_packet_t packet;
834    // There should be a RUNNING signal packet present and not SUSPENDED.
835    // This is from when the thread first started to run.
836    if (use_repeating) {
837        ASSERT_TRUE(port_wait_for_signal_repeating(port, 0u, &packet));
838    } else {
839        ASSERT_TRUE(port_wait_for_signal_once(port, thread_h, 0u, run_susp_mask, &packet));
840    }
841    ASSERT_EQ(packet.signal.observed & run_susp_mask, ZX_THREAD_RUNNING);
842
843    // Make sure there are no more packets.
844    if (use_repeating) {
845        ASSERT_EQ(zx_port_wait(port, 0u, &packet), ZX_ERR_TIMED_OUT);
846    } else {
847        // In the non-repeating case we have to do things differently as one of
848        // RUNNING or SUSPENDED is always asserted.
849        ASSERT_EQ(zx_object_wait_async(thread_h, port, 0u,
850                                       ZX_THREAD_SUSPENDED,
851                                       ZX_WAIT_ASYNC_ONCE),
852                  ZX_OK);
853        ASSERT_EQ(zx_port_wait(port, 0u, &packet), ZX_ERR_TIMED_OUT);
854        ASSERT_EQ(zx_port_cancel(port, thread_h, 0u), ZX_OK);
855    }
856
857    zx_handle_t suspend_token = ZX_HANDLE_INVALID;
858    ASSERT_TRUE(suspend_thread_synchronous(thread_h, &suspend_token));
859
860    zx_info_thread_t info;
861    ASSERT_TRUE(get_thread_info(thread_h, &info));
862    ASSERT_EQ(info.state, ZX_THREAD_STATE_SUSPENDED);
863
864    ASSERT_TRUE(resume_thread_synchronous(thread_h, suspend_token));
865    ASSERT_TRUE(get_thread_info(thread_h, &info));
866    // At this point the thread may be running or blocked waiting for an
867    // event. Either one is fine. threads_test_wait_fn() uses
868    // zx_object_wait_one() so we watch for that.
869    ASSERT_TRUE(info.state == ZX_THREAD_STATE_RUNNING ||
870                    info.state == ZX_THREAD_STATE_BLOCKED_WAIT_ONE);
871
872    // For repeating async waits we should see both SUSPENDED and RUNNING on
873    // the port. And we should see them at the same time (and not one followed
874    // by the other).
875    if (use_repeating) {
876        ASSERT_TRUE(port_wait_for_signal_repeating(port,
877                                                   zx_deadline_after(ZX_MSEC(100)),
878                                                   &packet));
879        ASSERT_EQ(packet.signal.observed & run_susp_mask, run_susp_mask);
880    } else {
881        // For non-repeating async waits we should see just RUNNING,
882        // and it should be immediately present (no deadline).
883        ASSERT_TRUE(port_wait_for_signal_once(port, thread_h, 0u, run_susp_mask,
884                                              &packet));
885        ASSERT_EQ(packet.signal.observed & run_susp_mask, ZX_THREAD_RUNNING);
886    }
887
888    // The thread should still be blocked on the event when it wakes up.
889    ASSERT_TRUE(wait_thread_blocked(thread_h, ZX_THREAD_STATE_BLOCKED_WAIT_ONE));
890
891    // Check that suspend/resume while blocked in a syscall results in
892    // the expected behavior and is visible via async wait.
893    suspend_token = ZX_HANDLE_INVALID;
894    ASSERT_EQ(zx_task_suspend_token(thread_h, &suspend_token), ZX_OK);
895    if (use_repeating) {
896        ASSERT_TRUE(port_wait_for_signal_repeating(port,
897                                                   zx_deadline_after(ZX_MSEC(100)),
898                                                   &packet));
899    } else {
900        ASSERT_TRUE(port_wait_for_signal_once(port, thread_h,
901                                              zx_deadline_after(ZX_MSEC(100)),
902                                              ZX_THREAD_SUSPENDED, &packet));
903    }
904    ASSERT_EQ(packet.signal.observed & run_susp_mask, ZX_THREAD_SUSPENDED);
905
906    ASSERT_TRUE(get_thread_info(thread_h, &info));
907    ASSERT_EQ(info.state, ZX_THREAD_STATE_SUSPENDED);
908    ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
909    if (use_repeating) {
910        ASSERT_TRUE(port_wait_for_signal_repeating(port,
911                                                   zx_deadline_after(ZX_MSEC(100)),
912                                                   &packet));
913    } else {
914        ASSERT_TRUE(port_wait_for_signal_once(port, thread_h,
915                                              zx_deadline_after(ZX_MSEC(100)),
916                                              ZX_THREAD_RUNNING, &packet));
917    }
918    ASSERT_EQ(packet.signal.observed & run_susp_mask, ZX_THREAD_RUNNING);
919
920    // Resumption from being suspended back into a blocking syscall will be
921    // in the RUNNING state and then BLOCKED.
922    ASSERT_TRUE(wait_thread_blocked(thread_h, ZX_THREAD_STATE_BLOCKED_WAIT_ONE));
923
924    ASSERT_EQ(zx_object_signal(event, 0, ZX_USER_SIGNAL_0), ZX_OK);
925    ASSERT_EQ(zx_object_wait_one(event, ZX_USER_SIGNAL_1, ZX_TIME_INFINITE, NULL), ZX_OK);
926
927    ASSERT_EQ(zx_object_wait_one(
928                  thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL),
929              ZX_OK);
930
931    ASSERT_EQ(zx_handle_close(port), ZX_OK);
932    ASSERT_EQ(zx_handle_close(event), ZX_OK);
933    ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
934
935    return true;
936}
937
938// Test signal delivery of suspended threads via single async wait.
939static bool test_suspend_single_wait_async_signal_delivery() {
940    BEGIN_TEST;
941    EXPECT_TRUE(test_suspend_wait_async_signal_delivery_worker(false));
942    END_TEST;
943}
944
945// Test signal delivery of suspended threads via repeating async wait.
946static bool test_suspend_repeating_wait_async_signal_delivery() {
947    BEGIN_TEST;
948    EXPECT_TRUE(test_suspend_wait_async_signal_delivery_worker(true));
949    END_TEST;
950}
951
952// Helper class for setting up a test for reading register state from a worker thread.
953template <typename RegisterStruct>
954class RegisterReadSetup {
955public:
956    using ThreadFunc = void (*)(RegisterStruct*);
957
958    RegisterReadSetup() = default;
959    ~RegisterReadSetup() {
960        zx_handle_close(suspend_token_);
961        zx_task_kill(thread_handle_);
962        // Wait for the thread termination to complete.
963        zx_object_wait_one(thread_handle_, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL);
964        zx_handle_close(thread_handle_);
965    }
966
967    zx_handle_t thread_handle() const { return thread_handle_; }
968
969    // Pass the thread function to run and the parameter to pass to it.
970    bool Init(ThreadFunc thread_func, RegisterStruct* state) {
971        BEGIN_HELPER;
972
973        ASSERT_TRUE(start_thread((void (*)(void*))thread_func, state, &thread_, &thread_handle_));
974
975        // Allow some time for the thread to begin execution and reach the
976        // instruction that spins.
977        ASSERT_EQ(zx_nanosleep(zx_deadline_after(ZX_MSEC(100))), ZX_OK);
978
979        ASSERT_TRUE(suspend_thread_synchronous(thread_handle_, &suspend_token_));
980
981        END_HELPER;
982    }
983
984private:
985    zxr_thread_t thread_;
986    zx_handle_t thread_handle_ = ZX_HANDLE_INVALID;
987    zx_handle_t suspend_token_ = ZX_HANDLE_INVALID;
988};
989
990// This tests the registers reported by zx_thread_read_state() for a
991// suspended thread.  It starts a thread which sets all the registers to
992// known test values.
993static bool test_reading_general_register_state() {
994    BEGIN_TEST;
995
996    zx_thread_state_general_regs_t gen_regs_expected;
997    general_regs_fill_test_values(&gen_regs_expected);
998    gen_regs_expected.REG_PC = (uintptr_t)spin_with_general_regs_spin_address;
999
1000    RegisterReadSetup<zx_thread_state_general_regs_t> setup;
1001    ASSERT_TRUE(setup.Init(&spin_with_general_regs, &gen_regs_expected));
1002
1003    zx_thread_state_general_regs_t regs;
1004    ASSERT_EQ(zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_GENERAL_REGS,
1005                                   &regs, sizeof(regs)),
1006              ZX_OK);
1007    ASSERT_TRUE(general_regs_expect_eq(regs, gen_regs_expected));
1008
1009    END_TEST;
1010}
1011
1012static bool test_reading_fp_register_state() {
1013    BEGIN_TEST;
1014
1015    zx_thread_state_fp_regs_t fp_regs_expected;
1016    fp_regs_fill_test_values(&fp_regs_expected);
1017
1018    RegisterReadSetup<zx_thread_state_fp_regs_t> setup;
1019    ASSERT_TRUE(setup.Init(&spin_with_fp_regs, &fp_regs_expected));
1020
1021    zx_thread_state_fp_regs_t regs;
1022    ASSERT_EQ(zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_FP_REGS,
1023                                   &regs, sizeof(regs)),
1024              ZX_OK);
1025    ASSERT_TRUE(fp_regs_expect_eq(regs, fp_regs_expected));
1026
1027    END_TEST;
1028}
1029
1030static bool test_reading_vector_register_state() {
1031    BEGIN_TEST;
1032
1033    zx_thread_state_vector_regs_t vector_regs_expected;
1034    vector_regs_fill_test_values(&vector_regs_expected);
1035
1036    RegisterReadSetup<zx_thread_state_vector_regs_t> setup;
1037    ASSERT_TRUE(setup.Init(&spin_with_vector_regs, &vector_regs_expected));
1038
1039    zx_thread_state_vector_regs_t regs;
1040    ASSERT_EQ(zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_VECTOR_REGS,
1041                                   &regs, sizeof(regs)),
1042              ZX_OK);
1043
1044    ASSERT_TRUE(vector_regs_expect_eq(regs, vector_regs_expected));
1045
1046    END_TEST;
1047}
1048
1049// Procedure:
1050//  1. Call Init() which will start a thread and suspend it.
1051//  2. Write the register state you want to the thread_handle().
1052//  3. Call DoSave with the save function and pointer. This will execute that code in the context of
1053//     the thread.
1054template <typename RegisterStruct>
1055class RegisterWriteSetup {
1056public:
1057    using SaveFunc = void (*)();
1058
1059    RegisterWriteSetup() = default;
1060    ~RegisterWriteSetup() {
1061        zx_handle_close(thread_handle_);
1062    }
1063
1064    zx_handle_t thread_handle() const { return thread_handle_; }
1065
1066    bool Init() {
1067        BEGIN_HELPER;
1068
1069        ASSERT_TRUE(start_thread(threads_test_busy_fn, nullptr, &thread_, &thread_handle_));
1070        // Allow some time for the thread to begin execution and reach the
1071        // instruction that spins.
1072        ASSERT_EQ(zx_nanosleep(zx_deadline_after(ZX_MSEC(100))), ZX_OK);
1073        ASSERT_TRUE(suspend_thread_synchronous(thread_handle_, &suspend_token_));
1074
1075        END_HELPER;
1076    }
1077
1078    // The IP and SP set in the general registers will be filled in to the optional output
1079    // parameters. This is for the general register test since we change those values out from
1080    // under it.
1081    bool DoSave(SaveFunc save_func, RegisterStruct* out,
1082                uint64_t* general_ip = nullptr, uint64_t* general_sp = nullptr) {
1083        BEGIN_HELPER;
1084
1085        // Modify the PC to point to the routine, and the SP to point to the output struct.
1086        zx_thread_state_general_regs_t general_regs;
1087        ASSERT_EQ(zx_thread_read_state(thread_handle_, ZX_THREAD_STATE_GENERAL_REGS,
1088                                       &general_regs, sizeof(general_regs)),
1089                  ZX_OK);
1090
1091        struct {
1092            // A small stack that is used for calling zx_thread_exit().
1093            char stack[1024] __ALIGNED(16);
1094            RegisterStruct regs_got; // STACK_PTR will point here.
1095        } stack;
1096        general_regs.REG_PC = (uintptr_t)save_func;
1097        general_regs.REG_STACK_PTR = (uintptr_t)(stack.stack + sizeof(stack.stack));
1098        ASSERT_EQ(zx_thread_write_state(thread_handle_, ZX_THREAD_STATE_GENERAL_REGS,
1099                                        &general_regs, sizeof(general_regs)),
1100                  ZX_OK);
1101
1102        if (general_ip)
1103            *general_ip = general_regs.REG_PC;
1104        if (general_sp)
1105            *general_sp = general_regs.REG_STACK_PTR;
1106
1107        // Unsuspend the thread and wait for it to finish executing, this will run the code
1108        // and fill the RegisterStruct we passed.
1109        ASSERT_EQ(zx_handle_close(suspend_token_), ZX_OK);
1110        suspend_token_ = ZX_HANDLE_INVALID;
1111        ASSERT_EQ(zx_object_wait_one(thread_handle_, ZX_THREAD_TERMINATED,
1112                                     ZX_TIME_INFINITE, NULL),
1113                  ZX_OK);
1114
1115        memcpy(out, &stack.regs_got, sizeof(RegisterStruct));
1116
1117        END_HELPER;
1118    }
1119
1120private:
1121    zxr_thread_t thread_;
1122    zx_handle_t thread_handle_ = ZX_HANDLE_INVALID;
1123    zx_handle_t suspend_token_ = ZX_HANDLE_INVALID;
1124};
1125
1126// This tests writing registers using zx_thread_write_state().  After
1127// setting registers using that syscall, it reads back the registers and
1128// checks their values.
1129static bool test_writing_general_register_state() {
1130    BEGIN_TEST;
1131
1132    RegisterWriteSetup<zx_thread_state_general_regs_t> setup;
1133    ASSERT_TRUE(setup.Init());
1134
1135    // Set the general registers.
1136    zx_thread_state_general_regs_t regs_to_set;
1137    general_regs_fill_test_values(&regs_to_set);
1138    ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_GENERAL_REGS,
1139                                    &regs_to_set, sizeof(regs_to_set)),
1140              ZX_OK);
1141
1142    zx_thread_state_general_regs_t regs;
1143    uint64_t ip = 0, sp = 0;
1144    ASSERT_TRUE(setup.DoSave(&save_general_regs_and_exit_thread, &regs, &ip, &sp));
1145
1146    // Fix up the expected values with the IP/SP required for the register read.
1147    regs_to_set.REG_PC = ip;
1148    regs_to_set.REG_STACK_PTR = sp;
1149    EXPECT_TRUE(general_regs_expect_eq(regs_to_set, regs));
1150
1151    END_TEST;
1152}
1153
1154static bool test_writing_fp_register_state() {
1155    BEGIN_TEST;
1156
1157    RegisterWriteSetup<zx_thread_state_fp_regs_t> setup;
1158    ASSERT_TRUE(setup.Init());
1159
1160    // The busyloop code executed initially by the setup class will have executed an MMX instruction
1161    // so that the MMX state is available to write.
1162    zx_thread_state_fp_regs_t regs_to_set;
1163    fp_regs_fill_test_values(&regs_to_set);
1164    ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_FP_REGS,
1165                                    &regs_to_set, sizeof(regs_to_set)),
1166              ZX_OK);
1167
1168    zx_thread_state_fp_regs_t regs;
1169    ASSERT_TRUE(setup.DoSave(&save_fp_regs_and_exit_thread, &regs));
1170    EXPECT_TRUE(fp_regs_expect_eq(regs_to_set, regs));
1171
1172    END_TEST;
1173}
1174
1175static bool test_writing_vector_register_state() {
1176    BEGIN_TEST;
1177
1178    RegisterWriteSetup<zx_thread_state_vector_regs_t> setup;
1179    ASSERT_TRUE(setup.Init());
1180
1181    zx_thread_state_vector_regs_t regs_to_set;
1182    vector_regs_fill_test_values(&regs_to_set);
1183    ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_VECTOR_REGS,
1184                                    &regs_to_set, sizeof(regs_to_set)),
1185              ZX_OK);
1186
1187    zx_thread_state_vector_regs_t regs;
1188    ASSERT_TRUE(setup.DoSave(&save_vector_regs_and_exit_thread, &regs));
1189    EXPECT_TRUE(vector_regs_expect_eq(regs_to_set, regs));
1190
1191    END_TEST;
1192}
1193
1194#if defined(__x86_64__)
1195
1196#include <cpuid.h>
1197
1198// This is based on code from kernel/ which isn't usable by code in system/.
1199enum { X86_CPUID_ADDR_WIDTH = 0x80000008 };
1200
1201static uint32_t x86_linear_address_width() {
1202    uint32_t eax, ebx, ecx, edx;
1203    __cpuid(X86_CPUID_ADDR_WIDTH, eax, ebx, ecx, edx);
1204    return (eax >> 8) & 0xff;
1205}
1206
1207#endif
1208
1209// Test that zx_thread_write_state() does not allow setting RIP to a
1210// non-canonical address for a thread that was suspended inside a syscall,
1211// because if the kernel returns to that address using SYSRET, that can
1212// cause a fault in kernel mode that is exploitable.  See
1213// sysret_problem.md.
1214static bool test_noncanonical_rip_address() {
1215    BEGIN_TEST;
1216
1217#if defined(__x86_64__)
1218    zx_handle_t event;
1219    ASSERT_EQ(zx_event_create(0, &event), ZX_OK);
1220    zxr_thread_t thread;
1221    zx_handle_t thread_handle;
1222    ASSERT_TRUE(start_thread(threads_test_wait_fn, &event, &thread, &thread_handle));
1223
1224    // Allow some time for the thread to begin execution and block inside
1225    // the syscall.
1226    ASSERT_EQ(zx_nanosleep(zx_deadline_after(ZX_MSEC(100))), ZX_OK);
1227
1228    zx_handle_t suspend_token = ZX_HANDLE_INVALID;
1229    ASSERT_TRUE(suspend_thread_synchronous(thread_handle, &suspend_token));
1230
1231    zx_thread_state_general_regs_t regs;
1232    ASSERT_EQ(zx_thread_read_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS,
1233                                   &regs, sizeof(regs)),
1234              ZX_OK);
1235
1236    // Example addresses to test.
1237    uintptr_t noncanonical_addr =
1238        ((uintptr_t)1) << (x86_linear_address_width() - 1);
1239    uintptr_t canonical_addr = noncanonical_addr - 1;
1240    uint64_t kKernelAddr = 0xffff800000000000;
1241
1242    zx_thread_state_general_regs_t regs_modified = regs;
1243
1244    // This RIP address must be disallowed.
1245    regs_modified.rip = noncanonical_addr;
1246    ASSERT_EQ(zx_thread_write_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS,
1247                                    &regs_modified, sizeof(regs_modified)),
1248              ZX_ERR_INVALID_ARGS);
1249
1250    regs_modified.rip = canonical_addr;
1251    ASSERT_EQ(zx_thread_write_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS,
1252                                    &regs_modified, sizeof(regs_modified)),
1253              ZX_OK);
1254
1255    // This RIP address does not need to be disallowed, but it is currently
1256    // disallowed because this simplifies the check and it's not useful to
1257    // allow this address.
1258    regs_modified.rip = kKernelAddr;
1259    ASSERT_EQ(zx_thread_write_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS,
1260                                    &regs_modified, sizeof(regs_modified)),
1261              ZX_ERR_INVALID_ARGS);
1262
1263    // Clean up: Restore the original register state.
1264    ASSERT_EQ(zx_thread_write_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS,
1265                                    &regs, sizeof(regs)),
1266              ZX_OK);
1267    // Allow the child thread to resume and exit.
1268    ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
1269    ASSERT_EQ(zx_object_signal(event, 0, ZX_USER_SIGNAL_0), ZX_OK);
1270    // Wait for the child thread to signal that it has continued.
1271    ASSERT_EQ(zx_object_wait_one(event, ZX_USER_SIGNAL_1, ZX_TIME_INFINITE,
1272                                 NULL),
1273              ZX_OK);
1274    // Wait for the child thread to exit.
1275    ASSERT_EQ(zx_object_wait_one(thread_handle, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE,
1276                                 NULL),
1277              ZX_OK);
1278    ASSERT_EQ(zx_handle_close(event), ZX_OK);
1279    ASSERT_EQ(zx_handle_close(thread_handle), ZX_OK);
1280#endif
1281
1282    END_TEST;
1283}
1284
1285// Test that, on ARM64, userland cannot use zx_thread_write_state() to
1286// modify flag bits such as I and F (bits 7 and 6), which are the IRQ and
1287// FIQ interrupt disable flags.  We don't want userland to be able to set
1288// those flags to 1, since that would disable interrupts.  Also, userland
1289// should not be able to read these bits.
1290static bool test_writing_arm_flags_register() {
1291    BEGIN_TEST;
1292
1293#if defined(__aarch64__)
1294    test_writing_thread_arg arg = {.v = 0};
1295    zxr_thread_t thread;
1296    zx_handle_t thread_handle;
1297    ASSERT_TRUE(start_thread(test_writing_thread_fn, &arg, &thread,
1298                             &thread_handle));
1299    // Wait for the thread to start executing and enter its main loop.
1300    while (arg.v != 1) {
1301        ASSERT_EQ(zx_nanosleep(zx_deadline_after(ZX_USEC(1))), ZX_OK);
1302    }
1303    zx_handle_t suspend_token = ZX_HANDLE_INVALID;
1304    ASSERT_TRUE(suspend_thread_synchronous(thread_handle, &suspend_token));
1305
1306    zx_thread_state_general_regs_t regs;
1307    ASSERT_EQ(zx_thread_read_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS,
1308                                   &regs, sizeof(regs)),
1309              ZX_OK);
1310
1311    // Check that zx_thread_read_state() does not report any more flag bits
1312    // than are readable via userland instructions.
1313    const uint64_t kUserVisibleFlags = 0xf0000000;
1314    EXPECT_EQ(regs.cpsr & ~kUserVisibleFlags, 0u);
1315
1316    // Try setting more flag bits.
1317    uint64_t original_cpsr = regs.cpsr;
1318    regs.cpsr |= ~kUserVisibleFlags;
1319    ASSERT_EQ(zx_thread_write_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS,
1320                                    &regs, sizeof(regs)),
1321              ZX_OK);
1322
1323    // Firstly, if we read back the register flag, the extra flag bits
1324    // should have been ignored and should not be reported as set.
1325    ASSERT_EQ(zx_thread_read_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS,
1326                                   &regs, sizeof(regs)),
1327              ZX_OK);
1328    EXPECT_EQ(regs.cpsr, original_cpsr);
1329
1330    // Secondly, if we resume the thread, we should be able to kill it.  If
1331    // zx_thread_write_state() set the interrupt disable flags, then if the
1332    // thread gets scheduled, it will never get interrupted and we will not
1333    // be able to kill and join the thread.
1334    arg.v = 0;
1335    ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
1336    // Wait until the thread has actually resumed execution.
1337    while (arg.v != 1) {
1338        ASSERT_EQ(zx_nanosleep(zx_deadline_after(ZX_USEC(1))), ZX_OK);
1339    }
1340    ASSERT_EQ(zx_task_kill(thread_handle), ZX_OK);
1341    ASSERT_EQ(zx_object_wait_one(thread_handle, ZX_THREAD_TERMINATED,
1342                                 ZX_TIME_INFINITE, NULL),
1343              ZX_OK);
1344
1345// Clean up.
1346#endif
1347
1348    END_TEST;
1349}
1350
1351BEGIN_TEST_CASE(threads_tests)
1352RUN_TEST(test_basics)
1353RUN_TEST(test_detach)
1354RUN_TEST(test_long_name_succeeds)
1355RUN_TEST(test_thread_start_on_initial_thread)
1356RUN_TEST_ENABLE_CRASH_HANDLER(test_thread_start_with_zero_instruction_pointer)
1357RUN_TEST(test_kill_busy_thread)
1358RUN_TEST(test_kill_sleep_thread)
1359RUN_TEST(test_kill_wait_thread)
1360RUN_TEST(test_bad_state_nonstarted_thread)
1361RUN_TEST(test_thread_kills_itself)
1362RUN_TEST(test_info_task_stats_fails)
1363RUN_TEST(test_resume_suspended)
1364RUN_TEST(test_suspend_sleeping)
1365RUN_TEST(test_suspend_channel_call)
1366RUN_TEST(test_suspend_port_call)
1367RUN_TEST(test_suspend_stops_thread)
1368RUN_TEST(test_suspend_multiple)
1369RUN_TEST(test_kill_suspended_thread)
1370RUN_TEST(test_suspend_single_wait_async_signal_delivery)
1371RUN_TEST(test_suspend_repeating_wait_async_signal_delivery)
1372RUN_TEST(test_reading_general_register_state)
1373RUN_TEST(test_reading_fp_register_state)
1374RUN_TEST(test_reading_vector_register_state)
1375RUN_TEST(test_writing_general_register_state)
1376RUN_TEST(test_writing_fp_register_state)
1377RUN_TEST(test_writing_vector_register_state)
1378RUN_TEST(test_noncanonical_rip_address)
1379RUN_TEST(test_writing_arm_flags_register)
1380END_TEST_CASE(threads_tests)
1381
1382#ifndef BUILD_COMBINED_TESTS
1383int main(int argc, char** argv) {
1384    return unittest_run_all_tests(argc, argv) ? 0 : -1;
1385}
1386#endif
1387