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