[libc] Provide baremetal implementation of getchar (#98059)

This introduces opaque type `struct __llvm_libc_stdin` and a symbol
`__llvm_libc_stdin_read` that's intended to be provided by the vendor.

`__llvm_libc_stdin_read` intentionally has the same signature as
`cookie_read_function_t` so it can be used with `fopencookie` to
represent `stdin` as `FILE *` in the future.
This commit is contained in:
Petr Hosek
2024-07-09 01:45:27 -07:00
committed by GitHub
parent dd2bf3b840
commit cfa2d7df11
6 changed files with 49 additions and 0 deletions

View File

@@ -83,6 +83,7 @@ set(TARGET_LIBC_ENTRYPOINTS
libc.src.inttypes.strtoumax
# stdio.h entrypoints
libc.src.stdio.getchar
libc.src.stdio.printf
libc.src.stdio.putchar
libc.src.stdio.puts

View File

@@ -79,6 +79,7 @@ set(TARGET_LIBC_ENTRYPOINTS
libc.src.inttypes.strtoumax
# stdio.h entrypoints
libc.src.stdio.getchar
libc.src.stdio.printf
libc.src.stdio.putchar
libc.src.stdio.puts

View File

@@ -11,10 +11,19 @@
#include "src/__support/CPP/string_view.h"
// This is intended to be provided by the vendor.
extern struct __llvm_libc_stdin __llvm_libc_stdin;
extern "C" ssize_t __llvm_libc_stdin_read(void *cookie, char *buf, size_t size);
extern "C" void __llvm_libc_log_write(const char *msg, size_t len);
namespace LIBC_NAMESPACE {
ssize_t read_from_stdin(char *buf, size_t size) {
return __llvm_libc_stdin_read(reinterpret_cast<void *>(&__llvm_libc_stdin),
buf, size);
}
void write_to_stderr(cpp::string_view msg) {
__llvm_libc_log_write(msg.data(), msg.size());
}

View File

@@ -9,10 +9,13 @@
#ifndef LLVM_LIBC_SRC___SUPPORT_OSUTIL_BAREMETAL_IO_H
#define LLVM_LIBC_SRC___SUPPORT_OSUTIL_BAREMETAL_IO_H
#include "include/llvm-libc-types/size_t.h"
#include "include/llvm-libc-types/ssize_t.h"
#include "src/__support/CPP/string_view.h"
namespace LIBC_NAMESPACE {
ssize_t read_from_stdin(char *buf, size_t size);
void write_to_stderr(cpp::string_view msg);
} // namespace LIBC_NAMESPACE

View File

@@ -1,3 +1,14 @@
add_entrypoint_object(
getchar
SRCS
getchar.cpp
HDRS
../getchar.h
DEPENDS
libc.src.__support.OSUtil.osutil
libc.src.__support.CPP.string_view
)
add_entrypoint_object(
remove
SRCS

View File

@@ -0,0 +1,24 @@
//===-- Baremetal implementation of getchar -------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "src/stdio/getchar.h"
#include "src/__support/OSUtil/io.h"
#include <stdio.h>
namespace LIBC_NAMESPACE {
LLVM_LIBC_FUNCTION(int, getchar, ()) {
char buf[1];
auto result = read_from_stdin(buf, sizeof(buf));
if (result < 0)
return EOF;
return buf[0];
}
} // namespace LIBC_NAMESPACE