70 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8 9#include "src/stdio/printf.h"10#include "src/__support/CPP/limits.h"11#include "src/__support/OSUtil/io.h"12#include "src/__support/arg_list.h"13#include "src/__support/libc_errno.h"14#include "src/__support/macros/config.h"15#include "src/stdio/printf_core/core_structs.h"16#include "src/stdio/printf_core/error_mapper.h"17#include "src/stdio/printf_core/printf_main.h"18#include "src/stdio/printf_core/writer.h"19 20#include <stdarg.h>21#include <stddef.h>22 23namespace LIBC_NAMESPACE_DECL {24 25namespace {26 27LIBC_INLINE int stdout_write_hook(cpp::string_view new_str, void *) {28 write_to_stdout(new_str);29 return printf_core::WRITE_OK;30}31 32} // namespace33 34LLVM_LIBC_FUNCTION(int, printf, (const char *__restrict format, ...)) {35 va_list vlist;36 va_start(vlist, format);37 internal::ArgList args(vlist); // This holder class allows for easier copying38 // and pointer semantics, as well as handling39 // destruction automatically.40 va_end(vlist);41 static constexpr size_t BUFF_SIZE = 1024;42 char buffer[BUFF_SIZE];43 44 printf_core::WriteBuffer<printf_core::WriteMode::FLUSH_TO_STREAM> wb(45 buffer, BUFF_SIZE, &stdout_write_hook, nullptr);46 printf_core::Writer<printf_core::WriteMode::FLUSH_TO_STREAM> writer(wb);47 48 auto retval = printf_core::printf_main(&writer, format, args);49 if (!retval.has_value()) {50 libc_errno = printf_core::internal_error_to_errno(retval.error());51 return -1;52 }53 54 int flushval = wb.overflow_write("");55 if (flushval != printf_core::WRITE_OK) {56 libc_errno = printf_core::internal_error_to_errno(-flushval);57 return -1;58 }59 60 if (retval.value() > static_cast<size_t>(cpp::numeric_limits<int>::max())) {61 libc_errno =62 printf_core::internal_error_to_errno(-printf_core::OVERFLOW_ERROR);63 return -1;64 }65 66 return static_cast<int>(retval.value());67}68 69} // namespace LIBC_NAMESPACE_DECL70