1 //===--- GPU helper functions for file I/O using RPC ----------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "src/__support/RPC/rpc_client.h"
10 #include "src/string/string_utils.h"
14 namespace LIBC_NAMESPACE
{
24 // When copying between the client and server we need to indicate if this is one
25 // of the special streams. We do this by enocding the low order bits of the
26 // pointer to indicate if we need to use the host's standard stream.
27 LIBC_INLINE
uintptr_t from_stream(::FILE *f
) {
29 return reinterpret_cast<uintptr_t>(f
) | Stdin
;
31 return reinterpret_cast<uintptr_t>(f
) | Stdout
;
33 return reinterpret_cast<uintptr_t>(f
) | Stderr
;
34 return reinterpret_cast<uintptr_t>(f
);
37 // Get the associated stream out of an encoded number.
38 LIBC_INLINE ::FILE *to_stream(uintptr_t f
) {
39 ::FILE *stream
= reinterpret_cast<FILE *>(f
& ~0x3ull
);
40 Stream type
= static_cast<Stream
>(f
& 0x3ull
);
50 template <uint16_t opcode
>
51 LIBC_INLINE
uint64_t write_impl(::FILE *file
, const void *data
, size_t size
) {
53 rpc::Client::Port port
= rpc::client
.open
<opcode
>();
55 if constexpr (opcode
== RPC_WRITE_TO_STREAM
) {
56 port
.send([&](rpc::Buffer
*buffer
) {
57 buffer
->data
[0] = reinterpret_cast<uintptr_t>(file
);
61 port
.send_n(data
, size
);
62 port
.recv([&](rpc::Buffer
*buffer
) {
63 ret
= reinterpret_cast<uint64_t *>(buffer
->data
)[0];
69 LIBC_INLINE
uint64_t write(::FILE *f
, const void *data
, size_t size
) {
71 return write_impl
<RPC_WRITE_TO_STDOUT
>(f
, data
, size
);
73 return write_impl
<RPC_WRITE_TO_STDERR
>(f
, data
, size
);
75 return write_impl
<RPC_WRITE_TO_STREAM
>(f
, data
, size
);
78 LIBC_INLINE
uint64_t read_from_stream(::FILE *file
, void *buf
, size_t size
) {
81 rpc::Client::Port port
= rpc::client
.open
<RPC_READ_FROM_STREAM
>();
82 port
.send([=](rpc::Buffer
*buffer
) {
83 buffer
->data
[0] = size
;
84 buffer
->data
[1] = from_stream(file
);
86 port
.recv_n(&buf
, &recv_size
, [&](uint64_t) { return buf
; });
87 port
.recv([&](rpc::Buffer
*buffer
) { ret
= buffer
->data
[0]; });
92 LIBC_INLINE
uint64_t read(::FILE *f
, void *data
, size_t size
) {
93 return read_from_stream(f
, data
, size
);
97 } // namespace LIBC_NAMESPACE