[libc-commits] [libc] ddae13c - [libc] fix scanf error handling

Michael Jones via libc-commits libc-commits at lists.llvm.org
Tue Dec 13 12:51:35 PST 2022


Author: Michael Jones
Date: 2022-12-13T12:51:26-08:00
New Revision: ddae13c30357087797991ebd59e200abe34bd800

URL: https://github.com/llvm/llvm-project/commit/ddae13c30357087797991ebd59e200abe34bd800
DIFF: https://github.com/llvm/llvm-project/commit/ddae13c30357087797991ebd59e200abe34bd800.diff

LOG: [libc] fix scanf error handling

Scanf is supposed to return EOF when it fails to make any conversions
and there is an input failure. Previously it would return EOF on a
matching failure, which may be an input failure but can also be a
parsing error.

Reviewed By: sivachandra

Differential Revision: https://reviews.llvm.org/D139891

Added: 
    

Modified: 
    libc/src/stdio/scanf_core/file_reader.h
    libc/src/stdio/scanf_core/reader.cpp
    libc/src/stdio/scanf_core/reader.h
    libc/src/stdio/scanf_core/scanf_main.cpp

Removed: 
    


################################################################################
diff  --git a/libc/src/stdio/scanf_core/file_reader.h b/libc/src/stdio/scanf_core/file_reader.h
index 5e97eb604e66b..a70e00bc24139 100644
--- a/libc/src/stdio/scanf_core/file_reader.h
+++ b/libc/src/stdio/scanf_core/file_reader.h
@@ -30,6 +30,7 @@ class FileReader {
 
   char get_char();
   void unget_char(char c);
+  bool has_error() { return file->error_unlocked(); }
 };
 
 } // namespace scanf_core

diff  --git a/libc/src/stdio/scanf_core/reader.cpp b/libc/src/stdio/scanf_core/reader.cpp
index 0d8d5a30f7c4d..4834f4d6a6e79 100644
--- a/libc/src/stdio/scanf_core/reader.cpp
+++ b/libc/src/stdio/scanf_core/reader.cpp
@@ -33,5 +33,12 @@ void Reader::ungetc(char c) {
   }
 }
 
+bool Reader::has_error() {
+  if (reader_type == ReaderType::File) {
+    return file_reader->has_error();
+  }
+  return false;
+}
+
 } // namespace scanf_core
 } // namespace __llvm_libc

diff  --git a/libc/src/stdio/scanf_core/reader.h b/libc/src/stdio/scanf_core/reader.h
index 4ca25cc0d0cab..000ab02ad28f2 100644
--- a/libc/src/stdio/scanf_core/reader.h
+++ b/libc/src/stdio/scanf_core/reader.h
@@ -45,6 +45,8 @@ class Reader final {
   void ungetc(char c);
 
   size_t chars_read() { return cur_chars_read; }
+
+  bool has_error();
 };
 
 } // namespace scanf_core

diff  --git a/libc/src/stdio/scanf_core/scanf_main.cpp b/libc/src/stdio/scanf_core/scanf_main.cpp
index fcf7af2083f22..ed509eca4c66f 100644
--- a/libc/src/stdio/scanf_core/scanf_main.cpp
+++ b/libc/src/stdio/scanf_core/scanf_main.cpp
@@ -35,7 +35,7 @@ int scanf_main(Reader *reader, const char *__restrict str,
     }
   }
 
-  if (conversions == 0 && ret_val != READ_OK) {
+  if (conversions == 0 && reader->has_error()) {
     // This is intended to be converted to EOF in the client call to avoid
     // including stdio.h in this internal file.
     return -1;


        


More information about the libc-commits mailing list