1// Copyright 2016 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <assert.h>
6#include <zircon/compiler.h>
7#include <zircon/rights.h>
8#include <zircon/syscalls.h>
9#include <zircon/syscalls/object.h>
10#include <unittest/unittest.h>
11#include <stdbool.h>
12#include <stdio.h>
13#include <stdlib.h>
14#include <threads.h>
15#include <unistd.h>
16
17static zx_handle_t _channel[4];
18
19/**
20 * Channel tests with wait multiple.
21 *
22 * Tests signal state persistence and various combinations of states on multiple handles.
23 *
24 * Test sequence (may not be exact due to concurrency):
25 *   1. Create 2 channels and start a reader thread.
26 *   2. Reader blocks wait on both channels.
27 *   3. Write to both channels and yield.
28 *   4. Reader wake up with channel 1 and channel 2 readable.
29 *   5. Reader reads from channel 1, and calls wait again.
30 *   6. Reader should wake up immediately, with channel 1 not readable and channel 2 readable.
31 *   7. Reader blocks on wait.
32 *   8. Write to channel 1 and yield.
33 *   9. Reader wake up with channel 1 readable and reads from channel 1.
34 *  10. Reader blocks on wait.
35 *  11. Write to channel 2 and close both channels, then yield.
36 *  12. Reader wake up with channel 2 closed and readable.
37 *  13. Read from channel 2 and wait.
38 *  14. Reader wake up with channel 2 closed, closes both channels and exit.
39 */
40
41static int reader_thread(void* arg) {
42    const unsigned int index = 2;
43    zx_handle_t* channel = &_channel[index];
44    __UNUSED zx_status_t status;
45    unsigned int packets[2] = {0, 0};
46    bool closed[2] = {false, false};
47    zx_wait_item_t items[2];
48    items[0].handle = channel[0];
49    items[1].handle = channel[1];
50    items[0].waitfor = ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED;
51    items[1].waitfor = ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED;
52    do {
53        status = zx_object_wait_many(items, 2, ZX_TIME_INFINITE);
54        assert(status == ZX_OK);
55        uint32_t data;
56        uint32_t num_bytes = sizeof(uint32_t);
57        if (items[0].pending & ZX_CHANNEL_READABLE) {
58            status = zx_channel_read(channel[0], 0u, &data, NULL,
59                                     num_bytes, 0, &num_bytes, NULL);
60            assert(status == ZX_OK);
61            packets[0] += 1;
62        } else if (items[1].pending & ZX_CHANNEL_READABLE) {
63            status = zx_channel_read(channel[1], 0u, &data, NULL,
64                                     num_bytes, 0, &num_bytes, NULL);
65            assert(status == ZX_OK);
66            packets[1] += 1;
67        } else {
68            if (items[0].pending & ZX_CHANNEL_PEER_CLOSED)
69                closed[0] = true;
70            if (items[1].pending & ZX_CHANNEL_PEER_CLOSED)
71                closed[1] = true;
72        }
73    } while (!closed[0] || !closed[1]);
74    assert(packets[0] == 3);
75    assert(packets[1] == 2);
76    return 0;
77}
78
79static zx_signals_t get_satisfied_signals(zx_handle_t handle) {
80    zx_signals_t pending = 0;
81    __UNUSED zx_status_t status = zx_object_wait_one(handle, 0u, 0u, &pending);
82    assert(status == ZX_ERR_TIMED_OUT);
83    return pending;
84}
85
86static bool channel_test(void) {
87    BEGIN_TEST;
88
89    zx_status_t status;
90
91    zx_handle_t h[2];
92    status = zx_channel_create(0, &h[0], &h[1]);
93    ASSERT_EQ(status, ZX_OK, "error in channel create");
94
95    // Check that koids line up.
96    zx_info_handle_basic_t info[2] = {};
97    status = zx_object_get_info(h[0], ZX_INFO_HANDLE_BASIC, &info[0], sizeof(info[0]), NULL, NULL);
98    ASSERT_EQ(status, ZX_OK, "");
99    status = zx_object_get_info(h[1], ZX_INFO_HANDLE_BASIC, &info[1], sizeof(info[1]), NULL, NULL);
100    ASSERT_EQ(status, ZX_OK, "");
101    ASSERT_NE(info[0].koid, 0u, "zero koid!");
102    ASSERT_NE(info[0].related_koid, 0u, "zero peer koid!");
103    ASSERT_NE(info[1].koid, 0u, "zero koid!");
104    ASSERT_NE(info[1].related_koid, 0u, "zero peer koid!");
105    ASSERT_EQ(info[0].koid, info[1].related_koid, "mismatched koids!");
106    ASSERT_EQ(info[1].koid, info[0].related_koid, "mismatched koids!");
107
108    ASSERT_EQ(get_satisfied_signals(h[0]), ZX_CHANNEL_WRITABLE, "");
109    ASSERT_EQ(get_satisfied_signals(h[1]), ZX_CHANNEL_WRITABLE, "");
110
111    _channel[0] = h[0];
112    _channel[2] = h[1];
113
114    static const uint32_t write_data = 0xdeadbeef;
115    status = zx_channel_write(_channel[0], 0u, &write_data, sizeof(uint32_t), NULL, 0u);
116    ASSERT_EQ(status, ZX_OK, "error in message write");
117    ASSERT_EQ(get_satisfied_signals(
118        _channel[0]), ZX_CHANNEL_WRITABLE, "");
119    ASSERT_EQ(get_satisfied_signals(
120        _channel[2]), ZX_CHANNEL_READABLE | ZX_CHANNEL_WRITABLE, "");
121
122    status = zx_channel_create(0, &h[0], &h[1]);
123    ASSERT_EQ(status, ZX_OK, "error in channel create");
124
125    _channel[1] = h[0];
126    _channel[3] = h[1];
127
128    thrd_t thread;
129    ASSERT_EQ(thrd_create(&thread, reader_thread, NULL), thrd_success, "error in thread create");
130
131    status = zx_channel_write(_channel[1], 0u, &write_data, sizeof(uint32_t), NULL, 0u);
132    ASSERT_EQ(status, ZX_OK, "error in message write");
133
134    usleep(1);
135
136    status = zx_channel_write(_channel[0], 0u, &write_data, sizeof(uint32_t), NULL, 0u);
137    ASSERT_EQ(status, ZX_OK, "error in message write");
138
139    status = zx_channel_write(_channel[0], 0u, &write_data, sizeof(uint32_t), NULL, 0u);
140    ASSERT_EQ(status, ZX_OK, "error in message write");
141
142    usleep(1);
143
144    status = zx_channel_write(_channel[1], 0u, &write_data, sizeof(uint32_t), NULL, 0u);
145    ASSERT_EQ(status, ZX_OK, "error in message write");
146
147    zx_handle_close(_channel[1]);
148    // The reader thread is reading from _channel[3], so we may or may not have "readable".
149    ASSERT_TRUE((get_satisfied_signals(_channel[3]) & ZX_CHANNEL_PEER_CLOSED), "");
150
151    usleep(1);
152    zx_handle_close(_channel[0]);
153
154    EXPECT_EQ(thrd_join(thread, NULL), thrd_success, "error in thread join");
155
156    // Since the the other side of _channel[3] is closed, and the read thread read everything
157    // from it, the only satisfied/satisfiable signals should be "peer closed".
158    ASSERT_EQ(get_satisfied_signals(
159        _channel[3]), ZX_CHANNEL_PEER_CLOSED, "");
160
161    zx_handle_close(_channel[2]);
162    zx_handle_close(_channel[3]);
163
164    END_TEST;
165}
166
167static bool channel_read_error_test(void) {
168    BEGIN_TEST;
169    zx_handle_t channel[2];
170    zx_status_t status = zx_channel_create(0, &channel[0], &channel[1]);
171    ASSERT_EQ(status, ZX_OK, "error in channel create");
172
173    // Read from an empty channel.
174    status = zx_channel_read(channel[0], 0u, NULL, NULL, 0, 0, NULL, NULL);
175    ASSERT_EQ(status, ZX_ERR_SHOULD_WAIT, "read on empty non-closed channel produced incorrect error");
176
177    char data = 'x';
178    status = zx_channel_write(channel[1], 0u, &data, 1u, NULL, 0u);
179    ASSERT_EQ(status, ZX_OK, "write failed");
180
181    zx_handle_close(channel[1]);
182
183    // Read a message with the peer closed, should yield the message.
184    char read_data = '\0';
185    uint32_t read_data_size = 1u;
186    status = zx_channel_read(channel[0], 0u, &read_data, NULL,
187                             read_data_size, 0, &read_data_size, NULL);
188    ASSERT_EQ(status, ZX_OK, "read failed with peer closed but message in the channel");
189    ASSERT_EQ(read_data_size, 1u, "read returned incorrect number of bytes");
190    ASSERT_EQ(read_data, 'x', "read returned incorrect data");
191
192    // Read from an empty channel with a closed peer, should yield a channel closed error.
193    status = zx_channel_read(channel[0], 0u, NULL, NULL, 0, 0, NULL, NULL);
194    ASSERT_EQ(status, ZX_ERR_PEER_CLOSED, "read on empty closed channel produced incorrect error");
195
196    END_TEST;
197}
198
199static bool channel_close_test(void) {
200    BEGIN_TEST;
201    zx_handle_t channel[2];
202
203    // Channels should gain PEER_CLOSED (and lose WRITABLE) if their peer is closed
204    ASSERT_EQ(zx_channel_create(0, &channel[0], &channel[1]), ZX_OK, "");
205    ASSERT_EQ(zx_handle_close(channel[1]), ZX_OK, "");
206    ASSERT_EQ(get_satisfied_signals(
207        channel[0]), ZX_CHANNEL_PEER_CLOSED, "");
208    ASSERT_EQ(zx_handle_close(channel[0]), ZX_OK, "");
209
210    ASSERT_EQ(zx_channel_create(0, &channel[0], &channel[1]), ZX_OK, "");
211    zx_handle_t channel1[2];
212    ASSERT_EQ(zx_channel_create(0, &channel1[0], &channel1[1]), ZX_OK, "");
213    zx_handle_t channel2[2];
214    ASSERT_EQ(zx_channel_create(0, &channel2[0], &channel2[1]), ZX_OK, "");
215
216    // Write channel1[0] to channel[0] (to be received by channel[1])
217    // and channel2[0] to channel[1] (to be received by channel[0]).
218    ASSERT_EQ(zx_channel_write(channel[0], 0u, NULL, 0u, &channel1[0], 1u), ZX_OK, "");
219    channel1[0] = ZX_HANDLE_INVALID;
220    ASSERT_EQ(zx_channel_write(channel[1], 0u, NULL, 0u, &channel2[0], 1u), ZX_OK, "");
221    channel2[0] = ZX_HANDLE_INVALID;
222
223    // Close channel[1]; the former channel1[0] should be closed, so channel1[1] should have
224    // peer closed.
225    ASSERT_EQ(zx_handle_close(channel[1]), ZX_OK, "");
226    channel[1] = ZX_HANDLE_INVALID;
227    ASSERT_EQ(zx_object_wait_one(
228        channel1[1], ZX_CHANNEL_PEER_CLOSED, ZX_TIME_INFINITE, NULL), ZX_OK, "");
229    ASSERT_EQ(get_satisfied_signals(
230        channel2[1]), ZX_CHANNEL_WRITABLE, "");
231
232    // Close channel[0]; the former channel2[0] should be closed, so channel2[1]
233    // should have peer closed.
234    ASSERT_EQ(zx_handle_close(channel[0]), ZX_OK, "");
235    channel[0] = ZX_HANDLE_INVALID;
236    ASSERT_EQ(get_satisfied_signals(
237        channel1[1]), ZX_CHANNEL_PEER_CLOSED, "");
238    ASSERT_EQ(zx_object_wait_one(
239        channel2[1], ZX_CHANNEL_PEER_CLOSED, ZX_TIME_INFINITE, NULL), ZX_OK, "");
240
241    ASSERT_EQ(zx_handle_close(channel1[1]), ZX_OK, "");
242    ASSERT_EQ(zx_handle_close(channel2[1]), ZX_OK, "");
243
244    END_TEST;
245}
246
247static bool channel_peer_closed_test(void) {
248    BEGIN_TEST;
249
250    zx_handle_t channel[2];
251    ASSERT_EQ(zx_channel_create(0, &channel[0], &channel[1]), ZX_OK, "");
252    ASSERT_EQ(zx_handle_close(channel[1]), ZX_OK, "");
253    ASSERT_EQ(zx_object_signal_peer(channel[0], 0u, ZX_USER_SIGNAL_0), ZX_ERR_PEER_CLOSED, "");
254    ASSERT_EQ(zx_handle_close(channel[0]), ZX_OK, "");
255
256    END_TEST;
257}
258
259static bool channel_non_transferable(void) {
260    BEGIN_TEST;
261
262    zx_handle_t channel[2];
263    ASSERT_EQ(zx_channel_create(0, &channel[0], &channel[1]), ZX_OK, "");
264    zx_handle_t event;
265    ASSERT_EQ(zx_event_create(0u, &event), 0, "failed to create event");
266    zx_info_handle_basic_t event_handle_info;
267
268    zx_status_t status = zx_object_get_info(event, ZX_INFO_HANDLE_BASIC, &event_handle_info,
269                                            sizeof(event_handle_info), NULL, NULL);
270    ASSERT_EQ(status, ZX_OK, "failed to get event info");
271    zx_rights_t initial_event_rights = event_handle_info.rights;
272    zx_handle_t non_transferable_event;
273    zx_handle_duplicate(
274        event, initial_event_rights & ~ZX_RIGHT_TRANSFER, &non_transferable_event);
275
276    zx_status_t write_result = zx_channel_write(
277        channel[0], 0u, NULL, 0, &non_transferable_event, 1u);
278    EXPECT_EQ(write_result, ZX_ERR_ACCESS_DENIED, "message_write should fail with ACCESS_DENIED");
279
280    zx_status_t close_result = zx_handle_close(non_transferable_event);
281    EXPECT_EQ(close_result, ZX_ERR_BAD_HANDLE, "");
282
283    END_TEST;
284}
285
286static bool channel_duplicate_handles(void) {
287    BEGIN_TEST;
288
289    zx_handle_t channel[2];
290    ASSERT_EQ(zx_channel_create(0, &channel[0], &channel[1]), ZX_OK, "");
291
292    zx_handle_t event;
293    ASSERT_EQ(zx_event_create(0u, &event), 0, "failed to create event");
294
295    zx_handle_t dup_handles[2] = { event, event };
296    zx_status_t write_result = zx_channel_write(channel[0], 0u, NULL, 0, dup_handles, 2u);
297    EXPECT_EQ(write_result, ZX_ERR_BAD_HANDLE, "message_write should fail with ZX_ERR_INVALID_ARGS");
298
299    zx_status_t close_result = zx_handle_close(event);
300    EXPECT_EQ(close_result, ZX_ERR_BAD_HANDLE, "");
301    close_result = zx_handle_close(channel[0]);
302    EXPECT_EQ(close_result, ZX_OK, "");
303    close_result = zx_handle_close(channel[1]);
304    EXPECT_EQ(close_result, ZX_OK, "");
305
306    END_TEST;
307}
308
309static const uint32_t multithread_read_num_messages = 5000u;
310
311#define MSG_UNSET       ((uint32_t)-1)
312#define MSG_READ_FAILED ((uint32_t)-2)
313#define MSG_WRONG_SIZE  ((uint32_t)-3)
314#define MSG_BAD_DATA    ((uint32_t)-4)
315
316static int multithread_reader(void* arg) {
317    for (uint32_t i = 0; i < multithread_read_num_messages / 2; i++) {
318        uint32_t msg = MSG_UNSET;
319        uint32_t msg_size = sizeof(msg);
320        zx_status_t status = zx_channel_read(_channel[0], 0u, &msg, NULL,
321                                             msg_size, 0, &msg_size, NULL);
322        if (status != ZX_OK) {
323            ((uint32_t*)arg)[i] = MSG_READ_FAILED;
324            break;
325        }
326        if (msg_size != sizeof(msg)) {
327            ((uint32_t*)arg)[i] = MSG_WRONG_SIZE;
328            break;
329        }
330        if (msg >= multithread_read_num_messages) {
331            ((uint32_t*)arg)[i] = MSG_BAD_DATA;
332            break;
333        }
334
335        ((uint32_t*)arg)[i] = msg;
336    }
337    return 0;
338}
339
340static bool channel_multithread_read(void) {
341    BEGIN_TEST;
342
343    // We'll write from channel[0] and read from channel[1].
344    zx_handle_t channel[2];
345    ASSERT_EQ(zx_channel_create(0, &channel[0], &channel[1]), ZX_OK, "");
346
347    for (uint32_t i = 0; i < multithread_read_num_messages; i++)
348        ASSERT_EQ(zx_channel_write(channel[0], 0, &i, sizeof(i), NULL, 0), ZX_OK, "");
349
350    _channel[0] = channel[1];
351
352    // Start two threads to read messages (each will read half). Each will store the received
353    // message data in the corresponding array.
354    uint32_t* received0 = malloc(multithread_read_num_messages / 2 * sizeof(uint32_t));
355    ASSERT_TRUE(received0, "malloc failed");
356    uint32_t* received1 = malloc(multithread_read_num_messages / 2 * sizeof(uint32_t));
357    ASSERT_TRUE(received1, "malloc failed");
358    thrd_t reader0;
359    ASSERT_EQ(thrd_create(&reader0, multithread_reader, received0), thrd_success,
360              "thrd_create failed");
361    thrd_t reader1;
362    ASSERT_EQ(thrd_create(&reader1, multithread_reader, received1), thrd_success,
363              "thrd_create failed");
364
365    // Wait for threads.
366    EXPECT_EQ(thrd_join(reader0, NULL), thrd_success, "");
367    EXPECT_EQ(thrd_join(reader1, NULL), thrd_success, "");
368
369    EXPECT_EQ(zx_handle_close(channel[0]), ZX_OK, "");
370    EXPECT_EQ(zx_handle_close(channel[1]), ZX_OK, "");
371
372    // Check data.
373    bool* received_flags = calloc(multithread_read_num_messages, sizeof(bool));
374
375    for (uint32_t i = 0; i < multithread_read_num_messages / 2; i++) {
376        uint32_t msg = received0[i];
377        ASSERT_NE(msg, MSG_READ_FAILED, "read failed");
378        ASSERT_NE(msg, MSG_WRONG_SIZE, "got wrong message size");
379        ASSERT_NE(msg, MSG_BAD_DATA, "got bad message data");
380        ASSERT_LT(msg, multithread_read_num_messages, "???");
381        ASSERT_FALSE(received_flags[msg], "got duplicate message");
382    }
383    for (uint32_t i = 0; i < multithread_read_num_messages / 2; i++) {
384        uint32_t msg = received1[i];
385        ASSERT_NE(msg, MSG_READ_FAILED, "read failed");
386        ASSERT_NE(msg, MSG_WRONG_SIZE, "got wrong message size");
387        ASSERT_NE(msg, MSG_BAD_DATA, "got bad message data");
388        ASSERT_LT(msg, multithread_read_num_messages, "???");
389        ASSERT_FALSE(received_flags[msg], "got duplicate message");
390    }
391
392    free(received0);
393    free(received1);
394    free(received_flags);
395
396    _channel[0] = ZX_HANDLE_INVALID;
397
398    END_TEST;
399}
400
401// |handle| must be valid (and duplicatable and transferable) if |num_handles > 0|.
402static void write_test_message(zx_handle_t channel,
403                               zx_handle_t handle,
404                               uint32_t size,
405                               uint32_t num_handles) {
406    static const char data[1000] = {};
407    zx_handle_t handles[10] = {};
408
409    assert(size <= sizeof(data));
410    assert(num_handles <= countof(handles));
411
412    for (uint32_t i = 0; i < num_handles; i++) {
413        zx_status_t status = zx_handle_duplicate(handle, ZX_RIGHT_TRANSFER, &handles[i]);
414        assert(status == ZX_OK);
415    }
416
417    __UNUSED zx_status_t status = zx_channel_write(channel, 0u, data, size, handles, num_handles);
418    assert(status == ZX_OK);
419}
420
421static bool channel_may_discard(void) {
422    BEGIN_TEST;
423
424    zx_handle_t channel[2];
425    ASSERT_EQ(zx_channel_create(0, &channel[0], &channel[1]), ZX_OK, "");
426
427    zx_handle_t event;
428    ASSERT_EQ(zx_event_create(0u, &event), 0, "failed to create event");
429
430    EXPECT_EQ(zx_object_wait_one(channel[1], ZX_CHANNEL_READABLE, 0u, NULL), ZX_ERR_TIMED_OUT, "");
431
432    write_test_message(channel[0], event, 10u, 0u);
433    EXPECT_EQ(zx_channel_read(channel[1], ZX_CHANNEL_READ_MAY_DISCARD, NULL, NULL, 0, 0, NULL, NULL),
434              ZX_ERR_BUFFER_TOO_SMALL, "");
435
436    EXPECT_EQ(zx_object_wait_one(channel[1], ZX_CHANNEL_READABLE, 0u, NULL), ZX_ERR_TIMED_OUT, "");
437
438    char data[1000];
439    uint32_t size;
440
441    write_test_message(channel[0], event, 100u, 0u);
442    size = 10u;
443    EXPECT_EQ(zx_channel_read(channel[1], ZX_CHANNEL_READ_MAY_DISCARD, data, NULL, size, 0, &size, NULL),
444              ZX_ERR_BUFFER_TOO_SMALL, "");
445    EXPECT_EQ(size, 100u, "wrong size");
446
447    EXPECT_EQ(zx_object_wait_one(channel[1], ZX_CHANNEL_READABLE, 0u, NULL), ZX_ERR_TIMED_OUT, "");
448
449    zx_handle_t handles[10];
450    uint32_t num_handles;
451
452    write_test_message(channel[0], event, 0u, 5u);
453    size = 10u;
454    num_handles = 1u;
455    EXPECT_EQ(zx_channel_read(channel[1], ZX_CHANNEL_READ_MAY_DISCARD, data, handles,
456                              size, num_handles, &size, &num_handles),
457              ZX_ERR_BUFFER_TOO_SMALL, "");
458    EXPECT_EQ(size, 0u, "wrong size");
459    EXPECT_EQ(num_handles, 5u, "wrong number of handles");
460
461    EXPECT_EQ(zx_object_wait_one(channel[1], ZX_CHANNEL_READABLE, 0u, NULL), ZX_ERR_TIMED_OUT, "");
462
463    write_test_message(channel[0], event, 100u, 5u);
464    size = 10u;
465    num_handles = 1u;
466    EXPECT_EQ(zx_channel_read(channel[1], ZX_CHANNEL_READ_MAY_DISCARD, data, handles,
467                              size, num_handles, &size, &num_handles),
468              ZX_ERR_BUFFER_TOO_SMALL, "");
469    EXPECT_EQ(size, 100u, "wrong size");
470    EXPECT_EQ(num_handles, 5u, "wrong number of handles");
471
472    EXPECT_EQ(zx_object_wait_one(channel[1], ZX_CHANNEL_READABLE, 0u, NULL), ZX_ERR_TIMED_OUT, "");
473
474    zx_status_t close_result = zx_handle_close(event);
475    EXPECT_EQ(close_result, ZX_OK, "");
476    close_result = zx_handle_close(channel[0]);
477    EXPECT_EQ(close_result, ZX_OK, "");
478    close_result = zx_handle_close(channel[1]);
479    EXPECT_EQ(close_result, ZX_OK, "");
480
481    END_TEST;
482}
483
484#define MAX_DELAY 4
485
486enum {
487    OP_ECHO = 0,
488    OP_NOTXID,
489    OP_RUNT,
490    OP_TOOBIG,
491    OP_DELAY,
492    OP_IGNORE,
493    OP_HANDLE,
494    OP_SHUTDOWN,
495    OP_POSTSHUTDOWN
496};
497
498typedef struct {
499    zx_txid_t txid;
500    uint32_t op;
501    unsigned data[8];
502} msg_t;
503
504static int cc_server(void* ptr) {
505    zx_status_t status;
506    zx_handle_t h = (zx_handle_t) (uintptr_t) ptr;
507
508    uint32_t pending[MAX_DELAY];
509    size_t pending_count = 0;
510
511    for (;;) {
512        zx_object_wait_one(h, ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED,
513                           ZX_TIME_INFINITE, NULL);
514
515        msg_t msg;
516        zx_handle_t handle = ZX_HANDLE_INVALID;
517        uint32_t bc = 0, hc = 0;
518        status = zx_channel_read(h, 0, &msg, &handle, sizeof(msg), 1, &bc, &hc);
519        if (status != ZX_OK) {
520            fprintf(stderr, "call_server() read failed: %d\n", status);
521            return -1;
522        }
523
524        if (bc != sizeof(msg)) {
525            msg.op = OP_RUNT;
526        }
527
528        if ((hc > 0) && (msg.op != OP_HANDLE)) {
529            fprintf(stderr, "call_server() got unexpected handle on op %u\n", msg.op);
530            return -1;
531        }
532
533        switch(msg.op) {
534        case OP_RUNT:
535            memset(msg.data, 0xee, sizeof(msg.data));
536            break;
537        case OP_ECHO:
538        case OP_TOOBIG:
539        case OP_HANDLE:
540            break;
541        case OP_DELAY:
542            for (unsigned n = 0; n < pending_count; n++) {
543                if (pending[n] == msg.txid) {
544                    fprintf(stderr, "call_server() kernel re-used a txid!\n");
545                    return -1;
546                }
547            }
548            pending[pending_count++] = msg.txid;
549            if (pending_count < MAX_DELAY) {
550                continue;
551            }
552            while (pending_count > 0) {
553                pending_count--;
554                msg.op = OP_DELAY;
555                msg.txid = pending[pending_count];
556                status = zx_channel_write(h, 0, &msg, sizeof(msg), NULL, 0);
557                if (status != ZX_OK) {
558                    fprintf(stderr, "call_server() replay write failed: %d\n", status);
559                    return -1;
560                }
561            }
562            continue;
563        case OP_IGNORE:
564            continue;
565        case OP_SHUTDOWN:
566            zx_handle_close(h);
567            return 0;
568        }
569
570        status = zx_channel_write(h, 0, &msg, sizeof(msg), &handle, hc);
571        if (status != ZX_OK) {
572            fprintf(stderr, "call_server() write failed: %d\n", status);
573            return -1;
574        }
575    }
576    return 0;
577}
578
579static unsigned fillbyte = 1;
580
581static zx_status_t do_cc(zx_handle_t cli, uint32_t op) {
582    msg_t msg;
583    msg_t rsp;
584    zx_handle_t h = ZX_HANDLE_INVALID;
585
586    unsigned fill = (op == OP_RUNT) ? 0xee : fillbyte++;
587
588    msg.txid = 0x11223344;
589    msg.op = op;
590    memset(msg.data, fill, sizeof(msg.data));
591
592    zx_channel_call_args_t args = {
593        .wr_bytes = &msg,
594        .wr_handles = &h,
595        .rd_bytes = &rsp,
596        .rd_handles = &h,
597        .wr_num_bytes = sizeof(msg),
598        .wr_num_handles = 0,
599        .rd_num_bytes = sizeof(msg),
600        .rd_num_handles = 0,
601    };
602
603    switch (op) {
604    case OP_RUNT:
605        args.wr_num_bytes = sizeof(zx_txid_t);
606        break;
607    case OP_NOTXID:
608        args.wr_num_bytes = 1;
609        break;
610    case OP_TOOBIG:
611        args.rd_num_bytes = sizeof(zx_txid_t);
612        break;
613    case OP_HANDLE:
614        if (zx_event_create(0, &h) != ZX_OK) {
615            return -1005;
616        }
617        args.wr_num_handles = 1;
618        args.rd_num_handles = 1;
619    }
620
621    zx_status_t status;
622    uint32_t bytes = 0;
623    uint32_t handles = 0;
624
625    zx_time_t timeout = (op == OP_IGNORE) ? 0 : ZX_TIME_INFINITE;
626
627    status = zx_channel_call(cli, 0, timeout, &args, &bytes, &handles);
628    if (status != ZX_OK) {
629        if ((op == OP_IGNORE) && (status == ZX_ERR_TIMED_OUT)) {
630            return ZX_OK;
631        }
632        if ((op == OP_NOTXID) && (status == ZX_ERR_INVALID_ARGS)) {
633            return ZX_OK;
634        }
635        if ((op == OP_SHUTDOWN) && (status == ZX_ERR_PEER_CLOSED)) {
636            return ZX_OK;
637        }
638        if ((op == OP_POSTSHUTDOWN) && (status == ZX_ERR_PEER_CLOSED)) {
639            return ZX_OK;
640        }
641        if ((op == OP_TOOBIG) && (status == ZX_ERR_BUFFER_TOO_SMALL)) {
642            return ZX_OK;
643        }
644        fprintf(stderr, "do_cc: channel_call() status=%d\n", status);
645        return -1000;
646    }
647
648    if (handles == 1) {
649        zx_handle_close(h);
650        if (op != OP_HANDLE) {
651            return -1004;
652        }
653    }
654
655    if ((bytes != sizeof(msg)) || ((op != OP_HANDLE) && (handles != 0))) {
656        return -1001;
657    }
658
659    if (msg.op != rsp.op) {
660        return -1002;
661    }
662
663    switch (op) {
664    case OP_HANDLE:
665    case OP_ECHO:
666    case OP_RUNT:
667        if (memcmp(msg.data, rsp.data, sizeof(msg.data))) {
668            return -1003;
669        }
670        break;
671    }
672
673    return ZX_OK;
674}
675
676static int cc_client(void* ptr) {
677    zx_handle_t cli = (zx_handle_t) (uintptr_t) ptr;
678    return do_cc(cli, OP_DELAY);
679}
680
681static bool channel_call(void) {
682    BEGIN_TEST;
683
684    zx_handle_t cli, srv;
685    ASSERT_EQ(zx_channel_create(0, &cli, &srv), ZX_OK, "");
686
687    // start test server
688    thrd_t srvt;
689    ASSERT_EQ(thrd_create(&srvt, cc_server, (void*) (uintptr_t) srv), thrd_success, "");
690
691    ASSERT_EQ(do_cc(cli, OP_ECHO), ZX_OK, "");
692    ASSERT_EQ(do_cc(cli, OP_RUNT), ZX_OK, "");
693    ASSERT_EQ(do_cc(cli, OP_TOOBIG), ZX_OK, "");
694    ASSERT_EQ(do_cc(cli, OP_ECHO), ZX_OK, "");
695    ASSERT_EQ(do_cc(cli, OP_NOTXID), ZX_OK, "");
696    ASSERT_EQ(do_cc(cli, OP_IGNORE), ZX_OK, "");
697    ASSERT_EQ(do_cc(cli, OP_HANDLE), ZX_OK, "");
698
699    // do four OP_DELAYs on four different threads
700    thrd_t a,b,c,d;
701    ASSERT_EQ(thrd_create(&a, cc_client, (void*) (uintptr_t) cli), thrd_success, "");
702    ASSERT_EQ(thrd_create(&b, cc_client, (void*) (uintptr_t) cli), thrd_success, "");
703    ASSERT_EQ(thrd_create(&c, cc_client, (void*) (uintptr_t) cli), thrd_success, "");
704    ASSERT_EQ(thrd_create(&d, cc_client, (void*) (uintptr_t) cli), thrd_success, "");
705
706    // server will respond in opposite order once it has received all of them
707
708    // verify that they all finish
709    int r;
710    ASSERT_EQ(thrd_join(a, &r), thrd_success, "");
711    ASSERT_EQ(r, 0, "");
712    ASSERT_EQ(thrd_join(b, &r), thrd_success, "");
713    ASSERT_EQ(r, 0, "");
714    ASSERT_EQ(thrd_join(c, &r), thrd_success, "");
715    ASSERT_EQ(r, 0, "");
716    ASSERT_EQ(thrd_join(d, &r), thrd_success, "");
717    ASSERT_EQ(r, 0, "");
718
719    ASSERT_EQ(do_cc(cli, OP_SHUTDOWN), ZX_OK, "");
720
721    ASSERT_EQ(do_cc(cli, OP_POSTSHUTDOWN), ZX_OK, "");
722    ASSERT_EQ(zx_handle_close(cli), ZX_OK, "");
723
724    END_TEST;
725}
726
727static bool channel_call_consumes_handles(void) {
728    BEGIN_TEST;
729
730    zx_handle_t cli, srv;
731    ASSERT_EQ(zx_channel_create(0, &cli, &srv), ZX_OK, "");
732    ASSERT_EQ(zx_handle_close(srv), ZX_OK, "");
733
734    zx_handle_t h;
735    ASSERT_EQ(zx_event_create(0, &h), ZX_OK, "");
736
737    uint8_t msg[64];
738    memset(msg, 0, sizeof(msg));
739
740    zx_channel_call_args_t args = {
741        .wr_bytes = &msg,
742        .wr_handles = &h,
743        .rd_bytes = &msg,
744        .rd_handles = NULL,
745        .wr_num_bytes = sizeof(msg),
746        .wr_num_handles = 1,
747        .rd_num_bytes = sizeof(msg),
748        .rd_num_handles = 0,
749    };
750
751    uint32_t act_bytes = 0xffffffff;
752    uint32_t act_handles = 0xffffffff;
753
754    zx_status_t r = zx_channel_call(cli, 42, ZX_TIME_INFINITE, &args, &act_bytes,
755                                    &act_handles);
756
757    ASSERT_EQ(r, ZX_ERR_INVALID_ARGS, "");
758    ASSERT_EQ(zx_handle_close(h), ZX_ERR_BAD_HANDLE, "");
759
760    END_TEST;
761}
762
763static bool create_and_nest(zx_handle_t out, zx_handle_t* end, size_t n) {
764    BEGIN_TEST;
765
766    zx_handle_t channel[2];
767    if (n == 1) {
768        ASSERT_EQ(zx_channel_create(0, &channel[0], end), ZX_OK, "");
769        ASSERT_EQ(zx_channel_write(out, 0u, NULL, 0u, channel, 1u), ZX_OK, "");
770        return true;
771    }
772
773    ASSERT_EQ(zx_channel_create(0, &channel[0], &channel[1]), ZX_OK, "");
774    ASSERT_TRUE(create_and_nest(channel[0], end, n - 1), "");
775    ASSERT_EQ(zx_channel_write(out, 0u, NULL, 0u, channel, 2u), ZX_OK, "");
776
777    END_TEST;
778}
779
780static int call_server2(void* ptr) {
781    zx_handle_t h = (zx_handle_t) (uintptr_t) ptr;
782    zx_nanosleep(zx_deadline_after(ZX_MSEC(250)));
783    zx_handle_close(h);
784    return 0;
785}
786
787static bool channel_call2(void) {
788    BEGIN_TEST;
789
790    zx_handle_t cli, srv;
791    ASSERT_EQ(zx_channel_create(0, &cli, &srv), ZX_OK, "");
792
793    thrd_t t;
794    ASSERT_EQ(thrd_create(&t, call_server2, (void*) (uintptr_t) srv), thrd_success, "");
795
796    char msg[8] = { 0, };
797    zx_channel_call_args_t args = {
798        .wr_bytes = msg,
799        .wr_handles = NULL,
800        .wr_num_bytes = sizeof(msg),
801        .wr_num_handles = 0,
802        .rd_bytes = NULL,
803        .rd_handles = NULL,
804        .rd_num_bytes = 0,
805        .rd_num_handles = 0,
806    };
807
808    uint32_t act_bytes = 0xffffffff;
809    uint32_t act_handles = 0xffffffff;
810
811    zx_status_t r = zx_channel_call(cli, 0, zx_deadline_after(ZX_MSEC(1000)), &args, &act_bytes,
812                                    &act_handles);
813
814    zx_handle_close(cli);
815
816    EXPECT_EQ(r, ZX_ERR_PEER_CLOSED, "");
817
818    int retv = 0;
819    EXPECT_EQ(thrd_join(t, &retv), thrd_success, "");
820    EXPECT_EQ(retv, 0, "");
821
822    END_TEST;
823}
824
825// SYSCALL_zx_channel_call_finish is an internal system call used in the
826// vDSO's implementation of zx_channel_call.  It's not part of the ABI and
827// so it's not exported from the vDSO.  It's hard to test the kernel's
828// invariants without calling this directly.  So use some chicanery to
829// find its address in the vDSO despite it not being public.
830//
831// The vdso-code.h header file is generated from the vDSO binary.  It gives
832// the offsets of the internal functions.  So take a public vDSO function,
833// subtract its offset to discover the vDSO base (could do this other ways,
834// but this is the simplest), and then add the offset of the internal
835// SYSCALL_zx_channel_call_finish function we want to call.
836#include "vdso-code.h"
837static zx_status_t zx_channel_call_finish(zx_time_t deadline,
838                                          const zx_channel_call_args_t* args,
839                                          uint32_t* actual_bytes,
840                                          uint32_t* actual_handles) {
841    uintptr_t vdso_base =
842        (uintptr_t)&zx_handle_close - VDSO_SYSCALL_zx_handle_close;
843    uintptr_t fnptr = vdso_base + VDSO_SYSCALL_zx_channel_call_finish;
844    return (*(__typeof(zx_channel_call_finish)*)fnptr)(
845        deadline, args, actual_bytes, actual_handles);
846}
847
848static bool bad_channel_call_finish(void) {
849    BEGIN_TEST;
850
851    char msg[8] = { 0, };
852    zx_channel_call_args_t args = {
853        .wr_bytes = msg,
854        .wr_handles = NULL,
855        .wr_num_bytes = sizeof(msg),
856        .wr_num_handles = 0,
857        .rd_bytes = NULL,
858        .rd_handles = NULL,
859        .rd_num_bytes = 0,
860        .rd_num_handles = 0,
861    };
862
863    uint32_t act_bytes = 0xffffffff;
864    uint32_t act_handles = 0xffffffff;
865
866    // Call channel_call_finish without having had a channel call interrupted
867    zx_status_t r = zx_channel_call_finish(zx_deadline_after(ZX_MSEC(1000)), &args, &act_bytes,
868                                           &act_handles);
869
870    EXPECT_EQ(r, ZX_ERR_BAD_STATE, "");
871
872    END_TEST;
873}
874
875static bool channel_nest(void) {
876    BEGIN_TEST;
877    zx_handle_t channel[2];
878
879    ASSERT_EQ(zx_channel_create(0, &channel[0], &channel[1]), ZX_OK, "");
880
881    zx_handle_t end;
882    // Nest 200 channels, each one in the payload of the previous one. Without
883    // the SafeDeleter in fbl_recycle() this blows the kernel stack when calling
884    // the destructors.
885    ASSERT_TRUE(create_and_nest(channel[0], &end, 200), "");
886    EXPECT_EQ(zx_handle_close(channel[1]), ZX_OK, "");
887    EXPECT_EQ(zx_object_wait_one(channel[0], ZX_CHANNEL_PEER_CLOSED, ZX_TIME_INFINITE, NULL), ZX_OK, "");
888
889    EXPECT_EQ(zx_object_wait_one(end, ZX_CHANNEL_PEER_CLOSED, ZX_TIME_INFINITE, NULL), ZX_OK, "");
890    EXPECT_EQ(zx_handle_close(end), ZX_OK, "");
891
892    EXPECT_EQ(zx_handle_close(channel[0]), ZX_OK, "");
893
894    END_TEST;
895}
896
897// Test the case of writing a channel handle to itself.  The kernel
898// currently disallows this, because otherwise it would create a reference
899// cycle and potentially allow channels to be leaked.
900static bool channel_disallow_write_to_self(void) {
901    BEGIN_TEST;
902
903    zx_handle_t channel[2];
904    ASSERT_EQ(zx_channel_create(0, &channel[0], &channel[1]), ZX_OK, "");
905    EXPECT_EQ(zx_channel_write(channel[0], 0, NULL, 0, &channel[0], 1),
906              ZX_ERR_NOT_SUPPORTED, "");
907    // Clean up.
908    EXPECT_EQ(zx_handle_close(channel[0]), ZX_ERR_BAD_HANDLE, "");
909    EXPECT_EQ(zx_handle_close(channel[1]), ZX_OK, "");
910
911    END_TEST;
912}
913
914static bool channel_read_etc(void) {
915    BEGIN_TEST;
916
917    zx_handle_t event;
918    ASSERT_EQ(zx_event_create(0u, &event), ZX_OK, "");
919    ASSERT_EQ(zx_handle_replace(event,  ZX_RIGHT_SIGNAL | ZX_RIGHT_TRANSFER, &event), ZX_OK, "");
920
921    zx_handle_t fifo[2];
922    ASSERT_EQ(zx_fifo_create(32u, 8u, 0u, &fifo[0], &fifo[1]), ZX_OK, "");
923
924    zx_handle_t sent[] = {
925        fifo[0],
926        event,
927        fifo[1]
928    };
929
930    zx_handle_t channel[2];
931    ASSERT_EQ(zx_channel_create(0, &channel[0], &channel[1]), ZX_OK, "");
932    EXPECT_EQ(zx_channel_write(channel[0], 0u, NULL, 0, sent, 3u), ZX_OK, "");
933
934    zx_handle_info_t recv[] = {{}, {}, {}};
935    uint32_t actual_bytes;
936    uint32_t actual_handles;
937
938    EXPECT_EQ(zx_channel_read_etc(
939        channel[1], 0u, NULL, recv, 0u, 3u, &actual_bytes, &actual_handles), ZX_OK, "");
940
941    EXPECT_EQ(actual_bytes, 0u, "");
942    EXPECT_EQ(actual_handles, 3u, "");
943    EXPECT_EQ(recv[0].type, ZX_OBJ_TYPE_FIFO, "");
944    EXPECT_EQ(recv[0].rights, ZX_DEFAULT_FIFO_RIGHTS, "");
945
946    EXPECT_EQ(recv[1].type, ZX_OBJ_TYPE_EVENT, "");
947    EXPECT_EQ(recv[1].rights, ZX_RIGHT_SIGNAL | ZX_RIGHT_TRANSFER, "");
948
949    EXPECT_EQ(recv[2].type, ZX_OBJ_TYPE_FIFO, "");
950    EXPECT_EQ(recv[2].rights, ZX_DEFAULT_FIFO_RIGHTS, "");
951
952    EXPECT_EQ(zx_handle_close(channel[0]), ZX_OK, "");
953    EXPECT_EQ(zx_handle_close(channel[1]), ZX_OK, "");
954    EXPECT_EQ(zx_handle_close(recv[0].handle), ZX_OK, "");
955    EXPECT_EQ(zx_handle_close(recv[1].handle), ZX_OK, "");
956    EXPECT_EQ(zx_handle_close(recv[2].handle), ZX_OK, "");
957
958    END_TEST;
959}
960
961// Write and read messages of different sizes.
962static bool channel_write_different_sizes(void) {
963    BEGIN_TEST;
964    zx_handle_t channel[2];
965    ASSERT_EQ(zx_channel_create(0, &channel[0], &channel[1]), ZX_OK, "");
966
967    char* data_to_send = malloc(ZX_CHANNEL_MAX_MSG_BYTES);
968    ASSERT_NE(NULL, data_to_send, "");
969    char* data_recv = malloc(ZX_CHANNEL_MAX_MSG_BYTES);
970    ASSERT_NE(NULL, data_recv, "");
971
972    uint32_t actual_bytes = 0;
973    uint32_t actual_handles = 0;
974
975    // Send a bunch of messages, each with a random number of bytes and handles.  num_msgs should be
976    // large enough to provide decent coverage and small enough so the test executes quickly.
977    const size_t num_msgs = 1000;
978    srand(0);
979    for (size_t i = 0; i < num_msgs; ++i) {
980        uint32_t num_bytes = rand() % ZX_CHANNEL_MAX_MSG_BYTES;
981        uint32_t num_handles = rand() % ZX_CHANNEL_MAX_MSG_HANDLES;
982
983        // Create some handle pairs.  Keep one of each pair in |handles|, put the other in
984        // |handles_to_send|.
985        zx_handle_t handles[ZX_CHANNEL_MAX_MSG_HANDLES] = {0};
986        zx_handle_t handles_to_send[ZX_CHANNEL_MAX_MSG_HANDLES] = {0};
987        zx_handle_t handles_recv[ZX_CHANNEL_MAX_MSG_HANDLES] = {0};
988        for (size_t i = 0; i < ZX_CHANNEL_MAX_MSG_HANDLES; ++i) {
989            if (i < num_handles) {
990                ASSERT_EQ(zx_channel_create(0u, &handles[i], &handles_to_send[i]), ZX_OK, "");
991            } else {
992                handles[i] = ZX_HANDLE_INVALID;
993                handles_to_send[i] = ZX_HANDLE_INVALID;
994            }
995            handles_recv[i] = ZX_HANDLE_INVALID;
996        }
997
998        memset(data_to_send, i % 256, i);
999        ASSERT_EQ(zx_channel_write(channel[0], 0u, data_to_send, num_bytes, handles_to_send,
1000                                   num_handles),
1001                  ZX_OK, "");
1002        memset(data_recv, 0, ZX_CHANNEL_MAX_MSG_BYTES);
1003        ASSERT_EQ(zx_channel_read(channel[1], 0u, data_recv, handles_recv, ZX_CHANNEL_MAX_MSG_BYTES,
1004                                  num_handles, &actual_bytes, &actual_handles),
1005                  ZX_OK, "");
1006        ASSERT_EQ(actual_bytes, num_bytes, "");
1007        ASSERT_EQ(actual_handles, num_handles, "");
1008        ASSERT_EQ(memcmp(data_to_send, data_recv, num_bytes), 0, "");
1009
1010        // Close them.
1011        for (size_t i = 0; i< ZX_CHANNEL_MAX_MSG_HANDLES; ++i) {
1012            if (i < num_handles) {
1013                ASSERT_EQ(zx_handle_close(handles_recv[i]), ZX_OK, "");
1014                ASSERT_EQ(zx_handle_close(handles[i]), ZX_OK, "");
1015            } else {
1016                ASSERT_EQ(handles_recv[i], ZX_HANDLE_INVALID, "");
1017            }
1018        }
1019    }
1020
1021    free(data_recv);
1022    free(data_to_send);
1023    EXPECT_EQ(zx_handle_close(channel[0]), ZX_OK, "");
1024    EXPECT_EQ(zx_handle_close(channel[1]), ZX_OK, "");
1025    END_TEST;
1026}
1027
1028BEGIN_TEST_CASE(channel_tests)
1029RUN_TEST(channel_test)
1030RUN_TEST(channel_read_error_test)
1031RUN_TEST(channel_close_test)
1032RUN_TEST(channel_peer_closed_test)
1033RUN_TEST(channel_non_transferable)
1034RUN_TEST(channel_duplicate_handles)
1035RUN_TEST(channel_multithread_read)
1036RUN_TEST(channel_may_discard)
1037RUN_TEST(channel_call)
1038RUN_TEST(channel_call_consumes_handles)
1039RUN_TEST(channel_call2)
1040RUN_TEST(bad_channel_call_finish)
1041RUN_TEST(channel_nest)
1042RUN_TEST(channel_disallow_write_to_self)
1043RUN_TEST(channel_read_etc)
1044RUN_TEST(channel_write_different_sizes)
1045END_TEST_CASE(channel_tests)
1046
1047#ifndef BUILD_COMBINED_TESTS
1048int main(int argc, char** argv) {
1049    return unittest_run_all_tests(argc, argv) ? 0 : -1;
1050}
1051#endif
1052