1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <gtest/gtest.h>
18 
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <limits.h>
22 #include <locale.h>
23 #include <math.h>
24 #include <stdio.h>
25 #include <sys/cdefs.h>
26 #include <sys/socket.h>
27 #include <sys/stat.h>
28 #include <sys/sysinfo.h>
29 #include <sys/types.h>
30 #include <unistd.h>
31 #include <wchar.h>
32 
33 #include <string>
34 #include <thread>
35 #include <vector>
36 
37 #include <android-base/file.h>
38 #include <android-base/silent_death_test.h>
39 #include <android-base/strings.h>
40 #include <android-base/test_utils.h>
41 #include <android-base/unique_fd.h>
42 
43 #include "utils.h"
44 
45 // This #include is actually a test too. We have to duplicate the
46 // definitions of the RENAME_ constants because <linux/fs.h> also contains
47 // pollution such as BLOCK_SIZE which conflicts with lots of user code.
48 // Important to check that we have matching definitions.
49 // There's no _MAX to test that we have all the constants, sadly.
50 #include <linux/fs.h>
51 
52 #if defined(NOFORTIFY)
53 #define STDIO_TEST stdio_nofortify
54 #define STDIO_DEATHTEST stdio_nofortify_DeathTest
55 #else
56 #define STDIO_TEST stdio
57 #define STDIO_DEATHTEST stdio_DeathTest
58 #endif
59 
60 using namespace std::string_literals;
61 
62 using stdio_DeathTest = SilentDeathTest;
63 using stdio_nofortify_DeathTest = SilentDeathTest;
64 
SetFileTo(const char * path,const char * content)65 static void SetFileTo(const char* path, const char* content) {
66   FILE* fp;
67   ASSERT_NE(nullptr, fp = fopen(path, "w"));
68   ASSERT_NE(EOF, fputs(content, fp));
69   ASSERT_EQ(0, fclose(fp));
70 }
71 
AssertFileIs(const char * path,const char * expected)72 static void AssertFileIs(const char* path, const char* expected) {
73   FILE* fp;
74   ASSERT_NE(nullptr, fp = fopen(path, "r"));
75   char* line = nullptr;
76   size_t length;
77   ASSERT_NE(EOF, getline(&line, &length, fp));
78   ASSERT_EQ(0, fclose(fp));
79   ASSERT_STREQ(expected, line);
80   free(line);
81 }
82 
AssertFileIs(FILE * fp,const char * expected,bool is_fmemopen=false)83 static void AssertFileIs(FILE* fp, const char* expected, bool is_fmemopen = false) {
84   rewind(fp);
85 
86   char line[1024];
87   memset(line, 0xff, sizeof(line));
88   ASSERT_EQ(line, fgets(line, sizeof(line), fp));
89   ASSERT_STREQ(expected, line);
90 
91   if (is_fmemopen) {
92     // fmemopen appends a trailing NUL byte, which probably shouldn't show up as an
93     // extra empty line, but does on every C library I tested...
94     ASSERT_EQ(line, fgets(line, sizeof(line), fp));
95     ASSERT_STREQ("", line);
96   }
97 
98   // Make sure there isn't anything else in the file.
99   ASSERT_EQ(nullptr, fgets(line, sizeof(line), fp)) << "junk at end of file: " << line;
100 }
101 
102 #define EXPECT_SNPRINTF_N(expected, n, fmt, ...)                        \
103   {                                                                     \
104     char buf[BUFSIZ];                                                   \
105     int w = snprintf(buf, sizeof(buf), fmt __VA_OPT__(, ) __VA_ARGS__); \
106     EXPECT_EQ(n, w);                                                    \
107     EXPECT_STREQ(expected, buf);                                        \
108   }
109 
110 #define EXPECT_SNPRINTF(expected, fmt, ...) \
111   EXPECT_SNPRINTF_N(expected, static_cast<int>(strlen(expected)), fmt __VA_OPT__(, ) __VA_ARGS__)
112 
113 #define EXPECT_SWPRINTF_N(expected, n, fmt, ...)                        \
114   {                                                                     \
115     wchar_t buf[BUFSIZ];                                                \
116     int w = swprintf(buf, sizeof(buf), fmt __VA_OPT__(, ) __VA_ARGS__); \
117     EXPECT_EQ(n, w);                                                    \
118     EXPECT_EQ(std::wstring(expected), std::wstring(buf, w));            \
119   }
120 #define EXPECT_SWPRINTF(expected, fmt, ...) \
121   EXPECT_SWPRINTF_N(expected, static_cast<int>(wcslen(expected)), fmt __VA_OPT__(, ) __VA_ARGS__)
122 
TEST(STDIO_TEST,flockfile_18208568_stderr)123 TEST(STDIO_TEST, flockfile_18208568_stderr) {
124   flockfile(stderr);
125   // Check that we're using a _recursive_ mutex for flockfile() by calling
126   // something that will take the lock.
127   ASSERT_EQ(0, feof(stderr));
128   funlockfile(stderr);
129 }
130 
TEST(STDIO_TEST,flockfile_18208568_regular)131 TEST(STDIO_TEST, flockfile_18208568_regular) {
132   // We never had a bug for streams other than stdin/stdout/stderr, but test anyway.
133   FILE* fp = fopen("/dev/null", "w");
134   ASSERT_TRUE(fp != nullptr);
135   flockfile(fp);
136   // Check that we're using a _recursive_ mutex for flockfile() by calling
137   // something that will take the lock.
138   ASSERT_EQ(0, feof(fp));
139   funlockfile(fp);
140   fclose(fp);
141 }
142 
TEST(STDIO_TEST,tmpfile_fileno_fprintf_rewind_fgets)143 TEST(STDIO_TEST, tmpfile_fileno_fprintf_rewind_fgets) {
144   FILE* fp = tmpfile();
145   ASSERT_TRUE(fp != nullptr);
146 
147   int fd = fileno(fp);
148   ASSERT_NE(fd, -1);
149 
150   struct stat sb;
151   int rc = fstat(fd, &sb);
152   ASSERT_NE(rc, -1);
153   ASSERT_EQ(sb.st_mode & 0777, 0600U);
154 
155   rc = fprintf(fp, "hello\n");
156   ASSERT_EQ(rc, 6);
157 
158   AssertFileIs(fp, "hello\n");
159   fclose(fp);
160 }
161 
TEST(STDIO_TEST,tmpfile64)162 TEST(STDIO_TEST, tmpfile64) {
163   FILE* fp = tmpfile64();
164   ASSERT_TRUE(fp != nullptr);
165   fclose(fp);
166 }
167 
TEST(STDIO_TEST,tmpfile_TMPDIR)168 TEST(STDIO_TEST, tmpfile_TMPDIR) {
169   TemporaryDir td;
170   setenv("TMPDIR", td.path, 1);
171 
172   FILE* fp = tmpfile();
173   ASSERT_TRUE(fp != nullptr);
174 
175   std::string fd_path = android::base::StringPrintf("/proc/self/fd/%d", fileno(fp));
176   char path[PATH_MAX];
177   ASSERT_GT(readlink(fd_path.c_str(), path, sizeof(path)), 0);
178   // $TMPDIR influenced where our temporary file ended up?
179   ASSERT_TRUE(android::base::StartsWith(path, td.path)) << path;
180   // And we used O_TMPFILE, right?
181   ASSERT_TRUE(android::base::EndsWith(path, " (deleted)")) << path;
182 }
183 
TEST(STDIO_TEST,dprintf)184 TEST(STDIO_TEST, dprintf) {
185   TemporaryFile tf;
186 
187   int rc = dprintf(tf.fd, "hello\n");
188   ASSERT_EQ(rc, 6);
189 
190   lseek(tf.fd, 0, SEEK_SET);
191   FILE* tfile = fdopen(tf.fd, "r");
192   ASSERT_TRUE(tfile != nullptr);
193 
194   AssertFileIs(tfile, "hello\n");
195   fclose(tfile);
196 }
197 
TEST(STDIO_TEST,getdelim)198 TEST(STDIO_TEST, getdelim) {
199   FILE* fp = tmpfile();
200   ASSERT_TRUE(fp != nullptr);
201 
202   const char* line_written = "This  is a test";
203   int rc = fprintf(fp, "%s", line_written);
204   ASSERT_EQ(rc, static_cast<int>(strlen(line_written)));
205 
206   rewind(fp);
207 
208   char* word_read = nullptr;
209   size_t allocated_length = 0;
210 
211   const char* expected[] = { "This ", " ", "is ", "a ", "test" };
212   for (size_t i = 0; i < 5; ++i) {
213     ASSERT_FALSE(feof(fp));
214     ASSERT_EQ(getdelim(&word_read, &allocated_length, ' ', fp), static_cast<int>(strlen(expected[i])));
215     ASSERT_GE(allocated_length, strlen(expected[i]));
216     ASSERT_STREQ(expected[i], word_read);
217   }
218   // The last read should have set the end-of-file indicator for the stream.
219   ASSERT_TRUE(feof(fp));
220   clearerr(fp);
221 
222   // getdelim returns -1 but doesn't set errno if we're already at EOF.
223   // It should set the end-of-file indicator for the stream, though.
224   errno = 0;
225   ASSERT_EQ(getdelim(&word_read, &allocated_length, ' ', fp), -1);
226   ASSERT_ERRNO(0);
227   ASSERT_TRUE(feof(fp));
228 
229   free(word_read);
230   fclose(fp);
231 }
232 
TEST(STDIO_TEST,getdelim_invalid)233 TEST(STDIO_TEST, getdelim_invalid) {
234 #pragma clang diagnostic push
235 #pragma clang diagnostic ignored "-Wnonnull"
236   FILE* fp = tmpfile();
237   ASSERT_TRUE(fp != nullptr);
238 
239   char* buffer = nullptr;
240   size_t buffer_length = 0;
241 
242   // The first argument can't be NULL.
243   errno = 0;
244   ASSERT_EQ(getdelim(nullptr, &buffer_length, ' ', fp), -1);
245   ASSERT_ERRNO(EINVAL);
246 
247   // The second argument can't be NULL.
248   errno = 0;
249   ASSERT_EQ(getdelim(&buffer, nullptr, ' ', fp), -1);
250   ASSERT_ERRNO(EINVAL);
251   fclose(fp);
252 #pragma clang diagnostic pop
253 }
254 
TEST(STDIO_TEST,getdelim_directory)255 TEST(STDIO_TEST, getdelim_directory) {
256   FILE* fp = fopen("/proc", "r");
257   ASSERT_TRUE(fp != nullptr);
258   char* word_read;
259   size_t allocated_length;
260   ASSERT_EQ(-1, getdelim(&word_read, &allocated_length, ' ', fp));
261   fclose(fp);
262 }
263 
TEST(STDIO_TEST,getline)264 TEST(STDIO_TEST, getline) {
265   FILE* fp = tmpfile();
266   ASSERT_TRUE(fp != nullptr);
267 
268   const char* line_written = "This is a test for getline\n";
269   const size_t line_count = 5;
270 
271   for (size_t i = 0; i < line_count; ++i) {
272     int rc = fprintf(fp, "%s", line_written);
273     ASSERT_EQ(rc, static_cast<int>(strlen(line_written)));
274   }
275 
276   rewind(fp);
277 
278   char* line_read = nullptr;
279   size_t allocated_length = 0;
280 
281   size_t read_line_count = 0;
282   ssize_t read_char_count;
283   while ((read_char_count = getline(&line_read, &allocated_length, fp)) != -1) {
284     ASSERT_EQ(read_char_count, static_cast<int>(strlen(line_written)));
285     ASSERT_GE(allocated_length, strlen(line_written));
286     ASSERT_STREQ(line_written, line_read);
287     ++read_line_count;
288   }
289   ASSERT_EQ(read_line_count, line_count);
290 
291   // The last read should have set the end-of-file indicator for the stream.
292   ASSERT_TRUE(feof(fp));
293   clearerr(fp);
294 
295   // getline returns -1 but doesn't set errno if we're already at EOF.
296   // It should set the end-of-file indicator for the stream, though.
297   errno = 0;
298   ASSERT_EQ(getline(&line_read, &allocated_length, fp), -1);
299   ASSERT_ERRNO(0);
300   ASSERT_TRUE(feof(fp));
301 
302   free(line_read);
303   fclose(fp);
304 }
305 
TEST(STDIO_TEST,getline_invalid)306 TEST(STDIO_TEST, getline_invalid) {
307 #pragma clang diagnostic push
308 #pragma clang diagnostic ignored "-Wnonnull"
309   FILE* fp = tmpfile();
310   ASSERT_TRUE(fp != nullptr);
311 
312   char* buffer = nullptr;
313   size_t buffer_length = 0;
314 
315   // The first argument can't be NULL.
316   errno = 0;
317   ASSERT_EQ(getline(nullptr, &buffer_length, fp), -1);
318   ASSERT_ERRNO(EINVAL);
319 
320   // The second argument can't be NULL.
321   errno = 0;
322   ASSERT_EQ(getline(&buffer, nullptr, fp), -1);
323   ASSERT_ERRNO(EINVAL);
324   fclose(fp);
325 #pragma clang diagnostic pop
326 }
327 
TEST(STDIO_TEST,printf_ssize_t)328 TEST(STDIO_TEST, printf_ssize_t) {
329   // http://b/8253769
330   ASSERT_EQ(sizeof(ssize_t), sizeof(long int));
331   ASSERT_EQ(sizeof(ssize_t), sizeof(size_t));
332   // For our 32-bit ABI, we had a ssize_t definition that confuses GCC into saying:
333   // error: format '%zd' expects argument of type 'signed size_t',
334   //     but argument 4 has type 'ssize_t {aka long int}' [-Werror=format]
335   ssize_t v = 1;
336   EXPECT_SNPRINTF("1", "%zd", v);
337   EXPECT_SWPRINTF(L"1", L"%zd", v);
338 }
339 
340 // https://code.google.com/p/android/issues/detail?id=64886
TEST(STDIO_TEST,snprintf_a)341 TEST(STDIO_TEST, snprintf_a) {
342   EXPECT_SNPRINTF("<0x1.3831e147ae148p+13>", "<%a>", 9990.235);
343 }
344 
345 // https://code.google.com/p/android/issues/detail?id=64886
TEST(STDIO_TEST,swprintf_a)346 TEST(STDIO_TEST, swprintf_a) {
347   EXPECT_SWPRINTF(L"<0x1.3831e147ae148p+13>", L"<%a>", 9990.235);
348 }
349 
350 // http://b/152588929
TEST(STDIO_TEST,snprintf_La)351 TEST(STDIO_TEST, snprintf_La) {
352 #if defined(__LP64__)
353   union {
354     uint64_t a[2];
355     long double v;
356   } u;
357 
358   u.a[0] = UINT64_C(0x9b9b9b9b9b9b9b9b);
359   u.a[1] = UINT64_C(0xdfdfdfdfdfdfdfdf);
360   EXPECT_SNPRINTF("<-0x1.dfdfdfdfdfdf9b9b9b9b9b9b9b9bp+8160>", "<%La>", u.v);
361 
362   u.a[0] = UINT64_C(0xffffffffffffffff);
363   u.a[1] = UINT64_C(0x7ffeffffffffffff);
364   EXPECT_SNPRINTF("<0x1.ffffffffffffffffffffffffffffp+16383>", "<%La>", u.v);
365 
366   u.a[0] = UINT64_C(0x0000000000000000);
367   u.a[1] = UINT64_C(0x0000000000000000);
368   EXPECT_SNPRINTF("<0x0p+0>", "<%La>", u.v);
369 #else
370   GTEST_SKIP() << "no ld128";
371 #endif
372 }
373 
374 // http://b/152588929
TEST(STDIO_TEST,swprintf_La)375 TEST(STDIO_TEST, swprintf_La) {
376 #if defined(__LP64__)
377   union {
378     uint64_t a[2];
379     long double v;
380   } u;
381 
382   u.a[0] = UINT64_C(0x9b9b9b9b9b9b9b9b);
383   u.a[1] = UINT64_C(0xdfdfdfdfdfdfdfdf);
384   EXPECT_SWPRINTF(L"<-0x1.dfdfdfdfdfdf9b9b9b9b9b9b9b9bp+8160>", L"<%La>", u.v);
385 
386   u.a[0] = UINT64_C(0xffffffffffffffff);
387   u.a[1] = UINT64_C(0x7ffeffffffffffff);
388   EXPECT_SWPRINTF(L"<0x1.ffffffffffffffffffffffffffffp+16383>", L"<%La>", u.v);
389 
390   u.a[0] = UINT64_C(0x0000000000000000);
391   u.a[1] = UINT64_C(0x0000000000000000);
392   EXPECT_SWPRINTF(L"<0x0p+0>", L"<%La>", u.v);
393 #else
394   GTEST_SKIP() << "no ld128";
395 #endif
396 }
397 
TEST(STDIO_TEST,snprintf_lc)398 TEST(STDIO_TEST, snprintf_lc) {
399   wint_t wc = L'a';
400   EXPECT_SNPRINTF("<a>", "<%lc>", wc);
401 }
402 
TEST(STDIO_TEST,swprintf_lc)403 TEST(STDIO_TEST, swprintf_lc) {
404   wint_t wc = L'a';
405   EXPECT_SWPRINTF(L"<a>", L"<%lc>", wc);
406 }
407 
TEST(STDIO_TEST,snprintf_C)408 TEST(STDIO_TEST, snprintf_C) {  // Synonym for %lc.
409   wchar_t wc = L'a';
410   EXPECT_SNPRINTF("<a>", "<%C>", wc);
411 }
412 
TEST(STDIO_TEST,swprintf_C)413 TEST(STDIO_TEST, swprintf_C) {  // Synonym for %lc.
414   wchar_t wc = L'a';
415   EXPECT_SWPRINTF(L"<a>", L"<%C>", wc);
416 }
417 
TEST(STDIO_TEST,snprintf_ls_null)418 TEST(STDIO_TEST, snprintf_ls_null) {
419   EXPECT_SNPRINTF("<(null)>", "<%ls>", static_cast<wchar_t*>(nullptr));
420 }
421 
TEST(STDIO_TEST,swprintf_ls_null)422 TEST(STDIO_TEST, swprintf_ls_null) {
423   EXPECT_SWPRINTF(L"<(null)>", L"<%ls>", static_cast<wchar_t*>(nullptr));
424 }
425 
TEST(STDIO_TEST,snprintf_ls)426 TEST(STDIO_TEST, snprintf_ls) {
427   static const wchar_t chars[] = L"Hello\u0666 World";
428   EXPECT_SNPRINTF("<Hello\xd9\xa6 World>", "<%ls>", chars);
429 }
430 
TEST(STDIO_TEST,swprintf_ls)431 TEST(STDIO_TEST, swprintf_ls) {
432   static const wchar_t chars[] = L"Hello\u0666 World";
433   EXPECT_SWPRINTF(L"<Hello\u0666 World>", L"<%ls>", chars);
434 }
435 
TEST(STDIO_TEST,snprintf_S_nullptr)436 TEST(STDIO_TEST, snprintf_S_nullptr) {  // Synonym for %ls.
437   EXPECT_SNPRINTF("<(null)>", "<%S>", static_cast<wchar_t*>(nullptr));
438 }
439 
TEST(STDIO_TEST,swprintf_S_nullptr)440 TEST(STDIO_TEST, swprintf_S_nullptr) {  // Synonym for %ls.
441   EXPECT_SWPRINTF(L"<(null)>", L"<%S>", static_cast<wchar_t*>(nullptr));
442 }
443 
TEST(STDIO_TEST,snprintf_S)444 TEST(STDIO_TEST, snprintf_S) { // Synonym for %ls.
445   static const wchar_t chars[] = L"Hello\u0666 World";
446   EXPECT_SNPRINTF("<Hello\xd9\xa6 World>", "<%S>", chars);
447 }
448 
TEST(STDIO_TEST,swprintf_S)449 TEST(STDIO_TEST, swprintf_S) {  // Synonym for %ls.
450   static const wchar_t chars[] = L"Hello\u0666 World";
451   EXPECT_SWPRINTF(L"<Hello\u0666 World>", L"<%S>", chars);
452 }
453 
TEST_F(STDIO_DEATHTEST,snprintf_n)454 TEST_F(STDIO_DEATHTEST, snprintf_n) {
455 #if defined(__BIONIC__)
456 #pragma clang diagnostic push
457 #pragma clang diagnostic ignored "-Wformat"
458   // http://b/14492135 and http://b/31832608.
459   char buf[32];
460   int i = 1234;
461   EXPECT_DEATH(snprintf(buf, sizeof(buf), "a %n b", &i), "%n not allowed on Android");
462 #pragma clang diagnostic pop
463 #else
464   GTEST_SKIP() << "glibc does allow %n";
465 #endif
466 }
467 
TEST_F(STDIO_DEATHTEST,swprintf_n)468 TEST_F(STDIO_DEATHTEST, swprintf_n) {
469 #if defined(__BIONIC__)
470 #pragma clang diagnostic push
471 #pragma clang diagnostic ignored "-Wformat"
472   // http://b/14492135 and http://b/31832608.
473   wchar_t buf[32];
474   int i = 1234;
475   EXPECT_DEATH(swprintf(buf, sizeof(buf), L"a %n b", &i), "%n not allowed on Android");
476 #pragma clang diagnostic pop
477 #else
478   GTEST_SKIP() << "glibc does allow %n";
479 #endif
480 }
481 
TEST(STDIO_TEST,snprintf_measure)482 TEST(STDIO_TEST, snprintf_measure) {
483   char buf[1] = {'x'};
484   ASSERT_EQ(11, snprintf(buf, 0, "Hello %s", "world"));
485   ASSERT_EQ('x', buf[0]);
486 }
487 
488 // Unlike snprintf(), you *can't* use swprintf() to measure.
TEST(STDIO_TEST,swprintf_measure)489 TEST(STDIO_TEST, swprintf_measure) {
490   wchar_t buf[1] = {L'x'};
491   ASSERT_EQ(-1, swprintf(buf, 0, L"Hello %S", L"world"));
492   ASSERT_EQ(L'x', buf[0]);
493 }
494 
TEST(STDIO_TEST,snprintf_smoke)495 TEST(STDIO_TEST, snprintf_smoke) {
496   EXPECT_SNPRINTF("a", "a");
497   EXPECT_SNPRINTF("%", "%%");
498   EXPECT_SNPRINTF("01234", "01234");
499   EXPECT_SNPRINTF("a01234b", "a%sb", "01234");
500 
501   EXPECT_SNPRINTF("a(null)b", "a%sb", static_cast<char*>(nullptr));
502   EXPECT_SNPRINTF("aabbcc", "aa%scc", "bb");
503   EXPECT_SNPRINTF("abc", "a%cc", 'b');
504   EXPECT_SNPRINTF("a1234b", "a%db", 1234);
505   EXPECT_SNPRINTF("a-8123b", "a%db", -8123);
506   EXPECT_SNPRINTF("a16b", "a%hdb", static_cast<short>(0x7fff0010));
507   EXPECT_SNPRINTF("a16b", "a%hhdb", static_cast<char>(0x7fffff10));
508   EXPECT_SNPRINTF("a68719476736b", "a%lldb", 0x1000000000LL);
509   EXPECT_SNPRINTF("a70000b", "a%ldb", 70000L);
510   EXPECT_SNPRINTF("a0xb0001234b", "a%pb", reinterpret_cast<void*>(0xb0001234));
511   EXPECT_SNPRINTF("a12abz", "a%xz", 0x12ab);
512   EXPECT_SNPRINTF("a12ABz", "a%Xz", 0x12ab);
513   EXPECT_SNPRINTF("a00123456z", "a%08xz", 0x123456);
514   EXPECT_SNPRINTF("a 1234z", "a%5dz", 1234);
515   EXPECT_SNPRINTF("a01234z", "a%05dz", 1234);
516   EXPECT_SNPRINTF("a    1234z", "a%8dz", 1234);
517   EXPECT_SNPRINTF("a1234    z", "a%-8dz", 1234);
518   EXPECT_SNPRINTF("Aabcdef     Z", "A%-11sZ", "abcdef");
519   EXPECT_SNPRINTF("Ahello:1234Z", "A%s:%dZ", "hello", 1234);
520   EXPECT_SNPRINTF("a005:5:05z", "a%03d:%d:%02dz", 5, 5, 5);
521 
522 #if defined(__BIONIC__)
523   EXPECT_SNPRINTF("a5,0x0z", "a%d,%pz", 5, static_cast<void*>(nullptr));
524 #else // __BIONIC__
525   EXPECT_SNPRINTF("a5,(nil)z", "a%d,%pz", 5, static_cast<void*>(nullptr));
526 #endif // __BIONIC__
527 
528   EXPECT_SNPRINTF("a68719476736,6,7,8z", "a%lld,%d,%d,%dz", 0x1000000000LL, 6, 7, 8);
529 
530   EXPECT_SNPRINTF("a_1.230000_b", "a_%f_b", 1.23f);
531   EXPECT_SNPRINTF("a_3.14_b", "a_%g_b", 3.14);
532   EXPECT_SNPRINTF("print_me_twice print_me_twice", "%1$s %1$s", "print_me_twice");
533 }
534 
TEST(STDIO_TEST,swprintf_smoke)535 TEST(STDIO_TEST, swprintf_smoke) {
536   EXPECT_SWPRINTF(L"a", L"a");
537   EXPECT_SWPRINTF(L"%", L"%%");
538   EXPECT_SWPRINTF(L"01234", L"01234");
539   EXPECT_SWPRINTF(L"a01234b", L"a%sb", "01234");
540 
541   EXPECT_SWPRINTF(L"a(null)b", L"a%sb", static_cast<char*>(nullptr));
542   EXPECT_SWPRINTF(L"aabbcc", L"aa%scc", "bb");
543   EXPECT_SWPRINTF(L"abc", L"a%cc", 'b');
544   EXPECT_SWPRINTF(L"a1234b", L"a%db", 1234);
545   EXPECT_SWPRINTF(L"a-8123b", L"a%db", -8123);
546   EXPECT_SWPRINTF(L"a16b", L"a%hdb", static_cast<short>(0x7fff0010));
547   EXPECT_SWPRINTF(L"a16b", L"a%hhdb", static_cast<char>(0x7fffff10));
548   EXPECT_SWPRINTF(L"a68719476736b", L"a%lldb", 0x1000000000LL);
549   EXPECT_SWPRINTF(L"a70000b", L"a%ldb", 70000L);
550   EXPECT_SWPRINTF(L"a0xb0001234b", L"a%pb", reinterpret_cast<void*>(0xb0001234));
551   EXPECT_SWPRINTF(L"a12abz", L"a%xz", 0x12ab);
552   EXPECT_SWPRINTF(L"a12ABz", L"a%Xz", 0x12ab);
553   EXPECT_SWPRINTF(L"a00123456z", L"a%08xz", 0x123456);
554   EXPECT_SWPRINTF(L"a 1234z", L"a%5dz", 1234);
555   EXPECT_SWPRINTF(L"a01234z", L"a%05dz", 1234);
556   EXPECT_SWPRINTF(L"a    1234z", L"a%8dz", 1234);
557   EXPECT_SWPRINTF(L"a1234    z", L"a%-8dz", 1234);
558   EXPECT_SWPRINTF(L"Aabcdef     Z", L"A%-11sZ", "abcdef");
559   EXPECT_SWPRINTF(L"Ahello:1234Z", L"A%s:%dZ", "hello", 1234);
560   EXPECT_SWPRINTF(L"a005:5:05z", L"a%03d:%d:%02dz", 5, 5, 5);
561 
562 #if defined(__BIONIC__)
563   EXPECT_SWPRINTF(L"a5,0x0z", L"a%d,%pz", 5, static_cast<void*>(nullptr));
564 #else   // __BIONIC__
565   EXPECT_SWPRINTF(L"a5,(nil)z", L"a%d,%pz", 5, static_cast<void*>(nullptr));
566 #endif  // __BIONIC__
567 
568   EXPECT_SWPRINTF(L"a68719476736,6,7,8z", L"a%lld,%d,%d,%dz", 0x1000000000LL, 6, 7, 8);
569 
570   EXPECT_SWPRINTF(L"a_1.230000_b", L"a_%f_b", 1.23f);
571   EXPECT_SWPRINTF(L"a_3.14_b", L"a_%g_b", 3.14);
572   EXPECT_SWPRINTF(L"print_me_twice print_me_twice", L"%1$s %1$s", "print_me_twice");
573 }
574 
575 template <typename T>
CheckInfNan(int snprintf_fn (T *,size_t,const T *,...),int sscanf_fn (const T *,const T *,...),const T * fmt_string,const T * fmt,const T * fmt_plus,const T * minus_inf,const T * inf_,const T * plus_inf,const T * minus_nan,const T * nan_,const T * plus_nan)576 static void CheckInfNan(int snprintf_fn(T*, size_t, const T*, ...),
577                         int sscanf_fn(const T*, const T*, ...),
578                         const T* fmt_string, const T* fmt, const T* fmt_plus,
579                         const T* minus_inf, const T* inf_, const T* plus_inf,
580                         const T* minus_nan, const T* nan_, const T* plus_nan) {
581   T buf[BUFSIZ];
582   float f;
583 
584   // NaN.
585 
586   snprintf_fn(buf, sizeof(buf), fmt, nan(""));
587   EXPECT_STREQ(nan_, buf) << fmt;
588   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
589   EXPECT_TRUE(isnan(f));
590 
591   snprintf_fn(buf, sizeof(buf), fmt, -nan(""));
592   EXPECT_STREQ(minus_nan, buf) << fmt;
593   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
594   EXPECT_TRUE(isnan(f));
595 
596   snprintf_fn(buf, sizeof(buf), fmt_plus, nan(""));
597   EXPECT_STREQ(plus_nan, buf) << fmt_plus;
598   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
599   EXPECT_TRUE(isnan(f));
600 
601   snprintf_fn(buf, sizeof(buf), fmt_plus, -nan(""));
602   EXPECT_STREQ(minus_nan, buf) << fmt_plus;
603   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
604   EXPECT_TRUE(isnan(f));
605 
606   // Inf.
607 
608   snprintf_fn(buf, sizeof(buf), fmt, HUGE_VALF);
609   EXPECT_STREQ(inf_, buf) << fmt;
610   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
611   EXPECT_EQ(HUGE_VALF, f);
612 
613   snprintf_fn(buf, sizeof(buf), fmt, -HUGE_VALF);
614   EXPECT_STREQ(minus_inf, buf) << fmt;
615   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
616   EXPECT_EQ(-HUGE_VALF, f);
617 
618   snprintf_fn(buf, sizeof(buf), fmt_plus, HUGE_VALF);
619   EXPECT_STREQ(plus_inf, buf) << fmt_plus;
620   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
621   EXPECT_EQ(HUGE_VALF, f);
622 
623   snprintf_fn(buf, sizeof(buf), fmt_plus, -HUGE_VALF);
624   EXPECT_STREQ(minus_inf, buf) << fmt_plus;
625   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
626   EXPECT_EQ(-HUGE_VALF, f);
627 
628   // Check case-insensitivity.
629   snprintf_fn(buf, sizeof(buf), fmt_string, "[InFiNiTy]");
630   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f)) << buf;
631   EXPECT_EQ(HUGE_VALF, f);
632   snprintf_fn(buf, sizeof(buf), fmt_string, "[NaN]");
633   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f)) << buf;
634   EXPECT_TRUE(isnan(f));
635 }
636 
TEST(STDIO_TEST,snprintf_sscanf_inf_nan)637 TEST(STDIO_TEST, snprintf_sscanf_inf_nan) {
638   CheckInfNan(snprintf, sscanf, "%s",
639               "[%a]", "[%+a]",
640               "[-inf]", "[inf]", "[+inf]",
641               "[-nan]", "[nan]", "[+nan]");
642   CheckInfNan(snprintf, sscanf, "%s",
643               "[%A]", "[%+A]",
644               "[-INF]", "[INF]", "[+INF]",
645               "[-NAN]", "[NAN]", "[+NAN]");
646   CheckInfNan(snprintf, sscanf, "%s",
647               "[%e]", "[%+e]",
648               "[-inf]", "[inf]", "[+inf]",
649               "[-nan]", "[nan]", "[+nan]");
650   CheckInfNan(snprintf, sscanf, "%s",
651               "[%E]", "[%+E]",
652               "[-INF]", "[INF]", "[+INF]",
653               "[-NAN]", "[NAN]", "[+NAN]");
654   CheckInfNan(snprintf, sscanf, "%s",
655               "[%f]", "[%+f]",
656               "[-inf]", "[inf]", "[+inf]",
657               "[-nan]", "[nan]", "[+nan]");
658   CheckInfNan(snprintf, sscanf, "%s",
659               "[%F]", "[%+F]",
660               "[-INF]", "[INF]", "[+INF]",
661               "[-NAN]", "[NAN]", "[+NAN]");
662   CheckInfNan(snprintf, sscanf, "%s",
663               "[%g]", "[%+g]",
664               "[-inf]", "[inf]", "[+inf]",
665               "[-nan]", "[nan]", "[+nan]");
666   CheckInfNan(snprintf, sscanf, "%s",
667               "[%G]", "[%+G]",
668               "[-INF]", "[INF]", "[+INF]",
669               "[-NAN]", "[NAN]", "[+NAN]");
670 }
671 
TEST(STDIO_TEST,swprintf_swscanf_inf_nan)672 TEST(STDIO_TEST, swprintf_swscanf_inf_nan) {
673   CheckInfNan(swprintf, swscanf, L"%s",
674               L"[%a]", L"[%+a]",
675               L"[-inf]", L"[inf]", L"[+inf]",
676               L"[-nan]", L"[nan]", L"[+nan]");
677   CheckInfNan(swprintf, swscanf, L"%s",
678               L"[%A]", L"[%+A]",
679               L"[-INF]", L"[INF]", L"[+INF]",
680               L"[-NAN]", L"[NAN]", L"[+NAN]");
681   CheckInfNan(swprintf, swscanf, L"%s",
682               L"[%e]", L"[%+e]",
683               L"[-inf]", L"[inf]", L"[+inf]",
684               L"[-nan]", L"[nan]", L"[+nan]");
685   CheckInfNan(swprintf, swscanf, L"%s",
686               L"[%E]", L"[%+E]",
687               L"[-INF]", L"[INF]", L"[+INF]",
688               L"[-NAN]", L"[NAN]", L"[+NAN]");
689   CheckInfNan(swprintf, swscanf, L"%s",
690               L"[%f]", L"[%+f]",
691               L"[-inf]", L"[inf]", L"[+inf]",
692               L"[-nan]", L"[nan]", L"[+nan]");
693   CheckInfNan(swprintf, swscanf, L"%s",
694               L"[%F]", L"[%+F]",
695               L"[-INF]", L"[INF]", L"[+INF]",
696               L"[-NAN]", L"[NAN]", L"[+NAN]");
697   CheckInfNan(swprintf, swscanf, L"%s",
698               L"[%g]", L"[%+g]",
699               L"[-inf]", L"[inf]", L"[+inf]",
700               L"[-nan]", L"[nan]", L"[+nan]");
701   CheckInfNan(swprintf, swscanf, L"%s",
702               L"[%G]", L"[%+G]",
703               L"[-INF]", L"[INF]", L"[+INF]",
704               L"[-NAN]", L"[NAN]", L"[+NAN]");
705 }
706 
TEST(STDIO_TEST,snprintf_jd_INTMAX_MAX)707 TEST(STDIO_TEST, snprintf_jd_INTMAX_MAX) {
708   EXPECT_SNPRINTF("9223372036854775807", "%jd", INTMAX_MAX);
709 }
710 
TEST(STDIO_TEST,swprintf_jd_INTMAX_MAX)711 TEST(STDIO_TEST, swprintf_jd_INTMAX_MAX) {
712   EXPECT_SWPRINTF(L"9223372036854775807", L"%jd", INTMAX_MAX);
713 }
714 
TEST(STDIO_TEST,snprintf_jd_INTMAX_MIN)715 TEST(STDIO_TEST, snprintf_jd_INTMAX_MIN) {
716   EXPECT_SNPRINTF("-9223372036854775808", "%jd", INTMAX_MIN);
717 }
718 
TEST(STDIO_TEST,swprintf_jd_INTMAX_MIN)719 TEST(STDIO_TEST, swprintf_jd_INTMAX_MIN) {
720   EXPECT_SWPRINTF(L"-9223372036854775808", L"%jd", INTMAX_MIN);
721 }
722 
TEST(STDIO_TEST,snprintf_ju_UINTMAX_MAX)723 TEST(STDIO_TEST, snprintf_ju_UINTMAX_MAX) {
724   EXPECT_SNPRINTF("18446744073709551615", "%ju", UINTMAX_MAX);
725 }
726 
TEST(STDIO_TEST,swprintf_ju_UINTMAX_MAX)727 TEST(STDIO_TEST, swprintf_ju_UINTMAX_MAX) {
728   EXPECT_SWPRINTF(L"18446744073709551615", L"%ju", UINTMAX_MAX);
729 }
730 
TEST(STDIO_TEST,snprintf_1$ju_UINTMAX_MAX)731 TEST(STDIO_TEST, snprintf_1$ju_UINTMAX_MAX) {
732   EXPECT_SNPRINTF("18446744073709551615", "%1$ju", UINTMAX_MAX);
733 }
734 
TEST(STDIO_TEST,swprintf_1$ju_UINTMAX_MAX)735 TEST(STDIO_TEST, swprintf_1$ju_UINTMAX_MAX) {
736   EXPECT_SWPRINTF(L"18446744073709551615", L"%1$ju", UINTMAX_MAX);
737 }
738 
TEST(STDIO_TEST,snprintf_d_INT_MAX)739 TEST(STDIO_TEST, snprintf_d_INT_MAX) {
740   EXPECT_SNPRINTF("2147483647", "%d", INT_MAX);
741 }
742 
TEST(STDIO_TEST,swprintf_d_INT_MAX)743 TEST(STDIO_TEST, swprintf_d_INT_MAX) {
744   EXPECT_SWPRINTF(L"2147483647", L"%d", INT_MAX);
745 }
746 
TEST(STDIO_TEST,snprintf_d_INT_MIN)747 TEST(STDIO_TEST, snprintf_d_INT_MIN) {
748   EXPECT_SNPRINTF("-2147483648", "%d", INT_MIN);
749 }
750 
TEST(STDIO_TEST,swprintf_d_INT_MIN)751 TEST(STDIO_TEST, swprintf_d_INT_MIN) {
752   EXPECT_SWPRINTF(L"-2147483648", L"%d", INT_MIN);
753 }
754 
TEST(STDIO_TEST,snprintf_ld_LONG_MAX)755 TEST(STDIO_TEST, snprintf_ld_LONG_MAX) {
756 #if defined(__LP64__)
757   EXPECT_SNPRINTF("9223372036854775807", "%ld", LONG_MAX);
758 #else
759   EXPECT_SNPRINTF("2147483647", "%ld", LONG_MAX);
760 #endif
761 }
762 
TEST(STDIO_TEST,swprintf_ld_LONG_MAX)763 TEST(STDIO_TEST, swprintf_ld_LONG_MAX) {
764 #if defined(__LP64__)
765   EXPECT_SWPRINTF(L"9223372036854775807", L"%ld", LONG_MAX);
766 #else
767   EXPECT_SWPRINTF(L"2147483647", L"%ld", LONG_MAX);
768 #endif
769 }
770 
TEST(STDIO_TEST,snprintf_ld_LONG_MIN)771 TEST(STDIO_TEST, snprintf_ld_LONG_MIN) {
772 #if defined(__LP64__)
773   EXPECT_SNPRINTF("-9223372036854775808", "%ld", LONG_MIN);
774 #else
775   EXPECT_SNPRINTF("-2147483648", "%ld", LONG_MIN);
776 #endif
777 }
778 
TEST(STDIO_TEST,swprintf_ld_LONG_MIN)779 TEST(STDIO_TEST, swprintf_ld_LONG_MIN) {
780 #if defined(__LP64__)
781   EXPECT_SWPRINTF(L"-9223372036854775808", L"%ld", LONG_MIN);
782 #else
783   EXPECT_SWPRINTF(L"-2147483648", L"%ld", LONG_MIN);
784 #endif
785 }
786 
TEST(STDIO_TEST,snprintf_lld_LLONG_MAX)787 TEST(STDIO_TEST, snprintf_lld_LLONG_MAX) {
788   EXPECT_SNPRINTF("9223372036854775807", "%lld", LLONG_MAX);
789 }
790 
TEST(STDIO_TEST,swprintf_lld_LLONG_MAX)791 TEST(STDIO_TEST, swprintf_lld_LLONG_MAX) {
792   EXPECT_SWPRINTF(L"9223372036854775807", L"%lld", LLONG_MAX);
793 }
794 
TEST(STDIO_TEST,snprintf_lld_LLONG_MIN)795 TEST(STDIO_TEST, snprintf_lld_LLONG_MIN) {
796   EXPECT_SNPRINTF("-9223372036854775808", "%lld", LLONG_MIN);
797 }
798 
TEST(STDIO_TEST,swprintf_lld_LLONG_MIN)799 TEST(STDIO_TEST, swprintf_lld_LLONG_MIN) {
800   EXPECT_SWPRINTF(L"-9223372036854775808", L"%lld", LLONG_MIN);
801 }
802 
TEST(STDIO_TEST,snprintf_o_UINT_MAX)803 TEST(STDIO_TEST, snprintf_o_UINT_MAX) {
804   EXPECT_SNPRINTF("37777777777", "%o", UINT_MAX);
805 }
806 
TEST(STDIO_TEST,swprintf_o_UINT_MAX)807 TEST(STDIO_TEST, swprintf_o_UINT_MAX) {
808   EXPECT_SWPRINTF(L"37777777777", L"%o", UINT_MAX);
809 }
810 
TEST(STDIO_TEST,snprintf_u_UINT_MAX)811 TEST(STDIO_TEST, snprintf_u_UINT_MAX) {
812   EXPECT_SNPRINTF("4294967295", "%u", UINT_MAX);
813 }
814 
TEST(STDIO_TEST,swprintf_u_UINT_MAX)815 TEST(STDIO_TEST, swprintf_u_UINT_MAX) {
816   EXPECT_SWPRINTF(L"4294967295", L"%u", UINT_MAX);
817 }
818 
TEST(STDIO_TEST,snprintf_x_UINT_MAX)819 TEST(STDIO_TEST, snprintf_x_UINT_MAX) {
820   EXPECT_SNPRINTF("ffffffff", "%x", UINT_MAX);
821 }
822 
TEST(STDIO_TEST,swprintf_x_UINT_MAX)823 TEST(STDIO_TEST, swprintf_x_UINT_MAX) {
824   EXPECT_SWPRINTF(L"ffffffff", L"%x", UINT_MAX);
825 }
826 
TEST(STDIO_TEST,snprintf_X_UINT_MAX)827 TEST(STDIO_TEST, snprintf_X_UINT_MAX) {
828   EXPECT_SNPRINTF("FFFFFFFF", "%X", UINT_MAX);
829 }
830 
TEST(STDIO_TEST,swprintf_X_UINT_MAX)831 TEST(STDIO_TEST, swprintf_X_UINT_MAX) {
832   EXPECT_SWPRINTF(L"FFFFFFFF", L"%X", UINT_MAX);
833 }
834 
TEST(STDIO_TEST,snprintf_e)835 TEST(STDIO_TEST, snprintf_e) {
836   EXPECT_SNPRINTF("1.500000e+00", "%e", 1.5);
837   EXPECT_SNPRINTF("1.500000e+00", "%Le", 1.5L);
838 }
839 
TEST(STDIO_TEST,swprintf_e)840 TEST(STDIO_TEST, swprintf_e) {
841   EXPECT_SWPRINTF(L"1.500000e+00", L"%e", 1.5);
842   EXPECT_SWPRINTF(L"1.500000e+00", L"%Le", 1.5L);
843 }
844 
TEST(STDIO_TEST,snprintf_negative_zero_5084292)845 TEST(STDIO_TEST, snprintf_negative_zero_5084292) {
846   EXPECT_SNPRINTF("-0.000000e+00", "%e", -0.0);
847   EXPECT_SNPRINTF("-0.000000E+00", "%E", -0.0);
848   EXPECT_SNPRINTF("-0.000000", "%f", -0.0);
849   EXPECT_SNPRINTF("-0.000000", "%F", -0.0);
850   EXPECT_SNPRINTF("-0", "%g", -0.0);
851   EXPECT_SNPRINTF("-0", "%G", -0.0);
852   EXPECT_SNPRINTF("-0x0p+0", "%a", -0.0);
853   EXPECT_SNPRINTF("-0X0P+0", "%A", -0.0);
854 }
855 
TEST(STDIO_TEST,swprintf_negative_zero_5084292)856 TEST(STDIO_TEST, swprintf_negative_zero_5084292) {
857   EXPECT_SWPRINTF(L"-0.000000e+00", L"%e", -0.0);
858   EXPECT_SWPRINTF(L"-0.000000E+00", L"%E", -0.0);
859   EXPECT_SWPRINTF(L"-0.000000", L"%f", -0.0);
860   EXPECT_SWPRINTF(L"-0.000000", L"%F", -0.0);
861   EXPECT_SWPRINTF(L"-0", L"%g", -0.0);
862   EXPECT_SWPRINTF(L"-0", L"%G", -0.0);
863   EXPECT_SWPRINTF(L"-0x0p+0", L"%a", -0.0);
864   EXPECT_SWPRINTF(L"-0X0P+0", L"%A", -0.0);
865 }
866 
TEST(STDIO_TEST,snprintf_utf8_15439554)867 TEST(STDIO_TEST, snprintf_utf8_15439554) {
868   locale_t cloc = newlocale(LC_ALL, "C.UTF-8", nullptr);
869   locale_t old_locale = uselocale(cloc);
870 
871   // http://b/15439554
872   char buf[BUFSIZ];
873 
874   // 1-byte character.
875   snprintf(buf, sizeof(buf), "%dx%d", 1, 2);
876   EXPECT_STREQ("1x2", buf);
877   // 2-byte character.
878   snprintf(buf, sizeof(buf), "%d\xc2\xa2%d", 1, 2);
879   EXPECT_STREQ("1¢2", buf);
880   // 3-byte character.
881   snprintf(buf, sizeof(buf), "%d\xe2\x82\xac%d", 1, 2);
882   EXPECT_STREQ("1€2", buf);
883   // 4-byte character.
884   snprintf(buf, sizeof(buf), "%d\xf0\xa4\xad\xa2%d", 1, 2);
885   EXPECT_STREQ("1��2", buf);
886 
887   uselocale(old_locale);
888   freelocale(cloc);
889 }
890 
snprintf_small_stack_fn(void *)891 static void* snprintf_small_stack_fn(void*) {
892   // Make life (realistically) hard for ourselves by allocating our own buffer for the result.
893   char buf[PATH_MAX];
894   snprintf(buf, sizeof(buf), "/proc/%d", getpid());
895   return nullptr;
896 }
897 
TEST(STDIO_TEST,snprintf_small_stack)898 TEST(STDIO_TEST, snprintf_small_stack) {
899   // Is it safe to call snprintf on a thread with a small stack?
900   // (The snprintf implementation puts some pretty large buffers on the stack.)
901   pthread_attr_t a;
902   ASSERT_EQ(0, pthread_attr_init(&a));
903   ASSERT_EQ(0, pthread_attr_setstacksize(&a, PTHREAD_STACK_MIN));
904 
905   pthread_t t;
906   ASSERT_EQ(0, pthread_create(&t, &a, snprintf_small_stack_fn, nullptr));
907   ASSERT_EQ(0, pthread_join(t, nullptr));
908 }
909 
TEST(STDIO_TEST,snprintf_asterisk_overflow)910 TEST(STDIO_TEST, snprintf_asterisk_overflow) {
911   char buf[128];
912   ASSERT_EQ(5, snprintf(buf, sizeof(buf), "%.*s%c", 4, "hello world", '!'));
913   ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.*s%c", INT_MAX/2, "hello world", '!'));
914   ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.*s%c", INT_MAX-1, "hello world", '!'));
915   ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.*s%c", INT_MAX, "hello world", '!'));
916   ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.*s%c", -1, "hello world", '!'));
917 
918   // INT_MAX-1, INT_MAX, INT_MAX+1.
919   ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.2147483646s%c", "hello world", '!'));
920   ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.2147483647s%c", "hello world", '!'));
921   ASSERT_EQ(-1, snprintf(buf, sizeof(buf), "%.2147483648s%c", "hello world", '!'));
922   ASSERT_ERRNO(ENOMEM);
923 }
924 
TEST(STDIO_TEST,swprintf_asterisk_overflow)925 TEST(STDIO_TEST, swprintf_asterisk_overflow) {
926   wchar_t buf[128];
927   ASSERT_EQ(5, swprintf(buf, sizeof(buf), L"%.*s%c", 4, "hello world", '!'));
928   ASSERT_EQ(12, swprintf(buf, sizeof(buf), L"%.*s%c", INT_MAX / 2, "hello world", '!'));
929   ASSERT_EQ(12, swprintf(buf, sizeof(buf), L"%.*s%c", INT_MAX - 1, "hello world", '!'));
930   ASSERT_EQ(12, swprintf(buf, sizeof(buf), L"%.*s%c", INT_MAX, "hello world", '!'));
931   ASSERT_EQ(12, swprintf(buf, sizeof(buf), L"%.*s%c", -1, "hello world", '!'));
932 
933   // INT_MAX-1, INT_MAX, INT_MAX+1.
934   ASSERT_EQ(12, swprintf(buf, sizeof(buf), L"%.2147483646s%c", "hello world", '!'));
935   ASSERT_EQ(12, swprintf(buf, sizeof(buf), L"%.2147483647s%c", "hello world", '!'));
936   ASSERT_EQ(-1, swprintf(buf, sizeof(buf), L"%.2147483648s%c", "hello world", '!'));
937   ASSERT_ERRNO(ENOMEM);
938 }
939 
940 // Inspired by https://github.com/landley/toybox/issues/163.
TEST(STDIO_TEST,printf_NULL)941 TEST(STDIO_TEST, printf_NULL) {
942   char* null = nullptr;
943   EXPECT_SNPRINTF("<(n>", "<%*.*s>", 2, 2, null);
944   EXPECT_SNPRINTF("<(null)>", "<%*.*s>", 2, 8, null);
945   EXPECT_SNPRINTF("<      (n>", "<%*.*s>", 8, 2, null);
946   EXPECT_SNPRINTF("<  (null)>", "<%*.*s>", 8, 8, null);
947 }
948 
TEST(STDIO_TEST,wprintf_NULL)949 TEST(STDIO_TEST, wprintf_NULL) {
950   char* null = nullptr;
951   EXPECT_SWPRINTF(L"<(n>", L"<%*.*s>", 2, 2, null);
952   EXPECT_SWPRINTF(L"<(null)>", L"<%*.*s>", 2, 8, null);
953   EXPECT_SWPRINTF(L"<      (n>", L"<%*.*s>", 8, 2, null);
954   EXPECT_SWPRINTF(L"<  (null)>", L"<%*.*s>", 8, 8, null);
955 }
956 
TEST(STDIO_TEST,fprintf)957 TEST(STDIO_TEST, fprintf) {
958   TemporaryFile tf;
959 
960   FILE* tfile = fdopen(tf.fd, "r+");
961   ASSERT_TRUE(tfile != nullptr);
962 
963   ASSERT_EQ(7, fprintf(tfile, "%d %s", 123, "abc"));
964   AssertFileIs(tfile, "123 abc");
965   fclose(tfile);
966 }
967 
TEST(STDIO_TEST,fprintf_failures_7229520)968 TEST(STDIO_TEST, fprintf_failures_7229520) {
969   // http://b/7229520
970   FILE* fp;
971   int fd_rdonly = open("/dev/null", O_RDONLY);
972   ASSERT_NE(-1, fd_rdonly);
973 
974   // Unbuffered case where the fprintf(3) itself fails.
975   ASSERT_NE(nullptr, fp = tmpfile());
976   setbuf(fp, nullptr);
977   ASSERT_EQ(4, fprintf(fp, "epic"));
978   ASSERT_NE(-1, dup2(fd_rdonly, fileno(fp)));
979   ASSERT_EQ(-1, fprintf(fp, "fail"));
980   ASSERT_EQ(0, fclose(fp));
981 
982   // Buffered case where we won't notice until the fclose(3).
983   // It's likely this is what was actually seen in http://b/7229520,
984   // and that expecting fprintf to fail is setting yourself up for
985   // disappointment. Remember to check fclose(3)'s return value, kids!
986   ASSERT_NE(nullptr, fp = tmpfile());
987   ASSERT_EQ(4, fprintf(fp, "epic"));
988   ASSERT_NE(-1, dup2(fd_rdonly, fileno(fp)));
989   ASSERT_EQ(4, fprintf(fp, "fail"));
990   ASSERT_EQ(-1, fclose(fp));
991 }
992 
TEST(STDIO_TEST,popen_r)993 TEST(STDIO_TEST, popen_r) {
994   FILE* fp = popen("cat /proc/version", "r");
995   ASSERT_TRUE(fp != nullptr);
996 
997   char buf[16];
998   char* s = fgets(buf, sizeof(buf), fp);
999   buf[13] = '\0';
1000   ASSERT_STREQ("Linux version", s);
1001 
1002   ASSERT_EQ(0, pclose(fp));
1003 }
1004 
TEST(STDIO_TEST,popen_socketpair)1005 TEST(STDIO_TEST, popen_socketpair) {
1006   FILE* fp = popen("cat", "r+");
1007   ASSERT_TRUE(fp != nullptr);
1008 
1009   fputs("hello\nworld\n", fp);
1010   fflush(fp);
1011 
1012   char buf[16];
1013   ASSERT_NE(nullptr, fgets(buf, sizeof(buf), fp));
1014   EXPECT_STREQ("hello\n", buf);
1015   ASSERT_NE(nullptr, fgets(buf, sizeof(buf), fp));
1016   EXPECT_STREQ("world\n", buf);
1017 
1018   ASSERT_EQ(0, pclose(fp));
1019 }
1020 
TEST(STDIO_TEST,popen_socketpair_shutdown)1021 TEST(STDIO_TEST, popen_socketpair_shutdown) {
1022   FILE* fp = popen("uniq -c", "r+");
1023   ASSERT_TRUE(fp != nullptr);
1024 
1025   fputs("a\na\na\na\nb\n", fp);
1026   fflush(fp);
1027   ASSERT_EQ(0, shutdown(fileno(fp), SHUT_WR));
1028 
1029   char buf[16];
1030   ASSERT_NE(nullptr, fgets(buf, sizeof(buf), fp));
1031   EXPECT_STREQ("      4 a\n", buf);
1032   ASSERT_NE(nullptr, fgets(buf, sizeof(buf), fp));
1033   EXPECT_STREQ("      1 b\n", buf);
1034 
1035   ASSERT_EQ(0, pclose(fp));
1036 }
1037 
TEST(STDIO_TEST,popen_return_value_0)1038 TEST(STDIO_TEST, popen_return_value_0) {
1039   FILE* fp = popen("true", "r");
1040   ASSERT_TRUE(fp != nullptr);
1041   int status = pclose(fp);
1042   EXPECT_TRUE(WIFEXITED(status));
1043   EXPECT_EQ(0, WEXITSTATUS(status));
1044 }
1045 
TEST(STDIO_TEST,popen_return_value_1)1046 TEST(STDIO_TEST, popen_return_value_1) {
1047   FILE* fp = popen("false", "r");
1048   ASSERT_TRUE(fp != nullptr);
1049   int status = pclose(fp);
1050   EXPECT_TRUE(WIFEXITED(status));
1051   EXPECT_EQ(1, WEXITSTATUS(status));
1052 }
1053 
TEST(STDIO_TEST,popen_return_value_signal)1054 TEST(STDIO_TEST, popen_return_value_signal) {
1055   // Use a realtime signal to avoid creating a tombstone when running.
1056   std::string cmd = android::base::StringPrintf("kill -%d $$", SIGRTMIN);
1057   FILE* fp = popen(cmd.c_str(), "r");
1058   ASSERT_TRUE(fp != nullptr);
1059   int status = pclose(fp);
1060   EXPECT_TRUE(WIFSIGNALED(status));
1061   EXPECT_EQ(SIGRTMIN, WTERMSIG(status));
1062 }
1063 
TEST(STDIO_TEST,getc)1064 TEST(STDIO_TEST, getc) {
1065   FILE* fp = fopen("/proc/version", "r");
1066   ASSERT_TRUE(fp != nullptr);
1067   ASSERT_EQ('L', getc(fp));
1068   ASSERT_EQ('i', getc(fp));
1069   ASSERT_EQ('n', getc(fp));
1070   ASSERT_EQ('u', getc(fp));
1071   ASSERT_EQ('x', getc(fp));
1072   fclose(fp);
1073 }
1074 
TEST(STDIO_TEST,putc)1075 TEST(STDIO_TEST, putc) {
1076   FILE* fp = fopen("/proc/version", "r");
1077   ASSERT_TRUE(fp != nullptr);
1078   ASSERT_EQ(EOF, putc('x', fp));
1079   fclose(fp);
1080 }
1081 
TEST(STDIO_TEST,sscanf_swscanf)1082 TEST(STDIO_TEST, sscanf_swscanf) {
1083   struct stuff {
1084     char s1[123];
1085     int i1, i2;
1086     char cs1[3];
1087     char s2[3];
1088     char c1;
1089     double d1;
1090     float f1;
1091     char s3[123];
1092 
1093     void Check() {
1094       EXPECT_STREQ("hello", s1);
1095       EXPECT_EQ(123, i1);
1096       EXPECT_EQ(456, i2);
1097       EXPECT_EQ('a', cs1[0]);
1098       EXPECT_EQ('b', cs1[1]);
1099       EXPECT_EQ('x', cs1[2]); // No terminating NUL.
1100       EXPECT_STREQ("AB", s2); // Terminating NUL.
1101       EXPECT_EQ('!', c1);
1102       EXPECT_DOUBLE_EQ(1.23, d1);
1103       EXPECT_FLOAT_EQ(9.0f, f1);
1104       EXPECT_STREQ("world", s3);
1105     }
1106   } s;
1107 
1108   memset(&s, 'x', sizeof(s));
1109   ASSERT_EQ(9, sscanf("  hello 123 456abAB! 1.23 0x1.2p3 world",
1110                       "%s %i%i%2c%[A-Z]%c %lf %f %s",
1111                       s.s1, &s.i1, &s.i2, s.cs1, s.s2, &s.c1, &s.d1, &s.f1, s.s3));
1112   s.Check();
1113 
1114   memset(&s, 'x', sizeof(s));
1115   ASSERT_EQ(9, swscanf(L"  hello 123 456abAB! 1.23 0x1.2p3 world",
1116                        L"%s %i%i%2c%[A-Z]%c %lf %f %s",
1117                        s.s1, &s.i1, &s.i2, s.cs1, s.s2, &s.c1, &s.d1, &s.f1, s.s3));
1118   s.Check();
1119 }
1120 
1121 template <typename T>
CheckScanf(int sscanf_fn (const T *,const T *,...),const T * input,const T * fmt,int expected_count,const char * expected_string)1122 static void CheckScanf(int sscanf_fn(const T*, const T*, ...),
1123                        const T* input, const T* fmt,
1124                        int expected_count, const char* expected_string) {
1125   char buf[256] = {};
1126   ASSERT_EQ(expected_count, sscanf_fn(input, fmt, &buf)) << fmt;
1127   ASSERT_STREQ(expected_string, buf) << fmt;
1128 }
1129 
TEST(STDIO_TEST,sscanf_ccl)1130 TEST(STDIO_TEST, sscanf_ccl) {
1131   // `abc` is just those characters.
1132   CheckScanf(sscanf, "abcd", "%[abc]", 1, "abc");
1133   // `a-c` is the range 'a' .. 'c'.
1134   CheckScanf(sscanf, "abcd", "%[a-c]", 1, "abc");
1135   CheckScanf(sscanf, "-d", "%[a-c]", 0, "");
1136   CheckScanf(sscanf, "ac-bAd", "%[a--c]", 1, "ac-bA");
1137   // `a-c-e` is equivalent to `a-e`.
1138   CheckScanf(sscanf, "abcdefg", "%[a-c-e]", 1, "abcde");
1139   // `e-a` is equivalent to `ae-` (because 'e' > 'a').
1140   CheckScanf(sscanf, "-a-e-b", "%[e-a]", 1, "-a-e-");
1141   // An initial '^' negates the set.
1142   CheckScanf(sscanf, "abcde", "%[^d]", 1, "abc");
1143   CheckScanf(sscanf, "abcdefgh", "%[^c-d]", 1, "ab");
1144   CheckScanf(sscanf, "hgfedcba", "%[^c-d]", 1, "hgfe");
1145   // The first character may be ']' or '-' without being special.
1146   CheckScanf(sscanf, "[[]]x", "%[][]", 1, "[[]]");
1147   CheckScanf(sscanf, "-a-x", "%[-a]", 1, "-a-");
1148   // The last character may be '-' without being special.
1149   CheckScanf(sscanf, "-a-x", "%[a-]", 1, "-a-");
1150   // X--Y is [X--] + Y, not [X--] + [--Y] (a bug in my initial implementation).
1151   CheckScanf(sscanf, "+,-/.", "%[+--/]", 1, "+,-/");
1152 }
1153 
TEST(STDIO_TEST,swscanf_ccl)1154 TEST(STDIO_TEST, swscanf_ccl) {
1155   // `abc` is just those characters.
1156   CheckScanf(swscanf, L"abcd", L"%[abc]", 1, "abc");
1157   // `a-c` is the range 'a' .. 'c'.
1158   CheckScanf(swscanf, L"abcd", L"%[a-c]", 1, "abc");
1159   CheckScanf(swscanf, L"-d", L"%[a-c]", 0, "");
1160   CheckScanf(swscanf, L"ac-bAd", L"%[a--c]", 1, "ac-bA");
1161   // `a-c-e` is equivalent to `a-e`.
1162   CheckScanf(swscanf, L"abcdefg", L"%[a-c-e]", 1, "abcde");
1163   // `e-a` is equivalent to `ae-` (because 'e' > 'a').
1164   CheckScanf(swscanf, L"-a-e-b", L"%[e-a]", 1, "-a-e-");
1165   // An initial '^' negates the set.
1166   CheckScanf(swscanf, L"abcde", L"%[^d]", 1, "abc");
1167   CheckScanf(swscanf, L"abcdefgh", L"%[^c-d]", 1, "ab");
1168   CheckScanf(swscanf, L"hgfedcba", L"%[^c-d]", 1, "hgfe");
1169   // The first character may be ']' or '-' without being special.
1170   CheckScanf(swscanf, L"[[]]x", L"%[][]", 1, "[[]]");
1171   CheckScanf(swscanf, L"-a-x", L"%[-a]", 1, "-a-");
1172   // The last character may be '-' without being special.
1173   CheckScanf(swscanf, L"-a-x", L"%[a-]", 1, "-a-");
1174   // X--Y is [X--] + Y, not [X--] + [--Y] (a bug in my initial implementation).
1175   CheckScanf(swscanf, L"+,-/.", L"%[+--/]", 1, "+,-/");
1176 }
1177 
1178 template <typename T1, typename T2>
CheckScanfM(int sscanf_fn (const T1 *,const T1 *,...),const T1 * input,const T1 * fmt,int expected_count,const T2 * expected_string)1179 static void CheckScanfM(int sscanf_fn(const T1*, const T1*, ...),
1180                         const T1* input, const T1* fmt,
1181                         int expected_count, const T2* expected_string) {
1182   T2* result = nullptr;
1183   ASSERT_EQ(expected_count, sscanf_fn(input, fmt, &result)) << fmt;
1184   if (expected_string == nullptr) {
1185     ASSERT_EQ(nullptr, result);
1186   } else {
1187     ASSERT_STREQ(expected_string, result) << fmt;
1188   }
1189   free(result);
1190 }
1191 
TEST(STDIO_TEST,sscanf_mc)1192 TEST(STDIO_TEST, sscanf_mc) {
1193   char* p1 = nullptr;
1194   char* p2 = nullptr;
1195   ASSERT_EQ(2, sscanf("hello", "%mc%mc", &p1, &p2));
1196   ASSERT_EQ('h', *p1);
1197   ASSERT_EQ('e', *p2);
1198   free(p1);
1199   free(p2);
1200 
1201   p1 = nullptr;
1202   ASSERT_EQ(1, sscanf("hello", "%4mc", &p1));
1203   ASSERT_EQ('h', p1[0]);
1204   ASSERT_EQ('e', p1[1]);
1205   ASSERT_EQ('l', p1[2]);
1206   ASSERT_EQ('l', p1[3]);
1207   free(p1);
1208 
1209   p1 = nullptr;
1210   ASSERT_EQ(1, sscanf("hello world", "%30mc", &p1));
1211   ASSERT_EQ('h', p1[0]);
1212   ASSERT_EQ('e', p1[1]);
1213   ASSERT_EQ('l', p1[2]);
1214   ASSERT_EQ('l', p1[3]);
1215   ASSERT_EQ('o', p1[4]);
1216   free(p1);
1217 }
1218 
TEST(STDIO_TEST,sscanf_mlc)1219 TEST(STDIO_TEST, sscanf_mlc) {
1220   // This is so useless that clang doesn't even believe it exists...
1221 #pragma clang diagnostic push
1222 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
1223 #pragma clang diagnostic ignored "-Wformat-extra-args"
1224 
1225   wchar_t* p1 = nullptr;
1226   wchar_t* p2 = nullptr;
1227   ASSERT_EQ(2, sscanf("hello", "%mlc%mlc", &p1, &p2));
1228   ASSERT_EQ(L'h', *p1);
1229   ASSERT_EQ(L'e', *p2);
1230   free(p1);
1231   free(p2);
1232 
1233   p1 = nullptr;
1234   ASSERT_EQ(1, sscanf("hello", "%4mlc", &p1));
1235   ASSERT_EQ(L'h', p1[0]);
1236   ASSERT_EQ(L'e', p1[1]);
1237   ASSERT_EQ(L'l', p1[2]);
1238   ASSERT_EQ(L'l', p1[3]);
1239   free(p1);
1240 
1241   p1 = nullptr;
1242   ASSERT_EQ(1, sscanf("hello world", "%30mlc", &p1));
1243   ASSERT_EQ(L'h', p1[0]);
1244   ASSERT_EQ(L'e', p1[1]);
1245   ASSERT_EQ(L'l', p1[2]);
1246   ASSERT_EQ(L'l', p1[3]);
1247   ASSERT_EQ(L'o', p1[4]);
1248   free(p1);
1249 #pragma clang diagnostic pop
1250 }
1251 
TEST(STDIO_TEST,sscanf_ms)1252 TEST(STDIO_TEST, sscanf_ms) {
1253   CheckScanfM(sscanf, "hello", "%ms", 1, "hello");
1254   CheckScanfM(sscanf, "hello", "%4ms", 1, "hell");
1255   CheckScanfM(sscanf, "hello world", "%30ms", 1, "hello");
1256 }
1257 
TEST(STDIO_TEST,sscanf_mls)1258 TEST(STDIO_TEST, sscanf_mls) {
1259   CheckScanfM(sscanf, "hello", "%mls", 1, L"hello");
1260   CheckScanfM(sscanf, "hello", "%4mls", 1, L"hell");
1261   CheckScanfM(sscanf, "hello world", "%30mls", 1, L"hello");
1262 }
1263 
TEST(STDIO_TEST,sscanf_m_ccl)1264 TEST(STDIO_TEST, sscanf_m_ccl) {
1265   CheckScanfM(sscanf, "hello", "%m[a-z]", 1, "hello");
1266   CheckScanfM(sscanf, "hello", "%4m[a-z]", 1, "hell");
1267   CheckScanfM(sscanf, "hello world", "%30m[a-z]", 1, "hello");
1268 }
1269 
TEST(STDIO_TEST,sscanf_ml_ccl)1270 TEST(STDIO_TEST, sscanf_ml_ccl) {
1271   CheckScanfM(sscanf, "hello", "%ml[a-z]", 1, L"hello");
1272   CheckScanfM(sscanf, "hello", "%4ml[a-z]", 1, L"hell");
1273   CheckScanfM(sscanf, "hello world", "%30ml[a-z]", 1, L"hello");
1274 }
1275 
TEST(STDIO_TEST,sscanf_ls)1276 TEST(STDIO_TEST, sscanf_ls) {
1277   wchar_t w[32] = {};
1278   ASSERT_EQ(1, sscanf("hello world", "%ls", w));
1279   ASSERT_EQ(L"hello", std::wstring(w));
1280 }
1281 
TEST(STDIO_TEST,sscanf_ls_suppress)1282 TEST(STDIO_TEST, sscanf_ls_suppress) {
1283   ASSERT_EQ(0, sscanf("hello world", "%*ls %*ls"));
1284 }
1285 
TEST(STDIO_TEST,sscanf_ls_n)1286 TEST(STDIO_TEST, sscanf_ls_n) {
1287   setlocale(LC_ALL, "C.UTF-8");
1288   wchar_t w[32] = {};
1289   int pos = 0;
1290   ASSERT_EQ(1, sscanf("\xc4\x80", "%ls%n", w, &pos));
1291   ASSERT_EQ(static_cast<wchar_t>(256), w[0]);
1292   ASSERT_EQ(2, pos);
1293 }
1294 
TEST(STDIO_TEST,sscanf_ls_realloc)1295 TEST(STDIO_TEST, sscanf_ls_realloc) {
1296   // This is so useless that clang doesn't even believe it exists...
1297 #pragma clang diagnostic push
1298 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
1299 #pragma clang diagnostic ignored "-Wformat-extra-args"
1300   wchar_t* p1 = nullptr;
1301   wchar_t* p2 = nullptr;
1302   ASSERT_EQ(2, sscanf("1234567890123456789012345678901234567890 world", "%mls %mls", &p1, &p2));
1303   ASSERT_EQ(L"1234567890123456789012345678901234567890", std::wstring(p1));
1304   ASSERT_EQ(L"world", std::wstring(p2));
1305 #pragma clang diagnostic pop
1306 }
1307 
1308 // https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=202240
TEST(STDIO_TEST,scanf_wscanf_EOF)1309 TEST(STDIO_TEST, scanf_wscanf_EOF) {
1310   EXPECT_EQ(0, sscanf("b", "ab"));
1311   EXPECT_EQ(EOF, sscanf("", "a"));
1312   EXPECT_EQ(0, swscanf(L"b", L"ab"));
1313   EXPECT_EQ(EOF, swscanf(L"", L"a"));
1314 }
1315 
TEST(STDIO_TEST,scanf_invalid_UTF8)1316 TEST(STDIO_TEST, scanf_invalid_UTF8) {
1317 #if 0 // TODO: more tests invented during code review; no regressions, so fix later.
1318   char buf[BUFSIZ];
1319   wchar_t wbuf[BUFSIZ];
1320 
1321   memset(buf, 0, sizeof(buf));
1322   memset(wbuf, 0, sizeof(wbuf));
1323   EXPECT_EQ(0, sscanf("\xc0" " foo", "%ls %s", wbuf, buf));
1324 #endif
1325 }
1326 
TEST(STDIO_TEST,scanf_no_match_no_termination)1327 TEST(STDIO_TEST, scanf_no_match_no_termination) {
1328   char buf[4] = "x";
1329   EXPECT_EQ(0, sscanf("d", "%[abc]", buf));
1330   EXPECT_EQ('x', buf[0]);
1331   EXPECT_EQ(0, swscanf(L"d", L"%[abc]", buf));
1332   EXPECT_EQ('x', buf[0]);
1333 
1334   wchar_t wbuf[4] = L"x";
1335   EXPECT_EQ(0, swscanf(L"d", L"%l[abc]", wbuf));
1336   EXPECT_EQ(L'x', wbuf[0]);
1337 
1338   EXPECT_EQ(EOF, sscanf("", "%s", buf));
1339   EXPECT_EQ('x', buf[0]);
1340 
1341   EXPECT_EQ(EOF, swscanf(L"", L"%ls", wbuf));
1342   EXPECT_EQ(L'x', wbuf[0]);
1343 }
1344 
TEST(STDIO_TEST,scanf_wscanf_wide_character_class)1345 TEST(STDIO_TEST, scanf_wscanf_wide_character_class) {
1346 #if 0 // TODO: more tests invented during code review; no regressions, so fix later.
1347   wchar_t buf[BUFSIZ];
1348 
1349   // A wide character shouldn't match an ASCII-only class for scanf or wscanf.
1350   memset(buf, 0, sizeof(buf));
1351   EXPECT_EQ(1, sscanf("xĀyz", "%l[xy]", buf));
1352   EXPECT_EQ(L"x"s, std::wstring(buf));
1353   memset(buf, 0, sizeof(buf));
1354   EXPECT_EQ(1, swscanf(L"xĀyz", L"%l[xy]", buf));
1355   EXPECT_EQ(L"x"s, std::wstring(buf));
1356 
1357   // Even if scanf has wide characters in a class, they won't match...
1358   // TODO: is that a bug?
1359   memset(buf, 0, sizeof(buf));
1360   EXPECT_EQ(1, sscanf("xĀyz", "%l[xĀy]", buf));
1361   EXPECT_EQ(L"x"s, std::wstring(buf));
1362   // ...unless you use wscanf.
1363   memset(buf, 0, sizeof(buf));
1364   EXPECT_EQ(1, swscanf(L"xĀyz", L"%l[xĀy]", buf));
1365   EXPECT_EQ(L"xĀy"s, std::wstring(buf));
1366 
1367   // Negation only covers ASCII for scanf...
1368   memset(buf, 0, sizeof(buf));
1369   EXPECT_EQ(1, sscanf("xĀyz", "%l[^ab]", buf));
1370   EXPECT_EQ(L"x"s, std::wstring(buf));
1371   // ...but covers wide characters for wscanf.
1372   memset(buf, 0, sizeof(buf));
1373   EXPECT_EQ(1, swscanf(L"xĀyz", L"%l[^ab]", buf));
1374   EXPECT_EQ(L"xĀyz"s, std::wstring(buf));
1375 
1376   // We already determined that non-ASCII characters are ignored in scanf classes.
1377   memset(buf, 0, sizeof(buf));
1378   EXPECT_EQ(1, sscanf("x"
1379                       "\xc4\x80" // Matches a byte from each wide char in the class.
1380                       "\xc6\x82" // Neither byte is in the class.
1381                       "yz",
1382                       "%l[xy" "\xc5\x80" "\xc4\x81" "]", buf));
1383   EXPECT_EQ(L"x", std::wstring(buf));
1384   // bionic and glibc both behave badly for wscanf, so let's call it right for now...
1385   memset(buf, 0, sizeof(buf));
1386   EXPECT_EQ(1, swscanf(L"x"
1387                        L"\xc4\x80"
1388                        L"\xc6\x82"
1389                        L"yz",
1390                        L"%l[xy" L"\xc5\x80" L"\xc4\x81" L"]", buf));
1391   // Note that this isn't L"xĀ" --- although the *bytes* matched, they're
1392   // not put back together as a wide character.
1393   EXPECT_EQ(L"x" L"\xc4" L"\x80", std::wstring(buf));
1394 #endif
1395 }
1396 
TEST(STDIO_TEST,cantwrite_EBADF)1397 TEST(STDIO_TEST, cantwrite_EBADF) {
1398   // If we open a file read-only...
1399   FILE* fp = fopen("/proc/version", "r");
1400 
1401   // ...all attempts to write to that file should return failure.
1402 
1403   // They should also set errno to EBADF. This isn't POSIX, but it's traditional.
1404   // glibc gets the wide-character functions wrong.
1405 
1406   errno = 0;
1407   EXPECT_EQ(EOF, putc('x', fp));
1408   EXPECT_ERRNO(EBADF);
1409 
1410   errno = 0;
1411   EXPECT_EQ(EOF, fprintf(fp, "hello"));
1412   EXPECT_ERRNO(EBADF);
1413 
1414   errno = 0;
1415   EXPECT_EQ(EOF, fwprintf(fp, L"hello"));
1416 #if defined(__BIONIC__)
1417   EXPECT_ERRNO(EBADF);
1418 #endif
1419 
1420   errno = 0;
1421   EXPECT_EQ(0U, fwrite("hello", 1, 2, fp));
1422   EXPECT_ERRNO(EBADF);
1423 
1424   errno = 0;
1425   EXPECT_EQ(EOF, fputs("hello", fp));
1426   EXPECT_ERRNO(EBADF);
1427 
1428   errno = 0;
1429   EXPECT_EQ(WEOF, fputwc(L'x', fp));
1430 #if defined(__BIONIC__)
1431   EXPECT_ERRNO(EBADF);
1432 #endif
1433 }
1434 
1435 // Tests that we can only have a consistent and correct fpos_t when using
1436 // f*pos functions (i.e. fpos doesn't get inside a multi byte character).
TEST(STDIO_TEST,consistent_fpos_t)1437 TEST(STDIO_TEST, consistent_fpos_t) {
1438   ASSERT_STREQ("C.UTF-8", setlocale(LC_CTYPE, "C.UTF-8"));
1439   uselocale(LC_GLOBAL_LOCALE);
1440 
1441   FILE* fp = tmpfile();
1442   ASSERT_TRUE(fp != nullptr);
1443 
1444   wchar_t mb_one_bytes = L'h';
1445   wchar_t mb_two_bytes = 0x00a2;
1446   wchar_t mb_three_bytes = 0x20ac;
1447   wchar_t mb_four_bytes = 0x24b62;
1448 
1449   // Write to file.
1450   ASSERT_EQ(mb_one_bytes, static_cast<wchar_t>(fputwc(mb_one_bytes, fp)));
1451   ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fputwc(mb_two_bytes, fp)));
1452   ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fputwc(mb_three_bytes, fp)));
1453   ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fputwc(mb_four_bytes, fp)));
1454 
1455   rewind(fp);
1456 
1457   // Record each character position.
1458   fpos_t pos1;
1459   fpos_t pos2;
1460   fpos_t pos3;
1461   fpos_t pos4;
1462   fpos_t pos5;
1463   EXPECT_EQ(0, fgetpos(fp, &pos1));
1464   ASSERT_EQ(mb_one_bytes, static_cast<wchar_t>(fgetwc(fp)));
1465   EXPECT_EQ(0, fgetpos(fp, &pos2));
1466   ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fgetwc(fp)));
1467   EXPECT_EQ(0, fgetpos(fp, &pos3));
1468   ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fgetwc(fp)));
1469   EXPECT_EQ(0, fgetpos(fp, &pos4));
1470   ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fgetwc(fp)));
1471   EXPECT_EQ(0, fgetpos(fp, &pos5));
1472 
1473 #if defined(__BIONIC__)
1474   // Bionic's fpos_t is just an alias for off_t. This is inherited from OpenBSD
1475   // upstream. Glibc differs by storing the mbstate_t inside its fpos_t. In
1476   // Bionic (and upstream OpenBSD) the mbstate_t is stored inside the FILE
1477   // structure.
1478   ASSERT_EQ(0, static_cast<off_t>(pos1));
1479   ASSERT_EQ(1, static_cast<off_t>(pos2));
1480   ASSERT_EQ(3, static_cast<off_t>(pos3));
1481   ASSERT_EQ(6, static_cast<off_t>(pos4));
1482   ASSERT_EQ(10, static_cast<off_t>(pos5));
1483 #endif
1484 
1485   // Exercise back and forth movements of the position.
1486   ASSERT_EQ(0, fsetpos(fp, &pos2));
1487   ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fgetwc(fp)));
1488   ASSERT_EQ(0, fsetpos(fp, &pos1));
1489   ASSERT_EQ(mb_one_bytes, static_cast<wchar_t>(fgetwc(fp)));
1490   ASSERT_EQ(0, fsetpos(fp, &pos4));
1491   ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fgetwc(fp)));
1492   ASSERT_EQ(0, fsetpos(fp, &pos3));
1493   ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fgetwc(fp)));
1494   ASSERT_EQ(0, fsetpos(fp, &pos5));
1495   ASSERT_EQ(WEOF, fgetwc(fp));
1496 
1497   fclose(fp);
1498 }
1499 
1500 // Exercise the interaction between fpos and seek.
TEST(STDIO_TEST,fpos_t_and_seek)1501 TEST(STDIO_TEST, fpos_t_and_seek) {
1502   ASSERT_STREQ("C.UTF-8", setlocale(LC_CTYPE, "C.UTF-8"));
1503   uselocale(LC_GLOBAL_LOCALE);
1504 
1505   // In glibc-2.16 fseek doesn't work properly in wide mode
1506   // (https://sourceware.org/bugzilla/show_bug.cgi?id=14543). One workaround is
1507   // to close and re-open the file. We do it in order to make the test pass
1508   // with all glibcs.
1509 
1510   TemporaryFile tf;
1511   FILE* fp = fdopen(tf.fd, "w+");
1512   ASSERT_TRUE(fp != nullptr);
1513 
1514   wchar_t mb_two_bytes = 0x00a2;
1515   wchar_t mb_three_bytes = 0x20ac;
1516   wchar_t mb_four_bytes = 0x24b62;
1517 
1518   // Write to file.
1519   ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fputwc(mb_two_bytes, fp)));
1520   ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fputwc(mb_three_bytes, fp)));
1521   ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fputwc(mb_four_bytes, fp)));
1522 
1523   fflush(fp);
1524   fclose(fp);
1525 
1526   fp = fopen(tf.path, "r");
1527   ASSERT_TRUE(fp != nullptr);
1528 
1529   // Store a valid position.
1530   fpos_t mb_two_bytes_pos;
1531   ASSERT_EQ(0, fgetpos(fp, &mb_two_bytes_pos));
1532 
1533   // Move inside mb_four_bytes with fseek.
1534   long offset_inside_mb = 6;
1535   ASSERT_EQ(0, fseek(fp, offset_inside_mb, SEEK_SET));
1536 
1537   // Store the "inside multi byte" position.
1538   fpos_t pos_inside_mb;
1539   ASSERT_EQ(0, fgetpos(fp, &pos_inside_mb));
1540 #if defined(__BIONIC__)
1541   ASSERT_EQ(offset_inside_mb, static_cast<off_t>(pos_inside_mb));
1542 #endif
1543 
1544   // Reading from within a byte should produce an error.
1545   ASSERT_EQ(WEOF, fgetwc(fp));
1546   ASSERT_ERRNO(EILSEQ);
1547 
1548   // Reverting to a valid position should work.
1549   ASSERT_EQ(0, fsetpos(fp, &mb_two_bytes_pos));
1550   ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fgetwc(fp)));
1551 
1552   // Moving withing a multi byte with fsetpos should work but reading should
1553   // produce an error.
1554   ASSERT_EQ(0, fsetpos(fp, &pos_inside_mb));
1555   ASSERT_EQ(WEOF, fgetwc(fp));
1556   ASSERT_ERRNO(EILSEQ);
1557 
1558   ASSERT_EQ(0, fclose(fp));
1559 }
1560 
TEST(STDIO_TEST,fmemopen)1561 TEST(STDIO_TEST, fmemopen) {
1562   char buf[16];
1563   memset(buf, 0, sizeof(buf));
1564   FILE* fp = fmemopen(buf, sizeof(buf), "r+");
1565   ASSERT_EQ('<', fputc('<', fp));
1566   ASSERT_NE(EOF, fputs("abc>\n", fp));
1567   fflush(fp);
1568 
1569   // We wrote to the buffer...
1570   ASSERT_STREQ("<abc>\n", buf);
1571 
1572   // And can read back from the file.
1573   AssertFileIs(fp, "<abc>\n", true);
1574   ASSERT_EQ(0, fclose(fp));
1575 }
1576 
TEST(STDIO_TEST,fmemopen_nullptr)1577 TEST(STDIO_TEST, fmemopen_nullptr) {
1578   FILE* fp = fmemopen(nullptr, 128, "r+");
1579   ASSERT_NE(EOF, fputs("xyz\n", fp));
1580 
1581   AssertFileIs(fp, "xyz\n", true);
1582   ASSERT_EQ(0, fclose(fp));
1583 }
1584 
TEST(STDIO_TEST,fmemopen_trailing_NUL_byte)1585 TEST(STDIO_TEST, fmemopen_trailing_NUL_byte) {
1586   FILE* fp;
1587   char buf[8];
1588 
1589   // POSIX: "When a stream open for writing is flushed or closed, a null byte
1590   // shall be written at the current position or at the end of the buffer,
1591   // depending on the size of the contents."
1592   memset(buf, 'x', sizeof(buf));
1593   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w"));
1594   // Even with nothing written (and not in truncate mode), we'll flush a NUL...
1595   ASSERT_EQ(0, fflush(fp));
1596   EXPECT_EQ("\0xxxxxxx"s, std::string(buf, buf + sizeof(buf)));
1597   // Now write and check that the NUL moves along with our writes...
1598   ASSERT_NE(EOF, fputs("hello", fp));
1599   ASSERT_EQ(0, fflush(fp));
1600   EXPECT_EQ("hello\0xx"s, std::string(buf, buf + sizeof(buf)));
1601   ASSERT_NE(EOF, fputs("wo", fp));
1602   ASSERT_EQ(0, fflush(fp));
1603   EXPECT_EQ("hellowo\0"s, std::string(buf, buf + sizeof(buf)));
1604   ASSERT_EQ(0, fclose(fp));
1605 
1606   // "If a stream open for update is flushed or closed and the last write has
1607   // advanced the current buffer size, a null byte shall be written at the end
1608   // of the buffer if it fits."
1609   memset(buf, 'x', sizeof(buf));
1610   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "r+"));
1611   // Nothing written yet, so no advance...
1612   ASSERT_EQ(0, fflush(fp));
1613   EXPECT_EQ("xxxxxxxx"s, std::string(buf, buf + sizeof(buf)));
1614   ASSERT_NE(EOF, fputs("hello", fp));
1615   ASSERT_EQ(0, fclose(fp));
1616 }
1617 
TEST(STDIO_TEST,fmemopen_size)1618 TEST(STDIO_TEST, fmemopen_size) {
1619   FILE* fp;
1620   char buf[16];
1621   memset(buf, 'x', sizeof(buf));
1622 
1623   // POSIX: "The stream shall also maintain the size of the current buffer
1624   // contents; use of fseek() or fseeko() on the stream with SEEK_END shall
1625   // seek relative to this size."
1626 
1627   // "For modes r and r+ the size shall be set to the value given by the size
1628   // argument."
1629   ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "r"));
1630   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1631   EXPECT_EQ(16, ftell(fp));
1632   EXPECT_EQ(16, ftello(fp));
1633   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1634   EXPECT_EQ(16, ftell(fp));
1635   EXPECT_EQ(16, ftello(fp));
1636   ASSERT_EQ(0, fclose(fp));
1637   ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "r+"));
1638   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1639   EXPECT_EQ(16, ftell(fp));
1640   EXPECT_EQ(16, ftello(fp));
1641   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1642   EXPECT_EQ(16, ftell(fp));
1643   EXPECT_EQ(16, ftello(fp));
1644   ASSERT_EQ(0, fclose(fp));
1645 
1646   // "For modes w and w+ the initial size shall be zero..."
1647   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "w"));
1648   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1649   EXPECT_EQ(0, ftell(fp));
1650   EXPECT_EQ(0, ftello(fp));
1651   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1652   EXPECT_EQ(0, ftell(fp));
1653   EXPECT_EQ(0, ftello(fp));
1654   ASSERT_EQ(0, fclose(fp));
1655   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "w+"));
1656   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1657   EXPECT_EQ(0, ftell(fp));
1658   EXPECT_EQ(0, ftello(fp));
1659   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1660   EXPECT_EQ(0, ftell(fp));
1661   EXPECT_EQ(0, ftello(fp));
1662   ASSERT_EQ(0, fclose(fp));
1663 
1664   // "...and for modes a and a+ the initial size shall be:
1665   // 1. Zero, if buf is a null pointer
1666   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "a"));
1667   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1668   EXPECT_EQ(0, ftell(fp));
1669   EXPECT_EQ(0, ftello(fp));
1670   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1671   EXPECT_EQ(0, ftell(fp));
1672   EXPECT_EQ(0, ftello(fp));
1673   ASSERT_EQ(0, fclose(fp));
1674   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "a+"));
1675   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1676   EXPECT_EQ(0, ftell(fp));
1677   EXPECT_EQ(0, ftello(fp));
1678   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1679   EXPECT_EQ(0, ftell(fp));
1680   EXPECT_EQ(0, ftello(fp));
1681   ASSERT_EQ(0, fclose(fp));
1682 
1683   // 2. The position of the first null byte in the buffer, if one is found
1684   memset(buf, 'x', sizeof(buf));
1685   buf[3] = '\0';
1686   ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "a"));
1687   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1688   EXPECT_EQ(3, ftell(fp));
1689   EXPECT_EQ(3, ftello(fp));
1690   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1691   EXPECT_EQ(3, ftell(fp));
1692   EXPECT_EQ(3, ftello(fp));
1693   ASSERT_EQ(0, fclose(fp));
1694   memset(buf, 'x', sizeof(buf));
1695   buf[3] = '\0';
1696   ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "a+"));
1697   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1698   EXPECT_EQ(3, ftell(fp));
1699   EXPECT_EQ(3, ftello(fp));
1700   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1701   EXPECT_EQ(3, ftell(fp));
1702   EXPECT_EQ(3, ftello(fp));
1703   ASSERT_EQ(0, fclose(fp));
1704 
1705   // 3. The value of the size argument, if buf is not a null pointer and no
1706   // null byte is found.
1707   memset(buf, 'x', sizeof(buf));
1708   ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "a"));
1709   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1710   EXPECT_EQ(16, ftell(fp));
1711   EXPECT_EQ(16, ftello(fp));
1712   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1713   EXPECT_EQ(16, ftell(fp));
1714   EXPECT_EQ(16, ftello(fp));
1715   ASSERT_EQ(0, fclose(fp));
1716   memset(buf, 'x', sizeof(buf));
1717   ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "a+"));
1718   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1719   EXPECT_EQ(16, ftell(fp));
1720   EXPECT_EQ(16, ftello(fp));
1721   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1722   EXPECT_EQ(16, ftell(fp));
1723   EXPECT_EQ(16, ftello(fp));
1724   ASSERT_EQ(0, fclose(fp));
1725 }
1726 
TEST(STDIO_TEST,fmemopen_SEEK_END)1727 TEST(STDIO_TEST, fmemopen_SEEK_END) {
1728   // fseek SEEK_END is relative to the current string length, not the buffer size.
1729   FILE* fp;
1730   char buf[8];
1731   memset(buf, 'x', sizeof(buf));
1732   strcpy(buf, "str");
1733   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w+"));
1734   ASSERT_NE(EOF, fputs("string", fp));
1735   EXPECT_EQ(0, fseek(fp, 0, SEEK_END));
1736   EXPECT_EQ(static_cast<long>(strlen("string")), ftell(fp));
1737   EXPECT_EQ(static_cast<off_t>(strlen("string")), ftello(fp));
1738   EXPECT_EQ(0, fclose(fp));
1739 
1740   // glibc < 2.22 interpreted SEEK_END the wrong way round (subtracting rather
1741   // than adding).
1742   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w+"));
1743   ASSERT_NE(EOF, fputs("54321", fp));
1744   EXPECT_EQ(0, fseek(fp, -2, SEEK_END));
1745   EXPECT_EQ('2', fgetc(fp));
1746   EXPECT_EQ(0, fclose(fp));
1747 }
1748 
TEST(STDIO_TEST,fmemopen_seek_invalid)1749 TEST(STDIO_TEST, fmemopen_seek_invalid) {
1750   char buf[8];
1751   memset(buf, 'x', sizeof(buf));
1752   FILE* fp = fmemopen(buf, sizeof(buf), "w");
1753   ASSERT_TRUE(fp != nullptr);
1754 
1755   // POSIX: "An attempt to seek ... to a negative position or to a position
1756   // larger than the buffer size given in the size argument shall fail."
1757   // (There's no mention of what errno should be set to, and glibc doesn't
1758   // set errno in any of these cases.)
1759   EXPECT_EQ(-1, fseek(fp, -2, SEEK_SET));
1760   EXPECT_EQ(-1, fseeko(fp, -2, SEEK_SET));
1761   EXPECT_EQ(-1, fseek(fp, sizeof(buf) + 1, SEEK_SET));
1762   EXPECT_EQ(-1, fseeko(fp, sizeof(buf) + 1, SEEK_SET));
1763 }
1764 
TEST(STDIO_TEST,fmemopen_read_EOF)1765 TEST(STDIO_TEST, fmemopen_read_EOF) {
1766   // POSIX: "A read operation on the stream shall not advance the current
1767   // buffer position beyond the current buffer size."
1768   char buf[8];
1769   memset(buf, 'x', sizeof(buf));
1770   FILE* fp = fmemopen(buf, sizeof(buf), "r");
1771   ASSERT_TRUE(fp != nullptr);
1772   char buf2[BUFSIZ];
1773   ASSERT_EQ(8U, fread(buf2, 1, sizeof(buf2), fp));
1774   // POSIX: "Reaching the buffer size in a read operation shall count as
1775   // end-of-file.
1776   ASSERT_TRUE(feof(fp));
1777   ASSERT_EQ(EOF, fgetc(fp));
1778   ASSERT_EQ(0, fclose(fp));
1779 }
1780 
TEST(STDIO_TEST,fmemopen_read_null_bytes)1781 TEST(STDIO_TEST, fmemopen_read_null_bytes) {
1782   // POSIX: "Null bytes in the buffer shall have no special meaning for reads."
1783   char buf[] = "h\0e\0l\0l\0o";
1784   FILE* fp = fmemopen(buf, sizeof(buf), "r");
1785   ASSERT_TRUE(fp != nullptr);
1786   ASSERT_EQ('h', fgetc(fp));
1787   ASSERT_EQ(0, fgetc(fp));
1788   ASSERT_EQ('e', fgetc(fp));
1789   ASSERT_EQ(0, fgetc(fp));
1790   ASSERT_EQ('l', fgetc(fp));
1791   ASSERT_EQ(0, fgetc(fp));
1792   // POSIX: "The read operation shall start at the current buffer position of
1793   // the stream."
1794   char buf2[8];
1795   memset(buf2, 'x', sizeof(buf2));
1796   ASSERT_EQ(4U, fread(buf2, 1, sizeof(buf2), fp));
1797   ASSERT_EQ('l', buf2[0]);
1798   ASSERT_EQ(0, buf2[1]);
1799   ASSERT_EQ('o', buf2[2]);
1800   ASSERT_EQ(0, buf2[3]);
1801   for (size_t i = 4; i < sizeof(buf2); ++i) ASSERT_EQ('x', buf2[i]) << i;
1802   ASSERT_TRUE(feof(fp));
1803   ASSERT_EQ(0, fclose(fp));
1804 }
1805 
TEST(STDIO_TEST,fmemopen_write)1806 TEST(STDIO_TEST, fmemopen_write) {
1807   FILE* fp;
1808   char buf[8];
1809 
1810   // POSIX: "A write operation shall start either at the current position of
1811   // the stream (if mode has not specified 'a' as the first character)..."
1812   memset(buf, 'x', sizeof(buf));
1813   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "r+"));
1814   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1815   ASSERT_EQ(0, fseek(fp, 2, SEEK_SET));
1816   ASSERT_EQ(' ', fputc(' ', fp));
1817   EXPECT_EQ("xx xxxxx", std::string(buf, buf + sizeof(buf)));
1818   ASSERT_EQ(0, fclose(fp));
1819 
1820   // "...or at the current size of the stream (if mode had 'a' as the first
1821   // character)." (See the fmemopen_size test for what "size" means, but for
1822   // mode "a", it's the first NUL byte.)
1823   memset(buf, 'x', sizeof(buf));
1824   buf[3] = '\0';
1825   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a+"));
1826   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1827   ASSERT_EQ(' ', fputc(' ', fp));
1828   EXPECT_EQ("xxx \0xxx"s, std::string(buf, buf + sizeof(buf)));
1829   ASSERT_EQ(0, fclose(fp));
1830 
1831   // "If the current position at the end of the write is larger than the
1832   // current buffer size, the current buffer size shall be set to the current
1833   // position." (See the fmemopen_size test for what "size" means, but to
1834   // query it we SEEK_END with offset 0, and then ftell.)
1835   memset(buf, 'x', sizeof(buf));
1836   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w+"));
1837   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1838   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1839   EXPECT_EQ(0, ftell(fp));
1840   ASSERT_EQ(' ', fputc(' ', fp));
1841   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1842   EXPECT_EQ(1, ftell(fp));
1843   ASSERT_NE(EOF, fputs("123", fp));
1844   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1845   EXPECT_EQ(4, ftell(fp));
1846   EXPECT_EQ(" 123\0xxx"s, std::string(buf, buf + sizeof(buf)));
1847   ASSERT_EQ(0, fclose(fp));
1848 }
1849 
TEST(STDIO_TEST,fmemopen_write_EOF)1850 TEST(STDIO_TEST, fmemopen_write_EOF) {
1851   // POSIX: "A write operation on the stream shall not advance the current
1852   // buffer size beyond the size given in the size argument."
1853   FILE* fp;
1854 
1855   // Scalar writes...
1856   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 4, "w"));
1857   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1858   ASSERT_EQ('x', fputc('x', fp));
1859   ASSERT_EQ('x', fputc('x', fp));
1860   ASSERT_EQ('x', fputc('x', fp));
1861   ASSERT_EQ(EOF, fputc('x', fp)); // Only 3 fit because of the implicit NUL.
1862   ASSERT_EQ(0, fclose(fp));
1863 
1864   // Vector writes...
1865   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 4, "w"));
1866   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1867   ASSERT_EQ(3U, fwrite("xxxx", 1, 4, fp));
1868   ASSERT_EQ(0, fclose(fp));
1869 }
1870 
TEST(STDIO_TEST,fmemopen_initial_position)1871 TEST(STDIO_TEST, fmemopen_initial_position) {
1872   // POSIX: "The ... current position in the buffer ... shall be initially
1873   // set to either the beginning of the buffer (for r and w modes) ..."
1874   char buf[] = "hello\0world";
1875   FILE* fp;
1876   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "r"));
1877   EXPECT_EQ(0L, ftell(fp));
1878   EXPECT_EQ(0, fclose(fp));
1879   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w"));
1880   EXPECT_EQ(0L, ftell(fp));
1881   EXPECT_EQ(0, fclose(fp));
1882   buf[0] = 'h'; // (Undo the effects of the above.)
1883 
1884   // POSIX: "...or to the first null byte in the buffer (for a modes)."
1885   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a"));
1886   EXPECT_EQ(5L, ftell(fp));
1887   EXPECT_EQ(0, fclose(fp));
1888 
1889   // POSIX: "If no null byte is found in append mode, the initial position
1890   // shall be set to one byte after the end of the buffer."
1891   memset(buf, 'x', sizeof(buf));
1892   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a"));
1893   EXPECT_EQ(static_cast<long>(sizeof(buf)), ftell(fp));
1894   EXPECT_EQ(0, fclose(fp));
1895 }
1896 
TEST(STDIO_TEST,fmemopen_initial_position_allocated)1897 TEST(STDIO_TEST, fmemopen_initial_position_allocated) {
1898   // POSIX: "If buf is a null pointer, the initial position shall always be
1899   // set to the beginning of the buffer."
1900   FILE* fp = fmemopen(nullptr, 128, "a+");
1901   ASSERT_TRUE(fp != nullptr);
1902   EXPECT_EQ(0L, ftell(fp));
1903   EXPECT_EQ(0L, fseek(fp, 0, SEEK_SET));
1904   EXPECT_EQ(0, fclose(fp));
1905 }
1906 
TEST(STDIO_TEST,fmemopen_zero_length)1907 TEST(STDIO_TEST, fmemopen_zero_length) {
1908   // POSIX says it's up to the implementation whether or not you can have a
1909   // zero-length buffer (but "A future version of this standard may require
1910   // support of zero-length buffer streams explicitly"). BSD and glibc < 2.22
1911   // agreed that you couldn't, but glibc >= 2.22 allows it for consistency.
1912   FILE* fp;
1913   char buf[16];
1914   ASSERT_NE(nullptr, fp = fmemopen(buf, 0, "r+"));
1915   ASSERT_EQ(EOF, fgetc(fp));
1916   ASSERT_TRUE(feof(fp));
1917   ASSERT_EQ(0, fclose(fp));
1918   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 0, "r+"));
1919   ASSERT_EQ(EOF, fgetc(fp));
1920   ASSERT_TRUE(feof(fp));
1921   ASSERT_EQ(0, fclose(fp));
1922 
1923   ASSERT_NE(nullptr, fp = fmemopen(buf, 0, "w+"));
1924   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1925   ASSERT_EQ(EOF, fputc('x', fp));
1926   ASSERT_EQ(0, fclose(fp));
1927   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 0, "w+"));
1928   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1929   ASSERT_EQ(EOF, fputc('x', fp));
1930   ASSERT_EQ(0, fclose(fp));
1931 }
1932 
TEST(STDIO_TEST,fmemopen_zero_length_buffer_overrun)1933 TEST(STDIO_TEST, fmemopen_zero_length_buffer_overrun) {
1934   char buf[2] = "x";
1935   ASSERT_EQ('x', buf[0]);
1936   FILE* fp = fmemopen(buf, 0, "w");
1937   ASSERT_EQ('x', buf[0]);
1938   ASSERT_EQ(0, fclose(fp));
1939 }
1940 
TEST(STDIO_TEST,fmemopen_write_only_allocated)1941 TEST(STDIO_TEST, fmemopen_write_only_allocated) {
1942   // POSIX says fmemopen "may fail if the mode argument does not include a '+'".
1943   // BSD fails, glibc doesn't. We side with the more lenient.
1944   FILE* fp;
1945   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "r"));
1946   ASSERT_EQ(0, fclose(fp));
1947   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "w"));
1948   ASSERT_EQ(0, fclose(fp));
1949 }
1950 
TEST(STDIO_TEST,fmemopen_fileno)1951 TEST(STDIO_TEST, fmemopen_fileno) {
1952   // There's no fd backing an fmemopen FILE*.
1953   FILE* fp = fmemopen(nullptr, 16, "r");
1954   ASSERT_TRUE(fp != nullptr);
1955   errno = 0;
1956   ASSERT_EQ(-1, fileno(fp));
1957   ASSERT_ERRNO(EBADF);
1958   ASSERT_EQ(0, fclose(fp));
1959 }
1960 
TEST(STDIO_TEST,fmemopen_append_after_seek)1961 TEST(STDIO_TEST, fmemopen_append_after_seek) {
1962   // In BSD and glibc < 2.22, append mode didn't force writes to append if
1963   // there had been an intervening seek.
1964 
1965   FILE* fp;
1966   char buf[] = "hello\0world";
1967   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a"));
1968   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1969   ASSERT_EQ(0, fseek(fp, 0, SEEK_SET));
1970   ASSERT_NE(EOF, fputc('!', fp));
1971   EXPECT_EQ("hello!\0orld\0"s, std::string(buf, buf + sizeof(buf)));
1972   ASSERT_EQ(0, fclose(fp));
1973 
1974   memcpy(buf, "hello\0world", sizeof(buf));
1975   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a+"));
1976   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1977   ASSERT_EQ(0, fseek(fp, 0, SEEK_SET));
1978   ASSERT_NE(EOF, fputc('!', fp));
1979   EXPECT_EQ("hello!\0orld\0"s, std::string(buf, buf + sizeof(buf)));
1980   ASSERT_EQ(0, fclose(fp));
1981 }
1982 
TEST(STDIO_TEST,open_memstream)1983 TEST(STDIO_TEST, open_memstream) {
1984   char* p = nullptr;
1985   size_t size = 0;
1986   FILE* fp = open_memstream(&p, &size);
1987   ASSERT_NE(EOF, fputs("hello, world!", fp));
1988   fclose(fp);
1989 
1990   ASSERT_STREQ("hello, world!", p);
1991   ASSERT_EQ(strlen("hello, world!"), size);
1992   free(p);
1993 }
1994 
TEST(STDIO_TEST,open_memstream_EINVAL)1995 TEST(STDIO_TEST, open_memstream_EINVAL) {
1996 #if defined(__BIONIC__)
1997 #pragma clang diagnostic push
1998 #pragma clang diagnostic ignored "-Wnonnull"
1999   char* p;
2000   size_t size;
2001 
2002   // Invalid buffer.
2003   errno = 0;
2004   ASSERT_EQ(nullptr, open_memstream(nullptr, &size));
2005   ASSERT_ERRNO(EINVAL);
2006 
2007   // Invalid size.
2008   errno = 0;
2009   ASSERT_EQ(nullptr, open_memstream(&p, nullptr));
2010   ASSERT_ERRNO(EINVAL);
2011 #pragma clang diagnostic pop
2012 #else
2013   GTEST_SKIP() << "glibc is broken";
2014 #endif
2015 }
2016 
TEST(STDIO_TEST,fdopen_add_CLOEXEC)2017 TEST(STDIO_TEST, fdopen_add_CLOEXEC) {
2018   // This fd doesn't have O_CLOEXEC...
2019   int fd = open("/proc/version", O_RDONLY);
2020   ASSERT_FALSE(CloseOnExec(fd));
2021   // ...but the new one does.
2022   FILE* fp = fdopen(fd, "re");
2023   ASSERT_TRUE(CloseOnExec(fileno(fp)));
2024   fclose(fp);
2025 }
2026 
TEST(STDIO_TEST,fdopen_remove_CLOEXEC)2027 TEST(STDIO_TEST, fdopen_remove_CLOEXEC) {
2028   // This fd has O_CLOEXEC...
2029   int fd = open("/proc/version", O_RDONLY | O_CLOEXEC);
2030   ASSERT_TRUE(CloseOnExec(fd));
2031   // ...but the new one doesn't.
2032   FILE* fp = fdopen(fd, "r");
2033   ASSERT_TRUE(CloseOnExec(fileno(fp)));
2034   fclose(fp);
2035 }
2036 
TEST(STDIO_TEST,freopen_add_CLOEXEC)2037 TEST(STDIO_TEST, freopen_add_CLOEXEC) {
2038   // This FILE* doesn't have O_CLOEXEC...
2039   FILE* fp = fopen("/proc/version", "r");
2040   ASSERT_FALSE(CloseOnExec(fileno(fp)));
2041   // ...but the new one does.
2042   fp = freopen("/proc/version", "re", fp);
2043   ASSERT_TRUE(CloseOnExec(fileno(fp)));
2044 
2045   fclose(fp);
2046 }
2047 
TEST(STDIO_TEST,freopen_remove_CLOEXEC)2048 TEST(STDIO_TEST, freopen_remove_CLOEXEC) {
2049   // This FILE* has O_CLOEXEC...
2050   FILE* fp = fopen("/proc/version", "re");
2051   ASSERT_TRUE(CloseOnExec(fileno(fp)));
2052   // ...but the new one doesn't.
2053   fp = freopen("/proc/version", "r", fp);
2054   ASSERT_FALSE(CloseOnExec(fileno(fp)));
2055   fclose(fp);
2056 }
2057 
TEST(STDIO_TEST,freopen_null_filename_add_CLOEXEC)2058 TEST(STDIO_TEST, freopen_null_filename_add_CLOEXEC) {
2059   // This FILE* doesn't have O_CLOEXEC...
2060   FILE* fp = fopen("/proc/version", "r");
2061   ASSERT_FALSE(CloseOnExec(fileno(fp)));
2062   // ...but the new one does.
2063   fp = freopen(nullptr, "re", fp);
2064   ASSERT_TRUE(CloseOnExec(fileno(fp)));
2065   fclose(fp);
2066 }
2067 
TEST(STDIO_TEST,freopen_null_filename_remove_CLOEXEC)2068 TEST(STDIO_TEST, freopen_null_filename_remove_CLOEXEC) {
2069   // This FILE* has O_CLOEXEC...
2070   FILE* fp = fopen("/proc/version", "re");
2071   ASSERT_TRUE(CloseOnExec(fileno(fp)));
2072   // ...but the new one doesn't.
2073   fp = freopen(nullptr, "r", fp);
2074   ASSERT_FALSE(CloseOnExec(fileno(fp)));
2075   fclose(fp);
2076 }
2077 
TEST(STDIO_TEST,fopen64_freopen64)2078 TEST(STDIO_TEST, fopen64_freopen64) {
2079   FILE* fp = fopen64("/proc/version", "r");
2080   ASSERT_TRUE(fp != nullptr);
2081   fp = freopen64("/proc/version", "re", fp);
2082   ASSERT_TRUE(fp != nullptr);
2083   fclose(fp);
2084 }
2085 
2086 // https://code.google.com/p/android/issues/detail?id=81155
2087 // http://b/18556607
TEST(STDIO_TEST,fread_unbuffered_pathological_performance)2088 TEST(STDIO_TEST, fread_unbuffered_pathological_performance) {
2089   FILE* fp = fopen("/dev/zero", "r");
2090   ASSERT_TRUE(fp != nullptr);
2091 
2092   // Make this stream unbuffered.
2093   setvbuf(fp, nullptr, _IONBF, 0);
2094 
2095   char buf[65*1024];
2096   memset(buf, 0xff, sizeof(buf));
2097 
2098   time_t t0 = time(nullptr);
2099   for (size_t i = 0; i < 1024; ++i) {
2100     ASSERT_EQ(1U, fread(buf, 64*1024, 1, fp));
2101   }
2102   time_t t1 = time(nullptr);
2103 
2104   fclose(fp);
2105 
2106   // 1024 64KiB reads should have been very quick.
2107   ASSERT_LE(t1 - t0, 1);
2108 
2109   for (size_t i = 0; i < 64*1024; ++i) {
2110     ASSERT_EQ('\0', buf[i]);
2111   }
2112   for (size_t i = 64*1024; i < 65*1024; ++i) {
2113     ASSERT_EQ('\xff', buf[i]);
2114   }
2115 }
2116 
TEST(STDIO_TEST,fread_EOF)2117 TEST(STDIO_TEST, fread_EOF) {
2118   std::string digits("0123456789");
2119   FILE* fp = fmemopen(&digits[0], digits.size(), "r");
2120 
2121   // Try to read too much, but little enough that it still fits in the FILE's internal buffer.
2122   char buf1[4 * 4];
2123   memset(buf1, 0, sizeof(buf1));
2124   ASSERT_EQ(2U, fread(buf1, 4, 4, fp));
2125   ASSERT_STREQ("0123456789", buf1);
2126   ASSERT_TRUE(feof(fp));
2127 
2128   rewind(fp);
2129 
2130   // Try to read way too much so stdio tries to read more direct from the stream.
2131   char buf2[4 * 4096];
2132   memset(buf2, 0, sizeof(buf2));
2133   ASSERT_EQ(2U, fread(buf2, 4, 4096, fp));
2134   ASSERT_STREQ("0123456789", buf2);
2135   ASSERT_TRUE(feof(fp));
2136 
2137   fclose(fp);
2138 }
2139 
test_fread_from_write_only_stream(size_t n)2140 static void test_fread_from_write_only_stream(size_t n) {
2141   FILE* fp = fopen("/dev/null", "w");
2142   std::vector<char> buf(n, 0);
2143   errno = 0;
2144   ASSERT_EQ(0U, fread(&buf[0], n, 1, fp));
2145   ASSERT_ERRNO(EBADF);
2146   ASSERT_TRUE(ferror(fp));
2147   ASSERT_FALSE(feof(fp));
2148   fclose(fp);
2149 }
2150 
TEST(STDIO_TEST,fread_from_write_only_stream_slow_path)2151 TEST(STDIO_TEST, fread_from_write_only_stream_slow_path) {
2152   test_fread_from_write_only_stream(1);
2153 }
2154 
TEST(STDIO_TEST,fread_from_write_only_stream_fast_path)2155 TEST(STDIO_TEST, fread_from_write_only_stream_fast_path) {
2156   test_fread_from_write_only_stream(64*1024);
2157 }
2158 
TEST(STDIO_TEST,fwrite_to_read_only_stream)2159 TEST(STDIO_TEST, fwrite_to_read_only_stream) {
2160   FILE* fp = fopen("/proc/version", "re");
2161   ASSERT_FALSE(ferror(fp));
2162   ASSERT_EQ(0U, fwrite("hello", 1, 5, fp));
2163   ASSERT_TRUE(ferror(fp));
2164 }
2165 
TEST(STDIO_TEST,fputc_to_read_only_stream)2166 TEST(STDIO_TEST, fputc_to_read_only_stream) {
2167   FILE* fp = fopen("/proc/version", "re");
2168   ASSERT_FALSE(ferror(fp));
2169   ASSERT_EQ(EOF, fputc('x', fp));
2170   ASSERT_TRUE(ferror(fp));
2171 }
2172 
TEST(STDIO_TEST,fprintf_to_read_only_stream)2173 TEST(STDIO_TEST, fprintf_to_read_only_stream) {
2174   FILE* fp = fopen("/proc/version", "re");
2175   ASSERT_FALSE(ferror(fp));
2176   ASSERT_EQ(-1, fprintf(fp, "%s%d", "hello", 123));
2177   ASSERT_TRUE(ferror(fp));
2178 }
2179 
test_fwrite_after_fread(size_t n)2180 static void test_fwrite_after_fread(size_t n) {
2181   TemporaryFile tf;
2182 
2183   FILE* fp = fdopen(tf.fd, "w+");
2184   ASSERT_EQ(1U, fwrite("1", 1, 1, fp));
2185   fflush(fp);
2186 
2187   // We've flushed but not rewound, so there's nothing to read.
2188   std::vector<char> buf(n, 0);
2189   ASSERT_EQ(0U, fread(&buf[0], 1, buf.size(), fp));
2190   ASSERT_TRUE(feof(fp));
2191 
2192   // But hitting EOF doesn't prevent us from writing...
2193   errno = 0;
2194   ASSERT_EQ(1U, fwrite("2", 1, 1, fp)) << strerror(errno);
2195 
2196   // And if we rewind, everything's there.
2197   rewind(fp);
2198   ASSERT_EQ(2U, fread(&buf[0], 1, buf.size(), fp));
2199   ASSERT_EQ('1', buf[0]);
2200   ASSERT_EQ('2', buf[1]);
2201 
2202   fclose(fp);
2203 }
2204 
TEST(STDIO_TEST,fwrite_after_fread_slow_path)2205 TEST(STDIO_TEST, fwrite_after_fread_slow_path) {
2206   test_fwrite_after_fread(16);
2207 }
2208 
TEST(STDIO_TEST,fwrite_after_fread_fast_path)2209 TEST(STDIO_TEST, fwrite_after_fread_fast_path) {
2210   test_fwrite_after_fread(64*1024);
2211 }
2212 
2213 // http://b/19172514
TEST(STDIO_TEST,fread_after_fseek)2214 TEST(STDIO_TEST, fread_after_fseek) {
2215   TemporaryFile tf;
2216 
2217   FILE* fp = fopen(tf.path, "w+");
2218   ASSERT_TRUE(fp != nullptr);
2219 
2220   char file_data[12288];
2221   for (size_t i = 0; i < 12288; i++) {
2222     file_data[i] = i;
2223   }
2224   ASSERT_EQ(12288U, fwrite(file_data, 1, 12288, fp));
2225   fclose(fp);
2226 
2227   fp = fopen(tf.path, "r");
2228   ASSERT_TRUE(fp != nullptr);
2229 
2230   char buffer[8192];
2231   size_t cur_location = 0;
2232   // Small read to populate internal buffer.
2233   ASSERT_EQ(100U, fread(buffer, 1, 100, fp));
2234   ASSERT_EQ(memcmp(file_data, buffer, 100), 0);
2235 
2236   cur_location = static_cast<size_t>(ftell(fp));
2237   // Large read to force reading into the user supplied buffer and bypassing
2238   // the internal buffer.
2239   ASSERT_EQ(8192U, fread(buffer, 1, 8192, fp));
2240   ASSERT_EQ(memcmp(file_data+cur_location, buffer, 8192), 0);
2241 
2242   // Small backwards seek to verify fseek does not reuse the internal buffer.
2243   ASSERT_EQ(0, fseek(fp, -22, SEEK_CUR)) << strerror(errno);
2244   cur_location = static_cast<size_t>(ftell(fp));
2245   ASSERT_EQ(22U, fread(buffer, 1, 22, fp));
2246   ASSERT_EQ(memcmp(file_data+cur_location, buffer, 22), 0);
2247 
2248   fclose(fp);
2249 }
2250 
2251 // https://code.google.com/p/android/issues/detail?id=184847
TEST(STDIO_TEST,fread_EOF_184847)2252 TEST(STDIO_TEST, fread_EOF_184847) {
2253   TemporaryFile tf;
2254   char buf[6] = {0};
2255 
2256   FILE* fw = fopen(tf.path, "w");
2257   ASSERT_TRUE(fw != nullptr);
2258 
2259   FILE* fr = fopen(tf.path, "r");
2260   ASSERT_TRUE(fr != nullptr);
2261 
2262   fwrite("a", 1, 1, fw);
2263   fflush(fw);
2264   ASSERT_EQ(1U, fread(buf, 1, 1, fr));
2265   ASSERT_STREQ("a", buf);
2266 
2267   // 'fr' is now at EOF.
2268   ASSERT_EQ(0U, fread(buf, 1, 1, fr));
2269   ASSERT_TRUE(feof(fr));
2270 
2271   // Write some more...
2272   fwrite("z", 1, 1, fw);
2273   fflush(fw);
2274 
2275   // ...and check that we can read it back.
2276   // (BSD thinks that once a stream has hit EOF, it must always return EOF. SysV disagrees.)
2277   ASSERT_EQ(1U, fread(buf, 1, 1, fr));
2278   ASSERT_STREQ("z", buf);
2279 
2280   // But now we're done.
2281   ASSERT_EQ(0U, fread(buf, 1, 1, fr));
2282 
2283   fclose(fr);
2284   fclose(fw);
2285 }
2286 
TEST(STDIO_TEST,fclose_invalidates_fd)2287 TEST(STDIO_TEST, fclose_invalidates_fd) {
2288   // The typical error we're trying to help people catch involves accessing
2289   // memory after it's been freed. But we know that stdin/stdout/stderr are
2290   // special and don't get deallocated, so this test uses stdin.
2291   ASSERT_EQ(0, fclose(stdin));
2292 
2293   // Even though using a FILE* after close is undefined behavior, I've closed
2294   // this bug as "WAI" too many times. We shouldn't hand out stale fds,
2295   // especially because they might actually correspond to a real stream.
2296   errno = 0;
2297   ASSERT_EQ(-1, fileno(stdin));
2298   ASSERT_ERRNO(EBADF);
2299 }
2300 
TEST(STDIO_TEST,fseek_ftell_unseekable)2301 TEST(STDIO_TEST, fseek_ftell_unseekable) {
2302 #if defined(__BIONIC__) // glibc has fopencookie instead.
2303   auto read_fn = [](void*, char*, int) { return -1; };
2304   FILE* fp = funopen(nullptr, read_fn, nullptr, nullptr, nullptr);
2305   ASSERT_TRUE(fp != nullptr);
2306 
2307   // Check that ftell balks on an unseekable FILE*.
2308   errno = 0;
2309   ASSERT_EQ(-1, ftell(fp));
2310   ASSERT_ERRNO(ESPIPE);
2311 
2312   // SEEK_CUR is rewritten as SEEK_SET internally...
2313   errno = 0;
2314   ASSERT_EQ(-1, fseek(fp, 0, SEEK_CUR));
2315   ASSERT_ERRNO(ESPIPE);
2316 
2317   // ...so it's worth testing the direct seek path too.
2318   errno = 0;
2319   ASSERT_EQ(-1, fseek(fp, 0, SEEK_SET));
2320   ASSERT_ERRNO(ESPIPE);
2321 
2322   fclose(fp);
2323 #else
2324   GTEST_SKIP() << "glibc uses fopencookie instead";
2325 #endif
2326 }
2327 
TEST(STDIO_TEST,funopen_EINVAL)2328 TEST(STDIO_TEST, funopen_EINVAL) {
2329 #if defined(__BIONIC__)
2330   errno = 0;
2331   ASSERT_EQ(nullptr, funopen(nullptr, nullptr, nullptr, nullptr, nullptr));
2332   ASSERT_ERRNO(EINVAL);
2333 #else
2334   GTEST_SKIP() << "glibc uses fopencookie instead";
2335 #endif
2336 }
2337 
TEST(STDIO_TEST,funopen_seek)2338 TEST(STDIO_TEST, funopen_seek) {
2339 #if defined(__BIONIC__)
2340   auto read_fn = [](void*, char*, int) { return -1; };
2341 
2342   auto seek_fn = [](void*, fpos_t, int) -> fpos_t { return 0xfedcba12; };
2343   auto seek64_fn = [](void*, fpos64_t, int) -> fpos64_t { return 0xfedcba12345678; };
2344 
2345   FILE* fp = funopen(nullptr, read_fn, nullptr, seek_fn, nullptr);
2346   ASSERT_TRUE(fp != nullptr);
2347   fpos_t pos;
2348 #if defined(__LP64__)
2349   EXPECT_EQ(0, fgetpos(fp, &pos)) << strerror(errno);
2350   EXPECT_EQ(0xfedcba12LL, pos);
2351 #else
2352   EXPECT_EQ(-1, fgetpos(fp, &pos)) << strerror(errno);
2353   EXPECT_ERRNO(EOVERFLOW);
2354 #endif
2355 
2356   FILE* fp64 = funopen64(nullptr, read_fn, nullptr, seek64_fn, nullptr);
2357   ASSERT_TRUE(fp64 != nullptr);
2358   fpos64_t pos64;
2359   EXPECT_EQ(0, fgetpos64(fp64, &pos64)) << strerror(errno);
2360   EXPECT_EQ(0xfedcba12345678, pos64);
2361 #else
2362   GTEST_SKIP() << "glibc uses fopencookie instead";
2363 #endif
2364 }
2365 
TEST(STDIO_TEST,lots_of_concurrent_files)2366 TEST(STDIO_TEST, lots_of_concurrent_files) {
2367   std::vector<TemporaryFile*> tfs;
2368   std::vector<FILE*> fps;
2369 
2370   for (size_t i = 0; i < 256; ++i) {
2371     TemporaryFile* tf = new TemporaryFile;
2372     tfs.push_back(tf);
2373     FILE* fp = fopen(tf->path, "w+");
2374     fps.push_back(fp);
2375     fprintf(fp, "hello %zu!\n", i);
2376     fflush(fp);
2377   }
2378 
2379   for (size_t i = 0; i < 256; ++i) {
2380     char expected[BUFSIZ];
2381     snprintf(expected, sizeof(expected), "hello %zu!\n", i);
2382 
2383     AssertFileIs(fps[i], expected);
2384     fclose(fps[i]);
2385     delete tfs[i];
2386   }
2387 }
2388 
AssertFileOffsetAt(FILE * fp,off64_t offset)2389 static void AssertFileOffsetAt(FILE* fp, off64_t offset) {
2390   EXPECT_EQ(offset, ftell(fp));
2391   EXPECT_EQ(offset, ftello(fp));
2392   EXPECT_EQ(offset, ftello64(fp));
2393   fpos_t pos;
2394   fpos64_t pos64;
2395   EXPECT_EQ(0, fgetpos(fp, &pos));
2396   EXPECT_EQ(0, fgetpos64(fp, &pos64));
2397 #if defined(__BIONIC__)
2398   EXPECT_EQ(offset, static_cast<off64_t>(pos));
2399   EXPECT_EQ(offset, static_cast<off64_t>(pos64));
2400 #else
2401   GTEST_SKIP() << "glibc's fpos_t is opaque";
2402 #endif
2403 }
2404 
TEST(STDIO_TEST,seek_tell_family_smoke)2405 TEST(STDIO_TEST, seek_tell_family_smoke) {
2406   TemporaryFile tf;
2407   FILE* fp = fdopen(tf.fd, "w+");
2408 
2409   // Initially we should be at 0.
2410   AssertFileOffsetAt(fp, 0);
2411 
2412   // Seek to offset 8192.
2413   ASSERT_EQ(0, fseek(fp, 8192, SEEK_SET));
2414   AssertFileOffsetAt(fp, 8192);
2415   fpos_t eight_k_pos;
2416   ASSERT_EQ(0, fgetpos(fp, &eight_k_pos));
2417 
2418   // Seek forward another 8192...
2419   ASSERT_EQ(0, fseek(fp, 8192, SEEK_CUR));
2420   AssertFileOffsetAt(fp, 8192 + 8192);
2421   fpos64_t sixteen_k_pos64;
2422   ASSERT_EQ(0, fgetpos64(fp, &sixteen_k_pos64));
2423 
2424   // Seek back 8192...
2425   ASSERT_EQ(0, fseek(fp, -8192, SEEK_CUR));
2426   AssertFileOffsetAt(fp, 8192);
2427 
2428   // Since we haven't written anything, the end is also at 0.
2429   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2430   AssertFileOffsetAt(fp, 0);
2431 
2432   // Check that our fpos64_t from 16KiB works...
2433   ASSERT_EQ(0, fsetpos64(fp, &sixteen_k_pos64));
2434   AssertFileOffsetAt(fp, 8192 + 8192);
2435   // ...as does our fpos_t from 8192.
2436   ASSERT_EQ(0, fsetpos(fp, &eight_k_pos));
2437   AssertFileOffsetAt(fp, 8192);
2438 
2439   // Do fseeko and fseeko64 work too?
2440   ASSERT_EQ(0, fseeko(fp, 1234, SEEK_SET));
2441   AssertFileOffsetAt(fp, 1234);
2442   ASSERT_EQ(0, fseeko64(fp, 5678, SEEK_SET));
2443   AssertFileOffsetAt(fp, 5678);
2444 
2445   fclose(fp);
2446 }
2447 
TEST(STDIO_TEST,fseek_fseeko_EINVAL)2448 TEST(STDIO_TEST, fseek_fseeko_EINVAL) {
2449   TemporaryFile tf;
2450   FILE* fp = fdopen(tf.fd, "w+");
2451 
2452   // Bad whence.
2453   errno = 0;
2454   ASSERT_EQ(-1, fseek(fp, 0, 123));
2455   ASSERT_ERRNO(EINVAL);
2456   errno = 0;
2457   ASSERT_EQ(-1, fseeko(fp, 0, 123));
2458   ASSERT_ERRNO(EINVAL);
2459   errno = 0;
2460   ASSERT_EQ(-1, fseeko64(fp, 0, 123));
2461   ASSERT_ERRNO(EINVAL);
2462 
2463   // Bad offset.
2464   errno = 0;
2465   ASSERT_EQ(-1, fseek(fp, -1, SEEK_SET));
2466   ASSERT_ERRNO(EINVAL);
2467   errno = 0;
2468   ASSERT_EQ(-1, fseeko(fp, -1, SEEK_SET));
2469   ASSERT_ERRNO(EINVAL);
2470   errno = 0;
2471   ASSERT_EQ(-1, fseeko64(fp, -1, SEEK_SET));
2472   ASSERT_ERRNO(EINVAL);
2473 
2474   fclose(fp);
2475 }
2476 
TEST(STDIO_TEST,ctermid)2477 TEST(STDIO_TEST, ctermid) {
2478   ASSERT_STREQ("/dev/tty", ctermid(nullptr));
2479 
2480   char buf[L_ctermid] = {};
2481   ASSERT_EQ(buf, ctermid(buf));
2482   ASSERT_STREQ("/dev/tty", buf);
2483 }
2484 
TEST(STDIO_TEST,remove)2485 TEST(STDIO_TEST, remove) {
2486   struct stat sb;
2487 
2488   TemporaryFile tf;
2489   ASSERT_EQ(0, remove(tf.path));
2490   ASSERT_EQ(-1, lstat(tf.path, &sb));
2491   ASSERT_ERRNO(ENOENT);
2492 
2493   TemporaryDir td;
2494   ASSERT_EQ(0, remove(td.path));
2495   ASSERT_EQ(-1, lstat(td.path, &sb));
2496   ASSERT_ERRNO(ENOENT);
2497 
2498   errno = 0;
2499   ASSERT_EQ(-1, remove(tf.path));
2500   ASSERT_ERRNO(ENOENT);
2501 
2502   errno = 0;
2503   ASSERT_EQ(-1, remove(td.path));
2504   ASSERT_ERRNO(ENOENT);
2505 }
2506 
TEST_F(STDIO_DEATHTEST,snprintf_30445072_known_buffer_size)2507 TEST_F(STDIO_DEATHTEST, snprintf_30445072_known_buffer_size) {
2508   char buf[16];
2509   ASSERT_EXIT(snprintf(buf, atol("-1"), "hello"),
2510               testing::KilledBySignal(SIGABRT),
2511 #if defined(NOFORTIFY)
2512               "FORTIFY: vsnprintf: size .* > SSIZE_MAX"
2513 #else
2514               "FORTIFY: vsnprintf: prevented .*-byte write into 16-byte buffer"
2515 #endif
2516               );
2517 }
2518 
TEST_F(STDIO_DEATHTEST,snprintf_30445072_unknown_buffer_size)2519 TEST_F(STDIO_DEATHTEST, snprintf_30445072_unknown_buffer_size) {
2520   std::string buf = "hello";  // So the compiler doesn't know the buffer size.
2521   ASSERT_EXIT(snprintf(&buf[0], atol("-1"), "hello"),
2522               testing::KilledBySignal(SIGABRT),
2523               "FORTIFY: vsnprintf: size .* > SSIZE_MAX");
2524 }
2525 
TEST(STDIO_TEST,sprintf_30445072)2526 TEST(STDIO_TEST, sprintf_30445072) {
2527   std::string buf = "world";
2528   sprintf(&buf[0], "hello");
2529   ASSERT_EQ(buf, "hello");
2530 }
2531 
TEST(STDIO_TEST,printf_m)2532 TEST(STDIO_TEST, printf_m) {
2533   errno = 0;
2534   EXPECT_SNPRINTF("<Success>", "<%m>");
2535   errno = -1;
2536   EXPECT_SNPRINTF("<Unknown error -1>", "<%m>");
2537   errno = EINVAL;
2538   EXPECT_SNPRINTF("<Invalid argument>", "<%m>");
2539 }
2540 
TEST(STDIO_TEST,wprintf_m)2541 TEST(STDIO_TEST, wprintf_m) {
2542   errno = 0;
2543   EXPECT_SWPRINTF(L"<Success>", L"<%m>");
2544   errno = -1;
2545   EXPECT_SWPRINTF(L"<Unknown error -1>", L"<%m>");
2546   errno = EINVAL;
2547   EXPECT_SWPRINTF(L"<Invalid argument>", L"<%m>");
2548 }
2549 
TEST(STDIO_TEST,printf_hash_m)2550 TEST(STDIO_TEST, printf_hash_m) {
2551   errno = 0;
2552   EXPECT_SNPRINTF("<0>", "<%#m>");
2553   errno = -1;
2554   EXPECT_SNPRINTF("<-1>", "<%#m>");
2555   errno = EINVAL;
2556   EXPECT_SNPRINTF("<EINVAL>", "<%#m>");
2557 }
2558 
TEST(STDIO_TEST,wprintf_hash_m)2559 TEST(STDIO_TEST, wprintf_hash_m) {
2560   errno = 0;
2561   EXPECT_SWPRINTF(L"<0>", L"<%#m>");
2562   errno = -1;
2563   EXPECT_SWPRINTF(L"<-1>", L"<%#m>");
2564   errno = EINVAL;
2565   EXPECT_SWPRINTF(L"<EINVAL>", L"<%#m>");
2566 }
2567 
TEST(STDIO_TEST,printf_m_does_not_clobber_strerror)2568 TEST(STDIO_TEST, printf_m_does_not_clobber_strerror) {
2569   const char* m = strerror(-1);
2570   ASSERT_STREQ("Unknown error -1", m);
2571   errno = -2;
2572   EXPECT_SNPRINTF("<Unknown error -2>", "<%m>");
2573   ASSERT_STREQ("Unknown error -1", m);
2574 }
2575 
TEST(STDIO_TEST,wprintf_m_does_not_clobber_strerror)2576 TEST(STDIO_TEST, wprintf_m_does_not_clobber_strerror) {
2577   const char* m = strerror(-1);
2578   ASSERT_STREQ("Unknown error -1", m);
2579   errno = -2;
2580   EXPECT_SWPRINTF(L"<Unknown error -2>", L"<%m>");
2581   ASSERT_STREQ("Unknown error -1", m);
2582 }
2583 
TEST(STDIO_TEST,fopen_append_mode_and_ftell)2584 TEST(STDIO_TEST, fopen_append_mode_and_ftell) {
2585   TemporaryFile tf;
2586   SetFileTo(tf.path, "0123456789");
2587   FILE* fp = fopen(tf.path, "a");
2588   EXPECT_EQ(10, ftell(fp));
2589   ASSERT_EQ(0, fseek(fp, 2, SEEK_SET));
2590   EXPECT_EQ(2, ftell(fp));
2591   ASSERT_NE(EOF, fputs("xxx", fp));
2592   ASSERT_EQ(0, fflush(fp));
2593   EXPECT_EQ(13, ftell(fp));
2594   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2595   EXPECT_EQ(13, ftell(fp));
2596   ASSERT_EQ(0, fclose(fp));
2597   AssertFileIs(tf.path, "0123456789xxx");
2598 }
2599 
TEST(STDIO_TEST,fdopen_append_mode_and_ftell)2600 TEST(STDIO_TEST, fdopen_append_mode_and_ftell) {
2601   TemporaryFile tf;
2602   SetFileTo(tf.path, "0123456789");
2603   int fd = open(tf.path, O_RDWR);
2604   ASSERT_NE(-1, fd);
2605   // POSIX: "The file position indicator associated with the new stream is set to the position
2606   // indicated by the file offset associated with the file descriptor."
2607   ASSERT_EQ(4, lseek(fd, 4, SEEK_SET));
2608   FILE* fp = fdopen(fd, "a");
2609   EXPECT_EQ(4, ftell(fp));
2610   ASSERT_EQ(0, fseek(fp, 2, SEEK_SET));
2611   EXPECT_EQ(2, ftell(fp));
2612   ASSERT_NE(EOF, fputs("xxx", fp));
2613   ASSERT_EQ(0, fflush(fp));
2614   EXPECT_EQ(13, ftell(fp));
2615   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2616   EXPECT_EQ(13, ftell(fp));
2617   ASSERT_EQ(0, fclose(fp));
2618   AssertFileIs(tf.path, "0123456789xxx");
2619 }
2620 
TEST(STDIO_TEST,freopen_append_mode_and_ftell)2621 TEST(STDIO_TEST, freopen_append_mode_and_ftell) {
2622   TemporaryFile tf;
2623   SetFileTo(tf.path, "0123456789");
2624   FILE* other_fp = fopen("/proc/version", "r");
2625   FILE* fp = freopen(tf.path, "a", other_fp);
2626   EXPECT_EQ(10, ftell(fp));
2627   ASSERT_EQ(0, fseek(fp, 2, SEEK_SET));
2628   EXPECT_EQ(2, ftell(fp));
2629   ASSERT_NE(EOF, fputs("xxx", fp));
2630   ASSERT_EQ(0, fflush(fp));
2631   EXPECT_EQ(13, ftell(fp));
2632   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2633   EXPECT_EQ(13, ftell(fp));
2634   ASSERT_EQ(0, fclose(fp));
2635   AssertFileIs(tf.path, "0123456789xxx");
2636 }
2637 
TEST(STDIO_TEST,constants)2638 TEST(STDIO_TEST, constants) {
2639   ASSERT_LE(FILENAME_MAX, PATH_MAX);
2640   ASSERT_EQ(L_tmpnam, PATH_MAX);
2641 }
2642 
TEST(STDIO_TEST,perror)2643 TEST(STDIO_TEST, perror) {
2644   ExecTestHelper eth;
2645   eth.Run([&]() { errno = EINVAL; perror("a b c"); exit(0); }, 0, "a b c: Invalid argument\n");
2646   eth.Run([&]() { errno = EINVAL; perror(nullptr); exit(0); }, 0, "Invalid argument\n");
2647   eth.Run([&]() { errno = EINVAL; perror(""); exit(0); }, 0, "Invalid argument\n");
2648 }
2649 
TEST(STDIO_TEST,puts)2650 TEST(STDIO_TEST, puts) {
2651   ExecTestHelper eth;
2652   eth.Run([&]() { exit(puts("a b c")); }, 0, "a b c\n");
2653 }
2654 
TEST(STDIO_TEST,putchar)2655 TEST(STDIO_TEST, putchar) {
2656   ExecTestHelper eth;
2657   eth.Run([&]() { exit(putchar('A')); }, 65, "A");
2658 }
2659 
TEST(STDIO_TEST,putchar_unlocked)2660 TEST(STDIO_TEST, putchar_unlocked) {
2661   ExecTestHelper eth;
2662   eth.Run([&]() { exit(putchar('B')); }, 66, "B");
2663 }
2664 
TEST(STDIO_TEST,unlocked)2665 TEST(STDIO_TEST, unlocked) {
2666   TemporaryFile tf;
2667 
2668   FILE* fp = fopen(tf.path, "w+");
2669   ASSERT_TRUE(fp != nullptr);
2670 
2671   clearerr_unlocked(fp);
2672   ASSERT_FALSE(feof_unlocked(fp));
2673   ASSERT_FALSE(ferror_unlocked(fp));
2674 
2675   ASSERT_EQ(fileno(fp), fileno_unlocked(fp));
2676 
2677   ASSERT_NE(EOF, putc_unlocked('a', fp));
2678   ASSERT_NE(EOF, putc('b', fp));
2679   ASSERT_NE(EOF, fputc_unlocked('c', fp));
2680   ASSERT_NE(EOF, fputc('d', fp));
2681 
2682   rewind(fp);
2683   ASSERT_EQ('a', getc_unlocked(fp));
2684   ASSERT_EQ('b', getc(fp));
2685   ASSERT_EQ('c', fgetc_unlocked(fp));
2686   ASSERT_EQ('d', fgetc(fp));
2687 
2688   rewind(fp);
2689   ASSERT_EQ(2U, fwrite_unlocked("AB", 1, 2, fp));
2690   ASSERT_EQ(2U, fwrite("CD", 1, 2, fp));
2691   ASSERT_EQ(0, fflush_unlocked(fp));
2692 
2693   rewind(fp);
2694   char buf[BUFSIZ] = {};
2695   ASSERT_EQ(2U, fread_unlocked(&buf[0], 1, 2, fp));
2696   ASSERT_EQ(2U, fread(&buf[2], 1, 2, fp));
2697   ASSERT_STREQ("ABCD", buf);
2698 
2699   rewind(fp);
2700   ASSERT_NE(EOF, fputs("hello ", fp));
2701   ASSERT_NE(EOF, fputs_unlocked("world", fp));
2702   ASSERT_NE(EOF, fputc('\n', fp));
2703 
2704   rewind(fp);
2705   ASSERT_TRUE(fgets_unlocked(buf, sizeof(buf), fp) != nullptr);
2706   ASSERT_STREQ("hello world\n", buf);
2707 
2708   ASSERT_EQ(0, fclose(fp));
2709 }
2710 
TEST(STDIO_TEST,fseek_64bit)2711 TEST(STDIO_TEST, fseek_64bit) {
2712   TemporaryFile tf;
2713   FILE* fp = fopen64(tf.path, "w+");
2714   ASSERT_TRUE(fp != nullptr);
2715   ASSERT_EQ(0, fseeko64(fp, 0x2'0000'0000, SEEK_SET));
2716   ASSERT_EQ(0x2'0000'0000, ftello64(fp));
2717   ASSERT_EQ(0, fseeko64(fp, 0x1'0000'0000, SEEK_CUR));
2718   ASSERT_EQ(0x3'0000'0000, ftello64(fp));
2719   ASSERT_EQ(0, fclose(fp));
2720 }
2721 
2722 // POSIX requires that fseek/fseeko fail with EOVERFLOW if the new file offset
2723 // isn't representable in long/off_t.
TEST(STDIO_TEST,fseek_overflow_32bit)2724 TEST(STDIO_TEST, fseek_overflow_32bit) {
2725   TemporaryFile tf;
2726   FILE* fp = fopen64(tf.path, "w+");
2727   ASSERT_EQ(0, ftruncate64(fileno(fp), 0x2'0000'0000));
2728 
2729   // Bionic implements overflow checking for SEEK_CUR, but glibc doesn't.
2730 #if defined(__BIONIC__) && !defined(__LP64__)
2731   ASSERT_EQ(0, fseek(fp, 0x7fff'ffff, SEEK_SET));
2732   ASSERT_EQ(-1, fseek(fp, 1, SEEK_CUR));
2733   ASSERT_ERRNO(EOVERFLOW);
2734 #endif
2735 
2736   // Neither Bionic nor glibc implement the overflow checking for SEEK_END.
2737   // (Aside: FreeBSD's libc is an example of a libc that checks both SEEK_CUR
2738   // and SEEK_END -- many C libraries check neither.)
2739   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2740   ASSERT_EQ(0x2'0000'0000, ftello64(fp));
2741 
2742   fclose(fp);
2743 }
2744 
TEST(STDIO_TEST,dev_std_files)2745 TEST(STDIO_TEST, dev_std_files) {
2746   // POSIX only mentions /dev/stdout, but we should have all three (http://b/31824379).
2747   char path[PATH_MAX];
2748   ssize_t length = readlink("/dev/stdin", path, sizeof(path));
2749   ASSERT_LT(0, length);
2750   ASSERT_EQ("/proc/self/fd/0", std::string(path, length));
2751 
2752   length = readlink("/dev/stdout", path, sizeof(path));
2753   ASSERT_LT(0, length);
2754   ASSERT_EQ("/proc/self/fd/1", std::string(path, length));
2755 
2756   length = readlink("/dev/stderr", path, sizeof(path));
2757   ASSERT_LT(0, length);
2758   ASSERT_EQ("/proc/self/fd/2", std::string(path, length));
2759 }
2760 
TEST(STDIO_TEST,fread_with_locked_file)2761 TEST(STDIO_TEST, fread_with_locked_file) {
2762   // Reading an unbuffered/line-buffered file from one thread shouldn't block on
2763   // files locked on other threads, even if it flushes some line-buffered files.
2764   FILE* fp1 = fopen("/dev/zero", "r");
2765   ASSERT_TRUE(fp1 != nullptr);
2766   flockfile(fp1);
2767 
2768   std::thread([] {
2769     for (int mode : { _IONBF, _IOLBF }) {
2770       FILE* fp2 = fopen("/dev/zero", "r");
2771       ASSERT_TRUE(fp2 != nullptr);
2772       setvbuf(fp2, nullptr, mode, 0);
2773       ASSERT_EQ('\0', fgetc(fp2));
2774       fclose(fp2);
2775     }
2776   }).join();
2777 
2778   funlockfile(fp1);
2779   fclose(fp1);
2780 }
2781 
TEST(STDIO_TEST,SEEK_macros)2782 TEST(STDIO_TEST, SEEK_macros) {
2783   ASSERT_EQ(0, SEEK_SET);
2784   ASSERT_EQ(1, SEEK_CUR);
2785   ASSERT_EQ(2, SEEK_END);
2786   ASSERT_EQ(3, SEEK_DATA);
2787   ASSERT_EQ(4, SEEK_HOLE);
2788   // So we'll notice if Linux grows another constant in <linux/fs.h>...
2789   ASSERT_EQ(SEEK_MAX, SEEK_HOLE);
2790 }
2791 
TEST(STDIO_TEST,rename)2792 TEST(STDIO_TEST, rename) {
2793   TemporaryDir td;
2794   std::string old_path = td.path + "/old"s;
2795   std::string new_path = td.path + "/new"s;
2796 
2797   // Create the file, check it exists.
2798   ASSERT_EQ(0, close(creat(old_path.c_str(), 0666)));
2799   struct stat sb;
2800   ASSERT_EQ(0, stat(old_path.c_str(), &sb));
2801   ASSERT_EQ(-1, stat(new_path.c_str(), &sb));
2802 
2803   // Rename and check it moved.
2804   ASSERT_EQ(0, rename(old_path.c_str(), new_path.c_str()));
2805   ASSERT_EQ(-1, stat(old_path.c_str(), &sb));
2806   ASSERT_EQ(0, stat(new_path.c_str(), &sb));
2807 }
2808 
TEST(STDIO_TEST,renameat)2809 TEST(STDIO_TEST, renameat) {
2810   TemporaryDir td;
2811   android::base::unique_fd dirfd{open(td.path, O_PATH)};
2812   std::string old_path = td.path + "/old"s;
2813   std::string new_path = td.path + "/new"s;
2814 
2815   // Create the file, check it exists.
2816   ASSERT_EQ(0, close(creat(old_path.c_str(), 0666)));
2817   struct stat sb;
2818   ASSERT_EQ(0, stat(old_path.c_str(), &sb));
2819   ASSERT_EQ(-1, stat(new_path.c_str(), &sb));
2820 
2821   // Rename and check it moved.
2822   ASSERT_EQ(0, renameat(dirfd, "old", dirfd, "new"));
2823   ASSERT_EQ(-1, stat(old_path.c_str(), &sb));
2824   ASSERT_EQ(0, stat(new_path.c_str(), &sb));
2825 }
2826 
TEST(STDIO_TEST,renameat2)2827 TEST(STDIO_TEST, renameat2) {
2828 #if defined(__GLIBC__) || defined(ANDROID_HOST_MUSL)
2829   GTEST_SKIP() << "glibc doesn't have renameat2 until 2.28 and musl doesn't have renameat2";
2830 #else
2831   TemporaryDir td;
2832   android::base::unique_fd dirfd{open(td.path, O_PATH)};
2833   std::string old_path = td.path + "/old"s;
2834   std::string new_path = td.path + "/new"s;
2835 
2836   // Create the file, check it exists.
2837   ASSERT_EQ(0, close(creat(old_path.c_str(), 0666)));
2838   struct stat sb;
2839   ASSERT_EQ(0, stat(old_path.c_str(), &sb));
2840   ASSERT_EQ(-1, stat(new_path.c_str(), &sb));
2841 
2842   // Rename and check it moved.
2843   ASSERT_EQ(0, renameat2(dirfd, "old", dirfd, "new", 0));
2844   ASSERT_EQ(-1, stat(old_path.c_str(), &sb));
2845   ASSERT_EQ(0, stat(new_path.c_str(), &sb));
2846 
2847   // After this, both "old" and "new" exist.
2848   ASSERT_EQ(0, close(creat(old_path.c_str(), 0666)));
2849 
2850   // Rename and check it moved.
2851   ASSERT_EQ(-1, renameat2(dirfd, "old", dirfd, "new", RENAME_NOREPLACE));
2852   ASSERT_ERRNO(EEXIST);
2853 #endif
2854 }
2855 
TEST(STDIO_TEST,renameat2_flags)2856 TEST(STDIO_TEST, renameat2_flags) {
2857 #if defined(__GLIBC__)
2858   GTEST_SKIP() << "glibc doesn't have renameat2 until 2.28";
2859 #else
2860  ASSERT_NE(0, RENAME_EXCHANGE);
2861  ASSERT_NE(0, RENAME_NOREPLACE);
2862  ASSERT_NE(0, RENAME_WHITEOUT);
2863 #endif
2864 }
2865 
TEST(STDIO_TEST,fdopen_failures)2866 TEST(STDIO_TEST, fdopen_failures) {
2867   FILE* fp;
2868   int fd = open("/proc/version", O_RDONLY);
2869   ASSERT_TRUE(fd != -1);
2870 
2871   // Nonsense mode.
2872   errno = 0;
2873   fp = fdopen(fd, "nonsense");
2874   ASSERT_TRUE(fp == nullptr);
2875   ASSERT_ERRNO(EINVAL);
2876 
2877   // Mode that isn't a subset of the fd's actual mode.
2878   errno = 0;
2879   fp = fdopen(fd, "w");
2880   ASSERT_TRUE(fp == nullptr);
2881   ASSERT_ERRNO(EINVAL);
2882 
2883   // Can't set append on the underlying fd.
2884   errno = 0;
2885   fp = fdopen(fd, "a");
2886   ASSERT_TRUE(fp == nullptr);
2887   ASSERT_ERRNO(EINVAL);
2888 
2889   // Bad fd.
2890   errno = 0;
2891   fp = fdopen(-1, "re");
2892   ASSERT_TRUE(fp == nullptr);
2893   ASSERT_ERRNO(EBADF);
2894 
2895   close(fd);
2896 }
2897 
TEST(STDIO_TEST,fmemopen_invalid_mode)2898 TEST(STDIO_TEST, fmemopen_invalid_mode) {
2899   errno = 0;
2900   FILE* fp = fmemopen(nullptr, 16, "nonsense");
2901   ASSERT_TRUE(fp == nullptr);
2902   ASSERT_ERRNO(EINVAL);
2903 }
2904 
TEST(STDIO_TEST,fopen_invalid_mode)2905 TEST(STDIO_TEST, fopen_invalid_mode) {
2906   errno = 0;
2907   FILE* fp = fopen("/proc/version", "nonsense");
2908   ASSERT_TRUE(fp == nullptr);
2909   ASSERT_ERRNO(EINVAL);
2910 }
2911 
TEST(STDIO_TEST,freopen_invalid_mode)2912 TEST(STDIO_TEST, freopen_invalid_mode) {
2913   FILE* fp = fopen("/proc/version", "re");
2914   ASSERT_TRUE(fp != nullptr);
2915 
2916   errno = 0;
2917   fp = freopen("/proc/version", "nonsense", fp);
2918   ASSERT_TRUE(fp == nullptr);
2919   ASSERT_ERRNO(EINVAL);
2920 }
2921 
TEST(STDIO_TEST,asprintf_smoke)2922 TEST(STDIO_TEST, asprintf_smoke) {
2923   char* p = nullptr;
2924   ASSERT_EQ(11, asprintf(&p, "hello %s", "world"));
2925   ASSERT_STREQ("hello world", p);
2926   free(p);
2927 }
2928 
TEST(STDIO_TEST,fopen_ENOENT)2929 TEST(STDIO_TEST, fopen_ENOENT) {
2930   errno = 0;
2931   FILE* fp = fopen("/proc/does-not-exist", "re");
2932   ASSERT_TRUE(fp == nullptr);
2933   ASSERT_ERRNO(ENOENT);
2934 }
2935 
tempnam_test(bool has_TMPDIR,const char * dir,const char * prefix,const char * re)2936 static void tempnam_test(bool has_TMPDIR, const char* dir, const char* prefix, const char* re) {
2937   if (has_TMPDIR) {
2938     setenv("TMPDIR", "/my/tmp/dir", 1);
2939   } else {
2940     unsetenv("TMPDIR");
2941   }
2942   char* s1 = tempnam(dir, prefix);
2943   char* s2 = tempnam(dir, prefix);
2944   ASSERT_MATCH(s1, re);
2945   ASSERT_MATCH(s2, re);
2946   ASSERT_STRNE(s1, s2);
2947   free(s1);
2948   free(s2);
2949 }
2950 
TEST(STDIO_TEST,tempnam__system_directory_system_prefix_with_TMPDIR)2951 TEST(STDIO_TEST, tempnam__system_directory_system_prefix_with_TMPDIR) {
2952   tempnam_test(true, nullptr, nullptr, "^/my/tmp/dir/.*");
2953 }
2954 
TEST(STDIO_TEST,tempnam__system_directory_system_prefix_without_TMPDIR)2955 TEST(STDIO_TEST, tempnam__system_directory_system_prefix_without_TMPDIR) {
2956   tempnam_test(false, nullptr, nullptr, "^/data/local/tmp/.*");
2957 }
2958 
TEST(STDIO_TEST,tempnam__system_directory_user_prefix_with_TMPDIR)2959 TEST(STDIO_TEST, tempnam__system_directory_user_prefix_with_TMPDIR) {
2960   tempnam_test(true, nullptr, "prefix", "^/my/tmp/dir/prefix.*");
2961 }
2962 
TEST(STDIO_TEST,tempnam__system_directory_user_prefix_without_TMPDIR)2963 TEST(STDIO_TEST, tempnam__system_directory_user_prefix_without_TMPDIR) {
2964   tempnam_test(false, nullptr, "prefix", "^/data/local/tmp/prefix.*");
2965 }
2966 
TEST(STDIO_TEST,tempnam__user_directory_system_prefix_with_TMPDIR)2967 TEST(STDIO_TEST, tempnam__user_directory_system_prefix_with_TMPDIR) {
2968   tempnam_test(true, "/a/b/c", nullptr, "^/my/tmp/dir/.*");
2969 }
2970 
TEST(STDIO_TEST,tempnam__user_directory_system_prefix_without_TMPDIR)2971 TEST(STDIO_TEST, tempnam__user_directory_system_prefix_without_TMPDIR) {
2972   tempnam_test(false, "/a/b/c", nullptr, "^/a/b/c/.*");
2973 }
2974 
TEST(STDIO_TEST,tempnam__user_directory_user_prefix_with_TMPDIR)2975 TEST(STDIO_TEST, tempnam__user_directory_user_prefix_with_TMPDIR) {
2976   tempnam_test(true, "/a/b/c", "prefix", "^/my/tmp/dir/prefix.*");
2977 }
2978 
TEST(STDIO_TEST,tempnam__user_directory_user_prefix_without_TMPDIR)2979 TEST(STDIO_TEST, tempnam__user_directory_user_prefix_without_TMPDIR) {
2980   tempnam_test(false, "/a/b/c", "prefix", "^/a/b/c/prefix.*");
2981 }
2982 
tmpnam_test(char * s)2983 static void tmpnam_test(char* s) {
2984   char s1[L_tmpnam], s2[L_tmpnam];
2985 
2986   strcpy(s1, tmpnam(s));
2987   strcpy(s2, tmpnam(s));
2988   ASSERT_MATCH(s1, "/tmp/.*");
2989   ASSERT_MATCH(s2, "/tmp/.*");
2990   ASSERT_STRNE(s1, s2);
2991 }
2992 
TEST(STDIO_TEST,tmpnam)2993 TEST(STDIO_TEST, tmpnam) {
2994   tmpnam_test(nullptr);
2995 }
2996 
TEST(STDIO_TEST,tmpnam_buf)2997 TEST(STDIO_TEST, tmpnam_buf) {
2998   char buf[L_tmpnam];
2999   tmpnam_test(buf);
3000 }
3001 
TEST(STDIO_TEST,freopen_null_filename_mode)3002 TEST(STDIO_TEST, freopen_null_filename_mode) {
3003   TemporaryFile tf;
3004   FILE* fp = fopen(tf.path, "r");
3005   ASSERT_TRUE(fp != nullptr);
3006 
3007   // "r" = O_RDONLY
3008   char buf[1];
3009   ASSERT_EQ(0, read(fileno(fp), buf, 1));
3010   ASSERT_EQ(-1, write(fileno(fp), "hello", 1));
3011   // "r+" = O_RDWR
3012   fp = freopen(nullptr, "r+", fp);
3013   ASSERT_EQ(0, read(fileno(fp), buf, 1));
3014   ASSERT_EQ(1, write(fileno(fp), "hello", 1));
3015   // "w" = O_WRONLY
3016   fp = freopen(nullptr, "w", fp);
3017   ASSERT_EQ(-1, read(fileno(fp), buf, 1));
3018   ASSERT_EQ(1, write(fileno(fp), "hello", 1));
3019 
3020   fclose(fp);
3021 }
3022 
3023 #if defined(__LP64__)
GetTotalRamGiB()3024 static int64_t GetTotalRamGiB() {
3025   struct sysinfo si;
3026   sysinfo(&si);
3027   return (static_cast<int64_t>(si.totalram) * si.mem_unit) / 1024 / 1024 / 1024;
3028 }
3029 #endif
3030 
TEST(STDIO_TEST,fread_int_overflow)3031 TEST(STDIO_TEST, fread_int_overflow) {
3032 #if defined(__LP64__)
3033   if (GetTotalRamGiB() <= 4) GTEST_SKIP() << "not enough memory";
3034 
3035   const size_t too_big_for_an_int = 0x80000000ULL;
3036   std::vector<char> buf(too_big_for_an_int);
3037   std::unique_ptr<FILE, decltype(&fclose)> fp{fopen("/dev/zero", "re"), fclose};
3038   ASSERT_EQ(too_big_for_an_int, fread(&buf[0], 1, too_big_for_an_int, fp.get()));
3039 #else
3040   GTEST_SKIP() << "32-bit can't allocate 2GiB";
3041 #endif
3042 }
3043 
TEST(STDIO_TEST,fwrite_int_overflow)3044 TEST(STDIO_TEST, fwrite_int_overflow) {
3045 #if defined(__LP64__)
3046   if (GetTotalRamGiB() <= 4) GTEST_SKIP() << "not enough memory";
3047 
3048   const size_t too_big_for_an_int = 0x80000000ULL;
3049   std::vector<char> buf(too_big_for_an_int);
3050   std::unique_ptr<FILE, decltype(&fclose)> fp{fopen("/dev/null", "we"), fclose};
3051   ASSERT_EQ(too_big_for_an_int, fwrite(&buf[0], 1, too_big_for_an_int, fp.get()));
3052 #else
3053   GTEST_SKIP() << "32-bit can't allocate 2GiB";
3054 #endif
3055 }
3056 
TEST(STDIO_TEST,snprintf_b_B)3057 TEST(STDIO_TEST, snprintf_b_B) {
3058 #if defined(__BIONIC__)
3059   uint8_t b = 5;
3060   EXPECT_SNPRINTF("<101>", "<%" PRIb8 ">", b);
3061   EXPECT_SNPRINTF("<101>", "<%" PRIB8 ">", b);
3062   EXPECT_SNPRINTF("<00000101>", "<%08" PRIb8 ">", b);
3063   EXPECT_SNPRINTF("<00000101>", "<%08" PRIB8 ">", b);
3064 
3065   uint16_t s = 0xaaaa;
3066   EXPECT_SNPRINTF("<1010101010101010>", "<%" PRIb16 ">", s);
3067   EXPECT_SNPRINTF("<1010101010101010>", "<%" PRIB16 ">", s);
3068   EXPECT_SNPRINTF("<0b1010101010101010>", "<%#" PRIb16 ">", s);
3069   EXPECT_SNPRINTF("<0B1010101010101010>", "<%#" PRIB16 ">", s);
3070 
3071   EXPECT_SNPRINTF("<10101010101010101010101010101010>", "<%" PRIb32 ">", 0xaaaaaaaa);
3072   EXPECT_SNPRINTF("<10101010101010101010101010101010>", "<%" PRIB32 ">", 0xaaaaaaaa);
3073   EXPECT_SNPRINTF("<0b10101010101010101010101010101010>", "<%#" PRIb32 ">", 0xaaaaaaaa);
3074   EXPECT_SNPRINTF("<0B10101010101010101010101010101010>", "<%#" PRIB32 ">", 0xaaaaaaaa);
3075 
3076   // clang doesn't like "%lb" (https://github.com/llvm/llvm-project/issues/62247)
3077 #pragma clang diagnostic push
3078 #pragma clang diagnostic ignored "-Wformat"
3079   EXPECT_SNPRINTF("<1010101010101010101010101010101010101010101010101010101010101010>",
3080                   "<%" PRIb64 ">", 0xaaaaaaaa'aaaaaaaa);
3081   EXPECT_SNPRINTF("<1010101010101010101010101010101010101010101010101010101010101010>",
3082                   "<%" PRIB64 ">", 0xaaaaaaaa'aaaaaaaa);
3083   EXPECT_SNPRINTF("<0b1010101010101010101010101010101010101010101010101010101010101010>",
3084                   "<%#" PRIb64 ">", 0xaaaaaaaa'aaaaaaaa);
3085   EXPECT_SNPRINTF("<0B1010101010101010101010101010101010101010101010101010101010101010>",
3086                   "<%#" PRIB64 ">", 0xaaaaaaaa'aaaaaaaa);
3087 #pragma clang diagnostic pop
3088 
3089   EXPECT_SNPRINTF("<0>", "<%#b>", 0);
3090   EXPECT_SNPRINTF("<0>", "<%#B>", 0);
3091 #else
3092   GTEST_SKIP() << "no %b in glibc";
3093 #endif
3094 }
3095 
TEST(STDIO_TEST,swprintf_b_B)3096 TEST(STDIO_TEST, swprintf_b_B) {
3097 #if defined(__BIONIC__)
3098   uint8_t b = 5;
3099   EXPECT_SWPRINTF(L"<101>", L"<%" PRIb8 ">", b);
3100   EXPECT_SWPRINTF(L"<101>", L"<%" PRIB8 ">", b);
3101   EXPECT_SWPRINTF(L"<0b101>", L"<%#" PRIb8 ">", b);
3102   EXPECT_SWPRINTF(L"<0B101>", L"<%#" PRIB8 ">", b);
3103   EXPECT_SWPRINTF(L"<00000101>", L"<%08" PRIb8 ">", b);
3104   EXPECT_SWPRINTF(L"<00000101>", L"<%08" PRIB8 ">", b);
3105 
3106   uint16_t s = 0xaaaa;
3107   EXPECT_SWPRINTF(L"<1010101010101010>", L"<%" PRIb16 ">", s);
3108   EXPECT_SWPRINTF(L"<1010101010101010>", L"<%" PRIB16 ">", s);
3109   EXPECT_SWPRINTF(L"<0b1010101010101010>", L"<%#" PRIb16 ">", s);
3110   EXPECT_SWPRINTF(L"<0B1010101010101010>", L"<%#" PRIB16 ">", s);
3111 
3112   EXPECT_SWPRINTF(L"<10101010101010101010101010101010>", L"<%" PRIb32 ">", 0xaaaaaaaa);
3113   EXPECT_SWPRINTF(L"<10101010101010101010101010101010>", L"<%" PRIB32 ">", 0xaaaaaaaa);
3114   EXPECT_SWPRINTF(L"<0b10101010101010101010101010101010>", L"<%#" PRIb32 ">", 0xaaaaaaaa);
3115   EXPECT_SWPRINTF(L"<0B10101010101010101010101010101010>", L"<%#" PRIB32 ">", 0xaaaaaaaa);
3116 
3117   // clang doesn't like "%lb" (https://github.com/llvm/llvm-project/issues/62247)
3118 #pragma clang diagnostic push
3119 #pragma clang diagnostic ignored "-Wformat"
3120   EXPECT_SWPRINTF(L"<1010101010101010101010101010101010101010101010101010101010101010>",
3121                   L"<%" PRIb64 ">", 0xaaaaaaaa'aaaaaaaa);
3122   EXPECT_SWPRINTF(L"<1010101010101010101010101010101010101010101010101010101010101010>",
3123                   L"<%" PRIB64 ">", 0xaaaaaaaa'aaaaaaaa);
3124   EXPECT_SWPRINTF(L"<0b1010101010101010101010101010101010101010101010101010101010101010>",
3125                   L"<%#" PRIb64 ">", 0xaaaaaaaa'aaaaaaaa);
3126   EXPECT_SWPRINTF(L"<0B1010101010101010101010101010101010101010101010101010101010101010>",
3127                   L"<%#" PRIB64 ">", 0xaaaaaaaa'aaaaaaaa);
3128 #pragma clang diagnostic pop
3129 
3130   EXPECT_SWPRINTF(L"<0>", L"<%#b>", 0);
3131   EXPECT_SWPRINTF(L"<0>", L"<%#B>", 0);
3132 #else
3133   GTEST_SKIP() << "no %b in glibc";
3134 #endif
3135 }
3136 
TEST(STDIO_TEST,scanf_i_decimal)3137 TEST(STDIO_TEST, scanf_i_decimal) {
3138   int i;
3139   EXPECT_EQ(1, sscanf("<123789>", "<%i>", &i));
3140   EXPECT_EQ(123789, i);
3141 
3142   long long int lli;
3143   char ch;
3144   EXPECT_EQ(2, sscanf("1234567890abcdefg", "%lli%c", &lli, &ch));
3145   EXPECT_EQ(1234567890, lli);
3146   EXPECT_EQ('a', ch);
3147 }
3148 
TEST(STDIO_TEST,scanf_i_hex)3149 TEST(STDIO_TEST, scanf_i_hex) {
3150   int i;
3151   EXPECT_EQ(1, sscanf("<0x123abf>", "<%i>", &i));
3152   EXPECT_EQ(0x123abf, i);
3153 
3154   long long int lli;
3155   char ch;
3156   EXPECT_EQ(2, sscanf("0x1234567890abcdefg", "%lli%c", &lli, &ch));
3157   EXPECT_EQ(0x1234567890abcdefLL, lli);
3158   EXPECT_EQ('g', ch);
3159 }
3160 
TEST(STDIO_TEST,scanf_i_octal)3161 TEST(STDIO_TEST, scanf_i_octal) {
3162   int i;
3163   EXPECT_EQ(1, sscanf("<01234567>", "<%i>", &i));
3164   EXPECT_EQ(01234567, i);
3165 
3166   long long int lli;
3167   char ch;
3168   EXPECT_EQ(2, sscanf("010234567890abcdefg", "%lli%c", &lli, &ch));
3169   EXPECT_EQ(010234567, lli);
3170   EXPECT_EQ('8', ch);
3171 }
3172 
TEST(STDIO_TEST,scanf_i_binary)3173 TEST(STDIO_TEST, scanf_i_binary) {
3174   int i;
3175   EXPECT_EQ(1, sscanf("<0b101>", "<%i>", &i));
3176   EXPECT_EQ(0b101, i);
3177 
3178   long long int lli;
3179   char ch;
3180   EXPECT_EQ(2, sscanf("0b10234567890abcdefg", "%lli%c", &lli, &ch));
3181   EXPECT_EQ(0b10, lli);
3182   EXPECT_EQ('2', ch);
3183 }
3184 
TEST(STDIO_TEST,wscanf_i_decimal)3185 TEST(STDIO_TEST, wscanf_i_decimal) {
3186   int i;
3187   EXPECT_EQ(1, swscanf(L"<123789>", L"<%i>", &i));
3188   EXPECT_EQ(123789, i);
3189 
3190   long long int lli;
3191   char ch;
3192   EXPECT_EQ(2, swscanf(L"1234567890abcdefg", L"%lli%c", &lli, &ch));
3193   EXPECT_EQ(1234567890, lli);
3194   EXPECT_EQ('a', ch);
3195 }
3196 
TEST(STDIO_TEST,wscanf_i_hex)3197 TEST(STDIO_TEST, wscanf_i_hex) {
3198   int i;
3199   EXPECT_EQ(1, swscanf(L"<0x123abf>", L"<%i>", &i));
3200   EXPECT_EQ(0x123abf, i);
3201 
3202   long long int lli;
3203   char ch;
3204   EXPECT_EQ(2, swscanf(L"0x1234567890abcdefg", L"%lli%c", &lli, &ch));
3205   EXPECT_EQ(0x1234567890abcdefLL, lli);
3206   EXPECT_EQ('g', ch);
3207 }
3208 
TEST(STDIO_TEST,wscanf_i_octal)3209 TEST(STDIO_TEST, wscanf_i_octal) {
3210   int i;
3211   EXPECT_EQ(1, swscanf(L"<01234567>", L"<%i>", &i));
3212   EXPECT_EQ(01234567, i);
3213 
3214   long long int lli;
3215   char ch;
3216   EXPECT_EQ(2, swscanf(L"010234567890abcdefg", L"%lli%c", &lli, &ch));
3217   EXPECT_EQ(010234567, lli);
3218   EXPECT_EQ('8', ch);
3219 }
3220 
TEST(STDIO_TEST,wscanf_i_binary)3221 TEST(STDIO_TEST, wscanf_i_binary) {
3222   int i;
3223   EXPECT_EQ(1, swscanf(L"<0b101>", L"<%i>", &i));
3224   EXPECT_EQ(0b101, i);
3225 
3226   long long int lli;
3227   char ch;
3228   EXPECT_EQ(2, swscanf(L"0b10234567890abcdefg", L"%lli%c", &lli, &ch));
3229   EXPECT_EQ(0b10, lli);
3230   EXPECT_EQ('2', ch);
3231 }
3232 
TEST(STDIO_TEST,scanf_b)3233 TEST(STDIO_TEST, scanf_b) {
3234   int i;
3235   char ch;
3236   EXPECT_EQ(2, sscanf("<1012>", "<%b%c>", &i, &ch));
3237   EXPECT_EQ(0b101, i);
3238   EXPECT_EQ('2', ch);
3239   EXPECT_EQ(1, sscanf("<00000101>", "<%08b>", &i));
3240   EXPECT_EQ(0b00000101, i);
3241   EXPECT_EQ(1, sscanf("<0b1010>", "<%b>", &i));
3242   EXPECT_EQ(0b1010, i);
3243   EXPECT_EQ(2, sscanf("-0b", "%i%c", &i, &ch));
3244   EXPECT_EQ(0, i);
3245   EXPECT_EQ('b', ch);
3246 }
3247 
TEST(STDIO_TEST,swscanf_b)3248 TEST(STDIO_TEST, swscanf_b) {
3249   int i;
3250   char ch;
3251   EXPECT_EQ(2, swscanf(L"<1012>", L"<%b%c>", &i, &ch));
3252   EXPECT_EQ(0b101, i);
3253   EXPECT_EQ('2', ch);
3254   EXPECT_EQ(1, swscanf(L"<00000101>", L"<%08b>", &i));
3255   EXPECT_EQ(0b00000101, i);
3256   EXPECT_EQ(1, swscanf(L"<0b1010>", L"<%b>", &i));
3257   EXPECT_EQ(0b1010, i);
3258   EXPECT_EQ(2, swscanf(L"-0b", L"%i%c", &i, &ch));
3259   EXPECT_EQ(0, i);
3260   EXPECT_EQ('b', ch);
3261 }
3262 
TEST(STDIO_TEST,snprintf_w_base)3263 TEST(STDIO_TEST, snprintf_w_base) {
3264 #if defined(__BIONIC__)
3265 #pragma clang diagnostic push
3266 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3267 #pragma clang diagnostic ignored "-Wconstant-conversion"
3268   int8_t a = 0b101;
3269   EXPECT_SNPRINTF("<101>", "<%w8b>", a);
3270   int8_t b1 = 0xFF;
3271   EXPECT_SNPRINTF("<-1>", "<%w8d>", b1);
3272   int8_t b2 = 0x1FF;
3273   EXPECT_SNPRINTF("<-1>", "<%w8d>", b2);
3274   int16_t c = 0xFFFF;
3275   EXPECT_SNPRINTF("<-1>", "<%w16i>", c);
3276   int32_t d = 021;
3277   EXPECT_SNPRINTF("<21>", "<%w32o>", d);
3278   uint32_t e = -1;
3279   EXPECT_SNPRINTF("<4294967295>", "<%w32u>", e);
3280   int64_t f = 0x3b;
3281   EXPECT_SNPRINTF("<3b>", "<%w64x>", f);
3282   EXPECT_SNPRINTF("<3B>", "<%w64X>", f);
3283 #pragma clang diagnostic pop
3284 #else
3285   GTEST_SKIP() << "no %w in glibc";
3286 #endif
3287 }
3288 
TEST(STDIO_TEST,swprintf_w_base)3289 TEST(STDIO_TEST, swprintf_w_base) {
3290 #if defined(__BIONIC__)
3291 #pragma clang diagnostic push
3292 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3293 #pragma clang diagnostic ignored "-Wconstant-conversion"
3294   int8_t a = 0b101;
3295   EXPECT_SWPRINTF(L"<101>", L"<%w8b>", a);
3296   int8_t b1 = 0xFF;
3297   EXPECT_SWPRINTF(L"<-1>", L"<%w8d>", b1);
3298   int8_t b2 = 0x1FF;
3299   EXPECT_SWPRINTF(L"<-1>", L"<%w8d>", b2);
3300   int16_t c = 0xFFFF;
3301   EXPECT_SWPRINTF(L"<-1>", L"<%w16i>", c);
3302   int32_t d = 021;
3303   EXPECT_SWPRINTF(L"<21>", L"<%w32o>", d);
3304   uint32_t e = -1;
3305   EXPECT_SWPRINTF(L"<4294967295>", L"<%w32u>", e);
3306   int64_t f = 0x3b;
3307   EXPECT_SWPRINTF(L"<3b>", L"<%w64x>", f);
3308   EXPECT_SWPRINTF(L"<3B>", L"<%w64X>", f);
3309 #pragma clang diagnostic pop
3310 #else
3311   GTEST_SKIP() << "no %w in glibc";
3312 #endif
3313 }
3314 
TEST(STDIO_TEST,snprintf_w_arguments_reordering)3315 TEST(STDIO_TEST, snprintf_w_arguments_reordering) {
3316 #if defined(__BIONIC__)
3317 #pragma clang diagnostic push
3318 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3319 #pragma clang diagnostic ignored "-Wformat-extra-args"
3320   int32_t a = 0xaaaaaaaa;
3321   int64_t b = 0x11111111'22222222;
3322   int64_t c = 0x33333333'44444444;
3323   int64_t d = 0xaaaaaaaa'aaaaaaaa;
3324   EXPECT_SNPRINTF("<10101010101010101010101010101010 --- 3333333344444444>",
3325                   "<%2$w32b --- %1$w64x>", c, a);
3326   EXPECT_SNPRINTF(
3327       "<1010101010101010101010101010101010101010101010101010101010101010 --- 1111111122222222 --- "
3328       "3333333344444444>",
3329       "<%3$w64b --- %1$w64x --- %2$w64x>", b, c, d);
3330 #pragma clang diagnostic pop
3331 #else
3332   GTEST_SKIP() << "no %w in glibc";
3333 #endif
3334 }
3335 
TEST(STDIO_TEST,swprintf_w_arguments_reordering)3336 TEST(STDIO_TEST, swprintf_w_arguments_reordering) {
3337 #if defined(__BIONIC__)
3338 #pragma clang diagnostic push
3339 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3340 #pragma clang diagnostic ignored "-Wformat-extra-args"
3341   int32_t a = 0xaaaaaaaa;
3342   int64_t b = 0x11111111'22222222;
3343   int64_t c = 0x33333333'44444444;
3344   int64_t d = 0xaaaaaaaa'aaaaaaaa;
3345   EXPECT_SWPRINTF(L"<10101010101010101010101010101010 --- 3333333344444444>",
3346                   L"<%2$w32b --- %1$w64x>", c, a);
3347   EXPECT_SWPRINTF(
3348       L"<1010101010101010101010101010101010101010101010101010101010101010 --- 1111111122222222 --- "
3349       L"3333333344444444>",
3350       L"<%3$w64b --- %1$w64x --- %2$w64x>", b, c, d);
3351 #pragma clang diagnostic pop
3352 #else
3353   GTEST_SKIP() << "no %w in glibc";
3354 #endif
3355 }
3356 
TEST_F(STDIO_DEATHTEST,snprintf_invalid_w_width)3357 TEST_F(STDIO_DEATHTEST, snprintf_invalid_w_width) {
3358 #if defined(__BIONIC__)
3359 #pragma clang diagnostic push
3360 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3361   char buf[BUFSIZ];
3362   int32_t a = 100;
3363   EXPECT_DEATH(snprintf(buf, sizeof(buf), "%w20d", &a), "%w20 is unsupported");
3364 #pragma clang diagnostic pop
3365 #else
3366   GTEST_SKIP() << "no %w in glibc";
3367 #endif
3368 }
3369 
TEST_F(STDIO_DEATHTEST,swprintf_invalid_w_width)3370 TEST_F(STDIO_DEATHTEST, swprintf_invalid_w_width) {
3371 #if defined(__BIONIC__)
3372 #pragma clang diagnostic push
3373 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3374   wchar_t buf[BUFSIZ];
3375   int32_t a = 100;
3376   EXPECT_DEATH(swprintf(buf, sizeof(buf), L"%w20d", &a), "%w20 is unsupported");
3377 #pragma clang diagnostic pop
3378 #else
3379   GTEST_SKIP() << "no %w in glibc";
3380 #endif
3381 }
3382 
TEST(STDIO_TEST,snprintf_wf_base)3383 TEST(STDIO_TEST, snprintf_wf_base) {
3384 #if defined(__BIONIC__)
3385 #pragma clang diagnostic push
3386 #pragma clang diagnostic ignored "-Wconstant-conversion"
3387 #pragma clang diagnostic ignored "-Wformat"
3388 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3389   int_fast8_t a = 0b101;
3390   EXPECT_SNPRINTF("<101>", "<%wf8b>", a);
3391   int_fast8_t b = 0x12341234'12341234;
3392   EXPECT_SNPRINTF("<34>", "<%wf8x>", b);
3393   uint_fast16_t c = 0x11111111'22222222;
3394 #if defined(__LP64__)
3395   EXPECT_SNPRINTF("<1111111122222222>", "<%wf16x>", c);
3396 #else
3397   EXPECT_SNPRINTF("<22222222>", "<%wf16x>", c);
3398 #endif
3399   int_fast32_t d = 0x33333333'44444444;
3400 #if defined(__LP64__)
3401   EXPECT_SNPRINTF("<3333333344444444>", "<%wf32x>", d);
3402 #else
3403   EXPECT_SNPRINTF("<44444444>", "<%wf32x>", d);
3404 #endif
3405   int_fast64_t e = 0xaaaaaaaa'aaaaaaaa;
3406   EXPECT_SNPRINTF("<aaaaaaaaaaaaaaaa>", "<%wf64x>", e);
3407   EXPECT_SNPRINTF("<AAAAAAAAAAAAAAAA>", "<%wf64X>", e);
3408 #pragma clang diagnostic pop
3409 #else
3410   GTEST_SKIP() << "no %wf in glibc";
3411 #endif
3412 }
TEST(STDIO_TEST,swprintf_wf_base)3413 TEST(STDIO_TEST, swprintf_wf_base) {
3414 #if defined(__BIONIC__)
3415 #pragma clang diagnostic push
3416 #pragma clang diagnostic ignored "-Wconstant-conversion"
3417 #pragma clang diagnostic ignored "-Wformat"
3418 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3419   int_fast8_t a = 0b101;
3420   EXPECT_SWPRINTF(L"<101>", L"<%wf8b>", a);
3421   int_fast8_t b = 0x12341234'12341234;
3422   EXPECT_SWPRINTF(L"<34>", L"<%wf8x>", b);
3423   uint_fast16_t c = 0x11111111'22222222;
3424 #if defined(__LP64__)
3425   EXPECT_SWPRINTF(L"<1111111122222222>", L"<%wf16x>", c);
3426 #else
3427   EXPECT_SWPRINTF(L"<22222222>", L"<%wf16x>", c);
3428 #endif
3429   int_fast32_t d = 0x33333333'44444444;
3430 #if defined(__LP64__)
3431   EXPECT_SWPRINTF(L"<3333333344444444>", L"<%wf32x>", d);
3432 #else
3433   EXPECT_SWPRINTF(L"<44444444>", L"<%wf32x>", d);
3434 #endif
3435   int_fast64_t e = 0xaaaaaaaa'aaaaaaaa;
3436   EXPECT_SWPRINTF(L"<aaaaaaaaaaaaaaaa>", L"<%wf64x>", e);
3437   EXPECT_SWPRINTF(L"<AAAAAAAAAAAAAAAA>", L"<%wf64X>", e);
3438 #pragma clang diagnostic pop
3439 #else
3440   GTEST_SKIP() << "no %wf in glibc";
3441 #endif
3442 }
3443 
TEST(STDIO_TEST,snprintf_wf_arguments_reordering)3444 TEST(STDIO_TEST, snprintf_wf_arguments_reordering) {
3445 #if defined(__BIONIC__)
3446 #pragma clang diagnostic push
3447 #pragma clang diagnostic ignored "-Wconstant-conversion"
3448 #pragma clang diagnostic ignored "-Wformat"
3449 #pragma clang diagnostic ignored "-Wformat-extra-args"
3450 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3451   int_fast16_t a = 0x11111111'22222222;
3452   int_fast32_t b = 0x33333333'44444444;
3453   int_fast32_t c = 0xaaaaaaaa'aaaaaaaa;
3454 #if defined(__LP64__)
3455   EXPECT_SNPRINTF(
3456       "<3333333344444444 --- 1010101010101010101010101010101010101010101010101010101010101010>",
3457       "<%2$wf32x --- %1$wf32b>", c, b);
3458 
3459   EXPECT_SNPRINTF(
3460       "<1010101010101010101010101010101010101010101010101010101010101010 --- 1111111122222222 --- "
3461       "3333333344444444>",
3462       "<%3$wf32b --- %1$wf16x --- %2$wf32x>", a, b, c);
3463 #else
3464   EXPECT_SNPRINTF("<44444444 --- 10101010101010101010101010101010>", "<%2$wf32x --- %1$wf32b>", c,
3465                   b);
3466   EXPECT_SNPRINTF("<10101010101010101010101010101010 --- 22222222 --- 44444444>",
3467                   "<%3$wf32b --- %1$wf16x --- %2$wf32x>", a, b, c);
3468 #endif
3469 #pragma clang diagnostic pop
3470 #else
3471   GTEST_SKIP() << "no %w in glibc";
3472 #endif
3473 }
3474 
TEST(STDIO_TEST,swprintf_wf_arguments_reordering)3475 TEST(STDIO_TEST, swprintf_wf_arguments_reordering) {
3476 #if defined(__BIONIC__)
3477 #pragma clang diagnostic push
3478 #pragma clang diagnostic ignored "-Wconstant-conversion"
3479 #pragma clang diagnostic ignored "-Wformat"
3480 #pragma clang diagnostic ignored "-Wformat-extra-args"
3481 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3482   int_fast16_t a = 0x11111111'22222222;
3483   int_fast32_t b = 0x33333333'44444444;
3484   int_fast32_t c = 0xaaaaaaaa'aaaaaaaa;
3485 #if defined(__LP64__)
3486   EXPECT_SWPRINTF(
3487       L"<3333333344444444 --- 1010101010101010101010101010101010101010101010101010101010101010>",
3488       L"<%2$wf32x --- %1$wf32b>", c, b);
3489 
3490   EXPECT_SWPRINTF(
3491       L"<1010101010101010101010101010101010101010101010101010101010101010 --- 1111111122222222 --- "
3492       L"3333333344444444>",
3493       L"<%3$wf32b --- %1$wf16x --- %2$wf32x>", a, b, c);
3494 #else
3495   EXPECT_SWPRINTF(L"<44444444 --- 10101010101010101010101010101010>", L"<%2$wf32x --- %1$wf32b>", c,
3496                   b);
3497   EXPECT_SWPRINTF(L"<10101010101010101010101010101010 --- 22222222 --- 44444444>",
3498                   L"<%3$wf32b --- %1$wf16x --- %2$wf32x>", a, b, c);
3499 #endif
3500 #pragma clang diagnostic pop
3501 #else
3502   GTEST_SKIP() << "no %w in glibc";
3503 #endif
3504 }
3505 
TEST_F(STDIO_DEATHTEST,snprintf_invalid_wf_width)3506 TEST_F(STDIO_DEATHTEST, snprintf_invalid_wf_width) {
3507 #if defined(__BIONIC__)
3508 #pragma clang diagnostic push
3509 #pragma clang diagnostic ignored "-Wformat"
3510 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3511   char buf[BUFSIZ];
3512   int_fast32_t a = 100;
3513   EXPECT_DEATH(snprintf(buf, sizeof(buf), "%wf20d", &a), "%wf20 is unsupported");
3514 #pragma clang diagnostic pop
3515 #else
3516   GTEST_SKIP() << "no %w in glibc";
3517 #endif
3518 }
3519 
TEST_F(STDIO_DEATHTEST,swprintf_invalid_wf_width)3520 TEST_F(STDIO_DEATHTEST, swprintf_invalid_wf_width) {
3521 #if defined(__BIONIC__)
3522 #pragma clang diagnostic push
3523 #pragma clang diagnostic ignored "-Wformat"
3524 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3525   wchar_t buf[BUFSIZ];
3526   int_fast32_t a = 100;
3527   EXPECT_DEATH(swprintf(buf, sizeof(buf), L"%wf20d", &a), "%wf20 is unsupported");
3528 #pragma clang diagnostic pop
3529 #else
3530   GTEST_SKIP() << "no %w in glibc";
3531 #endif
3532 }
3533 
TEST(STDIO_TEST,sscanf_w_or_wf_base)3534 TEST(STDIO_TEST, sscanf_w_or_wf_base) {
3535 #if defined(__BIONIC__)
3536 #pragma clang diagnostic push
3537 #pragma clang diagnostic ignored "-Wformat"
3538 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3539   int8_t a;
3540   EXPECT_EQ(1, sscanf("<0b101>", "<%w8b>", &a));
3541   EXPECT_EQ(0b101, a);
3542   int_fast8_t fast_a;
3543   EXPECT_EQ(1, sscanf("<0b101>", "<%wf8b>", &fast_a));
3544   EXPECT_EQ(0b101, fast_a);
3545   int8_t b1;
3546   EXPECT_EQ(1, sscanf("<0xFF>", "<%w8i>", &b1));
3547   EXPECT_EQ(-1, b1);
3548   int8_t b2;
3549   EXPECT_EQ(1, sscanf("<0x1FF>", "<%w8i>", &b2));
3550   EXPECT_EQ(-1, b2);
3551   int_fast8_t fast_b;
3552   EXPECT_EQ(1, sscanf("<0x1234123412341234>", "<%wf8x>", &fast_b));
3553   EXPECT_EQ(0x34, fast_b);
3554   int16_t c1;
3555   EXPECT_EQ(1, sscanf("<0xFFFF>", "<%w16i>", &c1));
3556   EXPECT_EQ(-1, c1);
3557   uint16_t c2;
3558   EXPECT_EQ(1, sscanf("<64>", "<%w16d>", &c2));
3559   EXPECT_EQ(64, c2);
3560   int_fast16_t fast_c;
3561 #if defined(__LP64__)
3562   EXPECT_EQ(1, sscanf("<0x1111111122222222>", "<%wf16x>", &fast_c));
3563   EXPECT_EQ(0x1111111122222222, fast_c);
3564 #else
3565   EXPECT_EQ(1, sscanf("<0x1111111122222222>", "<%wf16x>", &fast_c));
3566   EXPECT_EQ(0x22222222, fast_c);
3567 #endif
3568   int32_t d;
3569   EXPECT_EQ(1, sscanf("<021>", "<%w32o>", &d));
3570   EXPECT_EQ(021, d);
3571   int_fast32_t fast_d;
3572 #if defined(__LP64__)
3573   EXPECT_EQ(1, sscanf("<0x3333333344444444>", "<%wf32x>", &fast_d));
3574   EXPECT_EQ(0x3333333344444444, fast_d);
3575 #else
3576   EXPECT_EQ(1, sscanf("<0x3333333344444444>", "<%wf32x>", &fast_d));
3577   EXPECT_EQ(0x44444444, fast_d);
3578 #endif
3579   uint32_t e;
3580   EXPECT_EQ(1, sscanf("<-1>", "<%w32u>", &e));
3581   EXPECT_EQ(4294967295, e);
3582   int64_t f;
3583   EXPECT_EQ(1, sscanf("<0x3b>", "<%w64x>", &f));
3584   EXPECT_EQ(0x3b, f);
3585   EXPECT_EQ(1, sscanf("<0x3b>", "<%w64X>", &f));
3586   EXPECT_EQ(0x3B, f);
3587   uint_fast64_t fast_f;
3588   EXPECT_EQ(1, sscanf("<0xaaaaaaaa>", "<%wf64x>", &fast_f));
3589   EXPECT_EQ(0xaaaaaaaa, fast_f);
3590   EXPECT_EQ(1, sscanf("<0xaaaaaaaa>", "<%wf64X>", &fast_f));
3591   EXPECT_EQ(0xAAAAAAAA, fast_f);
3592 #pragma clang diagnostic pop
3593 #else
3594   GTEST_SKIP() << "no %w in glibc";
3595 #endif
3596 }
3597 
TEST(STDIO_TEST,sscanf_w_combination)3598 TEST(STDIO_TEST, sscanf_w_combination) {
3599 #if defined(__BIONIC__)
3600 #pragma clang diagnostic push
3601 #pragma clang diagnostic ignored "-Wformat"
3602 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3603 #pragma clang diagnostic ignored "-Wformat-extra-args"
3604   uint32_t a;
3605   int64_t b;
3606   char c;
3607 
3608   EXPECT_EQ(3, sscanf("<0b10101010101010101010101010101010 0x3333333344444444 1>",
3609                       "<%w32b %w64x %c>", &a, &b, &c));
3610   EXPECT_EQ(0xaaaaaaaa, a);
3611   EXPECT_EQ(0x3333333344444444, b);
3612   EXPECT_EQ('1', c);
3613 #pragma clang diagnostic pop
3614 #else
3615   GTEST_SKIP() << "no %w in glibc";
3616 #endif
3617 }
3618 
TEST_F(STDIO_DEATHTEST,sscanf_invalid_w_or_wf_width)3619 TEST_F(STDIO_DEATHTEST, sscanf_invalid_w_or_wf_width) {
3620 #if defined(__BIONIC__)
3621 #pragma clang diagnostic push
3622 #pragma clang diagnostic ignored "-Wformat"
3623 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3624   int32_t a;
3625   EXPECT_DEATH(sscanf("<100>", "<%w20d>", &a), "%w20 is unsupported");
3626   int_fast32_t fast_a;
3627   EXPECT_DEATH(sscanf("<100>", "<%wf20d>", &fast_a), "%wf20 is unsupported");
3628 #pragma clang diagnostic pop
3629 #else
3630   GTEST_SKIP() << "no %w in glibc";
3631 #endif
3632 }
3633 
TEST(STDIO_TEST,swscanf_w_or_wf_base)3634 TEST(STDIO_TEST, swscanf_w_or_wf_base) {
3635 #if defined(__BIONIC__)
3636 #pragma clang diagnostic push
3637 #pragma clang diagnostic ignored "-Wformat"
3638 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3639   int8_t a;
3640   EXPECT_EQ(1, swscanf(L"<0b101>", L"<%w8b>", &a));
3641   EXPECT_EQ(0b101, a);
3642   int_fast8_t fast_a;
3643   EXPECT_EQ(1, swscanf(L"<0b101>", L"<%wf8b>", &fast_a));
3644   EXPECT_EQ(0b101, fast_a);
3645   int8_t b1;
3646   EXPECT_EQ(1, swscanf(L"<0xFF>", L"<%w8i>", &b1));
3647   EXPECT_EQ(-1, b1);
3648   int8_t b2;
3649   EXPECT_EQ(1, swscanf(L"<0x1FF>", L"<%w8i>", &b2));
3650   EXPECT_EQ(-1, b2);
3651   int_fast8_t fast_b;
3652   EXPECT_EQ(1, swscanf(L"<0x1234123412341234>", L"<%wf8i>", &fast_b));
3653   EXPECT_EQ(0x34, fast_b);
3654   int16_t c1;
3655   EXPECT_EQ(1, swscanf(L"<0xFFFF>", L"<%w16i>", &c1));
3656   EXPECT_EQ(-1, c1);
3657   uint16_t c2;
3658   EXPECT_EQ(1, swscanf(L"<64>", L"<%w16d>", &c2));
3659   EXPECT_EQ(64, c2);
3660   int_fast16_t fast_c;
3661 #if defined(__LP64__)
3662   EXPECT_EQ(1, swscanf(L"<0x1111111122222222>", L"<%wf16x>", &fast_c));
3663   EXPECT_EQ(0x1111111122222222, fast_c);
3664 #else
3665   EXPECT_EQ(1, swscanf(L"<0x1111111122222222>", L"<%wf16x>", &fast_c));
3666   EXPECT_EQ(0x22222222, fast_c);
3667 #endif
3668   int32_t d;
3669   EXPECT_EQ(1, swscanf(L"<021>", L"<%w32o>", &d));
3670   EXPECT_EQ(021, d);
3671   int_fast32_t fast_d;
3672 #if defined(__LP64__)
3673   EXPECT_EQ(1, swscanf(L"<0x3333333344444444>", L"<%wf32x>", &fast_d));
3674   EXPECT_EQ(0x3333333344444444, fast_d);
3675 #else
3676   EXPECT_EQ(1, swscanf(L"<0x3333333344444444>", L"<%wf32x>", &fast_d));
3677   EXPECT_EQ(0x44444444, fast_d);
3678 #endif
3679   uint32_t e;
3680   EXPECT_EQ(1, swscanf(L"<-1>", L"<%w32u>", &e));
3681   EXPECT_EQ(4294967295, e);
3682   int64_t f;
3683   EXPECT_EQ(1, swscanf(L"<0x3b>", L"<%w64x>", &f));
3684   EXPECT_EQ(0x3b, f);
3685   EXPECT_EQ(1, swscanf(L"<0x3b>", L"<%w64X>", &f));
3686   EXPECT_EQ(0x3B, f);
3687   uint_fast64_t fast_f;
3688   EXPECT_EQ(1, swscanf(L"<0xaaaaaaaa>", L"<%wf64x>", &fast_f));
3689   EXPECT_EQ(0xaaaaaaaa, fast_f);
3690   EXPECT_EQ(1, swscanf(L"<0xaaaaaaaa>", L"<%wf64X>", &fast_f));
3691   EXPECT_EQ(0xAAAAAAAA, fast_f);
3692 #pragma clang diagnostic pop
3693 #else
3694   GTEST_SKIP() << "no %w in glibc";
3695 #endif
3696 }
3697 
TEST(STDIO_TEST,swscanf_w_combination)3698 TEST(STDIO_TEST, swscanf_w_combination) {
3699 #if defined(__BIONIC__)
3700 #pragma clang diagnostic push
3701 #pragma clang diagnostic ignored "-Wformat"
3702 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3703 #pragma clang diagnostic ignored "-Wformat-extra-args"
3704   uint32_t a;
3705   int64_t b;
3706   char c;
3707 
3708   EXPECT_EQ(3, swscanf(L"<0b10101010101010101010101010101010 0x3333333344444444 1>",
3709                        L"<%w32b %w64x %c>", &a, &b, &c));
3710   EXPECT_EQ(0xaaaaaaaa, a);
3711   EXPECT_EQ(0x3333333344444444, b);
3712   EXPECT_EQ('1', c);
3713 #pragma clang diagnostic pop
3714 #else
3715   GTEST_SKIP() << "no %w in glibc";
3716 #endif
3717 }
3718 
TEST_F(STDIO_DEATHTEST,swscanf_invalid_w_or_wf_width)3719 TEST_F(STDIO_DEATHTEST, swscanf_invalid_w_or_wf_width) {
3720 #if defined(__BIONIC__)
3721 #pragma clang diagnostic push
3722 #pragma clang diagnostic ignored "-Wformat"
3723 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
3724   int32_t a;
3725   EXPECT_DEATH(swscanf(L"<100>", L"<%w20d>", &a), "%w20 is unsupported");
3726   int_fast32_t fast_a;
3727   EXPECT_DEATH(swscanf(L"<100>", L"<%wf20d>", &fast_a), "%wf20 is unsupported");
3728 #pragma clang diagnostic pop
3729 #else
3730   GTEST_SKIP() << "no %w in glibc";
3731 #endif
3732 }
3733 
TEST(STDIO_TEST,printf_lc_0)3734 TEST(STDIO_TEST, printf_lc_0) {
3735   // https://austingroupbugs.net/view.php?id=1647
3736   char buf[BUFSIZ];
3737   EXPECT_EQ(3, snprintf(buf, sizeof(buf), "<%lc>", L'\0'));
3738   EXPECT_TRUE(!memcmp(buf, "<\0>", 3));
3739 }
3740