1 //===---------- Baremetal implementation of IO utils ------------*- C++ -*-===//
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 //===----------------------------------------------------------------------===//
11 #include "src/__support/CPP/string_view.h"
12 #include "src/__support/macros/config.h"
14 namespace LIBC_NAMESPACE_DECL
{
16 // These are intended to be provided by the vendor.
18 // The signature of these types and functions intentionally match `fopencookie`
19 // which allows the following:
22 // struct __llvm_libc_stdio_cookie { ... };
24 // struct __llvm_libc_stdio_cookie __llvm_libc_stdin_cookie;
25 // cookie_io_functions_t stdin_func = { .read = __llvm_libc_stdio_read };
26 // FILE *stdin = fopencookie(&__llvm_libc_stdin_cookie, "r", stdin_func);
28 // struct __llvm_libc_stdio_cookie __llvm_libc_stdout_cookie;
29 // cookie_io_functions_t stdout_func = { .write = __llvm_libc_stdio_write };
30 // FILE *stdout = fopencookie(&__llvm_libc_stdout_cookie, "w", stdout_func);
32 // struct __llvm_libc_stdio_cookie __llvm_libc_stderr_cookie;
33 // cookie_io_functions_t stderr_func = { .write = __llvm_libc_stdio_write };
34 // FILE *stderr = fopencookie(&__llvm_libc_stderr_cookie, "w", stderr_func);
37 // At the same time, implementation of functions like `printf` and `scanf` can
38 // use `__llvm_libc_stdio_read` and `__llvm_libc_stdio_write` directly to avoid
39 // the extra indirection.
41 // All three symbols `__llvm_libc_stdin_cookie`, `__llvm_libc_stdout_cookie`,
42 // and `__llvm_libc_stderr_cookie` must be provided, even if they don't point
45 struct __llvm_libc_stdio_cookie
;
47 extern "C" struct __llvm_libc_stdio_cookie __llvm_libc_stdin_cookie
;
48 extern "C" struct __llvm_libc_stdio_cookie __llvm_libc_stdout_cookie
;
49 extern "C" struct __llvm_libc_stdio_cookie __llvm_libc_stderr_cookie
;
51 extern "C" ssize_t
__llvm_libc_stdio_read(void *cookie
, char *buf
, size_t size
);
52 extern "C" ssize_t
__llvm_libc_stdio_write(void *cookie
, const char *buf
,
55 ssize_t
read_from_stdin(char *buf
, size_t size
) {
56 return __llvm_libc_stdio_read(static_cast<void *>(&__llvm_libc_stdin_cookie
),
60 void write_to_stdout(cpp::string_view msg
) {
61 __llvm_libc_stdio_write(static_cast<void *>(&__llvm_libc_stdout_cookie
),
62 msg
.data(), msg
.size());
65 void write_to_stderr(cpp::string_view msg
) {
66 __llvm_libc_stdio_write(static_cast<void *>(&__llvm_libc_stderr_cookie
),
67 msg
.data(), msg
.size());
70 } // namespace LIBC_NAMESPACE_DECL