• 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 <math.h>
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <sys/socket.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 #include <wchar.h>
29 #include <locale.h>
30 
31 #include <string>
32 #include <thread>
33 #include <vector>
34 
35 #include <android-base/file.h>
36 
37 #include "BionicDeathTest.h"
38 #include "utils.h"
39 
40 #if defined(NOFORTIFY)
41 #define STDIO_TEST stdio_nofortify
42 #define STDIO_DEATHTEST stdio_nofortify_DeathTest
43 #else
44 #define STDIO_TEST stdio
45 #define STDIO_DEATHTEST stdio_DeathTest
46 #endif
47 
48 using namespace std::string_literals;
49 
50 class stdio_DeathTest : public BionicDeathTest {};
51 class stdio_nofortify_DeathTest : public BionicDeathTest {};
52 
SetFileTo(const char * path,const char * content)53 static void SetFileTo(const char* path, const char* content) {
54   FILE* fp;
55   ASSERT_NE(nullptr, fp = fopen(path, "w"));
56   ASSERT_NE(EOF, fputs(content, fp));
57   ASSERT_EQ(0, fclose(fp));
58 }
59 
AssertFileIs(const char * path,const char * expected)60 static void AssertFileIs(const char* path, const char* expected) {
61   FILE* fp;
62   ASSERT_NE(nullptr, fp = fopen(path, "r"));
63   char* line = nullptr;
64   size_t length;
65   ASSERT_NE(EOF, getline(&line, &length, fp));
66   ASSERT_EQ(0, fclose(fp));
67   ASSERT_STREQ(expected, line);
68   free(line);
69 }
70 
AssertFileIs(FILE * fp,const char * expected,bool is_fmemopen=false)71 static void AssertFileIs(FILE* fp, const char* expected, bool is_fmemopen = false) {
72   rewind(fp);
73 
74   char line[1024];
75   memset(line, 0xff, sizeof(line));
76   ASSERT_EQ(line, fgets(line, sizeof(line), fp));
77   ASSERT_STREQ(expected, line);
78 
79   if (is_fmemopen) {
80     // fmemopen appends a trailing NUL byte, which probably shouldn't show up as an
81     // extra empty line, but does on every C library I tested...
82     ASSERT_EQ(line, fgets(line, sizeof(line), fp));
83     ASSERT_STREQ("", line);
84   }
85 
86   // Make sure there isn't anything else in the file.
87   ASSERT_EQ(nullptr, fgets(line, sizeof(line), fp)) << "junk at end of file: " << line;
88 }
89 
TEST(STDIO_TEST,flockfile_18208568_stderr)90 TEST(STDIO_TEST, flockfile_18208568_stderr) {
91   // Check that we have a _recursive_ mutex for flockfile.
92   flockfile(stderr);
93   feof(stderr); // We don't care about the result, but this needs to take the lock.
94   funlockfile(stderr);
95 }
96 
TEST(STDIO_TEST,flockfile_18208568_regular)97 TEST(STDIO_TEST, flockfile_18208568_regular) {
98   // We never had a bug for streams other than stdin/stdout/stderr, but test anyway.
99   FILE* fp = fopen("/dev/null", "w");
100   ASSERT_TRUE(fp != nullptr);
101   flockfile(fp);
102   feof(fp);
103   funlockfile(fp);
104   fclose(fp);
105 }
106 
TEST(STDIO_TEST,tmpfile_fileno_fprintf_rewind_fgets)107 TEST(STDIO_TEST, tmpfile_fileno_fprintf_rewind_fgets) {
108   FILE* fp = tmpfile();
109   ASSERT_TRUE(fp != nullptr);
110 
111   int fd = fileno(fp);
112   ASSERT_NE(fd, -1);
113 
114   struct stat sb;
115   int rc = fstat(fd, &sb);
116   ASSERT_NE(rc, -1);
117   ASSERT_EQ(sb.st_mode & 0777, 0600U);
118 
119   rc = fprintf(fp, "hello\n");
120   ASSERT_EQ(rc, 6);
121 
122   AssertFileIs(fp, "hello\n");
123   fclose(fp);
124 }
125 
TEST(STDIO_TEST,tmpfile64)126 TEST(STDIO_TEST, tmpfile64) {
127   FILE* fp = tmpfile64();
128   ASSERT_TRUE(fp != nullptr);
129   fclose(fp);
130 }
131 
TEST(STDIO_TEST,dprintf)132 TEST(STDIO_TEST, dprintf) {
133   TemporaryFile tf;
134 
135   int rc = dprintf(tf.fd, "hello\n");
136   ASSERT_EQ(rc, 6);
137 
138   lseek(tf.fd, 0, SEEK_SET);
139   FILE* tfile = fdopen(tf.fd, "r");
140   ASSERT_TRUE(tfile != nullptr);
141 
142   AssertFileIs(tfile, "hello\n");
143   fclose(tfile);
144 }
145 
TEST(STDIO_TEST,getdelim)146 TEST(STDIO_TEST, getdelim) {
147   FILE* fp = tmpfile();
148   ASSERT_TRUE(fp != nullptr);
149 
150   const char* line_written = "This  is a test";
151   int rc = fprintf(fp, "%s", line_written);
152   ASSERT_EQ(rc, static_cast<int>(strlen(line_written)));
153 
154   rewind(fp);
155 
156   char* word_read = nullptr;
157   size_t allocated_length = 0;
158 
159   const char* expected[] = { "This ", " ", "is ", "a ", "test" };
160   for (size_t i = 0; i < 5; ++i) {
161     ASSERT_FALSE(feof(fp));
162     ASSERT_EQ(getdelim(&word_read, &allocated_length, ' ', fp), static_cast<int>(strlen(expected[i])));
163     ASSERT_GE(allocated_length, strlen(expected[i]));
164     ASSERT_STREQ(expected[i], word_read);
165   }
166   // The last read should have set the end-of-file indicator for the stream.
167   ASSERT_TRUE(feof(fp));
168   clearerr(fp);
169 
170   // getdelim returns -1 but doesn't set errno if we're already at EOF.
171   // It should set the end-of-file indicator for the stream, though.
172   errno = 0;
173   ASSERT_EQ(getdelim(&word_read, &allocated_length, ' ', fp), -1);
174   ASSERT_EQ(0, errno);
175   ASSERT_TRUE(feof(fp));
176 
177   free(word_read);
178   fclose(fp);
179 }
180 
TEST(STDIO_TEST,getdelim_invalid)181 TEST(STDIO_TEST, getdelim_invalid) {
182   FILE* fp = tmpfile();
183   ASSERT_TRUE(fp != nullptr);
184 
185   char* buffer = nullptr;
186   size_t buffer_length = 0;
187 
188   // The first argument can't be NULL.
189   errno = 0;
190   ASSERT_EQ(getdelim(nullptr, &buffer_length, ' ', fp), -1);
191   ASSERT_EQ(EINVAL, errno);
192 
193   // The second argument can't be NULL.
194   errno = 0;
195   ASSERT_EQ(getdelim(&buffer, nullptr, ' ', fp), -1);
196   ASSERT_EQ(EINVAL, errno);
197   fclose(fp);
198 }
199 
TEST(STDIO_TEST,getdelim_directory)200 TEST(STDIO_TEST, getdelim_directory) {
201   FILE* fp = fopen("/proc", "r");
202   ASSERT_TRUE(fp != nullptr);
203   char* word_read;
204   size_t allocated_length;
205   ASSERT_EQ(-1, getdelim(&word_read, &allocated_length, ' ', fp));
206   fclose(fp);
207 }
208 
TEST(STDIO_TEST,getline)209 TEST(STDIO_TEST, getline) {
210   FILE* fp = tmpfile();
211   ASSERT_TRUE(fp != nullptr);
212 
213   const char* line_written = "This is a test for getline\n";
214   const size_t line_count = 5;
215 
216   for (size_t i = 0; i < line_count; ++i) {
217     int rc = fprintf(fp, "%s", line_written);
218     ASSERT_EQ(rc, static_cast<int>(strlen(line_written)));
219   }
220 
221   rewind(fp);
222 
223   char* line_read = nullptr;
224   size_t allocated_length = 0;
225 
226   size_t read_line_count = 0;
227   ssize_t read_char_count;
228   while ((read_char_count = getline(&line_read, &allocated_length, fp)) != -1) {
229     ASSERT_EQ(read_char_count, static_cast<int>(strlen(line_written)));
230     ASSERT_GE(allocated_length, strlen(line_written));
231     ASSERT_STREQ(line_written, line_read);
232     ++read_line_count;
233   }
234   ASSERT_EQ(read_line_count, line_count);
235 
236   // The last read should have set the end-of-file indicator for the stream.
237   ASSERT_TRUE(feof(fp));
238   clearerr(fp);
239 
240   // getline returns -1 but doesn't set errno if we're already at EOF.
241   // It should set the end-of-file indicator for the stream, though.
242   errno = 0;
243   ASSERT_EQ(getline(&line_read, &allocated_length, fp), -1);
244   ASSERT_EQ(0, errno);
245   ASSERT_TRUE(feof(fp));
246 
247   free(line_read);
248   fclose(fp);
249 }
250 
TEST(STDIO_TEST,getline_invalid)251 TEST(STDIO_TEST, getline_invalid) {
252   FILE* fp = tmpfile();
253   ASSERT_TRUE(fp != nullptr);
254 
255   char* buffer = nullptr;
256   size_t buffer_length = 0;
257 
258   // The first argument can't be NULL.
259   errno = 0;
260   ASSERT_EQ(getline(nullptr, &buffer_length, fp), -1);
261   ASSERT_EQ(EINVAL, errno);
262 
263   // The second argument can't be NULL.
264   errno = 0;
265   ASSERT_EQ(getline(&buffer, nullptr, fp), -1);
266   ASSERT_EQ(EINVAL, errno);
267   fclose(fp);
268 }
269 
TEST(STDIO_TEST,printf_ssize_t)270 TEST(STDIO_TEST, printf_ssize_t) {
271   // http://b/8253769
272   ASSERT_EQ(sizeof(ssize_t), sizeof(long int));
273   ASSERT_EQ(sizeof(ssize_t), sizeof(size_t));
274   // For our 32-bit ABI, we had a ssize_t definition that confuses GCC into saying:
275   // error: format '%zd' expects argument of type 'signed size_t',
276   //     but argument 4 has type 'ssize_t {aka long int}' [-Werror=format]
277   ssize_t v = 1;
278   char buf[32];
279   snprintf(buf, sizeof(buf), "%zd", v);
280 }
281 
282 // https://code.google.com/p/android/issues/detail?id=64886
TEST(STDIO_TEST,snprintf_a)283 TEST(STDIO_TEST, snprintf_a) {
284   char buf[BUFSIZ];
285   EXPECT_EQ(23, snprintf(buf, sizeof(buf), "<%a>", 9990.235));
286   EXPECT_STREQ("<0x1.3831e147ae148p+13>", buf);
287 }
288 
TEST(STDIO_TEST,snprintf_lc)289 TEST(STDIO_TEST, snprintf_lc) {
290   char buf[BUFSIZ];
291   wint_t wc = L'a';
292   EXPECT_EQ(3, snprintf(buf, sizeof(buf), "<%lc>", wc));
293   EXPECT_STREQ("<a>", buf);
294 }
295 
TEST(STDIO_TEST,snprintf_C)296 TEST(STDIO_TEST, snprintf_C) { // Synonym for %lc.
297   char buf[BUFSIZ];
298   wchar_t wc = L'a';
299   EXPECT_EQ(3, snprintf(buf, sizeof(buf), "<%C>", wc));
300   EXPECT_STREQ("<a>", buf);
301 }
302 
TEST(STDIO_TEST,snprintf_ls)303 TEST(STDIO_TEST, snprintf_ls) {
304   char buf[BUFSIZ];
305   wchar_t* ws = nullptr;
306   EXPECT_EQ(8, snprintf(buf, sizeof(buf), "<%ls>", ws));
307   EXPECT_STREQ("<(null)>", buf);
308 
309   wchar_t chars[] = { L'h', L'i', 0 };
310   ws = chars;
311   EXPECT_EQ(4, snprintf(buf, sizeof(buf), "<%ls>", ws));
312   EXPECT_STREQ("<hi>", buf);
313 }
314 
TEST(STDIO_TEST,snprintf_S)315 TEST(STDIO_TEST, snprintf_S) { // Synonym for %ls.
316   char buf[BUFSIZ];
317   wchar_t* ws = nullptr;
318   EXPECT_EQ(8, snprintf(buf, sizeof(buf), "<%S>", ws));
319   EXPECT_STREQ("<(null)>", buf);
320 
321   wchar_t chars[] = { L'h', L'i', 0 };
322   ws = chars;
323   EXPECT_EQ(4, snprintf(buf, sizeof(buf), "<%S>", ws));
324   EXPECT_STREQ("<hi>", buf);
325 }
326 
TEST(STDIO_TEST,snprintf_n)327 TEST(STDIO_TEST, snprintf_n) {
328 #if defined(__BIONIC__)
329   // http://b/14492135 and http://b/31832608.
330   char buf[32];
331   int i = 1234;
332   EXPECT_DEATH(snprintf(buf, sizeof(buf), "a %n b", &i), "%n not allowed on Android");
333 #else
334   GTEST_SKIP() << "glibc does allow %n";
335 #endif
336 }
337 
TEST(STDIO_TEST,snprintf_smoke)338 TEST(STDIO_TEST, snprintf_smoke) {
339   char buf[BUFSIZ];
340 
341   snprintf(buf, sizeof(buf), "a");
342   EXPECT_STREQ("a", buf);
343 
344   snprintf(buf, sizeof(buf), "%%");
345   EXPECT_STREQ("%", buf);
346 
347   snprintf(buf, sizeof(buf), "01234");
348   EXPECT_STREQ("01234", buf);
349 
350   snprintf(buf, sizeof(buf), "a%sb", "01234");
351   EXPECT_STREQ("a01234b", buf);
352 
353   char* s = nullptr;
354   snprintf(buf, sizeof(buf), "a%sb", s);
355   EXPECT_STREQ("a(null)b", buf);
356 
357   snprintf(buf, sizeof(buf), "aa%scc", "bb");
358   EXPECT_STREQ("aabbcc", buf);
359 
360   snprintf(buf, sizeof(buf), "a%cc", 'b');
361   EXPECT_STREQ("abc", buf);
362 
363   snprintf(buf, sizeof(buf), "a%db", 1234);
364   EXPECT_STREQ("a1234b", buf);
365 
366   snprintf(buf, sizeof(buf), "a%db", -8123);
367   EXPECT_STREQ("a-8123b", buf);
368 
369   snprintf(buf, sizeof(buf), "a%hdb", static_cast<short>(0x7fff0010));
370   EXPECT_STREQ("a16b", buf);
371 
372   snprintf(buf, sizeof(buf), "a%hhdb", static_cast<char>(0x7fffff10));
373   EXPECT_STREQ("a16b", buf);
374 
375   snprintf(buf, sizeof(buf), "a%lldb", 0x1000000000LL);
376   EXPECT_STREQ("a68719476736b", buf);
377 
378   snprintf(buf, sizeof(buf), "a%ldb", 70000L);
379   EXPECT_STREQ("a70000b", buf);
380 
381   snprintf(buf, sizeof(buf), "a%pb", reinterpret_cast<void*>(0xb0001234));
382   EXPECT_STREQ("a0xb0001234b", buf);
383 
384   snprintf(buf, sizeof(buf), "a%xz", 0x12ab);
385   EXPECT_STREQ("a12abz", buf);
386 
387   snprintf(buf, sizeof(buf), "a%Xz", 0x12ab);
388   EXPECT_STREQ("a12ABz", buf);
389 
390   snprintf(buf, sizeof(buf), "a%08xz", 0x123456);
391   EXPECT_STREQ("a00123456z", buf);
392 
393   snprintf(buf, sizeof(buf), "a%5dz", 1234);
394   EXPECT_STREQ("a 1234z", buf);
395 
396   snprintf(buf, sizeof(buf), "a%05dz", 1234);
397   EXPECT_STREQ("a01234z", buf);
398 
399   snprintf(buf, sizeof(buf), "a%8dz", 1234);
400   EXPECT_STREQ("a    1234z", buf);
401 
402   snprintf(buf, sizeof(buf), "a%-8dz", 1234);
403   EXPECT_STREQ("a1234    z", buf);
404 
405   snprintf(buf, sizeof(buf), "A%-11sZ", "abcdef");
406   EXPECT_STREQ("Aabcdef     Z", buf);
407 
408   snprintf(buf, sizeof(buf), "A%s:%dZ", "hello", 1234);
409   EXPECT_STREQ("Ahello:1234Z", buf);
410 
411   snprintf(buf, sizeof(buf), "a%03d:%d:%02dz", 5, 5, 5);
412   EXPECT_STREQ("a005:5:05z", buf);
413 
414   void* p = nullptr;
415   snprintf(buf, sizeof(buf), "a%d,%pz", 5, p);
416 #if defined(__BIONIC__)
417   EXPECT_STREQ("a5,0x0z", buf);
418 #else // __BIONIC__
419   EXPECT_STREQ("a5,(nil)z", buf);
420 #endif // __BIONIC__
421 
422   snprintf(buf, sizeof(buf), "a%lld,%d,%d,%dz", 0x1000000000LL, 6, 7, 8);
423   EXPECT_STREQ("a68719476736,6,7,8z", buf);
424 
425   snprintf(buf, sizeof(buf), "a_%f_b", 1.23f);
426   EXPECT_STREQ("a_1.230000_b", buf);
427 
428   snprintf(buf, sizeof(buf), "a_%g_b", 3.14);
429   EXPECT_STREQ("a_3.14_b", buf);
430 
431   snprintf(buf, sizeof(buf), "%1$s %1$s", "print_me_twice");
432   EXPECT_STREQ("print_me_twice print_me_twice", buf);
433 }
434 
435 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)436 static void CheckInfNan(int snprintf_fn(T*, size_t, const T*, ...),
437                         int sscanf_fn(const T*, const T*, ...),
438                         const T* fmt_string, const T* fmt, const T* fmt_plus,
439                         const T* minus_inf, const T* inf_, const T* plus_inf,
440                         const T* minus_nan, const T* nan_, const T* plus_nan) {
441   T buf[BUFSIZ];
442   float f;
443 
444   // NaN.
445 
446   snprintf_fn(buf, sizeof(buf), fmt, nanf(""));
447   EXPECT_STREQ(nan_, buf) << fmt;
448   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
449   EXPECT_TRUE(isnan(f));
450 
451   snprintf_fn(buf, sizeof(buf), fmt, -nanf(""));
452   EXPECT_STREQ(minus_nan, buf) << fmt;
453   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
454   EXPECT_TRUE(isnan(f));
455 
456   snprintf_fn(buf, sizeof(buf), fmt_plus, nanf(""));
457   EXPECT_STREQ(plus_nan, buf) << fmt_plus;
458   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
459   EXPECT_TRUE(isnan(f));
460 
461   snprintf_fn(buf, sizeof(buf), fmt_plus, -nanf(""));
462   EXPECT_STREQ(minus_nan, buf) << fmt_plus;
463   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
464   EXPECT_TRUE(isnan(f));
465 
466   // Inf.
467 
468   snprintf_fn(buf, sizeof(buf), fmt, HUGE_VALF);
469   EXPECT_STREQ(inf_, buf) << fmt;
470   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
471   EXPECT_EQ(HUGE_VALF, f);
472 
473   snprintf_fn(buf, sizeof(buf), fmt, -HUGE_VALF);
474   EXPECT_STREQ(minus_inf, buf) << fmt;
475   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
476   EXPECT_EQ(-HUGE_VALF, f);
477 
478   snprintf_fn(buf, sizeof(buf), fmt_plus, HUGE_VALF);
479   EXPECT_STREQ(plus_inf, buf) << fmt_plus;
480   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
481   EXPECT_EQ(HUGE_VALF, f);
482 
483   snprintf_fn(buf, sizeof(buf), fmt_plus, -HUGE_VALF);
484   EXPECT_STREQ(minus_inf, buf) << fmt_plus;
485   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
486   EXPECT_EQ(-HUGE_VALF, f);
487 
488   // Check case-insensitivity.
489   snprintf_fn(buf, sizeof(buf), fmt_string, "[InFiNiTy]");
490   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f)) << buf;
491   EXPECT_EQ(HUGE_VALF, f);
492   snprintf_fn(buf, sizeof(buf), fmt_string, "[NaN]");
493   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f)) << buf;
494   EXPECT_TRUE(isnan(f));
495 }
496 
TEST(STDIO_TEST,snprintf_sscanf_inf_nan)497 TEST(STDIO_TEST, snprintf_sscanf_inf_nan) {
498   CheckInfNan(snprintf, sscanf, "%s",
499               "[%a]", "[%+a]",
500               "[-inf]", "[inf]", "[+inf]",
501               "[-nan]", "[nan]", "[+nan]");
502   CheckInfNan(snprintf, sscanf, "%s",
503               "[%A]", "[%+A]",
504               "[-INF]", "[INF]", "[+INF]",
505               "[-NAN]", "[NAN]", "[+NAN]");
506   CheckInfNan(snprintf, sscanf, "%s",
507               "[%e]", "[%+e]",
508               "[-inf]", "[inf]", "[+inf]",
509               "[-nan]", "[nan]", "[+nan]");
510   CheckInfNan(snprintf, sscanf, "%s",
511               "[%E]", "[%+E]",
512               "[-INF]", "[INF]", "[+INF]",
513               "[-NAN]", "[NAN]", "[+NAN]");
514   CheckInfNan(snprintf, sscanf, "%s",
515               "[%f]", "[%+f]",
516               "[-inf]", "[inf]", "[+inf]",
517               "[-nan]", "[nan]", "[+nan]");
518   CheckInfNan(snprintf, sscanf, "%s",
519               "[%F]", "[%+F]",
520               "[-INF]", "[INF]", "[+INF]",
521               "[-NAN]", "[NAN]", "[+NAN]");
522   CheckInfNan(snprintf, sscanf, "%s",
523               "[%g]", "[%+g]",
524               "[-inf]", "[inf]", "[+inf]",
525               "[-nan]", "[nan]", "[+nan]");
526   CheckInfNan(snprintf, sscanf, "%s",
527               "[%G]", "[%+G]",
528               "[-INF]", "[INF]", "[+INF]",
529               "[-NAN]", "[NAN]", "[+NAN]");
530 }
531 
TEST(STDIO_TEST,swprintf_swscanf_inf_nan)532 TEST(STDIO_TEST, swprintf_swscanf_inf_nan) {
533   CheckInfNan(swprintf, swscanf, L"%s",
534               L"[%a]", L"[%+a]",
535               L"[-inf]", L"[inf]", L"[+inf]",
536               L"[-nan]", L"[nan]", L"[+nan]");
537   CheckInfNan(swprintf, swscanf, L"%s",
538               L"[%A]", L"[%+A]",
539               L"[-INF]", L"[INF]", L"[+INF]",
540               L"[-NAN]", L"[NAN]", L"[+NAN]");
541   CheckInfNan(swprintf, swscanf, L"%s",
542               L"[%e]", L"[%+e]",
543               L"[-inf]", L"[inf]", L"[+inf]",
544               L"[-nan]", L"[nan]", L"[+nan]");
545   CheckInfNan(swprintf, swscanf, L"%s",
546               L"[%E]", L"[%+E]",
547               L"[-INF]", L"[INF]", L"[+INF]",
548               L"[-NAN]", L"[NAN]", L"[+NAN]");
549   CheckInfNan(swprintf, swscanf, L"%s",
550               L"[%f]", L"[%+f]",
551               L"[-inf]", L"[inf]", L"[+inf]",
552               L"[-nan]", L"[nan]", L"[+nan]");
553   CheckInfNan(swprintf, swscanf, L"%s",
554               L"[%F]", L"[%+F]",
555               L"[-INF]", L"[INF]", L"[+INF]",
556               L"[-NAN]", L"[NAN]", L"[+NAN]");
557   CheckInfNan(swprintf, swscanf, L"%s",
558               L"[%g]", L"[%+g]",
559               L"[-inf]", L"[inf]", L"[+inf]",
560               L"[-nan]", L"[nan]", L"[+nan]");
561   CheckInfNan(swprintf, swscanf, L"%s",
562               L"[%G]", L"[%+G]",
563               L"[-INF]", L"[INF]", L"[+INF]",
564               L"[-NAN]", L"[NAN]", L"[+NAN]");
565 }
566 
TEST(STDIO_TEST,swprintf)567 TEST(STDIO_TEST, swprintf) {
568   constexpr size_t nchars = 32;
569   wchar_t buf[nchars];
570 
571   ASSERT_EQ(2, swprintf(buf, nchars, L"ab")) << strerror(errno);
572   ASSERT_EQ(std::wstring(L"ab"), buf);
573   ASSERT_EQ(5, swprintf(buf, nchars, L"%s", "abcde"));
574   ASSERT_EQ(std::wstring(L"abcde"), buf);
575 
576   // Unlike swprintf(), swprintf() returns -1 in case of truncation
577   // and doesn't necessarily zero-terminate the output!
578   ASSERT_EQ(-1, swprintf(buf, 4, L"%s", "abcde"));
579 
580   const char kString[] = "Hello, World";
581   ASSERT_EQ(12, swprintf(buf, nchars, L"%s", kString));
582   ASSERT_EQ(std::wstring(L"Hello, World"), buf);
583   ASSERT_EQ(12, swprintf(buf, 13, L"%s", kString));
584   ASSERT_EQ(std::wstring(L"Hello, World"), buf);
585 }
586 
TEST(STDIO_TEST,swprintf_a)587 TEST(STDIO_TEST, swprintf_a) {
588   constexpr size_t nchars = 32;
589   wchar_t buf[nchars];
590 
591   ASSERT_EQ(20, swprintf(buf, nchars, L"%a", 3.1415926535));
592   ASSERT_EQ(std::wstring(L"0x1.921fb54411744p+1"), buf);
593 }
594 
TEST(STDIO_TEST,swprintf_lc)595 TEST(STDIO_TEST, swprintf_lc) {
596   constexpr size_t nchars = 32;
597   wchar_t buf[nchars];
598 
599   wint_t wc = L'a';
600   EXPECT_EQ(3, swprintf(buf, nchars, L"<%lc>", wc));
601   EXPECT_EQ(std::wstring(L"<a>"), buf);
602 }
603 
TEST(STDIO_TEST,swprintf_C)604 TEST(STDIO_TEST, swprintf_C) { // Synonym for %lc.
605   constexpr size_t nchars = 32;
606   wchar_t buf[nchars];
607 
608   wint_t wc = L'a';
609   EXPECT_EQ(3, swprintf(buf, nchars, L"<%C>", wc));
610   EXPECT_EQ(std::wstring(L"<a>"), buf);
611 }
612 
TEST(STDIO_TEST,swprintf_jd_INTMAX_MAX)613 TEST(STDIO_TEST, swprintf_jd_INTMAX_MAX) {
614   constexpr size_t nchars = 32;
615   wchar_t buf[nchars];
616 
617   swprintf(buf, nchars, L"%jd", INTMAX_MAX);
618   EXPECT_EQ(std::wstring(L"9223372036854775807"), buf);
619 }
620 
TEST(STDIO_TEST,swprintf_jd_INTMAX_MIN)621 TEST(STDIO_TEST, swprintf_jd_INTMAX_MIN) {
622   constexpr size_t nchars = 32;
623   wchar_t buf[nchars];
624 
625   swprintf(buf, nchars, L"%jd", INTMAX_MIN);
626   EXPECT_EQ(std::wstring(L"-9223372036854775808"), buf);
627 }
628 
TEST(STDIO_TEST,swprintf_ju_UINTMAX_MAX)629 TEST(STDIO_TEST, swprintf_ju_UINTMAX_MAX) {
630   constexpr size_t nchars = 32;
631   wchar_t buf[nchars];
632 
633   swprintf(buf, nchars, L"%ju", UINTMAX_MAX);
634   EXPECT_EQ(std::wstring(L"18446744073709551615"), buf);
635 }
636 
TEST(STDIO_TEST,swprintf_1$ju_UINTMAX_MAX)637 TEST(STDIO_TEST, swprintf_1$ju_UINTMAX_MAX) {
638   constexpr size_t nchars = 32;
639   wchar_t buf[nchars];
640 
641   swprintf(buf, nchars, L"%1$ju", UINTMAX_MAX);
642   EXPECT_EQ(std::wstring(L"18446744073709551615"), buf);
643 }
644 
TEST(STDIO_TEST,swprintf_ls)645 TEST(STDIO_TEST, swprintf_ls) {
646   constexpr size_t nchars = 32;
647   wchar_t buf[nchars];
648 
649   static const wchar_t kWideString[] = L"Hello\uff41 World";
650   ASSERT_EQ(12, swprintf(buf, nchars, L"%ls", kWideString));
651   ASSERT_EQ(std::wstring(kWideString), buf);
652   ASSERT_EQ(12, swprintf(buf, 13, L"%ls", kWideString));
653   ASSERT_EQ(std::wstring(kWideString), buf);
654 }
655 
TEST(STDIO_TEST,swprintf_S)656 TEST(STDIO_TEST, swprintf_S) { // Synonym for %ls.
657   constexpr size_t nchars = 32;
658   wchar_t buf[nchars];
659 
660   static const wchar_t kWideString[] = L"Hello\uff41 World";
661   ASSERT_EQ(12, swprintf(buf, nchars, L"%S", kWideString));
662   ASSERT_EQ(std::wstring(kWideString), buf);
663   ASSERT_EQ(12, swprintf(buf, 13, L"%S", kWideString));
664   ASSERT_EQ(std::wstring(kWideString), buf);
665 }
666 
TEST(STDIO_TEST,snprintf_d_INT_MAX)667 TEST(STDIO_TEST, snprintf_d_INT_MAX) {
668   char buf[BUFSIZ];
669   snprintf(buf, sizeof(buf), "%d", INT_MAX);
670   EXPECT_STREQ("2147483647", buf);
671 }
672 
TEST(STDIO_TEST,snprintf_d_INT_MIN)673 TEST(STDIO_TEST, snprintf_d_INT_MIN) {
674   char buf[BUFSIZ];
675   snprintf(buf, sizeof(buf), "%d", INT_MIN);
676   EXPECT_STREQ("-2147483648", buf);
677 }
678 
TEST(STDIO_TEST,snprintf_jd_INTMAX_MAX)679 TEST(STDIO_TEST, snprintf_jd_INTMAX_MAX) {
680   char buf[BUFSIZ];
681   snprintf(buf, sizeof(buf), "%jd", INTMAX_MAX);
682   EXPECT_STREQ("9223372036854775807", buf);
683 }
684 
TEST(STDIO_TEST,snprintf_jd_INTMAX_MIN)685 TEST(STDIO_TEST, snprintf_jd_INTMAX_MIN) {
686   char buf[BUFSIZ];
687   snprintf(buf, sizeof(buf), "%jd", INTMAX_MIN);
688   EXPECT_STREQ("-9223372036854775808", buf);
689 }
690 
TEST(STDIO_TEST,snprintf_ju_UINTMAX_MAX)691 TEST(STDIO_TEST, snprintf_ju_UINTMAX_MAX) {
692   char buf[BUFSIZ];
693   snprintf(buf, sizeof(buf), "%ju", UINTMAX_MAX);
694   EXPECT_STREQ("18446744073709551615", buf);
695 }
696 
TEST(STDIO_TEST,snprintf_1$ju_UINTMAX_MAX)697 TEST(STDIO_TEST, snprintf_1$ju_UINTMAX_MAX) {
698   char buf[BUFSIZ];
699   snprintf(buf, sizeof(buf), "%1$ju", UINTMAX_MAX);
700   EXPECT_STREQ("18446744073709551615", buf);
701 }
702 
TEST(STDIO_TEST,snprintf_ld_LONG_MAX)703 TEST(STDIO_TEST, snprintf_ld_LONG_MAX) {
704   char buf[BUFSIZ];
705   snprintf(buf, sizeof(buf), "%ld", LONG_MAX);
706 #if defined(__LP64__)
707   EXPECT_STREQ("9223372036854775807", buf);
708 #else
709   EXPECT_STREQ("2147483647", buf);
710 #endif
711 }
712 
TEST(STDIO_TEST,snprintf_ld_LONG_MIN)713 TEST(STDIO_TEST, snprintf_ld_LONG_MIN) {
714   char buf[BUFSIZ];
715   snprintf(buf, sizeof(buf), "%ld", LONG_MIN);
716 #if defined(__LP64__)
717   EXPECT_STREQ("-9223372036854775808", buf);
718 #else
719   EXPECT_STREQ("-2147483648", buf);
720 #endif
721 }
722 
TEST(STDIO_TEST,snprintf_lld_LLONG_MAX)723 TEST(STDIO_TEST, snprintf_lld_LLONG_MAX) {
724   char buf[BUFSIZ];
725   snprintf(buf, sizeof(buf), "%lld", LLONG_MAX);
726   EXPECT_STREQ("9223372036854775807", buf);
727 }
728 
TEST(STDIO_TEST,snprintf_lld_LLONG_MIN)729 TEST(STDIO_TEST, snprintf_lld_LLONG_MIN) {
730   char buf[BUFSIZ];
731   snprintf(buf, sizeof(buf), "%lld", LLONG_MIN);
732   EXPECT_STREQ("-9223372036854775808", buf);
733 }
734 
TEST(STDIO_TEST,snprintf_o_UINT_MAX)735 TEST(STDIO_TEST, snprintf_o_UINT_MAX) {
736   char buf[BUFSIZ];
737   snprintf(buf, sizeof(buf), "%o", UINT_MAX);
738   EXPECT_STREQ("37777777777", buf);
739 }
740 
TEST(STDIO_TEST,snprintf_u_UINT_MAX)741 TEST(STDIO_TEST, snprintf_u_UINT_MAX) {
742   char buf[BUFSIZ];
743   snprintf(buf, sizeof(buf), "%u", UINT_MAX);
744   EXPECT_STREQ("4294967295", buf);
745 }
746 
TEST(STDIO_TEST,snprintf_x_UINT_MAX)747 TEST(STDIO_TEST, snprintf_x_UINT_MAX) {
748   char buf[BUFSIZ];
749   snprintf(buf, sizeof(buf), "%x", UINT_MAX);
750   EXPECT_STREQ("ffffffff", buf);
751 }
752 
TEST(STDIO_TEST,snprintf_X_UINT_MAX)753 TEST(STDIO_TEST, snprintf_X_UINT_MAX) {
754   char buf[BUFSIZ];
755   snprintf(buf, sizeof(buf), "%X", UINT_MAX);
756   EXPECT_STREQ("FFFFFFFF", buf);
757 }
758 
TEST(STDIO_TEST,snprintf_e)759 TEST(STDIO_TEST, snprintf_e) {
760   char buf[BUFSIZ];
761 
762   snprintf(buf, sizeof(buf), "%e", 1.5);
763   EXPECT_STREQ("1.500000e+00", buf);
764 
765   snprintf(buf, sizeof(buf), "%Le", 1.5L);
766   EXPECT_STREQ("1.500000e+00", buf);
767 }
768 
TEST(STDIO_TEST,snprintf_negative_zero_5084292)769 TEST(STDIO_TEST, snprintf_negative_zero_5084292) {
770   char buf[BUFSIZ];
771 
772   snprintf(buf, sizeof(buf), "%e", -0.0);
773   EXPECT_STREQ("-0.000000e+00", buf);
774   snprintf(buf, sizeof(buf), "%E", -0.0);
775   EXPECT_STREQ("-0.000000E+00", buf);
776   snprintf(buf, sizeof(buf), "%f", -0.0);
777   EXPECT_STREQ("-0.000000", buf);
778   snprintf(buf, sizeof(buf), "%F", -0.0);
779   EXPECT_STREQ("-0.000000", buf);
780   snprintf(buf, sizeof(buf), "%g", -0.0);
781   EXPECT_STREQ("-0", buf);
782   snprintf(buf, sizeof(buf), "%G", -0.0);
783   EXPECT_STREQ("-0", buf);
784   snprintf(buf, sizeof(buf), "%a", -0.0);
785   EXPECT_STREQ("-0x0p+0", buf);
786   snprintf(buf, sizeof(buf), "%A", -0.0);
787   EXPECT_STREQ("-0X0P+0", buf);
788 }
789 
TEST(STDIO_TEST,snprintf_utf8_15439554)790 TEST(STDIO_TEST, snprintf_utf8_15439554) {
791   locale_t cloc = newlocale(LC_ALL, "C.UTF-8", nullptr);
792   locale_t old_locale = uselocale(cloc);
793 
794   // http://b/15439554
795   char buf[BUFSIZ];
796 
797   // 1-byte character.
798   snprintf(buf, sizeof(buf), "%dx%d", 1, 2);
799   EXPECT_STREQ("1x2", buf);
800   // 2-byte character.
801   snprintf(buf, sizeof(buf), "%d\xc2\xa2%d", 1, 2);
802   EXPECT_STREQ("1¢2", buf);
803   // 3-byte character.
804   snprintf(buf, sizeof(buf), "%d\xe2\x82\xac%d", 1, 2);
805   EXPECT_STREQ("1€2", buf);
806   // 4-byte character.
807   snprintf(buf, sizeof(buf), "%d\xf0\xa4\xad\xa2%d", 1, 2);
808   EXPECT_STREQ("1��2", buf);
809 
810   uselocale(old_locale);
811   freelocale(cloc);
812 }
813 
snprintf_small_stack_fn(void *)814 static void* snprintf_small_stack_fn(void*) {
815   // Make life (realistically) hard for ourselves by allocating our own buffer for the result.
816   char buf[PATH_MAX];
817   snprintf(buf, sizeof(buf), "/proc/%d", getpid());
818   return nullptr;
819 }
820 
TEST(STDIO_TEST,snprintf_small_stack)821 TEST(STDIO_TEST, snprintf_small_stack) {
822   // Is it safe to call snprintf on a thread with a small stack?
823   // (The snprintf implementation puts some pretty large buffers on the stack.)
824   pthread_attr_t a;
825   ASSERT_EQ(0, pthread_attr_init(&a));
826   ASSERT_EQ(0, pthread_attr_setstacksize(&a, PTHREAD_STACK_MIN));
827 
828   pthread_t t;
829   ASSERT_EQ(0, pthread_create(&t, &a, snprintf_small_stack_fn, nullptr));
830   ASSERT_EQ(0, pthread_join(t, nullptr));
831 }
832 
TEST(STDIO_TEST,snprintf_asterisk_overflow)833 TEST(STDIO_TEST, snprintf_asterisk_overflow) {
834   char buf[128];
835   ASSERT_EQ(5, snprintf(buf, sizeof(buf), "%.*s%c", 4, "hello world", '!'));
836   ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.*s%c", INT_MAX/2, "hello world", '!'));
837   ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.*s%c", INT_MAX-1, "hello world", '!'));
838   ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.*s%c", INT_MAX, "hello world", '!'));
839   ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.*s%c", -1, "hello world", '!'));
840 
841   // INT_MAX-1, INT_MAX, INT_MAX+1.
842   ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.2147483646s%c", "hello world", '!'));
843   ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.2147483647s%c", "hello world", '!'));
844   ASSERT_EQ(-1, snprintf(buf, sizeof(buf), "%.2147483648s%c", "hello world", '!'));
845   ASSERT_EQ(ENOMEM, errno);
846 }
847 
TEST(STDIO_TEST,fprintf)848 TEST(STDIO_TEST, fprintf) {
849   TemporaryFile tf;
850 
851   FILE* tfile = fdopen(tf.fd, "r+");
852   ASSERT_TRUE(tfile != nullptr);
853 
854   ASSERT_EQ(7, fprintf(tfile, "%d %s", 123, "abc"));
855   AssertFileIs(tfile, "123 abc");
856   fclose(tfile);
857 }
858 
TEST(STDIO_TEST,fprintf_failures_7229520)859 TEST(STDIO_TEST, fprintf_failures_7229520) {
860   // http://b/7229520
861   FILE* fp;
862   int fd_rdonly = open("/dev/null", O_RDONLY);
863   ASSERT_NE(-1, fd_rdonly);
864 
865   // Unbuffered case where the fprintf(3) itself fails.
866   ASSERT_NE(nullptr, fp = tmpfile());
867   setbuf(fp, nullptr);
868   ASSERT_EQ(4, fprintf(fp, "epic"));
869   ASSERT_NE(-1, dup2(fd_rdonly, fileno(fp)));
870   ASSERT_EQ(-1, fprintf(fp, "fail"));
871   ASSERT_EQ(0, fclose(fp));
872 
873   // Buffered case where we won't notice until the fclose(3).
874   // It's likely this is what was actually seen in http://b/7229520,
875   // and that expecting fprintf to fail is setting yourself up for
876   // disappointment. Remember to check fclose(3)'s return value, kids!
877   ASSERT_NE(nullptr, fp = tmpfile());
878   ASSERT_EQ(4, fprintf(fp, "epic"));
879   ASSERT_NE(-1, dup2(fd_rdonly, fileno(fp)));
880   ASSERT_EQ(4, fprintf(fp, "fail"));
881   ASSERT_EQ(-1, fclose(fp));
882 }
883 
TEST(STDIO_TEST,popen_r)884 TEST(STDIO_TEST, popen_r) {
885   FILE* fp = popen("cat /proc/version", "r");
886   ASSERT_TRUE(fp != nullptr);
887 
888   char buf[16];
889   char* s = fgets(buf, sizeof(buf), fp);
890   buf[13] = '\0';
891   ASSERT_STREQ("Linux version", s);
892 
893   ASSERT_EQ(0, pclose(fp));
894 }
895 
TEST(STDIO_TEST,popen_socketpair)896 TEST(STDIO_TEST, popen_socketpair) {
897   FILE* fp = popen("cat", "r+");
898   ASSERT_TRUE(fp != nullptr);
899 
900   fputs("hello\nworld\n", fp);
901   fflush(fp);
902 
903   char buf[16];
904   ASSERT_NE(nullptr, fgets(buf, sizeof(buf), fp));
905   EXPECT_STREQ("hello\n", buf);
906   ASSERT_NE(nullptr, fgets(buf, sizeof(buf), fp));
907   EXPECT_STREQ("world\n", buf);
908 
909   ASSERT_EQ(0, pclose(fp));
910 }
911 
TEST(STDIO_TEST,popen_socketpair_shutdown)912 TEST(STDIO_TEST, popen_socketpair_shutdown) {
913   FILE* fp = popen("uniq -c", "r+");
914   ASSERT_TRUE(fp != nullptr);
915 
916   fputs("a\na\na\na\nb\n", fp);
917   fflush(fp);
918   ASSERT_EQ(0, shutdown(fileno(fp), SHUT_WR));
919 
920   char buf[16];
921   ASSERT_NE(nullptr, fgets(buf, sizeof(buf), fp));
922   EXPECT_STREQ("      4 a\n", buf);
923   ASSERT_NE(nullptr, fgets(buf, sizeof(buf), fp));
924   EXPECT_STREQ("      1 b\n", buf);
925 
926   ASSERT_EQ(0, pclose(fp));
927 }
928 
TEST(STDIO_TEST,popen_return_value_0)929 TEST(STDIO_TEST, popen_return_value_0) {
930   FILE* fp = popen("true", "r");
931   ASSERT_TRUE(fp != nullptr);
932   int status = pclose(fp);
933   EXPECT_TRUE(WIFEXITED(status));
934   EXPECT_EQ(0, WEXITSTATUS(status));
935 }
936 
TEST(STDIO_TEST,popen_return_value_1)937 TEST(STDIO_TEST, popen_return_value_1) {
938   FILE* fp = popen("false", "r");
939   ASSERT_TRUE(fp != nullptr);
940   int status = pclose(fp);
941   EXPECT_TRUE(WIFEXITED(status));
942   EXPECT_EQ(1, WEXITSTATUS(status));
943 }
944 
TEST(STDIO_TEST,popen_return_value_signal)945 TEST(STDIO_TEST, popen_return_value_signal) {
946   FILE* fp = popen("kill -7 $$", "r");
947   ASSERT_TRUE(fp != nullptr);
948   int status = pclose(fp);
949   EXPECT_TRUE(WIFSIGNALED(status));
950   EXPECT_EQ(7, WTERMSIG(status));
951 }
952 
TEST(STDIO_TEST,getc)953 TEST(STDIO_TEST, getc) {
954   FILE* fp = fopen("/proc/version", "r");
955   ASSERT_TRUE(fp != nullptr);
956   ASSERT_EQ('L', getc(fp));
957   ASSERT_EQ('i', getc(fp));
958   ASSERT_EQ('n', getc(fp));
959   ASSERT_EQ('u', getc(fp));
960   ASSERT_EQ('x', getc(fp));
961   fclose(fp);
962 }
963 
TEST(STDIO_TEST,putc)964 TEST(STDIO_TEST, putc) {
965   FILE* fp = fopen("/proc/version", "r");
966   ASSERT_TRUE(fp != nullptr);
967   ASSERT_EQ(EOF, putc('x', fp));
968   fclose(fp);
969 }
970 
TEST(STDIO_TEST,sscanf_swscanf)971 TEST(STDIO_TEST, sscanf_swscanf) {
972   struct stuff {
973     char s1[123];
974     int i1, i2;
975     char cs1[3];
976     char s2[3];
977     char c1;
978     double d1;
979     float f1;
980     char s3[123];
981 
982     void Check() {
983       EXPECT_STREQ("hello", s1);
984       EXPECT_EQ(123, i1);
985       EXPECT_EQ(456, i2);
986       EXPECT_EQ('a', cs1[0]);
987       EXPECT_EQ('b', cs1[1]);
988       EXPECT_EQ('x', cs1[2]); // No terminating NUL.
989       EXPECT_STREQ("AB", s2); // Terminating NUL.
990       EXPECT_EQ('!', c1);
991       EXPECT_DOUBLE_EQ(1.23, d1);
992       EXPECT_FLOAT_EQ(9.0f, f1);
993       EXPECT_STREQ("world", s3);
994     }
995   } s;
996 
997   memset(&s, 'x', sizeof(s));
998   ASSERT_EQ(9, sscanf("  hello 123 456abAB! 1.23 0x1.2p3 world",
999                       "%s %i%i%2c%[A-Z]%c %lf %f %s",
1000                       s.s1, &s.i1, &s.i2, s.cs1, s.s2, &s.c1, &s.d1, &s.f1, s.s3));
1001   s.Check();
1002 
1003   memset(&s, 'x', sizeof(s));
1004   ASSERT_EQ(9, swscanf(L"  hello 123 456abAB! 1.23 0x1.2p3 world",
1005                        L"%s %i%i%2c%[A-Z]%c %lf %f %s",
1006                        s.s1, &s.i1, &s.i2, s.cs1, s.s2, &s.c1, &s.d1, &s.f1, s.s3));
1007   s.Check();
1008 }
1009 
1010 template <typename T>
CheckScanf(int sscanf_fn (const T *,const T *,...),const T * input,const T * fmt,int expected_count,const char * expected_string)1011 static void CheckScanf(int sscanf_fn(const T*, const T*, ...),
1012                        const T* input, const T* fmt,
1013                        int expected_count, const char* expected_string) {
1014   char buf[256] = {};
1015   ASSERT_EQ(expected_count, sscanf_fn(input, fmt, &buf)) << fmt;
1016   ASSERT_STREQ(expected_string, buf) << fmt;
1017 }
1018 
TEST(STDIO_TEST,sscanf_ccl)1019 TEST(STDIO_TEST, sscanf_ccl) {
1020   // `abc` is just those characters.
1021   CheckScanf(sscanf, "abcd", "%[abc]", 1, "abc");
1022   // `a-c` is the range 'a' .. 'c'.
1023   CheckScanf(sscanf, "abcd", "%[a-c]", 1, "abc");
1024   CheckScanf(sscanf, "-d", "%[a-c]", 0, "");
1025   CheckScanf(sscanf, "ac-bAd", "%[a--c]", 1, "ac-bA");
1026   // `a-c-e` is equivalent to `a-e`.
1027   CheckScanf(sscanf, "abcdefg", "%[a-c-e]", 1, "abcde");
1028   // `e-a` is equivalent to `ae-` (because 'e' > 'a').
1029   CheckScanf(sscanf, "-a-e-b", "%[e-a]", 1, "-a-e-");
1030   // An initial '^' negates the set.
1031   CheckScanf(sscanf, "abcde", "%[^d]", 1, "abc");
1032   CheckScanf(sscanf, "abcdefgh", "%[^c-d]", 1, "ab");
1033   CheckScanf(sscanf, "hgfedcba", "%[^c-d]", 1, "hgfe");
1034   // The first character may be ']' or '-' without being special.
1035   CheckScanf(sscanf, "[[]]x", "%[][]", 1, "[[]]");
1036   CheckScanf(sscanf, "-a-x", "%[-a]", 1, "-a-");
1037   // The last character may be '-' without being special.
1038   CheckScanf(sscanf, "-a-x", "%[a-]", 1, "-a-");
1039   // X--Y is [X--] + Y, not [X--] + [--Y] (a bug in my initial implementation).
1040   CheckScanf(sscanf, "+,-/.", "%[+--/]", 1, "+,-/");
1041 }
1042 
TEST(STDIO_TEST,swscanf_ccl)1043 TEST(STDIO_TEST, swscanf_ccl) {
1044   // `abc` is just those characters.
1045   CheckScanf(swscanf, L"abcd", L"%[abc]", 1, "abc");
1046   // `a-c` is the range 'a' .. 'c'.
1047   CheckScanf(swscanf, L"abcd", L"%[a-c]", 1, "abc");
1048   CheckScanf(swscanf, L"-d", L"%[a-c]", 0, "");
1049   CheckScanf(swscanf, L"ac-bAd", L"%[a--c]", 1, "ac-bA");
1050   // `a-c-e` is equivalent to `a-e`.
1051   CheckScanf(swscanf, L"abcdefg", L"%[a-c-e]", 1, "abcde");
1052   // `e-a` is equivalent to `ae-` (because 'e' > 'a').
1053   CheckScanf(swscanf, L"-a-e-b", L"%[e-a]", 1, "-a-e-");
1054   // An initial '^' negates the set.
1055   CheckScanf(swscanf, L"abcde", L"%[^d]", 1, "abc");
1056   CheckScanf(swscanf, L"abcdefgh", L"%[^c-d]", 1, "ab");
1057   CheckScanf(swscanf, L"hgfedcba", L"%[^c-d]", 1, "hgfe");
1058   // The first character may be ']' or '-' without being special.
1059   CheckScanf(swscanf, L"[[]]x", L"%[][]", 1, "[[]]");
1060   CheckScanf(swscanf, L"-a-x", L"%[-a]", 1, "-a-");
1061   // The last character may be '-' without being special.
1062   CheckScanf(swscanf, L"-a-x", L"%[a-]", 1, "-a-");
1063   // X--Y is [X--] + Y, not [X--] + [--Y] (a bug in my initial implementation).
1064   CheckScanf(swscanf, L"+,-/.", L"%[+--/]", 1, "+,-/");
1065 }
1066 
1067 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)1068 static void CheckScanfM(int sscanf_fn(const T1*, const T1*, ...),
1069                         const T1* input, const T1* fmt,
1070                         int expected_count, const T2* expected_string) {
1071   T2* result = nullptr;
1072   ASSERT_EQ(expected_count, sscanf_fn(input, fmt, &result)) << fmt;
1073   if (expected_string == nullptr) {
1074     ASSERT_EQ(nullptr, result);
1075   } else {
1076     ASSERT_STREQ(expected_string, result) << fmt;
1077   }
1078   free(result);
1079 }
1080 
TEST(STDIO_TEST,sscanf_mc)1081 TEST(STDIO_TEST, sscanf_mc) {
1082   char* p1 = nullptr;
1083   char* p2 = nullptr;
1084   ASSERT_EQ(2, sscanf("hello", "%mc%mc", &p1, &p2));
1085   ASSERT_EQ('h', *p1);
1086   ASSERT_EQ('e', *p2);
1087   free(p1);
1088   free(p2);
1089 
1090   p1 = nullptr;
1091   ASSERT_EQ(1, sscanf("hello", "%4mc", &p1));
1092   ASSERT_EQ('h', p1[0]);
1093   ASSERT_EQ('e', p1[1]);
1094   ASSERT_EQ('l', p1[2]);
1095   ASSERT_EQ('l', p1[3]);
1096   free(p1);
1097 
1098   p1 = nullptr;
1099   ASSERT_EQ(1, sscanf("hello world", "%30mc", &p1));
1100   ASSERT_EQ('h', p1[0]);
1101   ASSERT_EQ('e', p1[1]);
1102   ASSERT_EQ('l', p1[2]);
1103   ASSERT_EQ('l', p1[3]);
1104   ASSERT_EQ('o', p1[4]);
1105   free(p1);
1106 }
1107 
1108 
TEST(STDIO_TEST,sscanf_mlc)1109 TEST(STDIO_TEST, sscanf_mlc) {
1110   // This is so useless that clang doesn't even believe it exists...
1111 #pragma clang diagnostic push
1112 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
1113 #pragma clang diagnostic ignored "-Wformat-extra-args"
1114 
1115   wchar_t* p1 = nullptr;
1116   wchar_t* p2 = nullptr;
1117   ASSERT_EQ(2, sscanf("hello", "%mlc%mlc", &p1, &p2));
1118   ASSERT_EQ(L'h', *p1);
1119   ASSERT_EQ(L'e', *p2);
1120   free(p1);
1121   free(p2);
1122 
1123   p1 = nullptr;
1124   ASSERT_EQ(1, sscanf("hello", "%4mlc", &p1));
1125   ASSERT_EQ(L'h', p1[0]);
1126   ASSERT_EQ(L'e', p1[1]);
1127   ASSERT_EQ(L'l', p1[2]);
1128   ASSERT_EQ(L'l', p1[3]);
1129   free(p1);
1130 
1131   p1 = nullptr;
1132   ASSERT_EQ(1, sscanf("hello world", "%30mlc", &p1));
1133   ASSERT_EQ(L'h', p1[0]);
1134   ASSERT_EQ(L'e', p1[1]);
1135   ASSERT_EQ(L'l', p1[2]);
1136   ASSERT_EQ(L'l', p1[3]);
1137   ASSERT_EQ(L'o', p1[4]);
1138   free(p1);
1139 #pragma clang diagnostic pop
1140 }
1141 
1142 
TEST(STDIO_TEST,sscanf_ms)1143 TEST(STDIO_TEST, sscanf_ms) {
1144   CheckScanfM(sscanf, "hello", "%ms", 1, "hello");
1145   CheckScanfM(sscanf, "hello", "%4ms", 1, "hell");
1146   CheckScanfM(sscanf, "hello world", "%30ms", 1, "hello");
1147 }
1148 
TEST(STDIO_TEST,sscanf_mls)1149 TEST(STDIO_TEST, sscanf_mls) {
1150   CheckScanfM(sscanf, "hello", "%mls", 1, L"hello");
1151   CheckScanfM(sscanf, "hello", "%4mls", 1, L"hell");
1152   CheckScanfM(sscanf, "hello world", "%30mls", 1, L"hello");
1153 }
1154 
TEST(STDIO_TEST,sscanf_m_ccl)1155 TEST(STDIO_TEST, sscanf_m_ccl) {
1156   CheckScanfM(sscanf, "hello", "%m[a-z]", 1, "hello");
1157   CheckScanfM(sscanf, "hello", "%4m[a-z]", 1, "hell");
1158   CheckScanfM(sscanf, "hello world", "%30m[a-z]", 1, "hello");
1159 }
1160 
TEST(STDIO_TEST,sscanf_ml_ccl)1161 TEST(STDIO_TEST, sscanf_ml_ccl) {
1162   CheckScanfM(sscanf, "hello", "%ml[a-z]", 1, L"hello");
1163   CheckScanfM(sscanf, "hello", "%4ml[a-z]", 1, L"hell");
1164   CheckScanfM(sscanf, "hello world", "%30ml[a-z]", 1, L"hello");
1165 }
1166 
TEST(STDIO_TEST,sscanf_ls)1167 TEST(STDIO_TEST, sscanf_ls) {
1168   wchar_t w[32] = {};
1169   ASSERT_EQ(1, sscanf("hello world", "%ls", w));
1170   ASSERT_EQ(L"hello", std::wstring(w));
1171 }
1172 
TEST(STDIO_TEST,sscanf_ls_suppress)1173 TEST(STDIO_TEST, sscanf_ls_suppress) {
1174   ASSERT_EQ(0, sscanf("hello world", "%*ls %*ls"));
1175 }
1176 
TEST(STDIO_TEST,sscanf_ls_n)1177 TEST(STDIO_TEST, sscanf_ls_n) {
1178   setlocale(LC_ALL, "C.UTF-8");
1179   wchar_t w[32] = {};
1180   int pos = 0;
1181   ASSERT_EQ(1, sscanf("\xc4\x80", "%ls%n", w, &pos));
1182   ASSERT_EQ(static_cast<wchar_t>(256), w[0]);
1183   ASSERT_EQ(2, pos);
1184 }
1185 
TEST(STDIO_TEST,sscanf_ls_realloc)1186 TEST(STDIO_TEST, sscanf_ls_realloc) {
1187   // This is so useless that clang doesn't even believe it exists...
1188 #pragma clang diagnostic push
1189 #pragma clang diagnostic ignored "-Wformat-invalid-specifier"
1190 #pragma clang diagnostic ignored "-Wformat-extra-args"
1191   wchar_t* p1 = nullptr;
1192   wchar_t* p2 = nullptr;
1193   ASSERT_EQ(2, sscanf("1234567890123456789012345678901234567890 world", "%mls %mls", &p1, &p2));
1194   ASSERT_EQ(L"1234567890123456789012345678901234567890", std::wstring(p1));
1195   ASSERT_EQ(L"world", std::wstring(p2));
1196 #pragma clang diagnostic pop
1197 }
1198 
1199 // https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=202240
TEST(STDIO_TEST,scanf_wscanf_EOF)1200 TEST(STDIO_TEST, scanf_wscanf_EOF) {
1201   EXPECT_EQ(0, sscanf("b", "ab"));
1202   EXPECT_EQ(EOF, sscanf("", "a"));
1203   EXPECT_EQ(0, swscanf(L"b", L"ab"));
1204   EXPECT_EQ(EOF, swscanf(L"", L"a"));
1205 }
1206 
TEST(STDIO_TEST,scanf_invalid_UTF8)1207 TEST(STDIO_TEST, scanf_invalid_UTF8) {
1208 #if 0 // TODO: more tests invented during code review; no regressions, so fix later.
1209   char buf[BUFSIZ];
1210   wchar_t wbuf[BUFSIZ];
1211 
1212   memset(buf, 0, sizeof(buf));
1213   memset(wbuf, 0, sizeof(wbuf));
1214   EXPECT_EQ(0, sscanf("\xc0" " foo", "%ls %s", wbuf, buf));
1215 #endif
1216 }
1217 
TEST(STDIO_TEST,scanf_no_match_no_termination)1218 TEST(STDIO_TEST, scanf_no_match_no_termination) {
1219   char buf[4] = "x";
1220   EXPECT_EQ(0, sscanf("d", "%[abc]", buf));
1221   EXPECT_EQ('x', buf[0]);
1222   EXPECT_EQ(0, swscanf(L"d", L"%[abc]", buf));
1223   EXPECT_EQ('x', buf[0]);
1224 
1225   wchar_t wbuf[4] = L"x";
1226   EXPECT_EQ(0, swscanf(L"d", L"%l[abc]", wbuf));
1227   EXPECT_EQ(L'x', wbuf[0]);
1228 
1229   EXPECT_EQ(EOF, sscanf("", "%s", buf));
1230   EXPECT_EQ('x', buf[0]);
1231 
1232   EXPECT_EQ(EOF, swscanf(L"", L"%ls", wbuf));
1233   EXPECT_EQ(L'x', wbuf[0]);
1234 }
1235 
TEST(STDIO_TEST,scanf_wscanf_wide_character_class)1236 TEST(STDIO_TEST, scanf_wscanf_wide_character_class) {
1237 #if 0 // TODO: more tests invented during code review; no regressions, so fix later.
1238   wchar_t buf[BUFSIZ];
1239 
1240   // A wide character shouldn't match an ASCII-only class for scanf or wscanf.
1241   memset(buf, 0, sizeof(buf));
1242   EXPECT_EQ(1, sscanf("xÄ€yz", "%l[xy]", buf));
1243   EXPECT_EQ(L"x"s, std::wstring(buf));
1244   memset(buf, 0, sizeof(buf));
1245   EXPECT_EQ(1, swscanf(L"xÄ€yz", L"%l[xy]", buf));
1246   EXPECT_EQ(L"x"s, std::wstring(buf));
1247 
1248   // Even if scanf has wide characters in a class, they won't match...
1249   // TODO: is that a bug?
1250   memset(buf, 0, sizeof(buf));
1251   EXPECT_EQ(1, sscanf("xÄ€yz", "%l[xÄ€y]", buf));
1252   EXPECT_EQ(L"x"s, std::wstring(buf));
1253   // ...unless you use wscanf.
1254   memset(buf, 0, sizeof(buf));
1255   EXPECT_EQ(1, swscanf(L"xÄ€yz", L"%l[xÄ€y]", buf));
1256   EXPECT_EQ(L"xÄ€y"s, std::wstring(buf));
1257 
1258   // Negation only covers ASCII for scanf...
1259   memset(buf, 0, sizeof(buf));
1260   EXPECT_EQ(1, sscanf("xÄ€yz", "%l[^ab]", buf));
1261   EXPECT_EQ(L"x"s, std::wstring(buf));
1262   // ...but covers wide characters for wscanf.
1263   memset(buf, 0, sizeof(buf));
1264   EXPECT_EQ(1, swscanf(L"xÄ€yz", L"%l[^ab]", buf));
1265   EXPECT_EQ(L"xÄ€yz"s, std::wstring(buf));
1266 
1267   // We already determined that non-ASCII characters are ignored in scanf classes.
1268   memset(buf, 0, sizeof(buf));
1269   EXPECT_EQ(1, sscanf("x"
1270                       "\xc4\x80" // Matches a byte from each wide char in the class.
1271                       "\xc6\x82" // Neither byte is in the class.
1272                       "yz",
1273                       "%l[xy" "\xc5\x80" "\xc4\x81" "]", buf));
1274   EXPECT_EQ(L"x", std::wstring(buf));
1275   // bionic and glibc both behave badly for wscanf, so let's call it right for now...
1276   memset(buf, 0, sizeof(buf));
1277   EXPECT_EQ(1, swscanf(L"x"
1278                        L"\xc4\x80"
1279                        L"\xc6\x82"
1280                        L"yz",
1281                        L"%l[xy" L"\xc5\x80" L"\xc4\x81" L"]", buf));
1282   // Note that this isn't L"xÄ€" --- although the *bytes* matched, they're
1283   // not put back together as a wide character.
1284   EXPECT_EQ(L"x" L"\xc4" L"\x80", std::wstring(buf));
1285 #endif
1286 }
1287 
TEST(STDIO_TEST,cantwrite_EBADF)1288 TEST(STDIO_TEST, cantwrite_EBADF) {
1289   // If we open a file read-only...
1290   FILE* fp = fopen("/proc/version", "r");
1291 
1292   // ...all attempts to write to that file should return failure.
1293 
1294   // They should also set errno to EBADF. This isn't POSIX, but it's traditional.
1295   // glibc gets the wide-character functions wrong.
1296 
1297   errno = 0;
1298   EXPECT_EQ(EOF, putc('x', fp));
1299   EXPECT_EQ(EBADF, errno);
1300 
1301   errno = 0;
1302   EXPECT_EQ(EOF, fprintf(fp, "hello"));
1303   EXPECT_EQ(EBADF, errno);
1304 
1305   errno = 0;
1306   EXPECT_EQ(EOF, fwprintf(fp, L"hello"));
1307 #if defined(__BIONIC__)
1308   EXPECT_EQ(EBADF, errno);
1309 #endif
1310 
1311   errno = 0;
1312   EXPECT_EQ(0U, fwrite("hello", 1, 2, fp));
1313   EXPECT_EQ(EBADF, errno);
1314 
1315   errno = 0;
1316   EXPECT_EQ(EOF, fputs("hello", fp));
1317   EXPECT_EQ(EBADF, errno);
1318 
1319   errno = 0;
1320   EXPECT_EQ(WEOF, fputwc(L'x', fp));
1321 #if defined(__BIONIC__)
1322   EXPECT_EQ(EBADF, errno);
1323 #endif
1324 }
1325 
1326 // Tests that we can only have a consistent and correct fpos_t when using
1327 // f*pos functions (i.e. fpos doesn't get inside a multi byte character).
TEST(STDIO_TEST,consistent_fpos_t)1328 TEST(STDIO_TEST, consistent_fpos_t) {
1329   ASSERT_STREQ("C.UTF-8", setlocale(LC_CTYPE, "C.UTF-8"));
1330   uselocale(LC_GLOBAL_LOCALE);
1331 
1332   FILE* fp = tmpfile();
1333   ASSERT_TRUE(fp != nullptr);
1334 
1335   wchar_t mb_one_bytes = L'h';
1336   wchar_t mb_two_bytes = 0x00a2;
1337   wchar_t mb_three_bytes = 0x20ac;
1338   wchar_t mb_four_bytes = 0x24b62;
1339 
1340   // Write to file.
1341   ASSERT_EQ(mb_one_bytes, static_cast<wchar_t>(fputwc(mb_one_bytes, fp)));
1342   ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fputwc(mb_two_bytes, fp)));
1343   ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fputwc(mb_three_bytes, fp)));
1344   ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fputwc(mb_four_bytes, fp)));
1345 
1346   rewind(fp);
1347 
1348   // Record each character position.
1349   fpos_t pos1;
1350   fpos_t pos2;
1351   fpos_t pos3;
1352   fpos_t pos4;
1353   fpos_t pos5;
1354   EXPECT_EQ(0, fgetpos(fp, &pos1));
1355   ASSERT_EQ(mb_one_bytes, static_cast<wchar_t>(fgetwc(fp)));
1356   EXPECT_EQ(0, fgetpos(fp, &pos2));
1357   ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fgetwc(fp)));
1358   EXPECT_EQ(0, fgetpos(fp, &pos3));
1359   ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fgetwc(fp)));
1360   EXPECT_EQ(0, fgetpos(fp, &pos4));
1361   ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fgetwc(fp)));
1362   EXPECT_EQ(0, fgetpos(fp, &pos5));
1363 
1364 #if defined(__BIONIC__)
1365   // Bionic's fpos_t is just an alias for off_t. This is inherited from OpenBSD
1366   // upstream. Glibc differs by storing the mbstate_t inside its fpos_t. In
1367   // Bionic (and upstream OpenBSD) the mbstate_t is stored inside the FILE
1368   // structure.
1369   ASSERT_EQ(0, static_cast<off_t>(pos1));
1370   ASSERT_EQ(1, static_cast<off_t>(pos2));
1371   ASSERT_EQ(3, static_cast<off_t>(pos3));
1372   ASSERT_EQ(6, static_cast<off_t>(pos4));
1373   ASSERT_EQ(10, static_cast<off_t>(pos5));
1374 #endif
1375 
1376   // Exercise back and forth movements of the position.
1377   ASSERT_EQ(0, fsetpos(fp, &pos2));
1378   ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fgetwc(fp)));
1379   ASSERT_EQ(0, fsetpos(fp, &pos1));
1380   ASSERT_EQ(mb_one_bytes, static_cast<wchar_t>(fgetwc(fp)));
1381   ASSERT_EQ(0, fsetpos(fp, &pos4));
1382   ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fgetwc(fp)));
1383   ASSERT_EQ(0, fsetpos(fp, &pos3));
1384   ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fgetwc(fp)));
1385   ASSERT_EQ(0, fsetpos(fp, &pos5));
1386   ASSERT_EQ(WEOF, fgetwc(fp));
1387 
1388   fclose(fp);
1389 }
1390 
1391 // Exercise the interaction between fpos and seek.
TEST(STDIO_TEST,fpos_t_and_seek)1392 TEST(STDIO_TEST, fpos_t_and_seek) {
1393   ASSERT_STREQ("C.UTF-8", setlocale(LC_CTYPE, "C.UTF-8"));
1394   uselocale(LC_GLOBAL_LOCALE);
1395 
1396   // In glibc-2.16 fseek doesn't work properly in wide mode
1397   // (https://sourceware.org/bugzilla/show_bug.cgi?id=14543). One workaround is
1398   // to close and re-open the file. We do it in order to make the test pass
1399   // with all glibcs.
1400 
1401   TemporaryFile tf;
1402   FILE* fp = fdopen(tf.fd, "w+");
1403   ASSERT_TRUE(fp != nullptr);
1404 
1405   wchar_t mb_two_bytes = 0x00a2;
1406   wchar_t mb_three_bytes = 0x20ac;
1407   wchar_t mb_four_bytes = 0x24b62;
1408 
1409   // Write to file.
1410   ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fputwc(mb_two_bytes, fp)));
1411   ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fputwc(mb_three_bytes, fp)));
1412   ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fputwc(mb_four_bytes, fp)));
1413 
1414   fflush(fp);
1415   fclose(fp);
1416 
1417   fp = fopen(tf.path, "r");
1418   ASSERT_TRUE(fp != nullptr);
1419 
1420   // Store a valid position.
1421   fpos_t mb_two_bytes_pos;
1422   ASSERT_EQ(0, fgetpos(fp, &mb_two_bytes_pos));
1423 
1424   // Move inside mb_four_bytes with fseek.
1425   long offset_inside_mb = 6;
1426   ASSERT_EQ(0, fseek(fp, offset_inside_mb, SEEK_SET));
1427 
1428   // Store the "inside multi byte" position.
1429   fpos_t pos_inside_mb;
1430   ASSERT_EQ(0, fgetpos(fp, &pos_inside_mb));
1431 #if defined(__BIONIC__)
1432   ASSERT_EQ(offset_inside_mb, static_cast<off_t>(pos_inside_mb));
1433 #endif
1434 
1435   // Reading from within a byte should produce an error.
1436   ASSERT_EQ(WEOF, fgetwc(fp));
1437   ASSERT_EQ(EILSEQ, errno);
1438 
1439   // Reverting to a valid position should work.
1440   ASSERT_EQ(0, fsetpos(fp, &mb_two_bytes_pos));
1441   ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fgetwc(fp)));
1442 
1443   // Moving withing a multi byte with fsetpos should work but reading should
1444   // produce an error.
1445   ASSERT_EQ(0, fsetpos(fp, &pos_inside_mb));
1446   ASSERT_EQ(WEOF, fgetwc(fp));
1447   ASSERT_EQ(EILSEQ, errno);
1448 
1449   ASSERT_EQ(0, fclose(fp));
1450 }
1451 
TEST(STDIO_TEST,fmemopen)1452 TEST(STDIO_TEST, fmemopen) {
1453   char buf[16];
1454   memset(buf, 0, sizeof(buf));
1455   FILE* fp = fmemopen(buf, sizeof(buf), "r+");
1456   ASSERT_EQ('<', fputc('<', fp));
1457   ASSERT_NE(EOF, fputs("abc>\n", fp));
1458   fflush(fp);
1459 
1460   // We wrote to the buffer...
1461   ASSERT_STREQ("<abc>\n", buf);
1462 
1463   // And can read back from the file.
1464   AssertFileIs(fp, "<abc>\n", true);
1465   ASSERT_EQ(0, fclose(fp));
1466 }
1467 
TEST(STDIO_TEST,fmemopen_nullptr)1468 TEST(STDIO_TEST, fmemopen_nullptr) {
1469   FILE* fp = fmemopen(nullptr, 128, "r+");
1470   ASSERT_NE(EOF, fputs("xyz\n", fp));
1471 
1472   AssertFileIs(fp, "xyz\n", true);
1473   ASSERT_EQ(0, fclose(fp));
1474 }
1475 
TEST(STDIO_TEST,fmemopen_trailing_NUL_byte)1476 TEST(STDIO_TEST, fmemopen_trailing_NUL_byte) {
1477   FILE* fp;
1478   char buf[8];
1479 
1480   // POSIX: "When a stream open for writing is flushed or closed, a null byte
1481   // shall be written at the current position or at the end of the buffer,
1482   // depending on the size of the contents."
1483   memset(buf, 'x', sizeof(buf));
1484   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w"));
1485   // Even with nothing written (and not in truncate mode), we'll flush a NUL...
1486   ASSERT_EQ(0, fflush(fp));
1487   EXPECT_EQ("\0xxxxxxx"s, std::string(buf, buf + sizeof(buf)));
1488   // Now write and check that the NUL moves along with our writes...
1489   ASSERT_NE(EOF, fputs("hello", fp));
1490   ASSERT_EQ(0, fflush(fp));
1491   EXPECT_EQ("hello\0xx"s, std::string(buf, buf + sizeof(buf)));
1492   ASSERT_NE(EOF, fputs("wo", fp));
1493   ASSERT_EQ(0, fflush(fp));
1494   EXPECT_EQ("hellowo\0"s, std::string(buf, buf + sizeof(buf)));
1495   ASSERT_EQ(0, fclose(fp));
1496 
1497   // "If a stream open for update is flushed or closed and the last write has
1498   // advanced the current buffer size, a null byte shall be written at the end
1499   // of the buffer if it fits."
1500   memset(buf, 'x', sizeof(buf));
1501   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "r+"));
1502   // Nothing written yet, so no advance...
1503   ASSERT_EQ(0, fflush(fp));
1504   EXPECT_EQ("xxxxxxxx"s, std::string(buf, buf + sizeof(buf)));
1505   ASSERT_NE(EOF, fputs("hello", fp));
1506   ASSERT_EQ(0, fclose(fp));
1507 }
1508 
TEST(STDIO_TEST,fmemopen_size)1509 TEST(STDIO_TEST, fmemopen_size) {
1510   FILE* fp;
1511   char buf[16];
1512   memset(buf, 'x', sizeof(buf));
1513 
1514   // POSIX: "The stream shall also maintain the size of the current buffer
1515   // contents; use of fseek() or fseeko() on the stream with SEEK_END shall
1516   // seek relative to this size."
1517 
1518   // "For modes r and r+ the size shall be set to the value given by the size
1519   // argument."
1520   ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "r"));
1521   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1522   EXPECT_EQ(16, ftell(fp));
1523   EXPECT_EQ(16, ftello(fp));
1524   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1525   EXPECT_EQ(16, ftell(fp));
1526   EXPECT_EQ(16, ftello(fp));
1527   ASSERT_EQ(0, fclose(fp));
1528   ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "r+"));
1529   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1530   EXPECT_EQ(16, ftell(fp));
1531   EXPECT_EQ(16, ftello(fp));
1532   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1533   EXPECT_EQ(16, ftell(fp));
1534   EXPECT_EQ(16, ftello(fp));
1535   ASSERT_EQ(0, fclose(fp));
1536 
1537   // "For modes w and w+ the initial size shall be zero..."
1538   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "w"));
1539   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1540   EXPECT_EQ(0, ftell(fp));
1541   EXPECT_EQ(0, ftello(fp));
1542   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1543   EXPECT_EQ(0, ftell(fp));
1544   EXPECT_EQ(0, ftello(fp));
1545   ASSERT_EQ(0, fclose(fp));
1546   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "w+"));
1547   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1548   EXPECT_EQ(0, ftell(fp));
1549   EXPECT_EQ(0, ftello(fp));
1550   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1551   EXPECT_EQ(0, ftell(fp));
1552   EXPECT_EQ(0, ftello(fp));
1553   ASSERT_EQ(0, fclose(fp));
1554 
1555   // "...and for modes a and a+ the initial size shall be:
1556   // 1. Zero, if buf is a null pointer
1557   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "a"));
1558   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1559   EXPECT_EQ(0, ftell(fp));
1560   EXPECT_EQ(0, ftello(fp));
1561   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1562   EXPECT_EQ(0, ftell(fp));
1563   EXPECT_EQ(0, ftello(fp));
1564   ASSERT_EQ(0, fclose(fp));
1565   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "a+"));
1566   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1567   EXPECT_EQ(0, ftell(fp));
1568   EXPECT_EQ(0, ftello(fp));
1569   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1570   EXPECT_EQ(0, ftell(fp));
1571   EXPECT_EQ(0, ftello(fp));
1572   ASSERT_EQ(0, fclose(fp));
1573 
1574   // 2. The position of the first null byte in the buffer, if one is found
1575   memset(buf, 'x', sizeof(buf));
1576   buf[3] = '\0';
1577   ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "a"));
1578   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1579   EXPECT_EQ(3, ftell(fp));
1580   EXPECT_EQ(3, ftello(fp));
1581   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1582   EXPECT_EQ(3, ftell(fp));
1583   EXPECT_EQ(3, ftello(fp));
1584   ASSERT_EQ(0, fclose(fp));
1585   memset(buf, 'x', sizeof(buf));
1586   buf[3] = '\0';
1587   ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "a+"));
1588   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1589   EXPECT_EQ(3, ftell(fp));
1590   EXPECT_EQ(3, ftello(fp));
1591   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1592   EXPECT_EQ(3, ftell(fp));
1593   EXPECT_EQ(3, ftello(fp));
1594   ASSERT_EQ(0, fclose(fp));
1595 
1596   // 3. The value of the size argument, if buf is not a null pointer and no
1597   // null byte is found.
1598   memset(buf, 'x', sizeof(buf));
1599   ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "a"));
1600   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1601   EXPECT_EQ(16, ftell(fp));
1602   EXPECT_EQ(16, ftello(fp));
1603   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1604   EXPECT_EQ(16, ftell(fp));
1605   EXPECT_EQ(16, ftello(fp));
1606   ASSERT_EQ(0, fclose(fp));
1607   memset(buf, 'x', sizeof(buf));
1608   ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "a+"));
1609   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1610   EXPECT_EQ(16, ftell(fp));
1611   EXPECT_EQ(16, ftello(fp));
1612   ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1613   EXPECT_EQ(16, ftell(fp));
1614   EXPECT_EQ(16, ftello(fp));
1615   ASSERT_EQ(0, fclose(fp));
1616 }
1617 
TEST(STDIO_TEST,fmemopen_SEEK_END)1618 TEST(STDIO_TEST, fmemopen_SEEK_END) {
1619   // fseek SEEK_END is relative to the current string length, not the buffer size.
1620   FILE* fp;
1621   char buf[8];
1622   memset(buf, 'x', sizeof(buf));
1623   strcpy(buf, "str");
1624   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w+"));
1625   ASSERT_NE(EOF, fputs("string", fp));
1626   EXPECT_EQ(0, fseek(fp, 0, SEEK_END));
1627   EXPECT_EQ(static_cast<long>(strlen("string")), ftell(fp));
1628   EXPECT_EQ(static_cast<off_t>(strlen("string")), ftello(fp));
1629   EXPECT_EQ(0, fclose(fp));
1630 
1631   // glibc < 2.22 interpreted SEEK_END the wrong way round (subtracting rather
1632   // than adding).
1633   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w+"));
1634   ASSERT_NE(EOF, fputs("54321", fp));
1635   EXPECT_EQ(0, fseek(fp, -2, SEEK_END));
1636   EXPECT_EQ('2', fgetc(fp));
1637   EXPECT_EQ(0, fclose(fp));
1638 }
1639 
TEST(STDIO_TEST,fmemopen_seek_invalid)1640 TEST(STDIO_TEST, fmemopen_seek_invalid) {
1641   char buf[8];
1642   memset(buf, 'x', sizeof(buf));
1643   FILE* fp = fmemopen(buf, sizeof(buf), "w");
1644   ASSERT_TRUE(fp != nullptr);
1645 
1646   // POSIX: "An attempt to seek ... to a negative position or to a position
1647   // larger than the buffer size given in the size argument shall fail."
1648   // (There's no mention of what errno should be set to, and glibc doesn't
1649   // set errno in any of these cases.)
1650   EXPECT_EQ(-1, fseek(fp, -2, SEEK_SET));
1651   EXPECT_EQ(-1, fseeko(fp, -2, SEEK_SET));
1652   EXPECT_EQ(-1, fseek(fp, sizeof(buf) + 1, SEEK_SET));
1653   EXPECT_EQ(-1, fseeko(fp, sizeof(buf) + 1, SEEK_SET));
1654 }
1655 
TEST(STDIO_TEST,fmemopen_read_EOF)1656 TEST(STDIO_TEST, fmemopen_read_EOF) {
1657   // POSIX: "A read operation on the stream shall not advance the current
1658   // buffer position beyond the current buffer size."
1659   char buf[8];
1660   memset(buf, 'x', sizeof(buf));
1661   FILE* fp = fmemopen(buf, sizeof(buf), "r");
1662   ASSERT_TRUE(fp != nullptr);
1663   char buf2[BUFSIZ];
1664   ASSERT_EQ(8U, fread(buf2, 1, sizeof(buf2), fp));
1665   // POSIX: "Reaching the buffer size in a read operation shall count as
1666   // end-of-file.
1667   ASSERT_TRUE(feof(fp));
1668   ASSERT_EQ(EOF, fgetc(fp));
1669   ASSERT_EQ(0, fclose(fp));
1670 }
1671 
TEST(STDIO_TEST,fmemopen_read_null_bytes)1672 TEST(STDIO_TEST, fmemopen_read_null_bytes) {
1673   // POSIX: "Null bytes in the buffer shall have no special meaning for reads."
1674   char buf[] = "h\0e\0l\0l\0o";
1675   FILE* fp = fmemopen(buf, sizeof(buf), "r");
1676   ASSERT_TRUE(fp != nullptr);
1677   ASSERT_EQ('h', fgetc(fp));
1678   ASSERT_EQ(0, fgetc(fp));
1679   ASSERT_EQ('e', fgetc(fp));
1680   ASSERT_EQ(0, fgetc(fp));
1681   ASSERT_EQ('l', fgetc(fp));
1682   ASSERT_EQ(0, fgetc(fp));
1683   // POSIX: "The read operation shall start at the current buffer position of
1684   // the stream."
1685   char buf2[8];
1686   memset(buf2, 'x', sizeof(buf2));
1687   ASSERT_EQ(4U, fread(buf2, 1, sizeof(buf2), fp));
1688   ASSERT_EQ('l', buf2[0]);
1689   ASSERT_EQ(0, buf2[1]);
1690   ASSERT_EQ('o', buf2[2]);
1691   ASSERT_EQ(0, buf2[3]);
1692   for (size_t i = 4; i < sizeof(buf2); ++i) ASSERT_EQ('x', buf2[i]) << i;
1693   ASSERT_TRUE(feof(fp));
1694   ASSERT_EQ(0, fclose(fp));
1695 }
1696 
TEST(STDIO_TEST,fmemopen_write)1697 TEST(STDIO_TEST, fmemopen_write) {
1698   FILE* fp;
1699   char buf[8];
1700 
1701   // POSIX: "A write operation shall start either at the current position of
1702   // the stream (if mode has not specified 'a' as the first character)..."
1703   memset(buf, 'x', sizeof(buf));
1704   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "r+"));
1705   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1706   ASSERT_EQ(0, fseek(fp, 2, SEEK_SET));
1707   ASSERT_EQ(' ', fputc(' ', fp));
1708   EXPECT_EQ("xx xxxxx", std::string(buf, buf + sizeof(buf)));
1709   ASSERT_EQ(0, fclose(fp));
1710 
1711   // "...or at the current size of the stream (if mode had 'a' as the first
1712   // character)." (See the fmemopen_size test for what "size" means, but for
1713   // mode "a", it's the first NUL byte.)
1714   memset(buf, 'x', sizeof(buf));
1715   buf[3] = '\0';
1716   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a+"));
1717   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1718   ASSERT_EQ(' ', fputc(' ', fp));
1719   EXPECT_EQ("xxx \0xxx"s, std::string(buf, buf + sizeof(buf)));
1720   ASSERT_EQ(0, fclose(fp));
1721 
1722   // "If the current position at the end of the write is larger than the
1723   // current buffer size, the current buffer size shall be set to the current
1724   // position." (See the fmemopen_size test for what "size" means, but to
1725   // query it we SEEK_END with offset 0, and then ftell.)
1726   memset(buf, 'x', sizeof(buf));
1727   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w+"));
1728   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1729   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1730   EXPECT_EQ(0, ftell(fp));
1731   ASSERT_EQ(' ', fputc(' ', fp));
1732   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1733   EXPECT_EQ(1, ftell(fp));
1734   ASSERT_NE(EOF, fputs("123", fp));
1735   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1736   EXPECT_EQ(4, ftell(fp));
1737   EXPECT_EQ(" 123\0xxx"s, std::string(buf, buf + sizeof(buf)));
1738   ASSERT_EQ(0, fclose(fp));
1739 }
1740 
TEST(STDIO_TEST,fmemopen_write_EOF)1741 TEST(STDIO_TEST, fmemopen_write_EOF) {
1742   // POSIX: "A write operation on the stream shall not advance the current
1743   // buffer size beyond the size given in the size argument."
1744   FILE* fp;
1745 
1746   // Scalar writes...
1747   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 4, "w"));
1748   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1749   ASSERT_EQ('x', fputc('x', fp));
1750   ASSERT_EQ('x', fputc('x', fp));
1751   ASSERT_EQ('x', fputc('x', fp));
1752   ASSERT_EQ(EOF, fputc('x', fp)); // Only 3 fit because of the implicit NUL.
1753   ASSERT_EQ(0, fclose(fp));
1754 
1755   // Vector writes...
1756   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 4, "w"));
1757   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1758   ASSERT_EQ(3U, fwrite("xxxx", 1, 4, fp));
1759   ASSERT_EQ(0, fclose(fp));
1760 }
1761 
TEST(STDIO_TEST,fmemopen_initial_position)1762 TEST(STDIO_TEST, fmemopen_initial_position) {
1763   // POSIX: "The ... current position in the buffer ... shall be initially
1764   // set to either the beginning of the buffer (for r and w modes) ..."
1765   char buf[] = "hello\0world";
1766   FILE* fp;
1767   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "r"));
1768   EXPECT_EQ(0L, ftell(fp));
1769   EXPECT_EQ(0, fclose(fp));
1770   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w"));
1771   EXPECT_EQ(0L, ftell(fp));
1772   EXPECT_EQ(0, fclose(fp));
1773   buf[0] = 'h'; // (Undo the effects of the above.)
1774 
1775   // POSIX: "...or to the first null byte in the buffer (for a modes)."
1776   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a"));
1777   EXPECT_EQ(5L, ftell(fp));
1778   EXPECT_EQ(0, fclose(fp));
1779 
1780   // POSIX: "If no null byte is found in append mode, the initial position
1781   // shall be set to one byte after the end of the buffer."
1782   memset(buf, 'x', sizeof(buf));
1783   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a"));
1784   EXPECT_EQ(static_cast<long>(sizeof(buf)), ftell(fp));
1785   EXPECT_EQ(0, fclose(fp));
1786 }
1787 
TEST(STDIO_TEST,fmemopen_initial_position_allocated)1788 TEST(STDIO_TEST, fmemopen_initial_position_allocated) {
1789   // POSIX: "If buf is a null pointer, the initial position shall always be
1790   // set to the beginning of the buffer."
1791   FILE* fp = fmemopen(nullptr, 128, "a+");
1792   ASSERT_TRUE(fp != nullptr);
1793   EXPECT_EQ(0L, ftell(fp));
1794   EXPECT_EQ(0L, fseek(fp, 0, SEEK_SET));
1795   EXPECT_EQ(0, fclose(fp));
1796 }
1797 
TEST(STDIO_TEST,fmemopen_zero_length)1798 TEST(STDIO_TEST, fmemopen_zero_length) {
1799   // POSIX says it's up to the implementation whether or not you can have a
1800   // zero-length buffer (but "A future version of this standard may require
1801   // support of zero-length buffer streams explicitly"). BSD and glibc < 2.22
1802   // agreed that you couldn't, but glibc >= 2.22 allows it for consistency.
1803   FILE* fp;
1804   char buf[16];
1805   ASSERT_NE(nullptr, fp = fmemopen(buf, 0, "r+"));
1806   ASSERT_EQ(EOF, fgetc(fp));
1807   ASSERT_TRUE(feof(fp));
1808   ASSERT_EQ(0, fclose(fp));
1809   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 0, "r+"));
1810   ASSERT_EQ(EOF, fgetc(fp));
1811   ASSERT_TRUE(feof(fp));
1812   ASSERT_EQ(0, fclose(fp));
1813 
1814   ASSERT_NE(nullptr, fp = fmemopen(buf, 0, "w+"));
1815   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1816   ASSERT_EQ(EOF, fputc('x', fp));
1817   ASSERT_EQ(0, fclose(fp));
1818   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 0, "w+"));
1819   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1820   ASSERT_EQ(EOF, fputc('x', fp));
1821   ASSERT_EQ(0, fclose(fp));
1822 }
1823 
TEST(STDIO_TEST,fmemopen_zero_length_buffer_overrun)1824 TEST(STDIO_TEST, fmemopen_zero_length_buffer_overrun) {
1825   char buf[2] = "x";
1826   ASSERT_EQ('x', buf[0]);
1827   FILE* fp = fmemopen(buf, 0, "w");
1828   ASSERT_EQ('x', buf[0]);
1829   ASSERT_EQ(0, fclose(fp));
1830 }
1831 
TEST(STDIO_TEST,fmemopen_write_only_allocated)1832 TEST(STDIO_TEST, fmemopen_write_only_allocated) {
1833   // POSIX says fmemopen "may fail if the mode argument does not include a '+'".
1834   // BSD fails, glibc doesn't. We side with the more lenient.
1835   FILE* fp;
1836   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "r"));
1837   ASSERT_EQ(0, fclose(fp));
1838   ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "w"));
1839   ASSERT_EQ(0, fclose(fp));
1840 }
1841 
TEST(STDIO_TEST,fmemopen_fileno)1842 TEST(STDIO_TEST, fmemopen_fileno) {
1843   // There's no fd backing an fmemopen FILE*.
1844   FILE* fp = fmemopen(nullptr, 16, "r");
1845   ASSERT_TRUE(fp != nullptr);
1846   errno = 0;
1847   ASSERT_EQ(-1, fileno(fp));
1848   ASSERT_EQ(EBADF, errno);
1849   ASSERT_EQ(0, fclose(fp));
1850 }
1851 
TEST(STDIO_TEST,fmemopen_append_after_seek)1852 TEST(STDIO_TEST, fmemopen_append_after_seek) {
1853   // In BSD and glibc < 2.22, append mode didn't force writes to append if
1854   // there had been an intervening seek.
1855 
1856   FILE* fp;
1857   char buf[] = "hello\0world";
1858   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a"));
1859   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1860   ASSERT_EQ(0, fseek(fp, 0, SEEK_SET));
1861   ASSERT_NE(EOF, fputc('!', fp));
1862   EXPECT_EQ("hello!\0orld\0"s, std::string(buf, buf + sizeof(buf)));
1863   ASSERT_EQ(0, fclose(fp));
1864 
1865   memcpy(buf, "hello\0world", sizeof(buf));
1866   ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a+"));
1867   setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1868   ASSERT_EQ(0, fseek(fp, 0, SEEK_SET));
1869   ASSERT_NE(EOF, fputc('!', fp));
1870   EXPECT_EQ("hello!\0orld\0"s, std::string(buf, buf + sizeof(buf)));
1871   ASSERT_EQ(0, fclose(fp));
1872 }
1873 
TEST(STDIO_TEST,open_memstream)1874 TEST(STDIO_TEST, open_memstream) {
1875   char* p = nullptr;
1876   size_t size = 0;
1877   FILE* fp = open_memstream(&p, &size);
1878   ASSERT_NE(EOF, fputs("hello, world!", fp));
1879   fclose(fp);
1880 
1881   ASSERT_STREQ("hello, world!", p);
1882   ASSERT_EQ(strlen("hello, world!"), size);
1883   free(p);
1884 }
1885 
TEST(STDIO_TEST,open_memstream_EINVAL)1886 TEST(STDIO_TEST, open_memstream_EINVAL) {
1887 #if defined(__BIONIC__)
1888   char* p;
1889   size_t size;
1890 
1891   // Invalid buffer.
1892   errno = 0;
1893   ASSERT_EQ(nullptr, open_memstream(nullptr, &size));
1894   ASSERT_EQ(EINVAL, errno);
1895 
1896   // Invalid size.
1897   errno = 0;
1898   ASSERT_EQ(nullptr, open_memstream(&p, nullptr));
1899   ASSERT_EQ(EINVAL, errno);
1900 #else
1901   GTEST_SKIP() << "glibc is broken";
1902 #endif
1903 }
1904 
TEST(STDIO_TEST,fdopen_CLOEXEC)1905 TEST(STDIO_TEST, fdopen_CLOEXEC) {
1906   int fd = open("/proc/version", O_RDONLY);
1907   ASSERT_TRUE(fd != -1);
1908 
1909   // This fd doesn't have O_CLOEXEC...
1910   AssertCloseOnExec(fd, false);
1911 
1912   FILE* fp = fdopen(fd, "re");
1913   ASSERT_TRUE(fp != nullptr);
1914 
1915   // ...but the new one does.
1916   AssertCloseOnExec(fileno(fp), true);
1917 
1918   fclose(fp);
1919 }
1920 
TEST(STDIO_TEST,freopen_CLOEXEC)1921 TEST(STDIO_TEST, freopen_CLOEXEC) {
1922   FILE* fp = fopen("/proc/version", "r");
1923   ASSERT_TRUE(fp != nullptr);
1924 
1925   // This FILE* doesn't have O_CLOEXEC...
1926   AssertCloseOnExec(fileno(fp), false);
1927 
1928   fp = freopen("/proc/version", "re", fp);
1929 
1930   // ...but the new one does.
1931   AssertCloseOnExec(fileno(fp), true);
1932 
1933   fclose(fp);
1934 }
1935 
TEST(STDIO_TEST,fopen64_freopen64)1936 TEST(STDIO_TEST, fopen64_freopen64) {
1937   FILE* fp = fopen64("/proc/version", "r");
1938   ASSERT_TRUE(fp != nullptr);
1939   fp = freopen64("/proc/version", "re", fp);
1940   ASSERT_TRUE(fp != nullptr);
1941   fclose(fp);
1942 }
1943 
1944 // https://code.google.com/p/android/issues/detail?id=81155
1945 // http://b/18556607
TEST(STDIO_TEST,fread_unbuffered_pathological_performance)1946 TEST(STDIO_TEST, fread_unbuffered_pathological_performance) {
1947   FILE* fp = fopen("/dev/zero", "r");
1948   ASSERT_TRUE(fp != nullptr);
1949 
1950   // Make this stream unbuffered.
1951   setvbuf(fp, nullptr, _IONBF, 0);
1952 
1953   char buf[65*1024];
1954   memset(buf, 0xff, sizeof(buf));
1955 
1956   time_t t0 = time(nullptr);
1957   for (size_t i = 0; i < 1024; ++i) {
1958     ASSERT_EQ(1U, fread(buf, 64*1024, 1, fp));
1959   }
1960   time_t t1 = time(nullptr);
1961 
1962   fclose(fp);
1963 
1964   // 1024 64KiB reads should have been very quick.
1965   ASSERT_LE(t1 - t0, 1);
1966 
1967   for (size_t i = 0; i < 64*1024; ++i) {
1968     ASSERT_EQ('\0', buf[i]);
1969   }
1970   for (size_t i = 64*1024; i < 65*1024; ++i) {
1971     ASSERT_EQ('\xff', buf[i]);
1972   }
1973 }
1974 
TEST(STDIO_TEST,fread_EOF)1975 TEST(STDIO_TEST, fread_EOF) {
1976   std::string digits("0123456789");
1977   FILE* fp = fmemopen(&digits[0], digits.size(), "r");
1978 
1979   // Try to read too much, but little enough that it still fits in the FILE's internal buffer.
1980   char buf1[4 * 4];
1981   memset(buf1, 0, sizeof(buf1));
1982   ASSERT_EQ(2U, fread(buf1, 4, 4, fp));
1983   ASSERT_STREQ("0123456789", buf1);
1984   ASSERT_TRUE(feof(fp));
1985 
1986   rewind(fp);
1987 
1988   // Try to read way too much so stdio tries to read more direct from the stream.
1989   char buf2[4 * 4096];
1990   memset(buf2, 0, sizeof(buf2));
1991   ASSERT_EQ(2U, fread(buf2, 4, 4096, fp));
1992   ASSERT_STREQ("0123456789", buf2);
1993   ASSERT_TRUE(feof(fp));
1994 
1995   fclose(fp);
1996 }
1997 
test_fread_from_write_only_stream(size_t n)1998 static void test_fread_from_write_only_stream(size_t n) {
1999   FILE* fp = fopen("/dev/null", "w");
2000   std::vector<char> buf(n, 0);
2001   errno = 0;
2002   ASSERT_EQ(0U, fread(&buf[0], n, 1, fp));
2003   ASSERT_EQ(EBADF, errno);
2004   ASSERT_TRUE(ferror(fp));
2005   ASSERT_FALSE(feof(fp));
2006   fclose(fp);
2007 }
2008 
TEST(STDIO_TEST,fread_from_write_only_stream_slow_path)2009 TEST(STDIO_TEST, fread_from_write_only_stream_slow_path) {
2010   test_fread_from_write_only_stream(1);
2011 }
2012 
TEST(STDIO_TEST,fread_from_write_only_stream_fast_path)2013 TEST(STDIO_TEST, fread_from_write_only_stream_fast_path) {
2014   test_fread_from_write_only_stream(64*1024);
2015 }
2016 
test_fwrite_after_fread(size_t n)2017 static void test_fwrite_after_fread(size_t n) {
2018   TemporaryFile tf;
2019 
2020   FILE* fp = fdopen(tf.fd, "w+");
2021   ASSERT_EQ(1U, fwrite("1", 1, 1, fp));
2022   fflush(fp);
2023 
2024   // We've flushed but not rewound, so there's nothing to read.
2025   std::vector<char> buf(n, 0);
2026   ASSERT_EQ(0U, fread(&buf[0], 1, buf.size(), fp));
2027   ASSERT_TRUE(feof(fp));
2028 
2029   // But hitting EOF doesn't prevent us from writing...
2030   errno = 0;
2031   ASSERT_EQ(1U, fwrite("2", 1, 1, fp)) << strerror(errno);
2032 
2033   // And if we rewind, everything's there.
2034   rewind(fp);
2035   ASSERT_EQ(2U, fread(&buf[0], 1, buf.size(), fp));
2036   ASSERT_EQ('1', buf[0]);
2037   ASSERT_EQ('2', buf[1]);
2038 
2039   fclose(fp);
2040 }
2041 
TEST(STDIO_TEST,fwrite_after_fread_slow_path)2042 TEST(STDIO_TEST, fwrite_after_fread_slow_path) {
2043   test_fwrite_after_fread(16);
2044 }
2045 
TEST(STDIO_TEST,fwrite_after_fread_fast_path)2046 TEST(STDIO_TEST, fwrite_after_fread_fast_path) {
2047   test_fwrite_after_fread(64*1024);
2048 }
2049 
2050 // http://b/19172514
TEST(STDIO_TEST,fread_after_fseek)2051 TEST(STDIO_TEST, fread_after_fseek) {
2052   TemporaryFile tf;
2053 
2054   FILE* fp = fopen(tf.path, "w+");
2055   ASSERT_TRUE(fp != nullptr);
2056 
2057   char file_data[12288];
2058   for (size_t i = 0; i < 12288; i++) {
2059     file_data[i] = i;
2060   }
2061   ASSERT_EQ(12288U, fwrite(file_data, 1, 12288, fp));
2062   fclose(fp);
2063 
2064   fp = fopen(tf.path, "r");
2065   ASSERT_TRUE(fp != nullptr);
2066 
2067   char buffer[8192];
2068   size_t cur_location = 0;
2069   // Small read to populate internal buffer.
2070   ASSERT_EQ(100U, fread(buffer, 1, 100, fp));
2071   ASSERT_EQ(memcmp(file_data, buffer, 100), 0);
2072 
2073   cur_location = static_cast<size_t>(ftell(fp));
2074   // Large read to force reading into the user supplied buffer and bypassing
2075   // the internal buffer.
2076   ASSERT_EQ(8192U, fread(buffer, 1, 8192, fp));
2077   ASSERT_EQ(memcmp(file_data+cur_location, buffer, 8192), 0);
2078 
2079   // Small backwards seek to verify fseek does not reuse the internal buffer.
2080   ASSERT_EQ(0, fseek(fp, -22, SEEK_CUR)) << strerror(errno);
2081   cur_location = static_cast<size_t>(ftell(fp));
2082   ASSERT_EQ(22U, fread(buffer, 1, 22, fp));
2083   ASSERT_EQ(memcmp(file_data+cur_location, buffer, 22), 0);
2084 
2085   fclose(fp);
2086 }
2087 
2088 // https://code.google.com/p/android/issues/detail?id=184847
TEST(STDIO_TEST,fread_EOF_184847)2089 TEST(STDIO_TEST, fread_EOF_184847) {
2090   TemporaryFile tf;
2091   char buf[6] = {0};
2092 
2093   FILE* fw = fopen(tf.path, "w");
2094   ASSERT_TRUE(fw != nullptr);
2095 
2096   FILE* fr = fopen(tf.path, "r");
2097   ASSERT_TRUE(fr != nullptr);
2098 
2099   fwrite("a", 1, 1, fw);
2100   fflush(fw);
2101   ASSERT_EQ(1U, fread(buf, 1, 1, fr));
2102   ASSERT_STREQ("a", buf);
2103 
2104   // 'fr' is now at EOF.
2105   ASSERT_EQ(0U, fread(buf, 1, 1, fr));
2106   ASSERT_TRUE(feof(fr));
2107 
2108   // Write some more...
2109   fwrite("z", 1, 1, fw);
2110   fflush(fw);
2111 
2112   // ...and check that we can read it back.
2113   // (BSD thinks that once a stream has hit EOF, it must always return EOF. SysV disagrees.)
2114   ASSERT_EQ(1U, fread(buf, 1, 1, fr));
2115   ASSERT_STREQ("z", buf);
2116 
2117   // But now we're done.
2118   ASSERT_EQ(0U, fread(buf, 1, 1, fr));
2119 
2120   fclose(fr);
2121   fclose(fw);
2122 }
2123 
TEST(STDIO_TEST,fclose_invalidates_fd)2124 TEST(STDIO_TEST, fclose_invalidates_fd) {
2125   // The typical error we're trying to help people catch involves accessing
2126   // memory after it's been freed. But we know that stdin/stdout/stderr are
2127   // special and don't get deallocated, so this test uses stdin.
2128   ASSERT_EQ(0, fclose(stdin));
2129 
2130   // Even though using a FILE* after close is undefined behavior, I've closed
2131   // this bug as "WAI" too many times. We shouldn't hand out stale fds,
2132   // especially because they might actually correspond to a real stream.
2133   errno = 0;
2134   ASSERT_EQ(-1, fileno(stdin));
2135   ASSERT_EQ(EBADF, errno);
2136 }
2137 
TEST(STDIO_TEST,fseek_ftell_unseekable)2138 TEST(STDIO_TEST, fseek_ftell_unseekable) {
2139 #if defined(__BIONIC__) // glibc has fopencookie instead.
2140   auto read_fn = [](void*, char*, int) { return -1; };
2141   FILE* fp = funopen(nullptr, read_fn, nullptr, nullptr, nullptr);
2142   ASSERT_TRUE(fp != nullptr);
2143 
2144   // Check that ftell balks on an unseekable FILE*.
2145   errno = 0;
2146   ASSERT_EQ(-1, ftell(fp));
2147   ASSERT_EQ(ESPIPE, errno);
2148 
2149   // SEEK_CUR is rewritten as SEEK_SET internally...
2150   errno = 0;
2151   ASSERT_EQ(-1, fseek(fp, 0, SEEK_CUR));
2152   ASSERT_EQ(ESPIPE, errno);
2153 
2154   // ...so it's worth testing the direct seek path too.
2155   errno = 0;
2156   ASSERT_EQ(-1, fseek(fp, 0, SEEK_SET));
2157   ASSERT_EQ(ESPIPE, errno);
2158 
2159   fclose(fp);
2160 #else
2161   GTEST_SKIP() << "glibc uses fopencookie instead";
2162 #endif
2163 }
2164 
TEST(STDIO_TEST,funopen_EINVAL)2165 TEST(STDIO_TEST, funopen_EINVAL) {
2166 #if defined(__BIONIC__)
2167   errno = 0;
2168   ASSERT_EQ(nullptr, funopen(nullptr, nullptr, nullptr, nullptr, nullptr));
2169   ASSERT_EQ(EINVAL, errno);
2170 #else
2171   GTEST_SKIP() << "glibc uses fopencookie instead";
2172 #endif
2173 }
2174 
TEST(STDIO_TEST,funopen_seek)2175 TEST(STDIO_TEST, funopen_seek) {
2176 #if defined(__BIONIC__)
2177   auto read_fn = [](void*, char*, int) { return -1; };
2178 
2179   auto seek_fn = [](void*, fpos_t, int) -> fpos_t { return 0xfedcba12; };
2180   auto seek64_fn = [](void*, fpos64_t, int) -> fpos64_t { return 0xfedcba12345678; };
2181 
2182   FILE* fp = funopen(nullptr, read_fn, nullptr, seek_fn, nullptr);
2183   ASSERT_TRUE(fp != nullptr);
2184   fpos_t pos;
2185 #if defined(__LP64__)
2186   EXPECT_EQ(0, fgetpos(fp, &pos)) << strerror(errno);
2187   EXPECT_EQ(0xfedcba12LL, pos);
2188 #else
2189   EXPECT_EQ(-1, fgetpos(fp, &pos)) << strerror(errno);
2190   EXPECT_EQ(EOVERFLOW, errno);
2191 #endif
2192 
2193   FILE* fp64 = funopen64(nullptr, read_fn, nullptr, seek64_fn, nullptr);
2194   ASSERT_TRUE(fp64 != nullptr);
2195   fpos64_t pos64;
2196   EXPECT_EQ(0, fgetpos64(fp64, &pos64)) << strerror(errno);
2197   EXPECT_EQ(0xfedcba12345678, pos64);
2198 #else
2199   GTEST_SKIP() << "glibc uses fopencookie instead";
2200 #endif
2201 }
2202 
TEST(STDIO_TEST,lots_of_concurrent_files)2203 TEST(STDIO_TEST, lots_of_concurrent_files) {
2204   std::vector<TemporaryFile*> tfs;
2205   std::vector<FILE*> fps;
2206 
2207   for (size_t i = 0; i < 256; ++i) {
2208     TemporaryFile* tf = new TemporaryFile;
2209     tfs.push_back(tf);
2210     FILE* fp = fopen(tf->path, "w+");
2211     fps.push_back(fp);
2212     fprintf(fp, "hello %zu!\n", i);
2213     fflush(fp);
2214   }
2215 
2216   for (size_t i = 0; i < 256; ++i) {
2217     char expected[BUFSIZ];
2218     snprintf(expected, sizeof(expected), "hello %zu!\n", i);
2219 
2220     AssertFileIs(fps[i], expected);
2221     fclose(fps[i]);
2222     delete tfs[i];
2223   }
2224 }
2225 
AssertFileOffsetAt(FILE * fp,off64_t offset)2226 static void AssertFileOffsetAt(FILE* fp, off64_t offset) {
2227   EXPECT_EQ(offset, ftell(fp));
2228   EXPECT_EQ(offset, ftello(fp));
2229   EXPECT_EQ(offset, ftello64(fp));
2230   fpos_t pos;
2231   fpos64_t pos64;
2232   EXPECT_EQ(0, fgetpos(fp, &pos));
2233   EXPECT_EQ(0, fgetpos64(fp, &pos64));
2234 #if defined(__BIONIC__)
2235   EXPECT_EQ(offset, static_cast<off64_t>(pos));
2236   EXPECT_EQ(offset, static_cast<off64_t>(pos64));
2237 #else
2238   GTEST_SKIP() << "glibc's fpos_t is opaque";
2239 #endif
2240 }
2241 
TEST(STDIO_TEST,seek_tell_family_smoke)2242 TEST(STDIO_TEST, seek_tell_family_smoke) {
2243   TemporaryFile tf;
2244   FILE* fp = fdopen(tf.fd, "w+");
2245 
2246   // Initially we should be at 0.
2247   AssertFileOffsetAt(fp, 0);
2248 
2249   // Seek to offset 8192.
2250   ASSERT_EQ(0, fseek(fp, 8192, SEEK_SET));
2251   AssertFileOffsetAt(fp, 8192);
2252   fpos_t eight_k_pos;
2253   ASSERT_EQ(0, fgetpos(fp, &eight_k_pos));
2254 
2255   // Seek forward another 8192...
2256   ASSERT_EQ(0, fseek(fp, 8192, SEEK_CUR));
2257   AssertFileOffsetAt(fp, 8192 + 8192);
2258   fpos64_t sixteen_k_pos64;
2259   ASSERT_EQ(0, fgetpos64(fp, &sixteen_k_pos64));
2260 
2261   // Seek back 8192...
2262   ASSERT_EQ(0, fseek(fp, -8192, SEEK_CUR));
2263   AssertFileOffsetAt(fp, 8192);
2264 
2265   // Since we haven't written anything, the end is also at 0.
2266   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2267   AssertFileOffsetAt(fp, 0);
2268 
2269   // Check that our fpos64_t from 16KiB works...
2270   ASSERT_EQ(0, fsetpos64(fp, &sixteen_k_pos64));
2271   AssertFileOffsetAt(fp, 8192 + 8192);
2272   // ...as does our fpos_t from 8192.
2273   ASSERT_EQ(0, fsetpos(fp, &eight_k_pos));
2274   AssertFileOffsetAt(fp, 8192);
2275 
2276   // Do fseeko and fseeko64 work too?
2277   ASSERT_EQ(0, fseeko(fp, 1234, SEEK_SET));
2278   AssertFileOffsetAt(fp, 1234);
2279   ASSERT_EQ(0, fseeko64(fp, 5678, SEEK_SET));
2280   AssertFileOffsetAt(fp, 5678);
2281 
2282   fclose(fp);
2283 }
2284 
TEST(STDIO_TEST,fseek_fseeko_EINVAL)2285 TEST(STDIO_TEST, fseek_fseeko_EINVAL) {
2286   TemporaryFile tf;
2287   FILE* fp = fdopen(tf.fd, "w+");
2288 
2289   // Bad whence.
2290   errno = 0;
2291   ASSERT_EQ(-1, fseek(fp, 0, 123));
2292   ASSERT_EQ(EINVAL, errno);
2293   errno = 0;
2294   ASSERT_EQ(-1, fseeko(fp, 0, 123));
2295   ASSERT_EQ(EINVAL, errno);
2296   errno = 0;
2297   ASSERT_EQ(-1, fseeko64(fp, 0, 123));
2298   ASSERT_EQ(EINVAL, errno);
2299 
2300   // Bad offset.
2301   errno = 0;
2302   ASSERT_EQ(-1, fseek(fp, -1, SEEK_SET));
2303   ASSERT_EQ(EINVAL, errno);
2304   errno = 0;
2305   ASSERT_EQ(-1, fseeko(fp, -1, SEEK_SET));
2306   ASSERT_EQ(EINVAL, errno);
2307   errno = 0;
2308   ASSERT_EQ(-1, fseeko64(fp, -1, SEEK_SET));
2309   ASSERT_EQ(EINVAL, errno);
2310 
2311   fclose(fp);
2312 }
2313 
TEST(STDIO_TEST,ctermid)2314 TEST(STDIO_TEST, ctermid) {
2315   ASSERT_STREQ("/dev/tty", ctermid(nullptr));
2316 
2317   char buf[L_ctermid] = {};
2318   ASSERT_EQ(buf, ctermid(buf));
2319   ASSERT_STREQ("/dev/tty", buf);
2320 }
2321 
TEST(STDIO_TEST,remove)2322 TEST(STDIO_TEST, remove) {
2323   struct stat sb;
2324 
2325   TemporaryFile tf;
2326   ASSERT_EQ(0, remove(tf.path));
2327   ASSERT_EQ(-1, lstat(tf.path, &sb));
2328   ASSERT_EQ(ENOENT, errno);
2329 
2330   TemporaryDir td;
2331   ASSERT_EQ(0, remove(td.path));
2332   ASSERT_EQ(-1, lstat(td.path, &sb));
2333   ASSERT_EQ(ENOENT, errno);
2334 
2335   errno = 0;
2336   ASSERT_EQ(-1, remove(tf.path));
2337   ASSERT_EQ(ENOENT, errno);
2338 
2339   errno = 0;
2340   ASSERT_EQ(-1, remove(td.path));
2341   ASSERT_EQ(ENOENT, errno);
2342 }
2343 
TEST(STDIO_DEATHTEST,snprintf_30445072_known_buffer_size)2344 TEST(STDIO_DEATHTEST, snprintf_30445072_known_buffer_size) {
2345   char buf[16];
2346   ASSERT_EXIT(snprintf(buf, atol("-1"), "hello"),
2347               testing::KilledBySignal(SIGABRT),
2348 #if defined(NOFORTIFY)
2349               "FORTIFY: vsnprintf: size .* > SSIZE_MAX"
2350 #else
2351               "FORTIFY: vsnprintf: prevented .*-byte write into 16-byte buffer"
2352 #endif
2353               );
2354 }
2355 
TEST(STDIO_DEATHTEST,snprintf_30445072_unknown_buffer_size)2356 TEST(STDIO_DEATHTEST, snprintf_30445072_unknown_buffer_size) {
2357   std::string buf = "world";
2358   ASSERT_EXIT(snprintf(&buf[0], atol("-1"), "hello"),
2359               testing::KilledBySignal(SIGABRT),
2360               "FORTIFY: vsnprintf: size .* > SSIZE_MAX");
2361 }
2362 
TEST(STDIO_TEST,sprintf_30445072)2363 TEST(STDIO_TEST, sprintf_30445072) {
2364   std::string buf = "world";
2365   sprintf(&buf[0], "hello");
2366   ASSERT_EQ(buf, "hello");
2367 }
2368 
TEST(STDIO_TEST,printf_m)2369 TEST(STDIO_TEST, printf_m) {
2370   char buf[BUFSIZ];
2371   errno = 0;
2372   snprintf(buf, sizeof(buf), "<%m>");
2373   ASSERT_STREQ("<Success>", buf);
2374   errno = -1;
2375   snprintf(buf, sizeof(buf), "<%m>");
2376   ASSERT_STREQ("<Unknown error -1>", buf);
2377   errno = EINVAL;
2378   snprintf(buf, sizeof(buf), "<%m>");
2379   ASSERT_STREQ("<Invalid argument>", buf);
2380 }
2381 
TEST(STDIO_TEST,printf_m_does_not_clobber_strerror)2382 TEST(STDIO_TEST, printf_m_does_not_clobber_strerror) {
2383   char buf[BUFSIZ];
2384   const char* m = strerror(-1);
2385   ASSERT_STREQ("Unknown error -1", m);
2386   errno = -2;
2387   snprintf(buf, sizeof(buf), "<%m>");
2388   ASSERT_STREQ("<Unknown error -2>", buf);
2389   ASSERT_STREQ("Unknown error -1", m);
2390 }
2391 
TEST(STDIO_TEST,wprintf_m)2392 TEST(STDIO_TEST, wprintf_m) {
2393   wchar_t buf[BUFSIZ];
2394   errno = 0;
2395   swprintf(buf, sizeof(buf), L"<%m>");
2396   ASSERT_EQ(std::wstring(L"<Success>"), buf);
2397   errno = -1;
2398   swprintf(buf, sizeof(buf), L"<%m>");
2399   ASSERT_EQ(std::wstring(L"<Unknown error -1>"), buf);
2400   errno = EINVAL;
2401   swprintf(buf, sizeof(buf), L"<%m>");
2402   ASSERT_EQ(std::wstring(L"<Invalid argument>"), buf);
2403 }
2404 
TEST(STDIO_TEST,wprintf_m_does_not_clobber_strerror)2405 TEST(STDIO_TEST, wprintf_m_does_not_clobber_strerror) {
2406   wchar_t buf[BUFSIZ];
2407   const char* m = strerror(-1);
2408   ASSERT_STREQ("Unknown error -1", m);
2409   errno = -2;
2410   swprintf(buf, sizeof(buf), L"<%m>");
2411   ASSERT_EQ(std::wstring(L"<Unknown error -2>"), buf);
2412   ASSERT_STREQ("Unknown error -1", m);
2413 }
2414 
TEST(STDIO_TEST,fopen_append_mode_and_ftell)2415 TEST(STDIO_TEST, fopen_append_mode_and_ftell) {
2416   TemporaryFile tf;
2417   SetFileTo(tf.path, "0123456789");
2418   FILE* fp = fopen(tf.path, "a");
2419   EXPECT_EQ(10, ftell(fp));
2420   ASSERT_EQ(0, fseek(fp, 2, SEEK_SET));
2421   EXPECT_EQ(2, ftell(fp));
2422   ASSERT_NE(EOF, fputs("xxx", fp));
2423   ASSERT_EQ(0, fflush(fp));
2424   EXPECT_EQ(13, ftell(fp));
2425   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2426   EXPECT_EQ(13, ftell(fp));
2427   ASSERT_EQ(0, fclose(fp));
2428   AssertFileIs(tf.path, "0123456789xxx");
2429 }
2430 
TEST(STDIO_TEST,fdopen_append_mode_and_ftell)2431 TEST(STDIO_TEST, fdopen_append_mode_and_ftell) {
2432   TemporaryFile tf;
2433   SetFileTo(tf.path, "0123456789");
2434   int fd = open(tf.path, O_RDWR);
2435   ASSERT_NE(-1, fd);
2436   // POSIX: "The file position indicator associated with the new stream is set to the position
2437   // indicated by the file offset associated with the file descriptor."
2438   ASSERT_EQ(4, lseek(fd, 4, SEEK_SET));
2439   FILE* fp = fdopen(fd, "a");
2440   EXPECT_EQ(4, ftell(fp));
2441   ASSERT_EQ(0, fseek(fp, 2, SEEK_SET));
2442   EXPECT_EQ(2, ftell(fp));
2443   ASSERT_NE(EOF, fputs("xxx", fp));
2444   ASSERT_EQ(0, fflush(fp));
2445   EXPECT_EQ(13, ftell(fp));
2446   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2447   EXPECT_EQ(13, ftell(fp));
2448   ASSERT_EQ(0, fclose(fp));
2449   AssertFileIs(tf.path, "0123456789xxx");
2450 }
2451 
TEST(STDIO_TEST,freopen_append_mode_and_ftell)2452 TEST(STDIO_TEST, freopen_append_mode_and_ftell) {
2453   TemporaryFile tf;
2454   SetFileTo(tf.path, "0123456789");
2455   FILE* other_fp = fopen("/proc/version", "r");
2456   FILE* fp = freopen(tf.path, "a", other_fp);
2457   EXPECT_EQ(10, ftell(fp));
2458   ASSERT_EQ(0, fseek(fp, 2, SEEK_SET));
2459   EXPECT_EQ(2, ftell(fp));
2460   ASSERT_NE(EOF, fputs("xxx", fp));
2461   ASSERT_EQ(0, fflush(fp));
2462   EXPECT_EQ(13, ftell(fp));
2463   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2464   EXPECT_EQ(13, ftell(fp));
2465   ASSERT_EQ(0, fclose(fp));
2466   AssertFileIs(tf.path, "0123456789xxx");
2467 }
2468 
TEST(STDIO_TEST,constants)2469 TEST(STDIO_TEST, constants) {
2470   ASSERT_LE(FILENAME_MAX, PATH_MAX);
2471   ASSERT_EQ(L_tmpnam, PATH_MAX);
2472 }
2473 
TEST(STDIO_TEST,perror)2474 TEST(STDIO_TEST, perror) {
2475   ExecTestHelper eth;
2476   eth.Run([&]() { errno = EINVAL; perror("a b c"); exit(0); }, 0, "a b c: Invalid argument\n");
2477   eth.Run([&]() { errno = EINVAL; perror(nullptr); exit(0); }, 0, "Invalid argument\n");
2478   eth.Run([&]() { errno = EINVAL; perror(""); exit(0); }, 0, "Invalid argument\n");
2479 }
2480 
TEST(STDIO_TEST,puts)2481 TEST(STDIO_TEST, puts) {
2482   ExecTestHelper eth;
2483   eth.Run([&]() { exit(puts("a b c")); }, 0, "a b c\n");
2484 }
2485 
TEST(STDIO_TEST,unlocked)2486 TEST(STDIO_TEST, unlocked) {
2487   TemporaryFile tf;
2488 
2489   FILE* fp = fopen(tf.path, "w+");
2490   ASSERT_TRUE(fp != nullptr);
2491 
2492   clearerr_unlocked(fp);
2493   ASSERT_FALSE(feof_unlocked(fp));
2494   ASSERT_FALSE(ferror_unlocked(fp));
2495 
2496   ASSERT_EQ(fileno(fp), fileno_unlocked(fp));
2497 
2498   ASSERT_NE(EOF, putc_unlocked('a', fp));
2499   ASSERT_NE(EOF, putc('b', fp));
2500   ASSERT_NE(EOF, fputc_unlocked('c', fp));
2501   ASSERT_NE(EOF, fputc('d', fp));
2502 
2503   rewind(fp);
2504   ASSERT_EQ('a', getc_unlocked(fp));
2505   ASSERT_EQ('b', getc(fp));
2506   ASSERT_EQ('c', fgetc_unlocked(fp));
2507   ASSERT_EQ('d', fgetc(fp));
2508 
2509   rewind(fp);
2510   ASSERT_EQ(2U, fwrite_unlocked("AB", 1, 2, fp));
2511   ASSERT_EQ(2U, fwrite("CD", 1, 2, fp));
2512   ASSERT_EQ(0, fflush_unlocked(fp));
2513 
2514   rewind(fp);
2515   char buf[BUFSIZ] = {};
2516   ASSERT_EQ(2U, fread_unlocked(&buf[0], 1, 2, fp));
2517   ASSERT_EQ(2U, fread(&buf[2], 1, 2, fp));
2518   ASSERT_STREQ("ABCD", buf);
2519 
2520   rewind(fp);
2521   ASSERT_NE(EOF, fputs("hello ", fp));
2522   ASSERT_NE(EOF, fputs_unlocked("world", fp));
2523   ASSERT_NE(EOF, fputc('\n', fp));
2524 
2525   rewind(fp);
2526   ASSERT_TRUE(fgets_unlocked(buf, sizeof(buf), fp) != nullptr);
2527   ASSERT_STREQ("hello world\n", buf);
2528 
2529   ASSERT_EQ(0, fclose(fp));
2530 }
2531 
TEST(STDIO_TEST,fseek_64bit)2532 TEST(STDIO_TEST, fseek_64bit) {
2533   TemporaryFile tf;
2534   FILE* fp = fopen64(tf.path, "w+");
2535   ASSERT_TRUE(fp != nullptr);
2536   ASSERT_EQ(0, fseeko64(fp, 0x2'0000'0000, SEEK_SET));
2537   ASSERT_EQ(0x2'0000'0000, ftello64(fp));
2538   ASSERT_EQ(0, fseeko64(fp, 0x1'0000'0000, SEEK_CUR));
2539   ASSERT_EQ(0x3'0000'0000, ftello64(fp));
2540   ASSERT_EQ(0, fclose(fp));
2541 }
2542 
2543 // POSIX requires that fseek/fseeko fail with EOVERFLOW if the new file offset
2544 // isn't representable in long/off_t.
TEST(STDIO_TEST,fseek_overflow_32bit)2545 TEST(STDIO_TEST, fseek_overflow_32bit) {
2546   TemporaryFile tf;
2547   FILE* fp = fopen64(tf.path, "w+");
2548   ASSERT_EQ(0, ftruncate64(fileno(fp), 0x2'0000'0000));
2549 
2550   // Bionic implements overflow checking for SEEK_CUR, but glibc doesn't.
2551 #if defined(__BIONIC__) && !defined(__LP64__)
2552   ASSERT_EQ(0, fseek(fp, 0x7fff'ffff, SEEK_SET));
2553   ASSERT_EQ(-1, fseek(fp, 1, SEEK_CUR));
2554   ASSERT_EQ(EOVERFLOW, errno);
2555 #endif
2556 
2557   // Neither Bionic nor glibc implement the overflow checking for SEEK_END.
2558   // (Aside: FreeBSD's libc is an example of a libc that checks both SEEK_CUR
2559   // and SEEK_END -- many C libraries check neither.)
2560   ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2561   ASSERT_EQ(0x2'0000'0000, ftello64(fp));
2562 
2563   fclose(fp);
2564 }
2565 
TEST(STDIO_TEST,dev_std_files)2566 TEST(STDIO_TEST, dev_std_files) {
2567   // POSIX only mentions /dev/stdout, but we should have all three (http://b/31824379).
2568   char path[PATH_MAX];
2569   ssize_t length = readlink("/dev/stdin", path, sizeof(path));
2570   ASSERT_LT(0, length);
2571   ASSERT_EQ("/proc/self/fd/0", std::string(path, length));
2572 
2573   length = readlink("/dev/stdout", path, sizeof(path));
2574   ASSERT_LT(0, length);
2575   ASSERT_EQ("/proc/self/fd/1", std::string(path, length));
2576 
2577   length = readlink("/dev/stderr", path, sizeof(path));
2578   ASSERT_LT(0, length);
2579   ASSERT_EQ("/proc/self/fd/2", std::string(path, length));
2580 }
2581 
TEST(STDIO_TEST,fread_with_locked_file)2582 TEST(STDIO_TEST, fread_with_locked_file) {
2583   // Reading an unbuffered/line-buffered file from one thread shouldn't block on
2584   // files locked on other threads, even if it flushes some line-buffered files.
2585   FILE* fp1 = fopen("/dev/zero", "r");
2586   ASSERT_TRUE(fp1 != nullptr);
2587   flockfile(fp1);
2588 
2589   std::thread([] {
2590     for (int mode : { _IONBF, _IOLBF }) {
2591       FILE* fp2 = fopen("/dev/zero", "r");
2592       ASSERT_TRUE(fp2 != nullptr);
2593       setvbuf(fp2, nullptr, mode, 0);
2594       ASSERT_EQ('\0', fgetc(fp2));
2595       fclose(fp2);
2596     }
2597   }).join();
2598 
2599   funlockfile(fp1);
2600   fclose(fp1);
2601 }
2602