1 //===-- Implementation of printf for baremetal ------------------*- 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 "src/stdio/printf.h"
10 #include "src/__support/arg_list.h"
11 #include "src/stdio/printf_core/core_structs.h"
12 #include "src/stdio/printf_core/printf_main.h"
13 #include "src/stdio/printf_core/writer.h"
14
15 #include <stdarg.h>
16
17 // TODO(https://github.com/llvm/llvm-project/issues/94685) unify baremetal hooks
18
19 // This is intended to be provided by the vendor.
20 extern "C" size_t __llvm_libc_raw_write(const char *s, size_t size);
21
22 namespace LIBC_NAMESPACE {
23
24 namespace {
25
raw_write_hook(cpp::string_view new_str,void *)26 LIBC_INLINE int raw_write_hook(cpp::string_view new_str, void *) {
27 size_t written = __llvm_libc_raw_write(new_str.data(), new_str.size());
28 if (written != new_str.size())
29 return printf_core::FILE_WRITE_ERROR;
30 return printf_core::WRITE_OK;
31 }
32
33 } // namespace
34
35 LLVM_LIBC_FUNCTION(int, printf, (const char *__restrict format, ...)) {
36 va_list vlist;
37 va_start(vlist, format);
38 internal::ArgList args(vlist); // This holder class allows for easier copying
39 // and pointer semantics, as well as handling
40 // destruction automatically.
41 va_end(vlist);
42 constexpr size_t BUFF_SIZE = 1024;
43 char buffer[BUFF_SIZE];
44
45 printf_core::WriteBuffer wb(buffer, BUFF_SIZE, &raw_write_hook, nullptr);
46 printf_core::Writer writer(&wb);
47
48 int retval = printf_core::printf_main(&writer, format, args);
49
50 int flushval = wb.overflow_write("");
51 if (flushval != printf_core::WRITE_OK)
52 retval = flushval;
53
54 return retval;
55 }
56
57 } // namespace LIBC_NAMESPACE
58