[libc] Implement perror (#143624)

The perror function writes an error message directly to stderr. This
patch adds an implementation, tests, and header generation details.
This commit is contained in:
Michael Jones
2025-06-12 10:45:47 -07:00
committed by GitHub
parent 4e765b7a6b
commit 5a6a4b6ba6
10 changed files with 170 additions and 0 deletions

View File

@@ -357,6 +357,18 @@ add_libc_test(
libc.src.stdio.puts
)
add_libc_test(
perror_test
HERMETIC_TEST_ONLY # writes to libc's stderr
SUITE
libc_stdio_unittests
SRCS
perror_test.cpp
DEPENDS
libc.src.stdio.perror
libc.src.errno.errno
)
add_libc_test(
fputs_test
HERMETIC_TEST_ONLY # writes to libc's stdout and stderr

View File

@@ -0,0 +1,32 @@
//===-- Unittests for perror ---------------------------------------------===//
//
// 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/perror.h"
#include "src/__support/libc_errno.h"
#include "test/UnitTest/Test.h"
// The standard says perror prints directly to stderr and returns nothing. This
// makes it rather difficult to test automatically.
// TODO: figure out redirecting stderr so this test can check correctness.
TEST(LlvmLibcPerrorTest, PrintOut) {
LIBC_NAMESPACE::libc_errno = 0;
constexpr char simple[] = "A simple string";
LIBC_NAMESPACE::perror(simple);
// stick to stdc errno values, specifically 0, EDOM, ERANGE, and EILSEQ.
LIBC_NAMESPACE::libc_errno = EDOM;
LIBC_NAMESPACE::perror("Print this and an error");
LIBC_NAMESPACE::libc_errno = EILSEQ;
LIBC_NAMESPACE::perror("\0 shouldn't print this.");
LIBC_NAMESPACE::libc_errno = ERANGE;
LIBC_NAMESPACE::perror(nullptr);
}