1//===---------- Baremetal implementation of IO utils ------------*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
9#include "io.h"
10
11#include "src/__support/CPP/string_view.h"
12#include "src/__support/macros/config.h"
13
14namespace LIBC_NAMESPACE_DECL {
15
16// These are intended to be provided by the vendor.
17//
18// The signature of these types and functions intentionally match `fopencookie`
19// which allows the following:
20//
21// ```
22// struct __llvm_libc_stdio_cookie { ... };
23// ...
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);
27// ...
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);
31// ...
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);
35// ```
36//
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.
40//
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
43// at anything.
44
45struct __llvm_libc_stdio_cookie;
46
47extern "C" struct __llvm_libc_stdio_cookie __llvm_libc_stdin_cookie;
48extern "C" struct __llvm_libc_stdio_cookie __llvm_libc_stdout_cookie;
49extern "C" struct __llvm_libc_stdio_cookie __llvm_libc_stderr_cookie;
50
51extern "C" ssize_t __llvm_libc_stdio_read(void *cookie, char *buf, size_t size);
52extern "C" ssize_t __llvm_libc_stdio_write(void *cookie, const char *buf,
53 size_t size);
54
55ssize_t read_from_stdin(char *buf, size_t size) {
56 return __llvm_libc_stdio_read(static_cast<void *>(&__llvm_libc_stdin_cookie),
57 buf, size);
58}
59
60void write_to_stdout(cpp::string_view msg) {
61 __llvm_libc_stdio_write(static_cast<void *>(&__llvm_libc_stdout_cookie),
62 msg.data(), msg.size());
63}
64
65void write_to_stderr(cpp::string_view msg) {
66 __llvm_libc_stdio_write(static_cast<void *>(&__llvm_libc_stderr_cookie),
67 msg.data(), msg.size());
68}
69
70} // namespace LIBC_NAMESPACE_DECL
71

source code of libc/src/__support/OSUtil/baremetal/io.cpp