blob: c5ffe2423d921fe7f86facbba8ae9572d21f1c65 [file] [log] [blame]
Elliott Hughes91875dc2012-09-24 17:55:15 -07001/*
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>
Elliott Hughesc9244bd2014-05-14 13:31:35 -070020#include <fcntl.h>
Elliott Hughes1d13c642013-09-23 16:02:39 -070021#include <limits.h>
Colin Cross14d15072021-08-16 16:35:27 -070022#include <locale.h>
Elliott Hughes7823f322014-04-14 12:11:28 -070023#include <math.h>
Elliott Hughes91875dc2012-09-24 17:55:15 -070024#include <stdio.h>
Colin Cross4c5595c2021-08-16 15:51:59 -070025#include <sys/cdefs.h>
Elliott Hughes468efc82018-07-10 14:39:49 -070026#include <sys/socket.h>
Elliott Hughes91875dc2012-09-24 17:55:15 -070027#include <sys/stat.h>
Elliott Hughesbe78fc92022-07-28 20:58:45 +000028#include <sys/sysinfo.h>
Colin Cross14d15072021-08-16 16:35:27 -070029#include <sys/types.h>
Elliott Hughes91875dc2012-09-24 17:55:15 -070030#include <unistd.h>
Elliott Hughes05493712014-04-17 17:30:03 -070031#include <wchar.h>
Calin Juravle03e4ebe2014-05-08 14:42:06 +010032
Elliott Hughes3a4c4542017-07-19 17:20:24 -070033#include <string>
Ryan Prichardc485cdb2019-04-30 14:47:34 -070034#include <thread>
Elliott Hughese6bb5a22015-01-23 17:48:15 -080035#include <vector>
36
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -080037#include <android-base/file.h>
Elliott Hughes141b9172021-04-09 17:13:09 -070038#include <android-base/silent_death_test.h>
Elliott Hughes8b86c0b2023-04-18 17:11:06 -070039#include <android-base/strings.h>
Elliott Hughes439ebbd2020-12-04 18:51:42 -080040#include <android-base/test_utils.h>
Elliott Hughes05b675e2019-04-17 13:01:06 -070041#include <android-base/unique_fd.h>
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -080042
Josh Gao2f06e102017-01-10 13:00:37 -080043#include "utils.h"
Elliott Hughes91875dc2012-09-24 17:55:15 -070044
Elliott Hughes05b675e2019-04-17 13:01:06 -070045// This #include is actually a test too. We have to duplicate the
46// definitions of the RENAME_ constants because <linux/fs.h> also contains
47// pollution such as BLOCK_SIZE which conflicts with lots of user code.
48// Important to check that we have matching definitions.
49// There's no _MAX to test that we have all the constants, sadly.
50#include <linux/fs.h>
51
Christopher Ferris13f26a72016-01-13 13:47:58 -080052#if defined(NOFORTIFY)
53#define STDIO_TEST stdio_nofortify
Elliott Hughesfb3873d2016-08-10 11:07:54 -070054#define STDIO_DEATHTEST stdio_nofortify_DeathTest
Christopher Ferris13f26a72016-01-13 13:47:58 -080055#else
56#define STDIO_TEST stdio
Elliott Hughesfb3873d2016-08-10 11:07:54 -070057#define STDIO_DEATHTEST stdio_DeathTest
Christopher Ferris13f26a72016-01-13 13:47:58 -080058#endif
59
Elliott Hughes3a4c4542017-07-19 17:20:24 -070060using namespace std::string_literals;
61
Elliott Hughes141b9172021-04-09 17:13:09 -070062using stdio_DeathTest = SilentDeathTest;
63using stdio_nofortify_DeathTest = SilentDeathTest;
Elliott Hughesfb3873d2016-08-10 11:07:54 -070064
Elliott Hughes33a8cb12017-07-25 18:06:46 -070065static void SetFileTo(const char* path, const char* content) {
66 FILE* fp;
67 ASSERT_NE(nullptr, fp = fopen(path, "w"));
68 ASSERT_NE(EOF, fputs(content, fp));
69 ASSERT_EQ(0, fclose(fp));
70}
71
72static void AssertFileIs(const char* path, const char* expected) {
73 FILE* fp;
74 ASSERT_NE(nullptr, fp = fopen(path, "r"));
75 char* line = nullptr;
76 size_t length;
77 ASSERT_NE(EOF, getline(&line, &length, fp));
78 ASSERT_EQ(0, fclose(fp));
79 ASSERT_STREQ(expected, line);
80 free(line);
81}
82
Elliott Hughes70715da2016-08-01 16:35:17 -070083static void AssertFileIs(FILE* fp, const char* expected, bool is_fmemopen = false) {
84 rewind(fp);
85
86 char line[1024];
Josh Gao2f06e102017-01-10 13:00:37 -080087 memset(line, 0xff, sizeof(line));
Elliott Hughes70715da2016-08-01 16:35:17 -070088 ASSERT_EQ(line, fgets(line, sizeof(line), fp));
89 ASSERT_STREQ(expected, line);
90
91 if (is_fmemopen) {
92 // fmemopen appends a trailing NUL byte, which probably shouldn't show up as an
93 // extra empty line, but does on every C library I tested...
94 ASSERT_EQ(line, fgets(line, sizeof(line), fp));
95 ASSERT_STREQ("", line);
96 }
97
98 // Make sure there isn't anything else in the file.
99 ASSERT_EQ(nullptr, fgets(line, sizeof(line), fp)) << "junk at end of file: " << line;
100}
101
Christopher Ferris13f26a72016-01-13 13:47:58 -0800102TEST(STDIO_TEST, flockfile_18208568_stderr) {
Elliott Hughes6a03abc2014-11-03 12:32:17 -0800103 // Check that we have a _recursive_ mutex for flockfile.
104 flockfile(stderr);
105 feof(stderr); // We don't care about the result, but this needs to take the lock.
106 funlockfile(stderr);
107}
108
Christopher Ferris13f26a72016-01-13 13:47:58 -0800109TEST(STDIO_TEST, flockfile_18208568_regular) {
Elliott Hughes6a03abc2014-11-03 12:32:17 -0800110 // We never had a bug for streams other than stdin/stdout/stderr, but test anyway.
111 FILE* fp = fopen("/dev/null", "w");
Yi Kong32bc0fc2018-08-02 17:31:13 -0700112 ASSERT_TRUE(fp != nullptr);
Elliott Hughes6a03abc2014-11-03 12:32:17 -0800113 flockfile(fp);
114 feof(fp);
115 funlockfile(fp);
116 fclose(fp);
117}
118
Christopher Ferris13f26a72016-01-13 13:47:58 -0800119TEST(STDIO_TEST, tmpfile_fileno_fprintf_rewind_fgets) {
Elliott Hughes91875dc2012-09-24 17:55:15 -0700120 FILE* fp = tmpfile();
Yi Kong32bc0fc2018-08-02 17:31:13 -0700121 ASSERT_TRUE(fp != nullptr);
Elliott Hughes91875dc2012-09-24 17:55:15 -0700122
123 int fd = fileno(fp);
124 ASSERT_NE(fd, -1);
125
126 struct stat sb;
127 int rc = fstat(fd, &sb);
128 ASSERT_NE(rc, -1);
129 ASSERT_EQ(sb.st_mode & 0777, 0600U);
130
131 rc = fprintf(fp, "hello\n");
132 ASSERT_EQ(rc, 6);
133
Elliott Hughes70715da2016-08-01 16:35:17 -0700134 AssertFileIs(fp, "hello\n");
Elliott Hughes91875dc2012-09-24 17:55:15 -0700135 fclose(fp);
136}
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300137
Elliott Hughesf226ee52016-02-03 11:24:28 -0800138TEST(STDIO_TEST, tmpfile64) {
139 FILE* fp = tmpfile64();
140 ASSERT_TRUE(fp != nullptr);
141 fclose(fp);
142}
143
Elliott Hughes8b86c0b2023-04-18 17:11:06 -0700144TEST(STDIO_TEST, tmpfile_TMPDIR) {
145 TemporaryDir td;
146 setenv("TMPDIR", td.path, 1);
147
148 FILE* fp = tmpfile();
149 ASSERT_TRUE(fp != nullptr);
150
151 std::string fd_path = android::base::StringPrintf("/proc/self/fd/%d", fileno(fp));
152 char path[PATH_MAX];
153 ASSERT_GT(readlink(fd_path.c_str(), path, sizeof(path)), 0);
154 // $TMPDIR influenced where our temporary file ended up?
155 ASSERT_TRUE(android::base::StartsWith(path, td.path)) << path;
156 // And we used O_TMPFILE, right?
157 ASSERT_TRUE(android::base::EndsWith(path, " (deleted)")) << path;
158}
159
Christopher Ferris13f26a72016-01-13 13:47:58 -0800160TEST(STDIO_TEST, dprintf) {
Calin Juravle6afb2a92014-05-22 11:47:47 +0100161 TemporaryFile tf;
162
163 int rc = dprintf(tf.fd, "hello\n");
164 ASSERT_EQ(rc, 6);
165
Yabin Cui5ca4a9e2014-11-06 19:55:09 -0800166 lseek(tf.fd, 0, SEEK_SET);
Christopher Ferris9e01ea62014-05-29 12:49:35 -0700167 FILE* tfile = fdopen(tf.fd, "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -0700168 ASSERT_TRUE(tfile != nullptr);
Calin Juravle6afb2a92014-05-22 11:47:47 +0100169
Elliott Hughes70715da2016-08-01 16:35:17 -0700170 AssertFileIs(tfile, "hello\n");
Christopher Ferris9e01ea62014-05-29 12:49:35 -0700171 fclose(tfile);
Calin Juravle6afb2a92014-05-22 11:47:47 +0100172}
173
Christopher Ferris13f26a72016-01-13 13:47:58 -0800174TEST(STDIO_TEST, getdelim) {
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300175 FILE* fp = tmpfile();
Yi Kong32bc0fc2018-08-02 17:31:13 -0700176 ASSERT_TRUE(fp != nullptr);
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300177
178 const char* line_written = "This is a test";
179 int rc = fprintf(fp, "%s", line_written);
180 ASSERT_EQ(rc, static_cast<int>(strlen(line_written)));
181
182 rewind(fp);
183
Yi Kong32bc0fc2018-08-02 17:31:13 -0700184 char* word_read = nullptr;
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300185 size_t allocated_length = 0;
186
187 const char* expected[] = { "This ", " ", "is ", "a ", "test" };
188 for (size_t i = 0; i < 5; ++i) {
189 ASSERT_FALSE(feof(fp));
190 ASSERT_EQ(getdelim(&word_read, &allocated_length, ' ', fp), static_cast<int>(strlen(expected[i])));
191 ASSERT_GE(allocated_length, strlen(expected[i]));
Elliott Hughes0ed7e082015-01-22 15:13:38 -0800192 ASSERT_STREQ(expected[i], word_read);
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300193 }
194 // The last read should have set the end-of-file indicator for the stream.
195 ASSERT_TRUE(feof(fp));
196 clearerr(fp);
197
198 // getdelim returns -1 but doesn't set errno if we're already at EOF.
199 // It should set the end-of-file indicator for the stream, though.
200 errno = 0;
201 ASSERT_EQ(getdelim(&word_read, &allocated_length, ' ', fp), -1);
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800202 ASSERT_EQ(0, errno);
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300203 ASSERT_TRUE(feof(fp));
204
205 free(word_read);
206 fclose(fp);
207}
208
Christopher Ferris13f26a72016-01-13 13:47:58 -0800209TEST(STDIO_TEST, getdelim_invalid) {
zijunzhao00a3dba2023-03-01 00:07:40 +0000210#pragma clang diagnostic push
211#pragma clang diagnostic ignored "-Wnonnull"
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300212 FILE* fp = tmpfile();
Yi Kong32bc0fc2018-08-02 17:31:13 -0700213 ASSERT_TRUE(fp != nullptr);
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300214
Yi Kong32bc0fc2018-08-02 17:31:13 -0700215 char* buffer = nullptr;
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300216 size_t buffer_length = 0;
217
218 // The first argument can't be NULL.
219 errno = 0;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700220 ASSERT_EQ(getdelim(nullptr, &buffer_length, ' ', fp), -1);
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800221 ASSERT_EQ(EINVAL, errno);
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300222
223 // The second argument can't be NULL.
224 errno = 0;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700225 ASSERT_EQ(getdelim(&buffer, nullptr, ' ', fp), -1);
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800226 ASSERT_EQ(EINVAL, errno);
Elliott Hughes20f8aec2014-05-12 15:15:37 -0700227 fclose(fp);
zijunzhao00a3dba2023-03-01 00:07:40 +0000228#pragma clang diagnostic pop
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300229}
230
Christopher Ferris13f26a72016-01-13 13:47:58 -0800231TEST(STDIO_TEST, getdelim_directory) {
Elliott Hughes694fd2d2015-04-05 10:51:56 -0700232 FILE* fp = fopen("/proc", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -0700233 ASSERT_TRUE(fp != nullptr);
Elliott Hughes694fd2d2015-04-05 10:51:56 -0700234 char* word_read;
235 size_t allocated_length;
236 ASSERT_EQ(-1, getdelim(&word_read, &allocated_length, ' ', fp));
237 fclose(fp);
238}
239
Christopher Ferris13f26a72016-01-13 13:47:58 -0800240TEST(STDIO_TEST, getline) {
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300241 FILE* fp = tmpfile();
Yi Kong32bc0fc2018-08-02 17:31:13 -0700242 ASSERT_TRUE(fp != nullptr);
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300243
244 const char* line_written = "This is a test for getline\n";
245 const size_t line_count = 5;
246
247 for (size_t i = 0; i < line_count; ++i) {
248 int rc = fprintf(fp, "%s", line_written);
249 ASSERT_EQ(rc, static_cast<int>(strlen(line_written)));
250 }
251
252 rewind(fp);
253
Yi Kong32bc0fc2018-08-02 17:31:13 -0700254 char* line_read = nullptr;
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300255 size_t allocated_length = 0;
256
257 size_t read_line_count = 0;
258 ssize_t read_char_count;
259 while ((read_char_count = getline(&line_read, &allocated_length, fp)) != -1) {
260 ASSERT_EQ(read_char_count, static_cast<int>(strlen(line_written)));
261 ASSERT_GE(allocated_length, strlen(line_written));
Elliott Hughes0ed7e082015-01-22 15:13:38 -0800262 ASSERT_STREQ(line_written, line_read);
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300263 ++read_line_count;
264 }
265 ASSERT_EQ(read_line_count, line_count);
266
267 // The last read should have set the end-of-file indicator for the stream.
268 ASSERT_TRUE(feof(fp));
269 clearerr(fp);
270
271 // getline returns -1 but doesn't set errno if we're already at EOF.
272 // It should set the end-of-file indicator for the stream, though.
273 errno = 0;
274 ASSERT_EQ(getline(&line_read, &allocated_length, fp), -1);
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800275 ASSERT_EQ(0, errno);
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300276 ASSERT_TRUE(feof(fp));
277
278 free(line_read);
279 fclose(fp);
280}
281
Christopher Ferris13f26a72016-01-13 13:47:58 -0800282TEST(STDIO_TEST, getline_invalid) {
zijunzhao00a3dba2023-03-01 00:07:40 +0000283#pragma clang diagnostic push
284#pragma clang diagnostic ignored "-Wnonnull"
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300285 FILE* fp = tmpfile();
Yi Kong32bc0fc2018-08-02 17:31:13 -0700286 ASSERT_TRUE(fp != nullptr);
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300287
Yi Kong32bc0fc2018-08-02 17:31:13 -0700288 char* buffer = nullptr;
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300289 size_t buffer_length = 0;
290
291 // The first argument can't be NULL.
292 errno = 0;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700293 ASSERT_EQ(getline(nullptr, &buffer_length, fp), -1);
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800294 ASSERT_EQ(EINVAL, errno);
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300295
296 // The second argument can't be NULL.
297 errno = 0;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700298 ASSERT_EQ(getline(&buffer, nullptr, fp), -1);
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800299 ASSERT_EQ(EINVAL, errno);
Elliott Hughes20f8aec2014-05-12 15:15:37 -0700300 fclose(fp);
zijunzhao00a3dba2023-03-01 00:07:40 +0000301#pragma clang diagnostic pop
Irina Tirdeaeac9eb42012-09-08 09:28:30 +0300302}
Thorsten Glaserc641caf2013-02-17 16:50:58 +0000303
Christopher Ferris13f26a72016-01-13 13:47:58 -0800304TEST(STDIO_TEST, printf_ssize_t) {
Elliott Hughese2556422013-02-28 10:51:14 -0800305 // http://b/8253769
Elliott Hughese2556422013-02-28 10:51:14 -0800306 ASSERT_EQ(sizeof(ssize_t), sizeof(long int));
Elliott Hughesb6e22482013-03-08 15:28:52 -0800307 ASSERT_EQ(sizeof(ssize_t), sizeof(size_t));
308 // For our 32-bit ABI, we had a ssize_t definition that confuses GCC into saying:
Thorsten Glaserc641caf2013-02-17 16:50:58 +0000309 // error: format '%zd' expects argument of type 'signed size_t',
310 // but argument 4 has type 'ssize_t {aka long int}' [-Werror=format]
311 ssize_t v = 1;
312 char buf[32];
313 snprintf(buf, sizeof(buf), "%zd", v);
314}
Elliott Hughes6b3f49a2013-03-06 16:20:55 -0800315
Elliott Hughes05493712014-04-17 17:30:03 -0700316// https://code.google.com/p/android/issues/detail?id=64886
Christopher Ferris13f26a72016-01-13 13:47:58 -0800317TEST(STDIO_TEST, snprintf_a) {
Elliott Hughes05493712014-04-17 17:30:03 -0700318 char buf[BUFSIZ];
319 EXPECT_EQ(23, snprintf(buf, sizeof(buf), "<%a>", 9990.235));
320 EXPECT_STREQ("<0x1.3831e147ae148p+13>", buf);
321}
322
Elliott Hughescdb4a262020-06-05 16:56:53 -0700323// http://b/152588929
324TEST(STDIO_TEST, snprintf_La) {
325#if defined(__LP64__)
326 char buf[BUFSIZ];
327 union {
328 uint64_t a[2];
329 long double v;
330 } u;
331
332 u.a[0] = UINT64_C(0x9b9b9b9b9b9b9b9b);
333 u.a[1] = UINT64_C(0xdfdfdfdfdfdfdfdf);
334 EXPECT_EQ(41, snprintf(buf, sizeof(buf), "<%La>", u.v));
335 EXPECT_STREQ("<-0x1.dfdfdfdfdfdf9b9b9b9b9b9b9b9bp+8160>", buf);
336
337 u.a[0] = UINT64_C(0xffffffffffffffff);
338 u.a[1] = UINT64_C(0x7ffeffffffffffff);
339 EXPECT_EQ(41, snprintf(buf, sizeof(buf), "<%La>", u.v));
340 EXPECT_STREQ("<0x1.ffffffffffffffffffffffffffffp+16383>", buf);
341
342 u.a[0] = UINT64_C(0x0000000000000000);
343 u.a[1] = UINT64_C(0x0000000000000000);
344 EXPECT_EQ(8, snprintf(buf, sizeof(buf), "<%La>", u.v));
345 EXPECT_STREQ("<0x0p+0>", buf);
346#else
347 GTEST_SKIP() << "no ld128";
348#endif
349}
350
Christopher Ferris13f26a72016-01-13 13:47:58 -0800351TEST(STDIO_TEST, snprintf_lc) {
Elliott Hughes05493712014-04-17 17:30:03 -0700352 char buf[BUFSIZ];
353 wint_t wc = L'a';
354 EXPECT_EQ(3, snprintf(buf, sizeof(buf), "<%lc>", wc));
355 EXPECT_STREQ("<a>", buf);
356}
357
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700358TEST(STDIO_TEST, snprintf_C) { // Synonym for %lc.
359 char buf[BUFSIZ];
360 wchar_t wc = L'a';
361 EXPECT_EQ(3, snprintf(buf, sizeof(buf), "<%C>", wc));
362 EXPECT_STREQ("<a>", buf);
363}
364
Christopher Ferris13f26a72016-01-13 13:47:58 -0800365TEST(STDIO_TEST, snprintf_ls) {
Elliott Hughes05493712014-04-17 17:30:03 -0700366 char buf[BUFSIZ];
Yi Kong32bc0fc2018-08-02 17:31:13 -0700367 wchar_t* ws = nullptr;
Elliott Hughes05493712014-04-17 17:30:03 -0700368 EXPECT_EQ(8, snprintf(buf, sizeof(buf), "<%ls>", ws));
369 EXPECT_STREQ("<(null)>", buf);
370
371 wchar_t chars[] = { L'h', L'i', 0 };
372 ws = chars;
373 EXPECT_EQ(4, snprintf(buf, sizeof(buf), "<%ls>", ws));
374 EXPECT_STREQ("<hi>", buf);
375}
376
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700377TEST(STDIO_TEST, snprintf_S) { // Synonym for %ls.
378 char buf[BUFSIZ];
Yi Kong32bc0fc2018-08-02 17:31:13 -0700379 wchar_t* ws = nullptr;
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700380 EXPECT_EQ(8, snprintf(buf, sizeof(buf), "<%S>", ws));
381 EXPECT_STREQ("<(null)>", buf);
382
383 wchar_t chars[] = { L'h', L'i', 0 };
384 ws = chars;
385 EXPECT_EQ(4, snprintf(buf, sizeof(buf), "<%S>", ws));
386 EXPECT_STREQ("<hi>", buf);
387}
388
Elliott Hughese657eb42021-02-18 17:11:56 -0800389TEST_F(STDIO_DEATHTEST, snprintf_n) {
Elliott Hughes063525c2014-05-13 11:19:57 -0700390#if defined(__BIONIC__)
Elliott Hughesb813a6a2022-08-01 22:18:40 +0000391#pragma clang diagnostic push
392#pragma clang diagnostic ignored "-Wformat"
Elliott Hughes41398d02018-03-07 13:32:58 -0800393 // http://b/14492135 and http://b/31832608.
Elliott Hughes7248a2d2013-09-24 18:01:33 -0700394 char buf[32];
Elliott Hughese2341d02014-05-02 18:16:32 -0700395 int i = 1234;
Elliott Hughes41398d02018-03-07 13:32:58 -0800396 EXPECT_DEATH(snprintf(buf, sizeof(buf), "a %n b", &i), "%n not allowed on Android");
Elliott Hughesb813a6a2022-08-01 22:18:40 +0000397#pragma clang diagnostic pop
Elliott Hughese2341d02014-05-02 18:16:32 -0700398#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -0800399 GTEST_SKIP() << "glibc does allow %n";
Elliott Hughese2341d02014-05-02 18:16:32 -0700400#endif
Elliott Hughes7248a2d2013-09-24 18:01:33 -0700401}
Elliott Hughes7248a2d2013-09-24 18:01:33 -0700402
Elliott Hughes7cebf832020-08-12 14:25:41 -0700403TEST(STDIO_TEST, snprintf_measure) {
404 char buf[16];
405 ASSERT_EQ(11, snprintf(buf, 0, "Hello %s", "world"));
406}
407
Christopher Ferris13f26a72016-01-13 13:47:58 -0800408TEST(STDIO_TEST, snprintf_smoke) {
Elliott Hughes1d13c642013-09-23 16:02:39 -0700409 char buf[BUFSIZ];
410
411 snprintf(buf, sizeof(buf), "a");
412 EXPECT_STREQ("a", buf);
413
414 snprintf(buf, sizeof(buf), "%%");
415 EXPECT_STREQ("%", buf);
416
417 snprintf(buf, sizeof(buf), "01234");
418 EXPECT_STREQ("01234", buf);
419
420 snprintf(buf, sizeof(buf), "a%sb", "01234");
421 EXPECT_STREQ("a01234b", buf);
422
Yi Kong32bc0fc2018-08-02 17:31:13 -0700423 char* s = nullptr;
Elliott Hughes1d13c642013-09-23 16:02:39 -0700424 snprintf(buf, sizeof(buf), "a%sb", s);
425 EXPECT_STREQ("a(null)b", buf);
426
427 snprintf(buf, sizeof(buf), "aa%scc", "bb");
428 EXPECT_STREQ("aabbcc", buf);
429
430 snprintf(buf, sizeof(buf), "a%cc", 'b');
431 EXPECT_STREQ("abc", buf);
432
433 snprintf(buf, sizeof(buf), "a%db", 1234);
434 EXPECT_STREQ("a1234b", buf);
435
436 snprintf(buf, sizeof(buf), "a%db", -8123);
437 EXPECT_STREQ("a-8123b", buf);
438
Stephen Hines6c7b3cb2013-10-11 16:03:21 -0700439 snprintf(buf, sizeof(buf), "a%hdb", static_cast<short>(0x7fff0010));
Elliott Hughes1d13c642013-09-23 16:02:39 -0700440 EXPECT_STREQ("a16b", buf);
441
Stephen Hines6c7b3cb2013-10-11 16:03:21 -0700442 snprintf(buf, sizeof(buf), "a%hhdb", static_cast<char>(0x7fffff10));
Elliott Hughes1d13c642013-09-23 16:02:39 -0700443 EXPECT_STREQ("a16b", buf);
444
445 snprintf(buf, sizeof(buf), "a%lldb", 0x1000000000LL);
446 EXPECT_STREQ("a68719476736b", buf);
447
448 snprintf(buf, sizeof(buf), "a%ldb", 70000L);
449 EXPECT_STREQ("a70000b", buf);
450
451 snprintf(buf, sizeof(buf), "a%pb", reinterpret_cast<void*>(0xb0001234));
452 EXPECT_STREQ("a0xb0001234b", buf);
453
454 snprintf(buf, sizeof(buf), "a%xz", 0x12ab);
455 EXPECT_STREQ("a12abz", buf);
456
457 snprintf(buf, sizeof(buf), "a%Xz", 0x12ab);
458 EXPECT_STREQ("a12ABz", buf);
459
460 snprintf(buf, sizeof(buf), "a%08xz", 0x123456);
461 EXPECT_STREQ("a00123456z", buf);
462
463 snprintf(buf, sizeof(buf), "a%5dz", 1234);
464 EXPECT_STREQ("a 1234z", buf);
465
466 snprintf(buf, sizeof(buf), "a%05dz", 1234);
467 EXPECT_STREQ("a01234z", buf);
468
469 snprintf(buf, sizeof(buf), "a%8dz", 1234);
470 EXPECT_STREQ("a 1234z", buf);
471
472 snprintf(buf, sizeof(buf), "a%-8dz", 1234);
473 EXPECT_STREQ("a1234 z", buf);
474
475 snprintf(buf, sizeof(buf), "A%-11sZ", "abcdef");
476 EXPECT_STREQ("Aabcdef Z", buf);
477
478 snprintf(buf, sizeof(buf), "A%s:%dZ", "hello", 1234);
479 EXPECT_STREQ("Ahello:1234Z", buf);
480
481 snprintf(buf, sizeof(buf), "a%03d:%d:%02dz", 5, 5, 5);
482 EXPECT_STREQ("a005:5:05z", buf);
483
Yi Kong32bc0fc2018-08-02 17:31:13 -0700484 void* p = nullptr;
Elliott Hughes1d13c642013-09-23 16:02:39 -0700485 snprintf(buf, sizeof(buf), "a%d,%pz", 5, p);
Christopher Ferris13613132013-10-28 15:24:04 -0700486#if defined(__BIONIC__)
Elliott Hughes1d13c642013-09-23 16:02:39 -0700487 EXPECT_STREQ("a5,0x0z", buf);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800488#else // __BIONIC__
Christopher Ferris13613132013-10-28 15:24:04 -0700489 EXPECT_STREQ("a5,(nil)z", buf);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800490#endif // __BIONIC__
Elliott Hughes1d13c642013-09-23 16:02:39 -0700491
492 snprintf(buf, sizeof(buf), "a%lld,%d,%d,%dz", 0x1000000000LL, 6, 7, 8);
493 EXPECT_STREQ("a68719476736,6,7,8z", buf);
494
495 snprintf(buf, sizeof(buf), "a_%f_b", 1.23f);
496 EXPECT_STREQ("a_1.230000_b", buf);
497
Stephen Hines6c7b3cb2013-10-11 16:03:21 -0700498 snprintf(buf, sizeof(buf), "a_%g_b", 3.14);
Elliott Hughes1d13c642013-09-23 16:02:39 -0700499 EXPECT_STREQ("a_3.14_b", buf);
Alexander Ivchenkoedd7c2e2014-04-01 17:01:39 +0400500
501 snprintf(buf, sizeof(buf), "%1$s %1$s", "print_me_twice");
502 EXPECT_STREQ("print_me_twice print_me_twice", buf);
Elliott Hughes1d13c642013-09-23 16:02:39 -0700503}
504
Elliott Hughes1b18aff2014-12-16 14:45:32 -0800505template <typename T>
Elliott Hughes7f0849f2016-08-26 16:17:17 -0700506static void CheckInfNan(int snprintf_fn(T*, size_t, const T*, ...),
507 int sscanf_fn(const T*, const T*, ...),
508 const T* fmt_string, const T* fmt, const T* fmt_plus,
509 const T* minus_inf, const T* inf_, const T* plus_inf,
510 const T* minus_nan, const T* nan_, const T* plus_nan) {
Elliott Hughes1b18aff2014-12-16 14:45:32 -0800511 T buf[BUFSIZ];
Elliott Hughes7f0849f2016-08-26 16:17:17 -0700512 float f;
Elliott Hughes7823f322014-04-14 12:11:28 -0700513
Elliott Hughes7f0849f2016-08-26 16:17:17 -0700514 // NaN.
515
Elliott Hughese0a9a382022-10-25 22:56:43 +0000516 snprintf_fn(buf, sizeof(buf), fmt, nan(""));
Elliott Hughes1b18aff2014-12-16 14:45:32 -0800517 EXPECT_STREQ(nan_, buf) << fmt;
Elliott Hughes7f0849f2016-08-26 16:17:17 -0700518 EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
519 EXPECT_TRUE(isnan(f));
520
Elliott Hughese0a9a382022-10-25 22:56:43 +0000521 snprintf_fn(buf, sizeof(buf), fmt, -nan(""));
Elliott Hughes1b18aff2014-12-16 14:45:32 -0800522 EXPECT_STREQ(minus_nan, buf) << fmt;
Elliott Hughes7f0849f2016-08-26 16:17:17 -0700523 EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
524 EXPECT_TRUE(isnan(f));
525
Elliott Hughese0a9a382022-10-25 22:56:43 +0000526 snprintf_fn(buf, sizeof(buf), fmt_plus, nan(""));
Elliott Hughes1b18aff2014-12-16 14:45:32 -0800527 EXPECT_STREQ(plus_nan, buf) << fmt_plus;
Elliott Hughes7f0849f2016-08-26 16:17:17 -0700528 EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
529 EXPECT_TRUE(isnan(f));
530
Elliott Hughese0a9a382022-10-25 22:56:43 +0000531 snprintf_fn(buf, sizeof(buf), fmt_plus, -nan(""));
Elliott Hughes1b18aff2014-12-16 14:45:32 -0800532 EXPECT_STREQ(minus_nan, buf) << fmt_plus;
Elliott Hughes7f0849f2016-08-26 16:17:17 -0700533 EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
534 EXPECT_TRUE(isnan(f));
Elliott Hughes1b18aff2014-12-16 14:45:32 -0800535
Elliott Hughes7f0849f2016-08-26 16:17:17 -0700536 // Inf.
537
538 snprintf_fn(buf, sizeof(buf), fmt, HUGE_VALF);
Elliott Hughes1b18aff2014-12-16 14:45:32 -0800539 EXPECT_STREQ(inf_, buf) << fmt;
Elliott Hughes7f0849f2016-08-26 16:17:17 -0700540 EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
541 EXPECT_EQ(HUGE_VALF, f);
542
543 snprintf_fn(buf, sizeof(buf), fmt, -HUGE_VALF);
Elliott Hughes1b18aff2014-12-16 14:45:32 -0800544 EXPECT_STREQ(minus_inf, buf) << fmt;
Elliott Hughes7f0849f2016-08-26 16:17:17 -0700545 EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
546 EXPECT_EQ(-HUGE_VALF, f);
547
548 snprintf_fn(buf, sizeof(buf), fmt_plus, HUGE_VALF);
Elliott Hughes1b18aff2014-12-16 14:45:32 -0800549 EXPECT_STREQ(plus_inf, buf) << fmt_plus;
Elliott Hughes7f0849f2016-08-26 16:17:17 -0700550 EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
551 EXPECT_EQ(HUGE_VALF, f);
552
553 snprintf_fn(buf, sizeof(buf), fmt_plus, -HUGE_VALF);
Elliott Hughes1b18aff2014-12-16 14:45:32 -0800554 EXPECT_STREQ(minus_inf, buf) << fmt_plus;
Elliott Hughes7f0849f2016-08-26 16:17:17 -0700555 EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
556 EXPECT_EQ(-HUGE_VALF, f);
557
558 // Check case-insensitivity.
559 snprintf_fn(buf, sizeof(buf), fmt_string, "[InFiNiTy]");
560 EXPECT_EQ(1, sscanf_fn(buf, fmt, &f)) << buf;
561 EXPECT_EQ(HUGE_VALF, f);
562 snprintf_fn(buf, sizeof(buf), fmt_string, "[NaN]");
563 EXPECT_EQ(1, sscanf_fn(buf, fmt, &f)) << buf;
564 EXPECT_TRUE(isnan(f));
Elliott Hughes7823f322014-04-14 12:11:28 -0700565}
566
Elliott Hughes7f0849f2016-08-26 16:17:17 -0700567TEST(STDIO_TEST, snprintf_sscanf_inf_nan) {
568 CheckInfNan(snprintf, sscanf, "%s",
569 "[%a]", "[%+a]",
570 "[-inf]", "[inf]", "[+inf]",
571 "[-nan]", "[nan]", "[+nan]");
572 CheckInfNan(snprintf, sscanf, "%s",
573 "[%A]", "[%+A]",
574 "[-INF]", "[INF]", "[+INF]",
575 "[-NAN]", "[NAN]", "[+NAN]");
576 CheckInfNan(snprintf, sscanf, "%s",
577 "[%e]", "[%+e]",
578 "[-inf]", "[inf]", "[+inf]",
579 "[-nan]", "[nan]", "[+nan]");
580 CheckInfNan(snprintf, sscanf, "%s",
581 "[%E]", "[%+E]",
582 "[-INF]", "[INF]", "[+INF]",
583 "[-NAN]", "[NAN]", "[+NAN]");
584 CheckInfNan(snprintf, sscanf, "%s",
585 "[%f]", "[%+f]",
586 "[-inf]", "[inf]", "[+inf]",
587 "[-nan]", "[nan]", "[+nan]");
588 CheckInfNan(snprintf, sscanf, "%s",
589 "[%F]", "[%+F]",
590 "[-INF]", "[INF]", "[+INF]",
591 "[-NAN]", "[NAN]", "[+NAN]");
592 CheckInfNan(snprintf, sscanf, "%s",
593 "[%g]", "[%+g]",
594 "[-inf]", "[inf]", "[+inf]",
595 "[-nan]", "[nan]", "[+nan]");
596 CheckInfNan(snprintf, sscanf, "%s",
597 "[%G]", "[%+G]",
598 "[-INF]", "[INF]", "[+INF]",
599 "[-NAN]", "[NAN]", "[+NAN]");
Elliott Hughes1b18aff2014-12-16 14:45:32 -0800600}
Elliott Hughes7823f322014-04-14 12:11:28 -0700601
Elliott Hughes7f0849f2016-08-26 16:17:17 -0700602TEST(STDIO_TEST, swprintf_swscanf_inf_nan) {
603 CheckInfNan(swprintf, swscanf, L"%s",
604 L"[%a]", L"[%+a]",
605 L"[-inf]", L"[inf]", L"[+inf]",
606 L"[-nan]", L"[nan]", L"[+nan]");
607 CheckInfNan(swprintf, swscanf, L"%s",
608 L"[%A]", L"[%+A]",
609 L"[-INF]", L"[INF]", L"[+INF]",
610 L"[-NAN]", L"[NAN]", L"[+NAN]");
611 CheckInfNan(swprintf, swscanf, L"%s",
612 L"[%e]", L"[%+e]",
613 L"[-inf]", L"[inf]", L"[+inf]",
614 L"[-nan]", L"[nan]", L"[+nan]");
615 CheckInfNan(swprintf, swscanf, L"%s",
616 L"[%E]", L"[%+E]",
617 L"[-INF]", L"[INF]", L"[+INF]",
618 L"[-NAN]", L"[NAN]", L"[+NAN]");
619 CheckInfNan(swprintf, swscanf, L"%s",
620 L"[%f]", L"[%+f]",
621 L"[-inf]", L"[inf]", L"[+inf]",
622 L"[-nan]", L"[nan]", L"[+nan]");
623 CheckInfNan(swprintf, swscanf, L"%s",
624 L"[%F]", L"[%+F]",
625 L"[-INF]", L"[INF]", L"[+INF]",
626 L"[-NAN]", L"[NAN]", L"[+NAN]");
627 CheckInfNan(swprintf, swscanf, L"%s",
628 L"[%g]", L"[%+g]",
629 L"[-inf]", L"[inf]", L"[+inf]",
630 L"[-nan]", L"[nan]", L"[+nan]");
631 CheckInfNan(swprintf, swscanf, L"%s",
632 L"[%G]", L"[%+G]",
633 L"[-INF]", L"[INF]", L"[+INF]",
634 L"[-NAN]", L"[NAN]", L"[+NAN]");
Elliott Hughes7823f322014-04-14 12:11:28 -0700635}
636
Dan Albert9601f162017-08-09 14:59:06 -0700637TEST(STDIO_TEST, swprintf) {
638 constexpr size_t nchars = 32;
639 wchar_t buf[nchars];
640
641 ASSERT_EQ(2, swprintf(buf, nchars, L"ab")) << strerror(errno);
642 ASSERT_EQ(std::wstring(L"ab"), buf);
643 ASSERT_EQ(5, swprintf(buf, nchars, L"%s", "abcde"));
644 ASSERT_EQ(std::wstring(L"abcde"), buf);
645
646 // Unlike swprintf(), swprintf() returns -1 in case of truncation
647 // and doesn't necessarily zero-terminate the output!
648 ASSERT_EQ(-1, swprintf(buf, 4, L"%s", "abcde"));
649
650 const char kString[] = "Hello, World";
651 ASSERT_EQ(12, swprintf(buf, nchars, L"%s", kString));
652 ASSERT_EQ(std::wstring(L"Hello, World"), buf);
653 ASSERT_EQ(12, swprintf(buf, 13, L"%s", kString));
654 ASSERT_EQ(std::wstring(L"Hello, World"), buf);
655}
656
657TEST(STDIO_TEST, swprintf_a) {
658 constexpr size_t nchars = 32;
659 wchar_t buf[nchars];
660
661 ASSERT_EQ(20, swprintf(buf, nchars, L"%a", 3.1415926535));
662 ASSERT_EQ(std::wstring(L"0x1.921fb54411744p+1"), buf);
663}
664
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700665TEST(STDIO_TEST, swprintf_lc) {
666 constexpr size_t nchars = 32;
667 wchar_t buf[nchars];
668
669 wint_t wc = L'a';
670 EXPECT_EQ(3, swprintf(buf, nchars, L"<%lc>", wc));
671 EXPECT_EQ(std::wstring(L"<a>"), buf);
672}
673
674TEST(STDIO_TEST, swprintf_C) { // Synonym for %lc.
675 constexpr size_t nchars = 32;
676 wchar_t buf[nchars];
677
678 wint_t wc = L'a';
679 EXPECT_EQ(3, swprintf(buf, nchars, L"<%C>", wc));
680 EXPECT_EQ(std::wstring(L"<a>"), buf);
681}
682
Elliott Hughes618303c2017-11-02 16:58:44 -0700683TEST(STDIO_TEST, swprintf_jd_INTMAX_MAX) {
684 constexpr size_t nchars = 32;
685 wchar_t buf[nchars];
686
687 swprintf(buf, nchars, L"%jd", INTMAX_MAX);
688 EXPECT_EQ(std::wstring(L"9223372036854775807"), buf);
689}
690
691TEST(STDIO_TEST, swprintf_jd_INTMAX_MIN) {
692 constexpr size_t nchars = 32;
693 wchar_t buf[nchars];
694
695 swprintf(buf, nchars, L"%jd", INTMAX_MIN);
696 EXPECT_EQ(std::wstring(L"-9223372036854775808"), buf);
697}
698
699TEST(STDIO_TEST, swprintf_ju_UINTMAX_MAX) {
700 constexpr size_t nchars = 32;
701 wchar_t buf[nchars];
702
703 swprintf(buf, nchars, L"%ju", UINTMAX_MAX);
704 EXPECT_EQ(std::wstring(L"18446744073709551615"), buf);
705}
706
707TEST(STDIO_TEST, swprintf_1$ju_UINTMAX_MAX) {
708 constexpr size_t nchars = 32;
709 wchar_t buf[nchars];
710
711 swprintf(buf, nchars, L"%1$ju", UINTMAX_MAX);
712 EXPECT_EQ(std::wstring(L"18446744073709551615"), buf);
713}
714
Dan Albert9601f162017-08-09 14:59:06 -0700715TEST(STDIO_TEST, swprintf_ls) {
716 constexpr size_t nchars = 32;
717 wchar_t buf[nchars];
718
719 static const wchar_t kWideString[] = L"Hello\uff41 World";
720 ASSERT_EQ(12, swprintf(buf, nchars, L"%ls", kWideString));
721 ASSERT_EQ(std::wstring(kWideString), buf);
722 ASSERT_EQ(12, swprintf(buf, 13, L"%ls", kWideString));
723 ASSERT_EQ(std::wstring(kWideString), buf);
724}
725
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700726TEST(STDIO_TEST, swprintf_S) { // Synonym for %ls.
727 constexpr size_t nchars = 32;
728 wchar_t buf[nchars];
729
730 static const wchar_t kWideString[] = L"Hello\uff41 World";
731 ASSERT_EQ(12, swprintf(buf, nchars, L"%S", kWideString));
732 ASSERT_EQ(std::wstring(kWideString), buf);
733 ASSERT_EQ(12, swprintf(buf, 13, L"%S", kWideString));
734 ASSERT_EQ(std::wstring(kWideString), buf);
735}
736
Christopher Ferris13f26a72016-01-13 13:47:58 -0800737TEST(STDIO_TEST, snprintf_d_INT_MAX) {
Elliott Hughes1d13c642013-09-23 16:02:39 -0700738 char buf[BUFSIZ];
739 snprintf(buf, sizeof(buf), "%d", INT_MAX);
740 EXPECT_STREQ("2147483647", buf);
741}
742
Christopher Ferris13f26a72016-01-13 13:47:58 -0800743TEST(STDIO_TEST, snprintf_d_INT_MIN) {
Elliott Hughes1d13c642013-09-23 16:02:39 -0700744 char buf[BUFSIZ];
745 snprintf(buf, sizeof(buf), "%d", INT_MIN);
746 EXPECT_STREQ("-2147483648", buf);
747}
748
Elliott Hughes618303c2017-11-02 16:58:44 -0700749TEST(STDIO_TEST, snprintf_jd_INTMAX_MAX) {
750 char buf[BUFSIZ];
751 snprintf(buf, sizeof(buf), "%jd", INTMAX_MAX);
752 EXPECT_STREQ("9223372036854775807", buf);
753}
754
755TEST(STDIO_TEST, snprintf_jd_INTMAX_MIN) {
756 char buf[BUFSIZ];
757 snprintf(buf, sizeof(buf), "%jd", INTMAX_MIN);
758 EXPECT_STREQ("-9223372036854775808", buf);
759}
760
761TEST(STDIO_TEST, snprintf_ju_UINTMAX_MAX) {
762 char buf[BUFSIZ];
763 snprintf(buf, sizeof(buf), "%ju", UINTMAX_MAX);
764 EXPECT_STREQ("18446744073709551615", buf);
765}
766
767TEST(STDIO_TEST, snprintf_1$ju_UINTMAX_MAX) {
768 char buf[BUFSIZ];
769 snprintf(buf, sizeof(buf), "%1$ju", UINTMAX_MAX);
770 EXPECT_STREQ("18446744073709551615", buf);
771}
772
Christopher Ferris13f26a72016-01-13 13:47:58 -0800773TEST(STDIO_TEST, snprintf_ld_LONG_MAX) {
Elliott Hughes1d13c642013-09-23 16:02:39 -0700774 char buf[BUFSIZ];
775 snprintf(buf, sizeof(buf), "%ld", LONG_MAX);
Josh Gaob36efa42016-09-15 13:55:41 -0700776#if defined(__LP64__)
Elliott Hughes925753a2013-10-18 13:17:18 -0700777 EXPECT_STREQ("9223372036854775807", buf);
778#else
Elliott Hughes1d13c642013-09-23 16:02:39 -0700779 EXPECT_STREQ("2147483647", buf);
Elliott Hughes925753a2013-10-18 13:17:18 -0700780#endif
Elliott Hughes1d13c642013-09-23 16:02:39 -0700781}
782
Christopher Ferris13f26a72016-01-13 13:47:58 -0800783TEST(STDIO_TEST, snprintf_ld_LONG_MIN) {
Elliott Hughes1d13c642013-09-23 16:02:39 -0700784 char buf[BUFSIZ];
785 snprintf(buf, sizeof(buf), "%ld", LONG_MIN);
Josh Gaob36efa42016-09-15 13:55:41 -0700786#if defined(__LP64__)
Elliott Hughes925753a2013-10-18 13:17:18 -0700787 EXPECT_STREQ("-9223372036854775808", buf);
788#else
Elliott Hughes1d13c642013-09-23 16:02:39 -0700789 EXPECT_STREQ("-2147483648", buf);
Elliott Hughes925753a2013-10-18 13:17:18 -0700790#endif
Elliott Hughes1d13c642013-09-23 16:02:39 -0700791}
792
Christopher Ferris13f26a72016-01-13 13:47:58 -0800793TEST(STDIO_TEST, snprintf_lld_LLONG_MAX) {
Elliott Hughes1d13c642013-09-23 16:02:39 -0700794 char buf[BUFSIZ];
795 snprintf(buf, sizeof(buf), "%lld", LLONG_MAX);
796 EXPECT_STREQ("9223372036854775807", buf);
797}
798
Christopher Ferris13f26a72016-01-13 13:47:58 -0800799TEST(STDIO_TEST, snprintf_lld_LLONG_MIN) {
Elliott Hughes1d13c642013-09-23 16:02:39 -0700800 char buf[BUFSIZ];
801 snprintf(buf, sizeof(buf), "%lld", LLONG_MIN);
802 EXPECT_STREQ("-9223372036854775808", buf);
803}
804
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700805TEST(STDIO_TEST, snprintf_o_UINT_MAX) {
806 char buf[BUFSIZ];
807 snprintf(buf, sizeof(buf), "%o", UINT_MAX);
808 EXPECT_STREQ("37777777777", buf);
809}
810
811TEST(STDIO_TEST, snprintf_u_UINT_MAX) {
812 char buf[BUFSIZ];
813 snprintf(buf, sizeof(buf), "%u", UINT_MAX);
814 EXPECT_STREQ("4294967295", buf);
815}
816
817TEST(STDIO_TEST, snprintf_x_UINT_MAX) {
818 char buf[BUFSIZ];
819 snprintf(buf, sizeof(buf), "%x", UINT_MAX);
820 EXPECT_STREQ("ffffffff", buf);
821}
822
823TEST(STDIO_TEST, snprintf_X_UINT_MAX) {
824 char buf[BUFSIZ];
825 snprintf(buf, sizeof(buf), "%X", UINT_MAX);
826 EXPECT_STREQ("FFFFFFFF", buf);
827}
828
Christopher Ferris13f26a72016-01-13 13:47:58 -0800829TEST(STDIO_TEST, snprintf_e) {
Elliott Hughes4bd97ce2014-04-10 17:48:14 -0700830 char buf[BUFSIZ];
831
832 snprintf(buf, sizeof(buf), "%e", 1.5);
833 EXPECT_STREQ("1.500000e+00", buf);
834
Chih-Hung Hsiehc2edae32018-12-11 15:16:24 -0800835 snprintf(buf, sizeof(buf), "%Le", 1.5L);
Elliott Hughes4bd97ce2014-04-10 17:48:14 -0700836 EXPECT_STREQ("1.500000e+00", buf);
837}
838
Christopher Ferris13f26a72016-01-13 13:47:58 -0800839TEST(STDIO_TEST, snprintf_negative_zero_5084292) {
Elliott Hughese77f38f2014-05-14 12:39:12 -0700840 char buf[BUFSIZ];
841
Elliott Hughes1b18aff2014-12-16 14:45:32 -0800842 snprintf(buf, sizeof(buf), "%e", -0.0);
843 EXPECT_STREQ("-0.000000e+00", buf);
844 snprintf(buf, sizeof(buf), "%E", -0.0);
845 EXPECT_STREQ("-0.000000E+00", buf);
Elliott Hughese77f38f2014-05-14 12:39:12 -0700846 snprintf(buf, sizeof(buf), "%f", -0.0);
847 EXPECT_STREQ("-0.000000", buf);
Elliott Hughes1b18aff2014-12-16 14:45:32 -0800848 snprintf(buf, sizeof(buf), "%F", -0.0);
849 EXPECT_STREQ("-0.000000", buf);
850 snprintf(buf, sizeof(buf), "%g", -0.0);
851 EXPECT_STREQ("-0", buf);
852 snprintf(buf, sizeof(buf), "%G", -0.0);
853 EXPECT_STREQ("-0", buf);
854 snprintf(buf, sizeof(buf), "%a", -0.0);
855 EXPECT_STREQ("-0x0p+0", buf);
856 snprintf(buf, sizeof(buf), "%A", -0.0);
857 EXPECT_STREQ("-0X0P+0", buf);
Elliott Hughese77f38f2014-05-14 12:39:12 -0700858}
859
Christopher Ferris13f26a72016-01-13 13:47:58 -0800860TEST(STDIO_TEST, snprintf_utf8_15439554) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700861 locale_t cloc = newlocale(LC_ALL, "C.UTF-8", nullptr);
Wally Yaua40fdbd2014-08-26 09:47:23 -0700862 locale_t old_locale = uselocale(cloc);
Dan Albert1aec7c12014-07-30 10:53:48 -0700863
Elliott Hughes69f05d22014-06-05 20:10:09 -0700864 // http://b/15439554
865 char buf[BUFSIZ];
866
867 // 1-byte character.
868 snprintf(buf, sizeof(buf), "%dx%d", 1, 2);
869 EXPECT_STREQ("1x2", buf);
870 // 2-byte character.
871 snprintf(buf, sizeof(buf), "%d\xc2\xa2%d", 1, 2);
872 EXPECT_STREQ("1¢2", buf);
873 // 3-byte character.
874 snprintf(buf, sizeof(buf), "%d\xe2\x82\xac%d", 1, 2);
875 EXPECT_STREQ("1€2", buf);
876 // 4-byte character.
877 snprintf(buf, sizeof(buf), "%d\xf0\xa4\xad\xa2%d", 1, 2);
878 EXPECT_STREQ("1𤭢2", buf);
Dan Albert1aec7c12014-07-30 10:53:48 -0700879
Wally Yaua40fdbd2014-08-26 09:47:23 -0700880 uselocale(old_locale);
Dan Albert1aec7c12014-07-30 10:53:48 -0700881 freelocale(cloc);
Elliott Hughes69f05d22014-06-05 20:10:09 -0700882}
883
Elliott Hughes43f7c872016-02-05 11:18:41 -0800884static void* snprintf_small_stack_fn(void*) {
885 // Make life (realistically) hard for ourselves by allocating our own buffer for the result.
886 char buf[PATH_MAX];
887 snprintf(buf, sizeof(buf), "/proc/%d", getpid());
888 return nullptr;
889}
890
891TEST(STDIO_TEST, snprintf_small_stack) {
892 // Is it safe to call snprintf on a thread with a small stack?
893 // (The snprintf implementation puts some pretty large buffers on the stack.)
894 pthread_attr_t a;
895 ASSERT_EQ(0, pthread_attr_init(&a));
896 ASSERT_EQ(0, pthread_attr_setstacksize(&a, PTHREAD_STACK_MIN));
897
898 pthread_t t;
899 ASSERT_EQ(0, pthread_create(&t, &a, snprintf_small_stack_fn, nullptr));
900 ASSERT_EQ(0, pthread_join(t, nullptr));
901}
902
Elliott Hughes8200e552016-02-05 21:57:37 -0800903TEST(STDIO_TEST, snprintf_asterisk_overflow) {
904 char buf[128];
905 ASSERT_EQ(5, snprintf(buf, sizeof(buf), "%.*s%c", 4, "hello world", '!'));
906 ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.*s%c", INT_MAX/2, "hello world", '!'));
907 ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.*s%c", INT_MAX-1, "hello world", '!'));
908 ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.*s%c", INT_MAX, "hello world", '!'));
909 ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.*s%c", -1, "hello world", '!'));
910
911 // INT_MAX-1, INT_MAX, INT_MAX+1.
912 ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.2147483646s%c", "hello world", '!'));
913 ASSERT_EQ(12, snprintf(buf, sizeof(buf), "%.2147483647s%c", "hello world", '!'));
914 ASSERT_EQ(-1, snprintf(buf, sizeof(buf), "%.2147483648s%c", "hello world", '!'));
915 ASSERT_EQ(ENOMEM, errno);
916}
917
Elliott Hughes5dc31302020-01-07 08:48:10 -0800918// Inspired by https://github.com/landley/toybox/issues/163.
919TEST(STDIO_TEST, printf_NULL) {
920 char buf[128];
921 char* null = nullptr;
922 EXPECT_EQ(4, snprintf(buf, sizeof(buf), "<%*.*s>", 2, 2, null));
923 EXPECT_STREQ("<(n>", buf);
924 EXPECT_EQ(8, snprintf(buf, sizeof(buf), "<%*.*s>", 2, 8, null));
925 EXPECT_STREQ("<(null)>", buf);
926 EXPECT_EQ(10, snprintf(buf, sizeof(buf), "<%*.*s>", 8, 2, null));
927 EXPECT_STREQ("< (n>", buf);
928 EXPECT_EQ(10, snprintf(buf, sizeof(buf), "<%*.*s>", 8, 8, null));
929 EXPECT_STREQ("< (null)>", buf);
930}
931
Elliott Hughes70715da2016-08-01 16:35:17 -0700932TEST(STDIO_TEST, fprintf) {
933 TemporaryFile tf;
934
935 FILE* tfile = fdopen(tf.fd, "r+");
936 ASSERT_TRUE(tfile != nullptr);
937
938 ASSERT_EQ(7, fprintf(tfile, "%d %s", 123, "abc"));
939 AssertFileIs(tfile, "123 abc");
940 fclose(tfile);
941}
942
Christopher Ferris13f26a72016-01-13 13:47:58 -0800943TEST(STDIO_TEST, fprintf_failures_7229520) {
Elliott Hughes69f05d22014-06-05 20:10:09 -0700944 // http://b/7229520
Elliott Hughesc9244bd2014-05-14 13:31:35 -0700945 FILE* fp;
Josh Gaof6e5b582018-06-01 15:30:54 -0700946 int fd_rdonly = open("/dev/null", O_RDONLY);
947 ASSERT_NE(-1, fd_rdonly);
Elliott Hughesc9244bd2014-05-14 13:31:35 -0700948
949 // Unbuffered case where the fprintf(3) itself fails.
950 ASSERT_NE(nullptr, fp = tmpfile());
Yi Kong32bc0fc2018-08-02 17:31:13 -0700951 setbuf(fp, nullptr);
Elliott Hughesc9244bd2014-05-14 13:31:35 -0700952 ASSERT_EQ(4, fprintf(fp, "epic"));
Josh Gaof6e5b582018-06-01 15:30:54 -0700953 ASSERT_NE(-1, dup2(fd_rdonly, fileno(fp)));
Elliott Hughesc9244bd2014-05-14 13:31:35 -0700954 ASSERT_EQ(-1, fprintf(fp, "fail"));
Josh Gaof6e5b582018-06-01 15:30:54 -0700955 ASSERT_EQ(0, fclose(fp));
Elliott Hughesc9244bd2014-05-14 13:31:35 -0700956
957 // Buffered case where we won't notice until the fclose(3).
958 // It's likely this is what was actually seen in http://b/7229520,
959 // and that expecting fprintf to fail is setting yourself up for
960 // disappointment. Remember to check fclose(3)'s return value, kids!
961 ASSERT_NE(nullptr, fp = tmpfile());
962 ASSERT_EQ(4, fprintf(fp, "epic"));
Josh Gaof6e5b582018-06-01 15:30:54 -0700963 ASSERT_NE(-1, dup2(fd_rdonly, fileno(fp)));
Elliott Hughesc9244bd2014-05-14 13:31:35 -0700964 ASSERT_EQ(4, fprintf(fp, "fail"));
965 ASSERT_EQ(-1, fclose(fp));
966}
967
Elliott Hughes468efc82018-07-10 14:39:49 -0700968TEST(STDIO_TEST, popen_r) {
Elliott Hughes6b3f49a2013-03-06 16:20:55 -0800969 FILE* fp = popen("cat /proc/version", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -0700970 ASSERT_TRUE(fp != nullptr);
Elliott Hughes6b3f49a2013-03-06 16:20:55 -0800971
972 char buf[16];
973 char* s = fgets(buf, sizeof(buf), fp);
974 buf[13] = '\0';
975 ASSERT_STREQ("Linux version", s);
976
977 ASSERT_EQ(0, pclose(fp));
978}
Elliott Hughes6b05c8e2013-04-11 13:54:48 -0700979
Elliott Hughes468efc82018-07-10 14:39:49 -0700980TEST(STDIO_TEST, popen_socketpair) {
981 FILE* fp = popen("cat", "r+");
Yi Kong32bc0fc2018-08-02 17:31:13 -0700982 ASSERT_TRUE(fp != nullptr);
Elliott Hughes468efc82018-07-10 14:39:49 -0700983
984 fputs("hello\nworld\n", fp);
985 fflush(fp);
986
987 char buf[16];
988 ASSERT_NE(nullptr, fgets(buf, sizeof(buf), fp));
989 EXPECT_STREQ("hello\n", buf);
990 ASSERT_NE(nullptr, fgets(buf, sizeof(buf), fp));
991 EXPECT_STREQ("world\n", buf);
992
993 ASSERT_EQ(0, pclose(fp));
994}
995
996TEST(STDIO_TEST, popen_socketpair_shutdown) {
997 FILE* fp = popen("uniq -c", "r+");
Yi Kong32bc0fc2018-08-02 17:31:13 -0700998 ASSERT_TRUE(fp != nullptr);
Elliott Hughes468efc82018-07-10 14:39:49 -0700999
1000 fputs("a\na\na\na\nb\n", fp);
1001 fflush(fp);
1002 ASSERT_EQ(0, shutdown(fileno(fp), SHUT_WR));
1003
1004 char buf[16];
1005 ASSERT_NE(nullptr, fgets(buf, sizeof(buf), fp));
1006 EXPECT_STREQ(" 4 a\n", buf);
1007 ASSERT_NE(nullptr, fgets(buf, sizeof(buf), fp));
1008 EXPECT_STREQ(" 1 b\n", buf);
1009
1010 ASSERT_EQ(0, pclose(fp));
1011}
1012
1013TEST(STDIO_TEST, popen_return_value_0) {
1014 FILE* fp = popen("true", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07001015 ASSERT_TRUE(fp != nullptr);
Elliott Hughes468efc82018-07-10 14:39:49 -07001016 int status = pclose(fp);
1017 EXPECT_TRUE(WIFEXITED(status));
1018 EXPECT_EQ(0, WEXITSTATUS(status));
1019}
1020
1021TEST(STDIO_TEST, popen_return_value_1) {
1022 FILE* fp = popen("false", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07001023 ASSERT_TRUE(fp != nullptr);
Elliott Hughes468efc82018-07-10 14:39:49 -07001024 int status = pclose(fp);
1025 EXPECT_TRUE(WIFEXITED(status));
1026 EXPECT_EQ(1, WEXITSTATUS(status));
1027}
1028
1029TEST(STDIO_TEST, popen_return_value_signal) {
1030 FILE* fp = popen("kill -7 $$", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07001031 ASSERT_TRUE(fp != nullptr);
Elliott Hughes468efc82018-07-10 14:39:49 -07001032 int status = pclose(fp);
1033 EXPECT_TRUE(WIFSIGNALED(status));
1034 EXPECT_EQ(7, WTERMSIG(status));
1035}
1036
Christopher Ferris13f26a72016-01-13 13:47:58 -08001037TEST(STDIO_TEST, getc) {
Elliott Hughes6b05c8e2013-04-11 13:54:48 -07001038 FILE* fp = fopen("/proc/version", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07001039 ASSERT_TRUE(fp != nullptr);
Elliott Hughes6b05c8e2013-04-11 13:54:48 -07001040 ASSERT_EQ('L', getc(fp));
1041 ASSERT_EQ('i', getc(fp));
1042 ASSERT_EQ('n', getc(fp));
1043 ASSERT_EQ('u', getc(fp));
1044 ASSERT_EQ('x', getc(fp));
1045 fclose(fp);
1046}
1047
Christopher Ferris13f26a72016-01-13 13:47:58 -08001048TEST(STDIO_TEST, putc) {
Elliott Hughes6b05c8e2013-04-11 13:54:48 -07001049 FILE* fp = fopen("/proc/version", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07001050 ASSERT_TRUE(fp != nullptr);
Elliott Hughes6b05c8e2013-04-11 13:54:48 -07001051 ASSERT_EQ(EOF, putc('x', fp));
1052 fclose(fp);
1053}
Elliott Hughes603332f2014-03-12 17:10:41 -07001054
Elliott Hughes7f0849f2016-08-26 16:17:17 -07001055TEST(STDIO_TEST, sscanf_swscanf) {
1056 struct stuff {
1057 char s1[123];
Elliott Hughes0d3ba1f2017-12-06 16:41:35 -08001058 int i1, i2;
1059 char cs1[3];
1060 char s2[3];
1061 char c1;
Elliott Hughes7f0849f2016-08-26 16:17:17 -07001062 double d1;
1063 float f1;
Elliott Hughes0d3ba1f2017-12-06 16:41:35 -08001064 char s3[123];
Elliott Hughes7f0849f2016-08-26 16:17:17 -07001065
1066 void Check() {
Elliott Hughes0d3ba1f2017-12-06 16:41:35 -08001067 EXPECT_STREQ("hello", s1);
1068 EXPECT_EQ(123, i1);
1069 EXPECT_EQ(456, i2);
1070 EXPECT_EQ('a', cs1[0]);
1071 EXPECT_EQ('b', cs1[1]);
1072 EXPECT_EQ('x', cs1[2]); // No terminating NUL.
1073 EXPECT_STREQ("AB", s2); // Terminating NUL.
1074 EXPECT_EQ('!', c1);
1075 EXPECT_DOUBLE_EQ(1.23, d1);
1076 EXPECT_FLOAT_EQ(9.0f, f1);
1077 EXPECT_STREQ("world", s3);
Elliott Hughes7f0849f2016-08-26 16:17:17 -07001078 }
1079 } s;
1080
Elliott Hughes0d3ba1f2017-12-06 16:41:35 -08001081 memset(&s, 'x', sizeof(s));
1082 ASSERT_EQ(9, sscanf(" hello 123 456abAB! 1.23 0x1.2p3 world",
1083 "%s %i%i%2c%[A-Z]%c %lf %f %s",
1084 s.s1, &s.i1, &s.i2, s.cs1, s.s2, &s.c1, &s.d1, &s.f1, s.s3));
Elliott Hughes7f0849f2016-08-26 16:17:17 -07001085 s.Check();
1086
Elliott Hughes0d3ba1f2017-12-06 16:41:35 -08001087 memset(&s, 'x', sizeof(s));
1088 ASSERT_EQ(9, swscanf(L" hello 123 456abAB! 1.23 0x1.2p3 world",
1089 L"%s %i%i%2c%[A-Z]%c %lf %f %s",
1090 s.s1, &s.i1, &s.i2, s.cs1, s.s2, &s.c1, &s.d1, &s.f1, s.s3));
Elliott Hughes7f0849f2016-08-26 16:17:17 -07001091 s.Check();
Elliott Hughes603332f2014-03-12 17:10:41 -07001092}
Elliott Hughes53b24382014-05-02 18:29:25 -07001093
Elliott Hughes0d3ba1f2017-12-06 16:41:35 -08001094template <typename T>
1095static void CheckScanf(int sscanf_fn(const T*, const T*, ...),
1096 const T* input, const T* fmt,
1097 int expected_count, const char* expected_string) {
1098 char buf[256] = {};
1099 ASSERT_EQ(expected_count, sscanf_fn(input, fmt, &buf)) << fmt;
1100 ASSERT_STREQ(expected_string, buf) << fmt;
1101}
1102
1103TEST(STDIO_TEST, sscanf_ccl) {
1104 // `abc` is just those characters.
1105 CheckScanf(sscanf, "abcd", "%[abc]", 1, "abc");
1106 // `a-c` is the range 'a' .. 'c'.
1107 CheckScanf(sscanf, "abcd", "%[a-c]", 1, "abc");
1108 CheckScanf(sscanf, "-d", "%[a-c]", 0, "");
1109 CheckScanf(sscanf, "ac-bAd", "%[a--c]", 1, "ac-bA");
1110 // `a-c-e` is equivalent to `a-e`.
1111 CheckScanf(sscanf, "abcdefg", "%[a-c-e]", 1, "abcde");
1112 // `e-a` is equivalent to `ae-` (because 'e' > 'a').
1113 CheckScanf(sscanf, "-a-e-b", "%[e-a]", 1, "-a-e-");
1114 // An initial '^' negates the set.
1115 CheckScanf(sscanf, "abcde", "%[^d]", 1, "abc");
1116 CheckScanf(sscanf, "abcdefgh", "%[^c-d]", 1, "ab");
1117 CheckScanf(sscanf, "hgfedcba", "%[^c-d]", 1, "hgfe");
1118 // The first character may be ']' or '-' without being special.
1119 CheckScanf(sscanf, "[[]]x", "%[][]", 1, "[[]]");
1120 CheckScanf(sscanf, "-a-x", "%[-a]", 1, "-a-");
1121 // The last character may be '-' without being special.
1122 CheckScanf(sscanf, "-a-x", "%[a-]", 1, "-a-");
1123 // X--Y is [X--] + Y, not [X--] + [--Y] (a bug in my initial implementation).
1124 CheckScanf(sscanf, "+,-/.", "%[+--/]", 1, "+,-/");
1125}
1126
1127TEST(STDIO_TEST, swscanf_ccl) {
1128 // `abc` is just those characters.
1129 CheckScanf(swscanf, L"abcd", L"%[abc]", 1, "abc");
1130 // `a-c` is the range 'a' .. 'c'.
1131 CheckScanf(swscanf, L"abcd", L"%[a-c]", 1, "abc");
1132 CheckScanf(swscanf, L"-d", L"%[a-c]", 0, "");
1133 CheckScanf(swscanf, L"ac-bAd", L"%[a--c]", 1, "ac-bA");
1134 // `a-c-e` is equivalent to `a-e`.
1135 CheckScanf(swscanf, L"abcdefg", L"%[a-c-e]", 1, "abcde");
1136 // `e-a` is equivalent to `ae-` (because 'e' > 'a').
1137 CheckScanf(swscanf, L"-a-e-b", L"%[e-a]", 1, "-a-e-");
1138 // An initial '^' negates the set.
1139 CheckScanf(swscanf, L"abcde", L"%[^d]", 1, "abc");
1140 CheckScanf(swscanf, L"abcdefgh", L"%[^c-d]", 1, "ab");
1141 CheckScanf(swscanf, L"hgfedcba", L"%[^c-d]", 1, "hgfe");
1142 // The first character may be ']' or '-' without being special.
1143 CheckScanf(swscanf, L"[[]]x", L"%[][]", 1, "[[]]");
1144 CheckScanf(swscanf, L"-a-x", L"%[-a]", 1, "-a-");
1145 // The last character may be '-' without being special.
1146 CheckScanf(swscanf, L"-a-x", L"%[a-]", 1, "-a-");
1147 // X--Y is [X--] + Y, not [X--] + [--Y] (a bug in my initial implementation).
1148 CheckScanf(swscanf, L"+,-/.", L"%[+--/]", 1, "+,-/");
1149}
1150
Elliott Hughes38e4aef2018-01-18 10:21:29 -08001151template <typename T1, typename T2>
1152static void CheckScanfM(int sscanf_fn(const T1*, const T1*, ...),
1153 const T1* input, const T1* fmt,
1154 int expected_count, const T2* expected_string) {
1155 T2* result = nullptr;
1156 ASSERT_EQ(expected_count, sscanf_fn(input, fmt, &result)) << fmt;
1157 if (expected_string == nullptr) {
1158 ASSERT_EQ(nullptr, result);
1159 } else {
1160 ASSERT_STREQ(expected_string, result) << fmt;
1161 }
1162 free(result);
1163}
1164
1165TEST(STDIO_TEST, sscanf_mc) {
1166 char* p1 = nullptr;
1167 char* p2 = nullptr;
1168 ASSERT_EQ(2, sscanf("hello", "%mc%mc", &p1, &p2));
1169 ASSERT_EQ('h', *p1);
1170 ASSERT_EQ('e', *p2);
1171 free(p1);
1172 free(p2);
1173
1174 p1 = nullptr;
1175 ASSERT_EQ(1, sscanf("hello", "%4mc", &p1));
1176 ASSERT_EQ('h', p1[0]);
1177 ASSERT_EQ('e', p1[1]);
1178 ASSERT_EQ('l', p1[2]);
1179 ASSERT_EQ('l', p1[3]);
1180 free(p1);
1181
1182 p1 = nullptr;
1183 ASSERT_EQ(1, sscanf("hello world", "%30mc", &p1));
1184 ASSERT_EQ('h', p1[0]);
1185 ASSERT_EQ('e', p1[1]);
1186 ASSERT_EQ('l', p1[2]);
1187 ASSERT_EQ('l', p1[3]);
1188 ASSERT_EQ('o', p1[4]);
1189 free(p1);
1190}
1191
Elliott Hughes38e4aef2018-01-18 10:21:29 -08001192TEST(STDIO_TEST, sscanf_mlc) {
1193 // This is so useless that clang doesn't even believe it exists...
1194#pragma clang diagnostic push
1195#pragma clang diagnostic ignored "-Wformat-invalid-specifier"
1196#pragma clang diagnostic ignored "-Wformat-extra-args"
1197
1198 wchar_t* p1 = nullptr;
1199 wchar_t* p2 = nullptr;
1200 ASSERT_EQ(2, sscanf("hello", "%mlc%mlc", &p1, &p2));
1201 ASSERT_EQ(L'h', *p1);
1202 ASSERT_EQ(L'e', *p2);
1203 free(p1);
1204 free(p2);
1205
1206 p1 = nullptr;
1207 ASSERT_EQ(1, sscanf("hello", "%4mlc", &p1));
1208 ASSERT_EQ(L'h', p1[0]);
1209 ASSERT_EQ(L'e', p1[1]);
1210 ASSERT_EQ(L'l', p1[2]);
1211 ASSERT_EQ(L'l', p1[3]);
1212 free(p1);
1213
1214 p1 = nullptr;
1215 ASSERT_EQ(1, sscanf("hello world", "%30mlc", &p1));
1216 ASSERT_EQ(L'h', p1[0]);
1217 ASSERT_EQ(L'e', p1[1]);
1218 ASSERT_EQ(L'l', p1[2]);
1219 ASSERT_EQ(L'l', p1[3]);
1220 ASSERT_EQ(L'o', p1[4]);
1221 free(p1);
1222#pragma clang diagnostic pop
1223}
1224
Elliott Hughes38e4aef2018-01-18 10:21:29 -08001225TEST(STDIO_TEST, sscanf_ms) {
1226 CheckScanfM(sscanf, "hello", "%ms", 1, "hello");
1227 CheckScanfM(sscanf, "hello", "%4ms", 1, "hell");
1228 CheckScanfM(sscanf, "hello world", "%30ms", 1, "hello");
1229}
1230
1231TEST(STDIO_TEST, sscanf_mls) {
1232 CheckScanfM(sscanf, "hello", "%mls", 1, L"hello");
1233 CheckScanfM(sscanf, "hello", "%4mls", 1, L"hell");
1234 CheckScanfM(sscanf, "hello world", "%30mls", 1, L"hello");
1235}
1236
1237TEST(STDIO_TEST, sscanf_m_ccl) {
1238 CheckScanfM(sscanf, "hello", "%m[a-z]", 1, "hello");
1239 CheckScanfM(sscanf, "hello", "%4m[a-z]", 1, "hell");
1240 CheckScanfM(sscanf, "hello world", "%30m[a-z]", 1, "hello");
1241}
1242
1243TEST(STDIO_TEST, sscanf_ml_ccl) {
1244 CheckScanfM(sscanf, "hello", "%ml[a-z]", 1, L"hello");
1245 CheckScanfM(sscanf, "hello", "%4ml[a-z]", 1, L"hell");
1246 CheckScanfM(sscanf, "hello world", "%30ml[a-z]", 1, L"hello");
1247}
1248
1249TEST(STDIO_TEST, sscanf_ls) {
1250 wchar_t w[32] = {};
1251 ASSERT_EQ(1, sscanf("hello world", "%ls", w));
1252 ASSERT_EQ(L"hello", std::wstring(w));
1253}
1254
1255TEST(STDIO_TEST, sscanf_ls_suppress) {
1256 ASSERT_EQ(0, sscanf("hello world", "%*ls %*ls"));
1257}
1258
1259TEST(STDIO_TEST, sscanf_ls_n) {
1260 setlocale(LC_ALL, "C.UTF-8");
1261 wchar_t w[32] = {};
1262 int pos = 0;
1263 ASSERT_EQ(1, sscanf("\xc4\x80", "%ls%n", w, &pos));
1264 ASSERT_EQ(static_cast<wchar_t>(256), w[0]);
1265 ASSERT_EQ(2, pos);
1266}
1267
1268TEST(STDIO_TEST, sscanf_ls_realloc) {
1269 // This is so useless that clang doesn't even believe it exists...
1270#pragma clang diagnostic push
1271#pragma clang diagnostic ignored "-Wformat-invalid-specifier"
1272#pragma clang diagnostic ignored "-Wformat-extra-args"
1273 wchar_t* p1 = nullptr;
1274 wchar_t* p2 = nullptr;
1275 ASSERT_EQ(2, sscanf("1234567890123456789012345678901234567890 world", "%mls %mls", &p1, &p2));
1276 ASSERT_EQ(L"1234567890123456789012345678901234567890", std::wstring(p1));
1277 ASSERT_EQ(L"world", std::wstring(p2));
1278#pragma clang diagnostic pop
1279}
1280
Elliott Hughesbf9cb9e2017-12-11 12:39:01 -08001281// https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=202240
1282TEST(STDIO_TEST, scanf_wscanf_EOF) {
1283 EXPECT_EQ(0, sscanf("b", "ab"));
1284 EXPECT_EQ(EOF, sscanf("", "a"));
1285 EXPECT_EQ(0, swscanf(L"b", L"ab"));
1286 EXPECT_EQ(EOF, swscanf(L"", L"a"));
1287}
1288
1289TEST(STDIO_TEST, scanf_invalid_UTF8) {
1290#if 0 // TODO: more tests invented during code review; no regressions, so fix later.
1291 char buf[BUFSIZ];
1292 wchar_t wbuf[BUFSIZ];
1293
1294 memset(buf, 0, sizeof(buf));
1295 memset(wbuf, 0, sizeof(wbuf));
1296 EXPECT_EQ(0, sscanf("\xc0" " foo", "%ls %s", wbuf, buf));
1297#endif
1298}
1299
1300TEST(STDIO_TEST, scanf_no_match_no_termination) {
1301 char buf[4] = "x";
1302 EXPECT_EQ(0, sscanf("d", "%[abc]", buf));
1303 EXPECT_EQ('x', buf[0]);
1304 EXPECT_EQ(0, swscanf(L"d", L"%[abc]", buf));
1305 EXPECT_EQ('x', buf[0]);
1306
1307 wchar_t wbuf[4] = L"x";
1308 EXPECT_EQ(0, swscanf(L"d", L"%l[abc]", wbuf));
1309 EXPECT_EQ(L'x', wbuf[0]);
1310
1311 EXPECT_EQ(EOF, sscanf("", "%s", buf));
1312 EXPECT_EQ('x', buf[0]);
1313
1314 EXPECT_EQ(EOF, swscanf(L"", L"%ls", wbuf));
1315 EXPECT_EQ(L'x', wbuf[0]);
1316}
1317
1318TEST(STDIO_TEST, scanf_wscanf_wide_character_class) {
1319#if 0 // TODO: more tests invented during code review; no regressions, so fix later.
1320 wchar_t buf[BUFSIZ];
1321
1322 // A wide character shouldn't match an ASCII-only class for scanf or wscanf.
1323 memset(buf, 0, sizeof(buf));
1324 EXPECT_EQ(1, sscanf("xĀyz", "%l[xy]", buf));
1325 EXPECT_EQ(L"x"s, std::wstring(buf));
1326 memset(buf, 0, sizeof(buf));
1327 EXPECT_EQ(1, swscanf(L"xĀyz", L"%l[xy]", buf));
1328 EXPECT_EQ(L"x"s, std::wstring(buf));
1329
1330 // Even if scanf has wide characters in a class, they won't match...
1331 // TODO: is that a bug?
1332 memset(buf, 0, sizeof(buf));
1333 EXPECT_EQ(1, sscanf("xĀyz", "%l[xĀy]", buf));
1334 EXPECT_EQ(L"x"s, std::wstring(buf));
1335 // ...unless you use wscanf.
1336 memset(buf, 0, sizeof(buf));
1337 EXPECT_EQ(1, swscanf(L"xĀyz", L"%l[xĀy]", buf));
1338 EXPECT_EQ(L"xĀy"s, std::wstring(buf));
1339
1340 // Negation only covers ASCII for scanf...
1341 memset(buf, 0, sizeof(buf));
1342 EXPECT_EQ(1, sscanf("xĀyz", "%l[^ab]", buf));
1343 EXPECT_EQ(L"x"s, std::wstring(buf));
1344 // ...but covers wide characters for wscanf.
1345 memset(buf, 0, sizeof(buf));
1346 EXPECT_EQ(1, swscanf(L"xĀyz", L"%l[^ab]", buf));
1347 EXPECT_EQ(L"xĀyz"s, std::wstring(buf));
1348
1349 // We already determined that non-ASCII characters are ignored in scanf classes.
1350 memset(buf, 0, sizeof(buf));
1351 EXPECT_EQ(1, sscanf("x"
1352 "\xc4\x80" // Matches a byte from each wide char in the class.
1353 "\xc6\x82" // Neither byte is in the class.
1354 "yz",
1355 "%l[xy" "\xc5\x80" "\xc4\x81" "]", buf));
1356 EXPECT_EQ(L"x", std::wstring(buf));
1357 // bionic and glibc both behave badly for wscanf, so let's call it right for now...
1358 memset(buf, 0, sizeof(buf));
1359 EXPECT_EQ(1, swscanf(L"x"
1360 L"\xc4\x80"
1361 L"\xc6\x82"
1362 L"yz",
1363 L"%l[xy" L"\xc5\x80" L"\xc4\x81" L"]", buf));
1364 // Note that this isn't L"xĀ" --- although the *bytes* matched, they're
1365 // not put back together as a wide character.
1366 EXPECT_EQ(L"x" L"\xc4" L"\x80", std::wstring(buf));
1367#endif
1368}
1369
Christopher Ferris13f26a72016-01-13 13:47:58 -08001370TEST(STDIO_TEST, cantwrite_EBADF) {
Elliott Hughes53b24382014-05-02 18:29:25 -07001371 // If we open a file read-only...
1372 FILE* fp = fopen("/proc/version", "r");
1373
1374 // ...all attempts to write to that file should return failure.
1375
1376 // They should also set errno to EBADF. This isn't POSIX, but it's traditional.
1377 // glibc gets the wide-character functions wrong.
1378
1379 errno = 0;
1380 EXPECT_EQ(EOF, putc('x', fp));
1381 EXPECT_EQ(EBADF, errno);
1382
1383 errno = 0;
1384 EXPECT_EQ(EOF, fprintf(fp, "hello"));
1385 EXPECT_EQ(EBADF, errno);
1386
1387 errno = 0;
1388 EXPECT_EQ(EOF, fwprintf(fp, L"hello"));
Elliott Hughes063525c2014-05-13 11:19:57 -07001389#if defined(__BIONIC__)
Elliott Hughes53b24382014-05-02 18:29:25 -07001390 EXPECT_EQ(EBADF, errno);
1391#endif
1392
1393 errno = 0;
Elliott Hughes53b24382014-05-02 18:29:25 -07001394 EXPECT_EQ(0U, fwrite("hello", 1, 2, fp));
1395 EXPECT_EQ(EBADF, errno);
1396
1397 errno = 0;
1398 EXPECT_EQ(EOF, fputs("hello", fp));
1399 EXPECT_EQ(EBADF, errno);
1400
1401 errno = 0;
1402 EXPECT_EQ(WEOF, fputwc(L'x', fp));
Elliott Hughes063525c2014-05-13 11:19:57 -07001403#if defined(__BIONIC__)
Elliott Hughes53b24382014-05-02 18:29:25 -07001404 EXPECT_EQ(EBADF, errno);
1405#endif
1406}
Calin Juravle03e4ebe2014-05-08 14:42:06 +01001407
1408// Tests that we can only have a consistent and correct fpos_t when using
1409// f*pos functions (i.e. fpos doesn't get inside a multi byte character).
Christopher Ferris13f26a72016-01-13 13:47:58 -08001410TEST(STDIO_TEST, consistent_fpos_t) {
Calin Juravle03e4ebe2014-05-08 14:42:06 +01001411 ASSERT_STREQ("C.UTF-8", setlocale(LC_CTYPE, "C.UTF-8"));
1412 uselocale(LC_GLOBAL_LOCALE);
1413
1414 FILE* fp = tmpfile();
Yi Kong32bc0fc2018-08-02 17:31:13 -07001415 ASSERT_TRUE(fp != nullptr);
Calin Juravle03e4ebe2014-05-08 14:42:06 +01001416
1417 wchar_t mb_one_bytes = L'h';
1418 wchar_t mb_two_bytes = 0x00a2;
1419 wchar_t mb_three_bytes = 0x20ac;
1420 wchar_t mb_four_bytes = 0x24b62;
1421
1422 // Write to file.
1423 ASSERT_EQ(mb_one_bytes, static_cast<wchar_t>(fputwc(mb_one_bytes, fp)));
1424 ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fputwc(mb_two_bytes, fp)));
1425 ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fputwc(mb_three_bytes, fp)));
1426 ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fputwc(mb_four_bytes, fp)));
1427
1428 rewind(fp);
1429
1430 // Record each character position.
1431 fpos_t pos1;
1432 fpos_t pos2;
1433 fpos_t pos3;
1434 fpos_t pos4;
1435 fpos_t pos5;
1436 EXPECT_EQ(0, fgetpos(fp, &pos1));
1437 ASSERT_EQ(mb_one_bytes, static_cast<wchar_t>(fgetwc(fp)));
1438 EXPECT_EQ(0, fgetpos(fp, &pos2));
1439 ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fgetwc(fp)));
1440 EXPECT_EQ(0, fgetpos(fp, &pos3));
1441 ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fgetwc(fp)));
1442 EXPECT_EQ(0, fgetpos(fp, &pos4));
1443 ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fgetwc(fp)));
1444 EXPECT_EQ(0, fgetpos(fp, &pos5));
1445
Elliott Hughes063525c2014-05-13 11:19:57 -07001446#if defined(__BIONIC__)
Calin Juravle03e4ebe2014-05-08 14:42:06 +01001447 // Bionic's fpos_t is just an alias for off_t. This is inherited from OpenBSD
1448 // upstream. Glibc differs by storing the mbstate_t inside its fpos_t. In
1449 // Bionic (and upstream OpenBSD) the mbstate_t is stored inside the FILE
1450 // structure.
1451 ASSERT_EQ(0, static_cast<off_t>(pos1));
1452 ASSERT_EQ(1, static_cast<off_t>(pos2));
1453 ASSERT_EQ(3, static_cast<off_t>(pos3));
1454 ASSERT_EQ(6, static_cast<off_t>(pos4));
1455 ASSERT_EQ(10, static_cast<off_t>(pos5));
1456#endif
1457
1458 // Exercise back and forth movements of the position.
1459 ASSERT_EQ(0, fsetpos(fp, &pos2));
1460 ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fgetwc(fp)));
1461 ASSERT_EQ(0, fsetpos(fp, &pos1));
1462 ASSERT_EQ(mb_one_bytes, static_cast<wchar_t>(fgetwc(fp)));
1463 ASSERT_EQ(0, fsetpos(fp, &pos4));
1464 ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fgetwc(fp)));
1465 ASSERT_EQ(0, fsetpos(fp, &pos3));
1466 ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fgetwc(fp)));
1467 ASSERT_EQ(0, fsetpos(fp, &pos5));
1468 ASSERT_EQ(WEOF, fgetwc(fp));
1469
1470 fclose(fp);
1471}
1472
1473// Exercise the interaction between fpos and seek.
Christopher Ferris13f26a72016-01-13 13:47:58 -08001474TEST(STDIO_TEST, fpos_t_and_seek) {
Calin Juravle03e4ebe2014-05-08 14:42:06 +01001475 ASSERT_STREQ("C.UTF-8", setlocale(LC_CTYPE, "C.UTF-8"));
1476 uselocale(LC_GLOBAL_LOCALE);
1477
Calin Juravle9b95ea92014-05-14 17:07:10 +01001478 // In glibc-2.16 fseek doesn't work properly in wide mode
1479 // (https://sourceware.org/bugzilla/show_bug.cgi?id=14543). One workaround is
1480 // to close and re-open the file. We do it in order to make the test pass
1481 // with all glibcs.
1482
Calin Juravle03e4ebe2014-05-08 14:42:06 +01001483 TemporaryFile tf;
1484 FILE* fp = fdopen(tf.fd, "w+");
Yi Kong32bc0fc2018-08-02 17:31:13 -07001485 ASSERT_TRUE(fp != nullptr);
Calin Juravle03e4ebe2014-05-08 14:42:06 +01001486
1487 wchar_t mb_two_bytes = 0x00a2;
1488 wchar_t mb_three_bytes = 0x20ac;
1489 wchar_t mb_four_bytes = 0x24b62;
1490
1491 // Write to file.
1492 ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fputwc(mb_two_bytes, fp)));
1493 ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fputwc(mb_three_bytes, fp)));
1494 ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fputwc(mb_four_bytes, fp)));
1495
1496 fflush(fp);
1497 fclose(fp);
1498
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08001499 fp = fopen(tf.path, "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07001500 ASSERT_TRUE(fp != nullptr);
Calin Juravle03e4ebe2014-05-08 14:42:06 +01001501
1502 // Store a valid position.
1503 fpos_t mb_two_bytes_pos;
1504 ASSERT_EQ(0, fgetpos(fp, &mb_two_bytes_pos));
1505
1506 // Move inside mb_four_bytes with fseek.
1507 long offset_inside_mb = 6;
1508 ASSERT_EQ(0, fseek(fp, offset_inside_mb, SEEK_SET));
1509
1510 // Store the "inside multi byte" position.
1511 fpos_t pos_inside_mb;
1512 ASSERT_EQ(0, fgetpos(fp, &pos_inside_mb));
Elliott Hughes063525c2014-05-13 11:19:57 -07001513#if defined(__BIONIC__)
1514 ASSERT_EQ(offset_inside_mb, static_cast<off_t>(pos_inside_mb));
1515#endif
Calin Juravle03e4ebe2014-05-08 14:42:06 +01001516
1517 // Reading from within a byte should produce an error.
1518 ASSERT_EQ(WEOF, fgetwc(fp));
1519 ASSERT_EQ(EILSEQ, errno);
1520
1521 // Reverting to a valid position should work.
1522 ASSERT_EQ(0, fsetpos(fp, &mb_two_bytes_pos));
1523 ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fgetwc(fp)));
1524
1525 // Moving withing a multi byte with fsetpos should work but reading should
1526 // produce an error.
1527 ASSERT_EQ(0, fsetpos(fp, &pos_inside_mb));
1528 ASSERT_EQ(WEOF, fgetwc(fp));
1529 ASSERT_EQ(EILSEQ, errno);
1530
Elliott Hughes3a4c4542017-07-19 17:20:24 -07001531 ASSERT_EQ(0, fclose(fp));
Calin Juravle03e4ebe2014-05-08 14:42:06 +01001532}
Elliott Hughes6b841db2014-08-20 16:10:49 -07001533
Christopher Ferris13f26a72016-01-13 13:47:58 -08001534TEST(STDIO_TEST, fmemopen) {
Elliott Hughes6b841db2014-08-20 16:10:49 -07001535 char buf[16];
1536 memset(buf, 0, sizeof(buf));
1537 FILE* fp = fmemopen(buf, sizeof(buf), "r+");
1538 ASSERT_EQ('<', fputc('<', fp));
1539 ASSERT_NE(EOF, fputs("abc>\n", fp));
1540 fflush(fp);
1541
Elliott Hughes3a4c4542017-07-19 17:20:24 -07001542 // We wrote to the buffer...
Elliott Hughes6b841db2014-08-20 16:10:49 -07001543 ASSERT_STREQ("<abc>\n", buf);
1544
Elliott Hughes3a4c4542017-07-19 17:20:24 -07001545 // And can read back from the file.
Elliott Hughes70715da2016-08-01 16:35:17 -07001546 AssertFileIs(fp, "<abc>\n", true);
Elliott Hughes3a4c4542017-07-19 17:20:24 -07001547 ASSERT_EQ(0, fclose(fp));
Elliott Hughes6b841db2014-08-20 16:10:49 -07001548}
1549
Elliott Hughes3a4c4542017-07-19 17:20:24 -07001550TEST(STDIO_TEST, fmemopen_nullptr) {
Elliott Hughes6b841db2014-08-20 16:10:49 -07001551 FILE* fp = fmemopen(nullptr, 128, "r+");
1552 ASSERT_NE(EOF, fputs("xyz\n", fp));
1553
Elliott Hughes70715da2016-08-01 16:35:17 -07001554 AssertFileIs(fp, "xyz\n", true);
Elliott Hughes3a4c4542017-07-19 17:20:24 -07001555 ASSERT_EQ(0, fclose(fp));
Elliott Hughes6b841db2014-08-20 16:10:49 -07001556}
1557
Elliott Hughes3a4c4542017-07-19 17:20:24 -07001558TEST(STDIO_TEST, fmemopen_trailing_NUL_byte) {
1559 FILE* fp;
1560 char buf[8];
1561
1562 // POSIX: "When a stream open for writing is flushed or closed, a null byte
1563 // shall be written at the current position or at the end of the buffer,
1564 // depending on the size of the contents."
1565 memset(buf, 'x', sizeof(buf));
1566 ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w"));
1567 // Even with nothing written (and not in truncate mode), we'll flush a NUL...
1568 ASSERT_EQ(0, fflush(fp));
1569 EXPECT_EQ("\0xxxxxxx"s, std::string(buf, buf + sizeof(buf)));
1570 // Now write and check that the NUL moves along with our writes...
1571 ASSERT_NE(EOF, fputs("hello", fp));
1572 ASSERT_EQ(0, fflush(fp));
1573 EXPECT_EQ("hello\0xx"s, std::string(buf, buf + sizeof(buf)));
1574 ASSERT_NE(EOF, fputs("wo", fp));
1575 ASSERT_EQ(0, fflush(fp));
1576 EXPECT_EQ("hellowo\0"s, std::string(buf, buf + sizeof(buf)));
1577 ASSERT_EQ(0, fclose(fp));
1578
1579 // "If a stream open for update is flushed or closed and the last write has
1580 // advanced the current buffer size, a null byte shall be written at the end
1581 // of the buffer if it fits."
1582 memset(buf, 'x', sizeof(buf));
1583 ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "r+"));
1584 // Nothing written yet, so no advance...
1585 ASSERT_EQ(0, fflush(fp));
1586 EXPECT_EQ("xxxxxxxx"s, std::string(buf, buf + sizeof(buf)));
1587 ASSERT_NE(EOF, fputs("hello", fp));
1588 ASSERT_EQ(0, fclose(fp));
1589}
1590
1591TEST(STDIO_TEST, fmemopen_size) {
1592 FILE* fp;
Elliott Hughes6b841db2014-08-20 16:10:49 -07001593 char buf[16];
Elliott Hughes3a4c4542017-07-19 17:20:24 -07001594 memset(buf, 'x', sizeof(buf));
Elliott Hughes6b841db2014-08-20 16:10:49 -07001595
Elliott Hughes3a4c4542017-07-19 17:20:24 -07001596 // POSIX: "The stream shall also maintain the size of the current buffer
1597 // contents; use of fseek() or fseeko() on the stream with SEEK_END shall
1598 // seek relative to this size."
Elliott Hughes6b841db2014-08-20 16:10:49 -07001599
Elliott Hughes3a4c4542017-07-19 17:20:24 -07001600 // "For modes r and r+ the size shall be set to the value given by the size
1601 // argument."
1602 ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "r"));
1603 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1604 EXPECT_EQ(16, ftell(fp));
1605 EXPECT_EQ(16, ftello(fp));
1606 ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1607 EXPECT_EQ(16, ftell(fp));
1608 EXPECT_EQ(16, ftello(fp));
1609 ASSERT_EQ(0, fclose(fp));
1610 ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "r+"));
1611 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1612 EXPECT_EQ(16, ftell(fp));
1613 EXPECT_EQ(16, ftello(fp));
1614 ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1615 EXPECT_EQ(16, ftell(fp));
1616 EXPECT_EQ(16, ftello(fp));
1617 ASSERT_EQ(0, fclose(fp));
1618
1619 // "For modes w and w+ the initial size shall be zero..."
1620 ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "w"));
1621 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1622 EXPECT_EQ(0, ftell(fp));
1623 EXPECT_EQ(0, ftello(fp));
1624 ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1625 EXPECT_EQ(0, ftell(fp));
1626 EXPECT_EQ(0, ftello(fp));
1627 ASSERT_EQ(0, fclose(fp));
1628 ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "w+"));
1629 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1630 EXPECT_EQ(0, ftell(fp));
1631 EXPECT_EQ(0, ftello(fp));
1632 ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1633 EXPECT_EQ(0, ftell(fp));
1634 EXPECT_EQ(0, ftello(fp));
1635 ASSERT_EQ(0, fclose(fp));
1636
1637 // "...and for modes a and a+ the initial size shall be:
1638 // 1. Zero, if buf is a null pointer
1639 ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "a"));
1640 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1641 EXPECT_EQ(0, ftell(fp));
1642 EXPECT_EQ(0, ftello(fp));
1643 ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1644 EXPECT_EQ(0, ftell(fp));
1645 EXPECT_EQ(0, ftello(fp));
1646 ASSERT_EQ(0, fclose(fp));
1647 ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "a+"));
1648 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1649 EXPECT_EQ(0, ftell(fp));
1650 EXPECT_EQ(0, ftello(fp));
1651 ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1652 EXPECT_EQ(0, ftell(fp));
1653 EXPECT_EQ(0, ftello(fp));
1654 ASSERT_EQ(0, fclose(fp));
1655
1656 // 2. The position of the first null byte in the buffer, if one is found
1657 memset(buf, 'x', sizeof(buf));
1658 buf[3] = '\0';
1659 ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "a"));
1660 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1661 EXPECT_EQ(3, ftell(fp));
1662 EXPECT_EQ(3, ftello(fp));
1663 ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1664 EXPECT_EQ(3, ftell(fp));
1665 EXPECT_EQ(3, ftello(fp));
1666 ASSERT_EQ(0, fclose(fp));
1667 memset(buf, 'x', sizeof(buf));
1668 buf[3] = '\0';
1669 ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "a+"));
1670 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1671 EXPECT_EQ(3, ftell(fp));
1672 EXPECT_EQ(3, ftello(fp));
1673 ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1674 EXPECT_EQ(3, ftell(fp));
1675 EXPECT_EQ(3, ftello(fp));
1676 ASSERT_EQ(0, fclose(fp));
1677
1678 // 3. The value of the size argument, if buf is not a null pointer and no
1679 // null byte is found.
1680 memset(buf, 'x', sizeof(buf));
1681 ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "a"));
1682 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1683 EXPECT_EQ(16, ftell(fp));
1684 EXPECT_EQ(16, ftello(fp));
1685 ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1686 EXPECT_EQ(16, ftell(fp));
1687 EXPECT_EQ(16, ftello(fp));
1688 ASSERT_EQ(0, fclose(fp));
1689 memset(buf, 'x', sizeof(buf));
1690 ASSERT_NE(nullptr, fp = fmemopen(buf, 16, "a+"));
1691 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1692 EXPECT_EQ(16, ftell(fp));
1693 EXPECT_EQ(16, ftello(fp));
1694 ASSERT_EQ(0, fseeko(fp, 0, SEEK_END));
1695 EXPECT_EQ(16, ftell(fp));
1696 EXPECT_EQ(16, ftello(fp));
1697 ASSERT_EQ(0, fclose(fp));
1698}
1699
1700TEST(STDIO_TEST, fmemopen_SEEK_END) {
1701 // fseek SEEK_END is relative to the current string length, not the buffer size.
1702 FILE* fp;
1703 char buf[8];
1704 memset(buf, 'x', sizeof(buf));
1705 strcpy(buf, "str");
1706 ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w+"));
1707 ASSERT_NE(EOF, fputs("string", fp));
1708 EXPECT_EQ(0, fseek(fp, 0, SEEK_END));
1709 EXPECT_EQ(static_cast<long>(strlen("string")), ftell(fp));
1710 EXPECT_EQ(static_cast<off_t>(strlen("string")), ftello(fp));
1711 EXPECT_EQ(0, fclose(fp));
1712
1713 // glibc < 2.22 interpreted SEEK_END the wrong way round (subtracting rather
1714 // than adding).
1715 ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w+"));
1716 ASSERT_NE(EOF, fputs("54321", fp));
1717 EXPECT_EQ(0, fseek(fp, -2, SEEK_END));
1718 EXPECT_EQ('2', fgetc(fp));
1719 EXPECT_EQ(0, fclose(fp));
1720}
1721
1722TEST(STDIO_TEST, fmemopen_seek_invalid) {
1723 char buf[8];
1724 memset(buf, 'x', sizeof(buf));
1725 FILE* fp = fmemopen(buf, sizeof(buf), "w");
1726 ASSERT_TRUE(fp != nullptr);
1727
1728 // POSIX: "An attempt to seek ... to a negative position or to a position
1729 // larger than the buffer size given in the size argument shall fail."
1730 // (There's no mention of what errno should be set to, and glibc doesn't
1731 // set errno in any of these cases.)
1732 EXPECT_EQ(-1, fseek(fp, -2, SEEK_SET));
1733 EXPECT_EQ(-1, fseeko(fp, -2, SEEK_SET));
1734 EXPECT_EQ(-1, fseek(fp, sizeof(buf) + 1, SEEK_SET));
1735 EXPECT_EQ(-1, fseeko(fp, sizeof(buf) + 1, SEEK_SET));
1736}
1737
1738TEST(STDIO_TEST, fmemopen_read_EOF) {
1739 // POSIX: "A read operation on the stream shall not advance the current
1740 // buffer position beyond the current buffer size."
1741 char buf[8];
1742 memset(buf, 'x', sizeof(buf));
1743 FILE* fp = fmemopen(buf, sizeof(buf), "r");
1744 ASSERT_TRUE(fp != nullptr);
1745 char buf2[BUFSIZ];
1746 ASSERT_EQ(8U, fread(buf2, 1, sizeof(buf2), fp));
1747 // POSIX: "Reaching the buffer size in a read operation shall count as
1748 // end-of-file.
1749 ASSERT_TRUE(feof(fp));
1750 ASSERT_EQ(EOF, fgetc(fp));
1751 ASSERT_EQ(0, fclose(fp));
1752}
1753
1754TEST(STDIO_TEST, fmemopen_read_null_bytes) {
1755 // POSIX: "Null bytes in the buffer shall have no special meaning for reads."
1756 char buf[] = "h\0e\0l\0l\0o";
1757 FILE* fp = fmemopen(buf, sizeof(buf), "r");
1758 ASSERT_TRUE(fp != nullptr);
1759 ASSERT_EQ('h', fgetc(fp));
1760 ASSERT_EQ(0, fgetc(fp));
1761 ASSERT_EQ('e', fgetc(fp));
1762 ASSERT_EQ(0, fgetc(fp));
1763 ASSERT_EQ('l', fgetc(fp));
1764 ASSERT_EQ(0, fgetc(fp));
1765 // POSIX: "The read operation shall start at the current buffer position of
1766 // the stream."
1767 char buf2[8];
1768 memset(buf2, 'x', sizeof(buf2));
1769 ASSERT_EQ(4U, fread(buf2, 1, sizeof(buf2), fp));
1770 ASSERT_EQ('l', buf2[0]);
1771 ASSERT_EQ(0, buf2[1]);
1772 ASSERT_EQ('o', buf2[2]);
1773 ASSERT_EQ(0, buf2[3]);
1774 for (size_t i = 4; i < sizeof(buf2); ++i) ASSERT_EQ('x', buf2[i]) << i;
1775 ASSERT_TRUE(feof(fp));
1776 ASSERT_EQ(0, fclose(fp));
1777}
1778
1779TEST(STDIO_TEST, fmemopen_write) {
1780 FILE* fp;
1781 char buf[8];
1782
1783 // POSIX: "A write operation shall start either at the current position of
1784 // the stream (if mode has not specified 'a' as the first character)..."
1785 memset(buf, 'x', sizeof(buf));
1786 ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "r+"));
1787 setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1788 ASSERT_EQ(0, fseek(fp, 2, SEEK_SET));
1789 ASSERT_EQ(' ', fputc(' ', fp));
1790 EXPECT_EQ("xx xxxxx", std::string(buf, buf + sizeof(buf)));
1791 ASSERT_EQ(0, fclose(fp));
1792
1793 // "...or at the current size of the stream (if mode had 'a' as the first
1794 // character)." (See the fmemopen_size test for what "size" means, but for
1795 // mode "a", it's the first NUL byte.)
1796 memset(buf, 'x', sizeof(buf));
1797 buf[3] = '\0';
1798 ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a+"));
1799 setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1800 ASSERT_EQ(' ', fputc(' ', fp));
1801 EXPECT_EQ("xxx \0xxx"s, std::string(buf, buf + sizeof(buf)));
1802 ASSERT_EQ(0, fclose(fp));
1803
1804 // "If the current position at the end of the write is larger than the
1805 // current buffer size, the current buffer size shall be set to the current
1806 // position." (See the fmemopen_size test for what "size" means, but to
1807 // query it we SEEK_END with offset 0, and then ftell.)
1808 memset(buf, 'x', sizeof(buf));
1809 ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w+"));
1810 setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1811 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1812 EXPECT_EQ(0, ftell(fp));
1813 ASSERT_EQ(' ', fputc(' ', fp));
1814 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1815 EXPECT_EQ(1, ftell(fp));
1816 ASSERT_NE(EOF, fputs("123", fp));
1817 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
1818 EXPECT_EQ(4, ftell(fp));
1819 EXPECT_EQ(" 123\0xxx"s, std::string(buf, buf + sizeof(buf)));
1820 ASSERT_EQ(0, fclose(fp));
1821}
1822
1823TEST(STDIO_TEST, fmemopen_write_EOF) {
1824 // POSIX: "A write operation on the stream shall not advance the current
1825 // buffer size beyond the size given in the size argument."
1826 FILE* fp;
1827
1828 // Scalar writes...
1829 ASSERT_NE(nullptr, fp = fmemopen(nullptr, 4, "w"));
1830 setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1831 ASSERT_EQ('x', fputc('x', fp));
1832 ASSERT_EQ('x', fputc('x', fp));
1833 ASSERT_EQ('x', fputc('x', fp));
1834 ASSERT_EQ(EOF, fputc('x', fp)); // Only 3 fit because of the implicit NUL.
1835 ASSERT_EQ(0, fclose(fp));
1836
1837 // Vector writes...
1838 ASSERT_NE(nullptr, fp = fmemopen(nullptr, 4, "w"));
1839 setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1840 ASSERT_EQ(3U, fwrite("xxxx", 1, 4, fp));
1841 ASSERT_EQ(0, fclose(fp));
1842}
1843
1844TEST(STDIO_TEST, fmemopen_initial_position) {
1845 // POSIX: "The ... current position in the buffer ... shall be initially
1846 // set to either the beginning of the buffer (for r and w modes) ..."
1847 char buf[] = "hello\0world";
1848 FILE* fp;
1849 ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "r"));
1850 EXPECT_EQ(0L, ftell(fp));
1851 EXPECT_EQ(0, fclose(fp));
1852 ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "w"));
1853 EXPECT_EQ(0L, ftell(fp));
1854 EXPECT_EQ(0, fclose(fp));
1855 buf[0] = 'h'; // (Undo the effects of the above.)
1856
1857 // POSIX: "...or to the first null byte in the buffer (for a modes)."
1858 ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a"));
1859 EXPECT_EQ(5L, ftell(fp));
1860 EXPECT_EQ(0, fclose(fp));
1861
1862 // POSIX: "If no null byte is found in append mode, the initial position
1863 // shall be set to one byte after the end of the buffer."
1864 memset(buf, 'x', sizeof(buf));
1865 ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a"));
1866 EXPECT_EQ(static_cast<long>(sizeof(buf)), ftell(fp));
1867 EXPECT_EQ(0, fclose(fp));
1868}
1869
1870TEST(STDIO_TEST, fmemopen_initial_position_allocated) {
1871 // POSIX: "If buf is a null pointer, the initial position shall always be
1872 // set to the beginning of the buffer."
1873 FILE* fp = fmemopen(nullptr, 128, "a+");
1874 ASSERT_TRUE(fp != nullptr);
1875 EXPECT_EQ(0L, ftell(fp));
1876 EXPECT_EQ(0L, fseek(fp, 0, SEEK_SET));
1877 EXPECT_EQ(0, fclose(fp));
1878}
1879
1880TEST(STDIO_TEST, fmemopen_zero_length) {
1881 // POSIX says it's up to the implementation whether or not you can have a
1882 // zero-length buffer (but "A future version of this standard may require
1883 // support of zero-length buffer streams explicitly"). BSD and glibc < 2.22
1884 // agreed that you couldn't, but glibc >= 2.22 allows it for consistency.
1885 FILE* fp;
1886 char buf[16];
1887 ASSERT_NE(nullptr, fp = fmemopen(buf, 0, "r+"));
1888 ASSERT_EQ(EOF, fgetc(fp));
1889 ASSERT_TRUE(feof(fp));
1890 ASSERT_EQ(0, fclose(fp));
1891 ASSERT_NE(nullptr, fp = fmemopen(nullptr, 0, "r+"));
1892 ASSERT_EQ(EOF, fgetc(fp));
1893 ASSERT_TRUE(feof(fp));
1894 ASSERT_EQ(0, fclose(fp));
1895
1896 ASSERT_NE(nullptr, fp = fmemopen(buf, 0, "w+"));
1897 setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1898 ASSERT_EQ(EOF, fputc('x', fp));
1899 ASSERT_EQ(0, fclose(fp));
1900 ASSERT_NE(nullptr, fp = fmemopen(nullptr, 0, "w+"));
1901 setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1902 ASSERT_EQ(EOF, fputc('x', fp));
1903 ASSERT_EQ(0, fclose(fp));
1904}
1905
Elliott Hughes288465d2019-02-05 15:00:13 -08001906TEST(STDIO_TEST, fmemopen_zero_length_buffer_overrun) {
1907 char buf[2] = "x";
1908 ASSERT_EQ('x', buf[0]);
1909 FILE* fp = fmemopen(buf, 0, "w");
1910 ASSERT_EQ('x', buf[0]);
1911 ASSERT_EQ(0, fclose(fp));
1912}
1913
Elliott Hughes3a4c4542017-07-19 17:20:24 -07001914TEST(STDIO_TEST, fmemopen_write_only_allocated) {
1915 // POSIX says fmemopen "may fail if the mode argument does not include a '+'".
1916 // BSD fails, glibc doesn't. We side with the more lenient.
1917 FILE* fp;
1918 ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "r"));
1919 ASSERT_EQ(0, fclose(fp));
1920 ASSERT_NE(nullptr, fp = fmemopen(nullptr, 16, "w"));
1921 ASSERT_EQ(0, fclose(fp));
1922}
1923
1924TEST(STDIO_TEST, fmemopen_fileno) {
1925 // There's no fd backing an fmemopen FILE*.
1926 FILE* fp = fmemopen(nullptr, 16, "r");
1927 ASSERT_TRUE(fp != nullptr);
Elliott Hughes6b841db2014-08-20 16:10:49 -07001928 errno = 0;
Elliott Hughes3a4c4542017-07-19 17:20:24 -07001929 ASSERT_EQ(-1, fileno(fp));
1930 ASSERT_EQ(EBADF, errno);
1931 ASSERT_EQ(0, fclose(fp));
1932}
1933
1934TEST(STDIO_TEST, fmemopen_append_after_seek) {
1935 // In BSD and glibc < 2.22, append mode didn't force writes to append if
1936 // there had been an intervening seek.
1937
1938 FILE* fp;
1939 char buf[] = "hello\0world";
1940 ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a"));
1941 setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1942 ASSERT_EQ(0, fseek(fp, 0, SEEK_SET));
1943 ASSERT_NE(EOF, fputc('!', fp));
1944 EXPECT_EQ("hello!\0orld\0"s, std::string(buf, buf + sizeof(buf)));
1945 ASSERT_EQ(0, fclose(fp));
1946
1947 memcpy(buf, "hello\0world", sizeof(buf));
1948 ASSERT_NE(nullptr, fp = fmemopen(buf, sizeof(buf), "a+"));
1949 setbuf(fp, nullptr); // Turn off buffering so we can see what's happening as it happens.
1950 ASSERT_EQ(0, fseek(fp, 0, SEEK_SET));
1951 ASSERT_NE(EOF, fputc('!', fp));
1952 EXPECT_EQ("hello!\0orld\0"s, std::string(buf, buf + sizeof(buf)));
1953 ASSERT_EQ(0, fclose(fp));
Elliott Hughes6b841db2014-08-20 16:10:49 -07001954}
1955
Christopher Ferris13f26a72016-01-13 13:47:58 -08001956TEST(STDIO_TEST, open_memstream) {
Elliott Hughes6b841db2014-08-20 16:10:49 -07001957 char* p = nullptr;
1958 size_t size = 0;
1959 FILE* fp = open_memstream(&p, &size);
1960 ASSERT_NE(EOF, fputs("hello, world!", fp));
1961 fclose(fp);
1962
1963 ASSERT_STREQ("hello, world!", p);
1964 ASSERT_EQ(strlen("hello, world!"), size);
1965 free(p);
1966}
1967
Christopher Ferris13f26a72016-01-13 13:47:58 -08001968TEST(STDIO_TEST, open_memstream_EINVAL) {
Elliott Hughes6b841db2014-08-20 16:10:49 -07001969#if defined(__BIONIC__)
zijunzhao00a3dba2023-03-01 00:07:40 +00001970#pragma clang diagnostic push
1971#pragma clang diagnostic ignored "-Wnonnull"
Elliott Hughes6b841db2014-08-20 16:10:49 -07001972 char* p;
1973 size_t size;
1974
1975 // Invalid buffer.
1976 errno = 0;
1977 ASSERT_EQ(nullptr, open_memstream(nullptr, &size));
1978 ASSERT_EQ(EINVAL, errno);
1979
1980 // Invalid size.
1981 errno = 0;
1982 ASSERT_EQ(nullptr, open_memstream(&p, nullptr));
1983 ASSERT_EQ(EINVAL, errno);
zijunzhao00a3dba2023-03-01 00:07:40 +00001984#pragma clang diagnostic pop
Elliott Hughes6b841db2014-08-20 16:10:49 -07001985#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001986 GTEST_SKIP() << "glibc is broken";
Elliott Hughes6b841db2014-08-20 16:10:49 -07001987#endif
1988}
Elliott Hughes31165ed2014-09-23 17:34:29 -07001989
Elliott Hughesf9cfecf2021-02-04 16:58:13 -08001990TEST(STDIO_TEST, fdopen_add_CLOEXEC) {
Elliott Hughes31165ed2014-09-23 17:34:29 -07001991 // This fd doesn't have O_CLOEXEC...
Elliott Hughesf9cfecf2021-02-04 16:58:13 -08001992 int fd = open("/proc/version", O_RDONLY);
1993 ASSERT_FALSE(CloseOnExec(fd));
Elliott Hughes31165ed2014-09-23 17:34:29 -07001994 // ...but the new one does.
Elliott Hughesf9cfecf2021-02-04 16:58:13 -08001995 FILE* fp = fdopen(fd, "re");
1996 ASSERT_TRUE(CloseOnExec(fileno(fp)));
1997 fclose(fp);
1998}
1999
2000TEST(STDIO_TEST, fdopen_remove_CLOEXEC) {
2001 // This fd has O_CLOEXEC...
2002 int fd = open("/proc/version", O_RDONLY | O_CLOEXEC);
2003 ASSERT_TRUE(CloseOnExec(fd));
2004 // ...but the new one doesn't.
2005 FILE* fp = fdopen(fd, "r");
2006 ASSERT_TRUE(CloseOnExec(fileno(fp)));
2007 fclose(fp);
2008}
2009
2010TEST(STDIO_TEST, freopen_add_CLOEXEC) {
2011 // This FILE* doesn't have O_CLOEXEC...
2012 FILE* fp = fopen("/proc/version", "r");
2013 ASSERT_FALSE(CloseOnExec(fileno(fp)));
2014 // ...but the new one does.
2015 fp = freopen("/proc/version", "re", fp);
2016 ASSERT_TRUE(CloseOnExec(fileno(fp)));
Elliott Hughes31165ed2014-09-23 17:34:29 -07002017
2018 fclose(fp);
Elliott Hughes31165ed2014-09-23 17:34:29 -07002019}
2020
Elliott Hughesf9cfecf2021-02-04 16:58:13 -08002021TEST(STDIO_TEST, freopen_remove_CLOEXEC) {
2022 // This FILE* has O_CLOEXEC...
2023 FILE* fp = fopen("/proc/version", "re");
2024 ASSERT_TRUE(CloseOnExec(fileno(fp)));
2025 // ...but the new one doesn't.
2026 fp = freopen("/proc/version", "r", fp);
2027 ASSERT_FALSE(CloseOnExec(fileno(fp)));
2028 fclose(fp);
2029}
Elliott Hughes31165ed2014-09-23 17:34:29 -07002030
Elliott Hughesf9cfecf2021-02-04 16:58:13 -08002031TEST(STDIO_TEST, freopen_null_filename_add_CLOEXEC) {
Elliott Hughes31165ed2014-09-23 17:34:29 -07002032 // This FILE* doesn't have O_CLOEXEC...
Elliott Hughesf9cfecf2021-02-04 16:58:13 -08002033 FILE* fp = fopen("/proc/version", "r");
2034 ASSERT_FALSE(CloseOnExec(fileno(fp)));
Elliott Hughes31165ed2014-09-23 17:34:29 -07002035 // ...but the new one does.
Elliott Hughesf9cfecf2021-02-04 16:58:13 -08002036 fp = freopen(nullptr, "re", fp);
2037 ASSERT_TRUE(CloseOnExec(fileno(fp)));
2038 fclose(fp);
2039}
Elliott Hughes31165ed2014-09-23 17:34:29 -07002040
Elliott Hughesf9cfecf2021-02-04 16:58:13 -08002041TEST(STDIO_TEST, freopen_null_filename_remove_CLOEXEC) {
2042 // This FILE* has O_CLOEXEC...
2043 FILE* fp = fopen("/proc/version", "re");
2044 ASSERT_TRUE(CloseOnExec(fileno(fp)));
2045 // ...but the new one doesn't.
2046 fp = freopen(nullptr, "r", fp);
2047 ASSERT_FALSE(CloseOnExec(fileno(fp)));
Elliott Hughes31165ed2014-09-23 17:34:29 -07002048 fclose(fp);
2049}
Elliott Hughes20841a12014-12-01 16:13:30 -08002050
Elliott Hughesf226ee52016-02-03 11:24:28 -08002051TEST(STDIO_TEST, fopen64_freopen64) {
2052 FILE* fp = fopen64("/proc/version", "r");
2053 ASSERT_TRUE(fp != nullptr);
2054 fp = freopen64("/proc/version", "re", fp);
2055 ASSERT_TRUE(fp != nullptr);
2056 fclose(fp);
2057}
2058
Elliott Hughes20841a12014-12-01 16:13:30 -08002059// https://code.google.com/p/android/issues/detail?id=81155
2060// http://b/18556607
Christopher Ferris13f26a72016-01-13 13:47:58 -08002061TEST(STDIO_TEST, fread_unbuffered_pathological_performance) {
Elliott Hughes20841a12014-12-01 16:13:30 -08002062 FILE* fp = fopen("/dev/zero", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07002063 ASSERT_TRUE(fp != nullptr);
Elliott Hughes20841a12014-12-01 16:13:30 -08002064
2065 // Make this stream unbuffered.
Yi Kong32bc0fc2018-08-02 17:31:13 -07002066 setvbuf(fp, nullptr, _IONBF, 0);
Elliott Hughes20841a12014-12-01 16:13:30 -08002067
2068 char buf[65*1024];
2069 memset(buf, 0xff, sizeof(buf));
2070
Yi Kong32bc0fc2018-08-02 17:31:13 -07002071 time_t t0 = time(nullptr);
Elliott Hughes20841a12014-12-01 16:13:30 -08002072 for (size_t i = 0; i < 1024; ++i) {
Elliott Hughese6bb5a22015-01-23 17:48:15 -08002073 ASSERT_EQ(1U, fread(buf, 64*1024, 1, fp));
Elliott Hughes20841a12014-12-01 16:13:30 -08002074 }
Yi Kong32bc0fc2018-08-02 17:31:13 -07002075 time_t t1 = time(nullptr);
Elliott Hughes20841a12014-12-01 16:13:30 -08002076
2077 fclose(fp);
2078
2079 // 1024 64KiB reads should have been very quick.
2080 ASSERT_LE(t1 - t0, 1);
2081
2082 for (size_t i = 0; i < 64*1024; ++i) {
2083 ASSERT_EQ('\0', buf[i]);
2084 }
2085 for (size_t i = 64*1024; i < 65*1024; ++i) {
2086 ASSERT_EQ('\xff', buf[i]);
2087 }
2088}
Elliott Hughes75b99382015-01-20 11:23:50 -08002089
Christopher Ferris13f26a72016-01-13 13:47:58 -08002090TEST(STDIO_TEST, fread_EOF) {
Elliott Hughes0ed7e082015-01-22 15:13:38 -08002091 std::string digits("0123456789");
2092 FILE* fp = fmemopen(&digits[0], digits.size(), "r");
Elliott Hughes75b99382015-01-20 11:23:50 -08002093
2094 // Try to read too much, but little enough that it still fits in the FILE's internal buffer.
2095 char buf1[4 * 4];
2096 memset(buf1, 0, sizeof(buf1));
2097 ASSERT_EQ(2U, fread(buf1, 4, 4, fp));
Elliott Hughes0ed7e082015-01-22 15:13:38 -08002098 ASSERT_STREQ("0123456789", buf1);
Elliott Hughes75b99382015-01-20 11:23:50 -08002099 ASSERT_TRUE(feof(fp));
2100
2101 rewind(fp);
2102
Elliott Hughes0ed7e082015-01-22 15:13:38 -08002103 // Try to read way too much so stdio tries to read more direct from the stream.
2104 char buf2[4 * 4096];
Elliott Hughes75b99382015-01-20 11:23:50 -08002105 memset(buf2, 0, sizeof(buf2));
2106 ASSERT_EQ(2U, fread(buf2, 4, 4096, fp));
Elliott Hughes0ed7e082015-01-22 15:13:38 -08002107 ASSERT_STREQ("0123456789", buf2);
Elliott Hughes75b99382015-01-20 11:23:50 -08002108 ASSERT_TRUE(feof(fp));
2109
2110 fclose(fp);
2111}
Elliott Hughese6bb5a22015-01-23 17:48:15 -08002112
2113static void test_fread_from_write_only_stream(size_t n) {
2114 FILE* fp = fopen("/dev/null", "w");
2115 std::vector<char> buf(n, 0);
2116 errno = 0;
2117 ASSERT_EQ(0U, fread(&buf[0], n, 1, fp));
2118 ASSERT_EQ(EBADF, errno);
2119 ASSERT_TRUE(ferror(fp));
2120 ASSERT_FALSE(feof(fp));
2121 fclose(fp);
2122}
2123
Christopher Ferris13f26a72016-01-13 13:47:58 -08002124TEST(STDIO_TEST, fread_from_write_only_stream_slow_path) {
Elliott Hughese6bb5a22015-01-23 17:48:15 -08002125 test_fread_from_write_only_stream(1);
2126}
2127
Christopher Ferris13f26a72016-01-13 13:47:58 -08002128TEST(STDIO_TEST, fread_from_write_only_stream_fast_path) {
Elliott Hughese6bb5a22015-01-23 17:48:15 -08002129 test_fread_from_write_only_stream(64*1024);
2130}
2131
2132static void test_fwrite_after_fread(size_t n) {
2133 TemporaryFile tf;
2134
2135 FILE* fp = fdopen(tf.fd, "w+");
2136 ASSERT_EQ(1U, fwrite("1", 1, 1, fp));
2137 fflush(fp);
2138
2139 // We've flushed but not rewound, so there's nothing to read.
2140 std::vector<char> buf(n, 0);
2141 ASSERT_EQ(0U, fread(&buf[0], 1, buf.size(), fp));
2142 ASSERT_TRUE(feof(fp));
2143
2144 // But hitting EOF doesn't prevent us from writing...
2145 errno = 0;
Elliott Hughes9677fab2016-01-25 15:50:59 -08002146 ASSERT_EQ(1U, fwrite("2", 1, 1, fp)) << strerror(errno);
Elliott Hughese6bb5a22015-01-23 17:48:15 -08002147
2148 // And if we rewind, everything's there.
2149 rewind(fp);
2150 ASSERT_EQ(2U, fread(&buf[0], 1, buf.size(), fp));
2151 ASSERT_EQ('1', buf[0]);
2152 ASSERT_EQ('2', buf[1]);
2153
2154 fclose(fp);
2155}
2156
Christopher Ferris13f26a72016-01-13 13:47:58 -08002157TEST(STDIO_TEST, fwrite_after_fread_slow_path) {
Elliott Hughese6bb5a22015-01-23 17:48:15 -08002158 test_fwrite_after_fread(16);
2159}
2160
Christopher Ferris13f26a72016-01-13 13:47:58 -08002161TEST(STDIO_TEST, fwrite_after_fread_fast_path) {
Elliott Hughese6bb5a22015-01-23 17:48:15 -08002162 test_fwrite_after_fread(64*1024);
2163}
Christopher Ferriscc9ca102015-02-27 18:22:45 -08002164
2165// http://b/19172514
Christopher Ferris13f26a72016-01-13 13:47:58 -08002166TEST(STDIO_TEST, fread_after_fseek) {
Christopher Ferriscc9ca102015-02-27 18:22:45 -08002167 TemporaryFile tf;
2168
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002169 FILE* fp = fopen(tf.path, "w+");
Christopher Ferriscc9ca102015-02-27 18:22:45 -08002170 ASSERT_TRUE(fp != nullptr);
2171
2172 char file_data[12288];
2173 for (size_t i = 0; i < 12288; i++) {
2174 file_data[i] = i;
2175 }
2176 ASSERT_EQ(12288U, fwrite(file_data, 1, 12288, fp));
2177 fclose(fp);
2178
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002179 fp = fopen(tf.path, "r");
Christopher Ferriscc9ca102015-02-27 18:22:45 -08002180 ASSERT_TRUE(fp != nullptr);
2181
2182 char buffer[8192];
2183 size_t cur_location = 0;
2184 // Small read to populate internal buffer.
2185 ASSERT_EQ(100U, fread(buffer, 1, 100, fp));
2186 ASSERT_EQ(memcmp(file_data, buffer, 100), 0);
2187
2188 cur_location = static_cast<size_t>(ftell(fp));
2189 // Large read to force reading into the user supplied buffer and bypassing
2190 // the internal buffer.
2191 ASSERT_EQ(8192U, fread(buffer, 1, 8192, fp));
2192 ASSERT_EQ(memcmp(file_data+cur_location, buffer, 8192), 0);
2193
2194 // Small backwards seek to verify fseek does not reuse the internal buffer.
Elliott Hughes9677fab2016-01-25 15:50:59 -08002195 ASSERT_EQ(0, fseek(fp, -22, SEEK_CUR)) << strerror(errno);
Christopher Ferriscc9ca102015-02-27 18:22:45 -08002196 cur_location = static_cast<size_t>(ftell(fp));
2197 ASSERT_EQ(22U, fread(buffer, 1, 22, fp));
2198 ASSERT_EQ(memcmp(file_data+cur_location, buffer, 22), 0);
2199
2200 fclose(fp);
2201}
Elliott Hughes8ab433d2015-10-09 17:57:26 -07002202
2203// https://code.google.com/p/android/issues/detail?id=184847
Christopher Ferris13f26a72016-01-13 13:47:58 -08002204TEST(STDIO_TEST, fread_EOF_184847) {
Elliott Hughes8ab433d2015-10-09 17:57:26 -07002205 TemporaryFile tf;
2206 char buf[6] = {0};
2207
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002208 FILE* fw = fopen(tf.path, "w");
Elliott Hughes8ab433d2015-10-09 17:57:26 -07002209 ASSERT_TRUE(fw != nullptr);
2210
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002211 FILE* fr = fopen(tf.path, "r");
Elliott Hughes8ab433d2015-10-09 17:57:26 -07002212 ASSERT_TRUE(fr != nullptr);
2213
2214 fwrite("a", 1, 1, fw);
2215 fflush(fw);
2216 ASSERT_EQ(1U, fread(buf, 1, 1, fr));
2217 ASSERT_STREQ("a", buf);
2218
2219 // 'fr' is now at EOF.
2220 ASSERT_EQ(0U, fread(buf, 1, 1, fr));
2221 ASSERT_TRUE(feof(fr));
2222
2223 // Write some more...
2224 fwrite("z", 1, 1, fw);
2225 fflush(fw);
2226
2227 // ...and check that we can read it back.
2228 // (BSD thinks that once a stream has hit EOF, it must always return EOF. SysV disagrees.)
2229 ASSERT_EQ(1U, fread(buf, 1, 1, fr));
2230 ASSERT_STREQ("z", buf);
2231
2232 // But now we're done.
2233 ASSERT_EQ(0U, fread(buf, 1, 1, fr));
2234
2235 fclose(fr);
2236 fclose(fw);
2237}
Elliott Hughes923f1652016-01-19 15:46:05 -08002238
2239TEST(STDIO_TEST, fclose_invalidates_fd) {
2240 // The typical error we're trying to help people catch involves accessing
2241 // memory after it's been freed. But we know that stdin/stdout/stderr are
2242 // special and don't get deallocated, so this test uses stdin.
2243 ASSERT_EQ(0, fclose(stdin));
2244
2245 // Even though using a FILE* after close is undefined behavior, I've closed
2246 // this bug as "WAI" too many times. We shouldn't hand out stale fds,
2247 // especially because they might actually correspond to a real stream.
2248 errno = 0;
2249 ASSERT_EQ(-1, fileno(stdin));
2250 ASSERT_EQ(EBADF, errno);
2251}
Elliott Hughes2704bd12016-01-20 17:14:53 -08002252
2253TEST(STDIO_TEST, fseek_ftell_unseekable) {
2254#if defined(__BIONIC__) // glibc has fopencookie instead.
2255 auto read_fn = [](void*, char*, int) { return -1; };
2256 FILE* fp = funopen(nullptr, read_fn, nullptr, nullptr, nullptr);
2257 ASSERT_TRUE(fp != nullptr);
2258
2259 // Check that ftell balks on an unseekable FILE*.
2260 errno = 0;
2261 ASSERT_EQ(-1, ftell(fp));
2262 ASSERT_EQ(ESPIPE, errno);
2263
2264 // SEEK_CUR is rewritten as SEEK_SET internally...
2265 errno = 0;
2266 ASSERT_EQ(-1, fseek(fp, 0, SEEK_CUR));
2267 ASSERT_EQ(ESPIPE, errno);
2268
2269 // ...so it's worth testing the direct seek path too.
2270 errno = 0;
2271 ASSERT_EQ(-1, fseek(fp, 0, SEEK_SET));
2272 ASSERT_EQ(ESPIPE, errno);
2273
2274 fclose(fp);
Elliott Hughes03e65eb2016-01-26 14:13:04 -08002275#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002276 GTEST_SKIP() << "glibc uses fopencookie instead";
Elliott Hughes03e65eb2016-01-26 14:13:04 -08002277#endif
2278}
2279
2280TEST(STDIO_TEST, funopen_EINVAL) {
2281#if defined(__BIONIC__)
2282 errno = 0;
2283 ASSERT_EQ(nullptr, funopen(nullptr, nullptr, nullptr, nullptr, nullptr));
2284 ASSERT_EQ(EINVAL, errno);
2285#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002286 GTEST_SKIP() << "glibc uses fopencookie instead";
Elliott Hughes03e65eb2016-01-26 14:13:04 -08002287#endif
2288}
2289
2290TEST(STDIO_TEST, funopen_seek) {
2291#if defined(__BIONIC__)
2292 auto read_fn = [](void*, char*, int) { return -1; };
2293
2294 auto seek_fn = [](void*, fpos_t, int) -> fpos_t { return 0xfedcba12; };
2295 auto seek64_fn = [](void*, fpos64_t, int) -> fpos64_t { return 0xfedcba12345678; };
2296
2297 FILE* fp = funopen(nullptr, read_fn, nullptr, seek_fn, nullptr);
2298 ASSERT_TRUE(fp != nullptr);
2299 fpos_t pos;
Elliott Hughes955426e2016-01-26 18:25:52 -08002300#if defined(__LP64__)
2301 EXPECT_EQ(0, fgetpos(fp, &pos)) << strerror(errno);
2302 EXPECT_EQ(0xfedcba12LL, pos);
2303#else
2304 EXPECT_EQ(-1, fgetpos(fp, &pos)) << strerror(errno);
2305 EXPECT_EQ(EOVERFLOW, errno);
2306#endif
Elliott Hughes03e65eb2016-01-26 14:13:04 -08002307
2308 FILE* fp64 = funopen64(nullptr, read_fn, nullptr, seek64_fn, nullptr);
2309 ASSERT_TRUE(fp64 != nullptr);
2310 fpos64_t pos64;
Elliott Hughes955426e2016-01-26 18:25:52 -08002311 EXPECT_EQ(0, fgetpos64(fp64, &pos64)) << strerror(errno);
2312 EXPECT_EQ(0xfedcba12345678, pos64);
Elliott Hughes03e65eb2016-01-26 14:13:04 -08002313#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002314 GTEST_SKIP() << "glibc uses fopencookie instead";
Elliott Hughes2704bd12016-01-20 17:14:53 -08002315#endif
2316}
Elliott Hughes71288cb2016-01-22 19:22:44 -08002317
2318TEST(STDIO_TEST, lots_of_concurrent_files) {
2319 std::vector<TemporaryFile*> tfs;
2320 std::vector<FILE*> fps;
2321
2322 for (size_t i = 0; i < 256; ++i) {
2323 TemporaryFile* tf = new TemporaryFile;
2324 tfs.push_back(tf);
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002325 FILE* fp = fopen(tf->path, "w+");
Elliott Hughes71288cb2016-01-22 19:22:44 -08002326 fps.push_back(fp);
2327 fprintf(fp, "hello %zu!\n", i);
2328 fflush(fp);
2329 }
2330
2331 for (size_t i = 0; i < 256; ++i) {
Elliott Hughes71288cb2016-01-22 19:22:44 -08002332 char expected[BUFSIZ];
2333 snprintf(expected, sizeof(expected), "hello %zu!\n", i);
Elliott Hughes71288cb2016-01-22 19:22:44 -08002334
Elliott Hughes70715da2016-08-01 16:35:17 -07002335 AssertFileIs(fps[i], expected);
Elliott Hughes71288cb2016-01-22 19:22:44 -08002336 fclose(fps[i]);
2337 delete tfs[i];
2338 }
2339}
Elliott Hughes9677fab2016-01-25 15:50:59 -08002340
2341static void AssertFileOffsetAt(FILE* fp, off64_t offset) {
2342 EXPECT_EQ(offset, ftell(fp));
2343 EXPECT_EQ(offset, ftello(fp));
Elliott Hughese4fa6e92016-02-02 22:39:15 -08002344 EXPECT_EQ(offset, ftello64(fp));
Elliott Hughes9677fab2016-01-25 15:50:59 -08002345 fpos_t pos;
2346 fpos64_t pos64;
2347 EXPECT_EQ(0, fgetpos(fp, &pos));
2348 EXPECT_EQ(0, fgetpos64(fp, &pos64));
2349#if defined(__BIONIC__)
2350 EXPECT_EQ(offset, static_cast<off64_t>(pos));
2351 EXPECT_EQ(offset, static_cast<off64_t>(pos64));
2352#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002353 GTEST_SKIP() << "glibc's fpos_t is opaque";
Elliott Hughes9677fab2016-01-25 15:50:59 -08002354#endif
2355}
2356
2357TEST(STDIO_TEST, seek_tell_family_smoke) {
2358 TemporaryFile tf;
2359 FILE* fp = fdopen(tf.fd, "w+");
2360
2361 // Initially we should be at 0.
2362 AssertFileOffsetAt(fp, 0);
2363
2364 // Seek to offset 8192.
2365 ASSERT_EQ(0, fseek(fp, 8192, SEEK_SET));
2366 AssertFileOffsetAt(fp, 8192);
2367 fpos_t eight_k_pos;
2368 ASSERT_EQ(0, fgetpos(fp, &eight_k_pos));
2369
2370 // Seek forward another 8192...
2371 ASSERT_EQ(0, fseek(fp, 8192, SEEK_CUR));
2372 AssertFileOffsetAt(fp, 8192 + 8192);
2373 fpos64_t sixteen_k_pos64;
2374 ASSERT_EQ(0, fgetpos64(fp, &sixteen_k_pos64));
2375
2376 // Seek back 8192...
2377 ASSERT_EQ(0, fseek(fp, -8192, SEEK_CUR));
2378 AssertFileOffsetAt(fp, 8192);
2379
2380 // Since we haven't written anything, the end is also at 0.
2381 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2382 AssertFileOffsetAt(fp, 0);
2383
2384 // Check that our fpos64_t from 16KiB works...
2385 ASSERT_EQ(0, fsetpos64(fp, &sixteen_k_pos64));
2386 AssertFileOffsetAt(fp, 8192 + 8192);
2387 // ...as does our fpos_t from 8192.
2388 ASSERT_EQ(0, fsetpos(fp, &eight_k_pos));
2389 AssertFileOffsetAt(fp, 8192);
2390
2391 // Do fseeko and fseeko64 work too?
2392 ASSERT_EQ(0, fseeko(fp, 1234, SEEK_SET));
2393 AssertFileOffsetAt(fp, 1234);
2394 ASSERT_EQ(0, fseeko64(fp, 5678, SEEK_SET));
2395 AssertFileOffsetAt(fp, 5678);
2396
2397 fclose(fp);
2398}
2399
2400TEST(STDIO_TEST, fseek_fseeko_EINVAL) {
2401 TemporaryFile tf;
2402 FILE* fp = fdopen(tf.fd, "w+");
2403
2404 // Bad whence.
2405 errno = 0;
2406 ASSERT_EQ(-1, fseek(fp, 0, 123));
2407 ASSERT_EQ(EINVAL, errno);
2408 errno = 0;
2409 ASSERT_EQ(-1, fseeko(fp, 0, 123));
2410 ASSERT_EQ(EINVAL, errno);
2411 errno = 0;
2412 ASSERT_EQ(-1, fseeko64(fp, 0, 123));
2413 ASSERT_EQ(EINVAL, errno);
2414
2415 // Bad offset.
2416 errno = 0;
2417 ASSERT_EQ(-1, fseek(fp, -1, SEEK_SET));
2418 ASSERT_EQ(EINVAL, errno);
2419 errno = 0;
2420 ASSERT_EQ(-1, fseeko(fp, -1, SEEK_SET));
2421 ASSERT_EQ(EINVAL, errno);
2422 errno = 0;
2423 ASSERT_EQ(-1, fseeko64(fp, -1, SEEK_SET));
2424 ASSERT_EQ(EINVAL, errno);
2425
2426 fclose(fp);
2427}
Elliott Hughes20788ae2016-06-09 15:16:32 -07002428
2429TEST(STDIO_TEST, ctermid) {
2430 ASSERT_STREQ("/dev/tty", ctermid(nullptr));
2431
2432 char buf[L_ctermid] = {};
2433 ASSERT_EQ(buf, ctermid(buf));
2434 ASSERT_STREQ("/dev/tty", buf);
2435}
Elliott Hughesd1f25a72016-08-05 15:53:03 -07002436
2437TEST(STDIO_TEST, remove) {
2438 struct stat sb;
2439
2440 TemporaryFile tf;
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002441 ASSERT_EQ(0, remove(tf.path));
2442 ASSERT_EQ(-1, lstat(tf.path, &sb));
Elliott Hughesd1f25a72016-08-05 15:53:03 -07002443 ASSERT_EQ(ENOENT, errno);
2444
2445 TemporaryDir td;
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002446 ASSERT_EQ(0, remove(td.path));
2447 ASSERT_EQ(-1, lstat(td.path, &sb));
Elliott Hughesd1f25a72016-08-05 15:53:03 -07002448 ASSERT_EQ(ENOENT, errno);
2449
2450 errno = 0;
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002451 ASSERT_EQ(-1, remove(tf.path));
Elliott Hughesd1f25a72016-08-05 15:53:03 -07002452 ASSERT_EQ(ENOENT, errno);
2453
2454 errno = 0;
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002455 ASSERT_EQ(-1, remove(td.path));
Elliott Hughesd1f25a72016-08-05 15:53:03 -07002456 ASSERT_EQ(ENOENT, errno);
2457}
Elliott Hughesfb3873d2016-08-10 11:07:54 -07002458
Elliott Hughese657eb42021-02-18 17:11:56 -08002459TEST_F(STDIO_DEATHTEST, snprintf_30445072_known_buffer_size) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -07002460 char buf[16];
2461 ASSERT_EXIT(snprintf(buf, atol("-1"), "hello"),
2462 testing::KilledBySignal(SIGABRT),
2463#if defined(NOFORTIFY)
2464 "FORTIFY: vsnprintf: size .* > SSIZE_MAX"
2465#else
2466 "FORTIFY: vsnprintf: prevented .*-byte write into 16-byte buffer"
2467#endif
2468 );
2469}
2470
Elliott Hughese657eb42021-02-18 17:11:56 -08002471TEST_F(STDIO_DEATHTEST, snprintf_30445072_unknown_buffer_size) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -07002472 std::string buf = "world";
2473 ASSERT_EXIT(snprintf(&buf[0], atol("-1"), "hello"),
2474 testing::KilledBySignal(SIGABRT),
2475 "FORTIFY: vsnprintf: size .* > SSIZE_MAX");
2476}
2477
2478TEST(STDIO_TEST, sprintf_30445072) {
2479 std::string buf = "world";
2480 sprintf(&buf[0], "hello");
2481 ASSERT_EQ(buf, "hello");
2482}
Elliott Hughes33a8cb12017-07-25 18:06:46 -07002483
Elliott Hughes654cd832018-08-30 16:00:42 -07002484TEST(STDIO_TEST, printf_m) {
2485 char buf[BUFSIZ];
2486 errno = 0;
2487 snprintf(buf, sizeof(buf), "<%m>");
2488 ASSERT_STREQ("<Success>", buf);
2489 errno = -1;
2490 snprintf(buf, sizeof(buf), "<%m>");
2491 ASSERT_STREQ("<Unknown error -1>", buf);
2492 errno = EINVAL;
2493 snprintf(buf, sizeof(buf), "<%m>");
Steven Moreland4ef83d62021-10-07 00:19:18 +00002494 ASSERT_STREQ("<Invalid argument>", buf);
Elliott Hughes654cd832018-08-30 16:00:42 -07002495}
2496
Elliott Hughesf340a562018-09-06 10:42:40 -07002497TEST(STDIO_TEST, printf_m_does_not_clobber_strerror) {
2498 char buf[BUFSIZ];
2499 const char* m = strerror(-1);
2500 ASSERT_STREQ("Unknown error -1", m);
2501 errno = -2;
2502 snprintf(buf, sizeof(buf), "<%m>");
2503 ASSERT_STREQ("<Unknown error -2>", buf);
2504 ASSERT_STREQ("Unknown error -1", m);
2505}
2506
Elliott Hughes654cd832018-08-30 16:00:42 -07002507TEST(STDIO_TEST, wprintf_m) {
2508 wchar_t buf[BUFSIZ];
2509 errno = 0;
2510 swprintf(buf, sizeof(buf), L"<%m>");
2511 ASSERT_EQ(std::wstring(L"<Success>"), buf);
2512 errno = -1;
2513 swprintf(buf, sizeof(buf), L"<%m>");
2514 ASSERT_EQ(std::wstring(L"<Unknown error -1>"), buf);
2515 errno = EINVAL;
2516 swprintf(buf, sizeof(buf), L"<%m>");
Steven Moreland4ef83d62021-10-07 00:19:18 +00002517 ASSERT_EQ(std::wstring(L"<Invalid argument>"), buf);
Elliott Hughes654cd832018-08-30 16:00:42 -07002518}
2519
Elliott Hughesf340a562018-09-06 10:42:40 -07002520TEST(STDIO_TEST, wprintf_m_does_not_clobber_strerror) {
2521 wchar_t buf[BUFSIZ];
2522 const char* m = strerror(-1);
2523 ASSERT_STREQ("Unknown error -1", m);
2524 errno = -2;
2525 swprintf(buf, sizeof(buf), L"<%m>");
2526 ASSERT_EQ(std::wstring(L"<Unknown error -2>"), buf);
2527 ASSERT_STREQ("Unknown error -1", m);
2528}
2529
Elliott Hughes33a8cb12017-07-25 18:06:46 -07002530TEST(STDIO_TEST, fopen_append_mode_and_ftell) {
2531 TemporaryFile tf;
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002532 SetFileTo(tf.path, "0123456789");
2533 FILE* fp = fopen(tf.path, "a");
Elliott Hughes33a8cb12017-07-25 18:06:46 -07002534 EXPECT_EQ(10, ftell(fp));
2535 ASSERT_EQ(0, fseek(fp, 2, SEEK_SET));
2536 EXPECT_EQ(2, ftell(fp));
2537 ASSERT_NE(EOF, fputs("xxx", fp));
2538 ASSERT_EQ(0, fflush(fp));
2539 EXPECT_EQ(13, ftell(fp));
2540 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2541 EXPECT_EQ(13, ftell(fp));
2542 ASSERT_EQ(0, fclose(fp));
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002543 AssertFileIs(tf.path, "0123456789xxx");
Elliott Hughes33a8cb12017-07-25 18:06:46 -07002544}
2545
2546TEST(STDIO_TEST, fdopen_append_mode_and_ftell) {
2547 TemporaryFile tf;
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002548 SetFileTo(tf.path, "0123456789");
2549 int fd = open(tf.path, O_RDWR);
Elliott Hughes33a8cb12017-07-25 18:06:46 -07002550 ASSERT_NE(-1, fd);
2551 // POSIX: "The file position indicator associated with the new stream is set to the position
2552 // indicated by the file offset associated with the file descriptor."
2553 ASSERT_EQ(4, lseek(fd, 4, SEEK_SET));
2554 FILE* fp = fdopen(fd, "a");
2555 EXPECT_EQ(4, ftell(fp));
2556 ASSERT_EQ(0, fseek(fp, 2, SEEK_SET));
2557 EXPECT_EQ(2, ftell(fp));
2558 ASSERT_NE(EOF, fputs("xxx", fp));
2559 ASSERT_EQ(0, fflush(fp));
2560 EXPECT_EQ(13, ftell(fp));
2561 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2562 EXPECT_EQ(13, ftell(fp));
2563 ASSERT_EQ(0, fclose(fp));
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002564 AssertFileIs(tf.path, "0123456789xxx");
Elliott Hughes33a8cb12017-07-25 18:06:46 -07002565}
2566
2567TEST(STDIO_TEST, freopen_append_mode_and_ftell) {
2568 TemporaryFile tf;
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002569 SetFileTo(tf.path, "0123456789");
Elliott Hughes33a8cb12017-07-25 18:06:46 -07002570 FILE* other_fp = fopen("/proc/version", "r");
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002571 FILE* fp = freopen(tf.path, "a", other_fp);
Elliott Hughes33a8cb12017-07-25 18:06:46 -07002572 EXPECT_EQ(10, ftell(fp));
2573 ASSERT_EQ(0, fseek(fp, 2, SEEK_SET));
2574 EXPECT_EQ(2, ftell(fp));
2575 ASSERT_NE(EOF, fputs("xxx", fp));
2576 ASSERT_EQ(0, fflush(fp));
2577 EXPECT_EQ(13, ftell(fp));
2578 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2579 EXPECT_EQ(13, ftell(fp));
2580 ASSERT_EQ(0, fclose(fp));
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002581 AssertFileIs(tf.path, "0123456789xxx");
Elliott Hughes33a8cb12017-07-25 18:06:46 -07002582}
Elliott Hughesb15feb72017-07-31 17:20:18 -07002583
2584TEST(STDIO_TEST, constants) {
2585 ASSERT_LE(FILENAME_MAX, PATH_MAX);
2586 ASSERT_EQ(L_tmpnam, PATH_MAX);
2587}
Elliott Hughes37ad9592017-10-30 17:47:12 -07002588
2589TEST(STDIO_TEST, perror) {
2590 ExecTestHelper eth;
Steven Moreland4ef83d62021-10-07 00:19:18 +00002591 eth.Run([&]() { errno = EINVAL; perror("a b c"); exit(0); }, 0, "a b c: Invalid argument\n");
2592 eth.Run([&]() { errno = EINVAL; perror(nullptr); exit(0); }, 0, "Invalid argument\n");
2593 eth.Run([&]() { errno = EINVAL; perror(""); exit(0); }, 0, "Invalid argument\n");
Elliott Hughes37ad9592017-10-30 17:47:12 -07002594}
2595
2596TEST(STDIO_TEST, puts) {
2597 ExecTestHelper eth;
2598 eth.Run([&]() { exit(puts("a b c")); }, 0, "a b c\n");
2599}
2600
Elliott Hughes7cebf832020-08-12 14:25:41 -07002601TEST(STDIO_TEST, putchar) {
2602 ExecTestHelper eth;
2603 eth.Run([&]() { exit(putchar('A')); }, 65, "A");
2604}
2605
2606TEST(STDIO_TEST, putchar_unlocked) {
2607 ExecTestHelper eth;
2608 eth.Run([&]() { exit(putchar('B')); }, 66, "B");
2609}
2610
Elliott Hughes37ad9592017-10-30 17:47:12 -07002611TEST(STDIO_TEST, unlocked) {
2612 TemporaryFile tf;
2613
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002614 FILE* fp = fopen(tf.path, "w+");
Elliott Hughes37ad9592017-10-30 17:47:12 -07002615 ASSERT_TRUE(fp != nullptr);
2616
2617 clearerr_unlocked(fp);
2618 ASSERT_FALSE(feof_unlocked(fp));
2619 ASSERT_FALSE(ferror_unlocked(fp));
2620
2621 ASSERT_EQ(fileno(fp), fileno_unlocked(fp));
2622
2623 ASSERT_NE(EOF, putc_unlocked('a', fp));
2624 ASSERT_NE(EOF, putc('b', fp));
2625 ASSERT_NE(EOF, fputc_unlocked('c', fp));
2626 ASSERT_NE(EOF, fputc('d', fp));
2627
2628 rewind(fp);
2629 ASSERT_EQ('a', getc_unlocked(fp));
2630 ASSERT_EQ('b', getc(fp));
2631 ASSERT_EQ('c', fgetc_unlocked(fp));
2632 ASSERT_EQ('d', fgetc(fp));
2633
2634 rewind(fp);
2635 ASSERT_EQ(2U, fwrite_unlocked("AB", 1, 2, fp));
2636 ASSERT_EQ(2U, fwrite("CD", 1, 2, fp));
2637 ASSERT_EQ(0, fflush_unlocked(fp));
2638
2639 rewind(fp);
2640 char buf[BUFSIZ] = {};
2641 ASSERT_EQ(2U, fread_unlocked(&buf[0], 1, 2, fp));
2642 ASSERT_EQ(2U, fread(&buf[2], 1, 2, fp));
2643 ASSERT_STREQ("ABCD", buf);
2644
2645 rewind(fp);
2646 ASSERT_NE(EOF, fputs("hello ", fp));
2647 ASSERT_NE(EOF, fputs_unlocked("world", fp));
2648 ASSERT_NE(EOF, fputc('\n', fp));
2649
2650 rewind(fp);
2651 ASSERT_TRUE(fgets_unlocked(buf, sizeof(buf), fp) != nullptr);
2652 ASSERT_STREQ("hello world\n", buf);
2653
2654 ASSERT_EQ(0, fclose(fp));
2655}
Ryan Prichardbf549862017-11-07 15:30:32 -08002656
2657TEST(STDIO_TEST, fseek_64bit) {
2658 TemporaryFile tf;
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002659 FILE* fp = fopen64(tf.path, "w+");
Ryan Prichardbf549862017-11-07 15:30:32 -08002660 ASSERT_TRUE(fp != nullptr);
2661 ASSERT_EQ(0, fseeko64(fp, 0x2'0000'0000, SEEK_SET));
2662 ASSERT_EQ(0x2'0000'0000, ftello64(fp));
2663 ASSERT_EQ(0, fseeko64(fp, 0x1'0000'0000, SEEK_CUR));
2664 ASSERT_EQ(0x3'0000'0000, ftello64(fp));
2665 ASSERT_EQ(0, fclose(fp));
2666}
2667
2668// POSIX requires that fseek/fseeko fail with EOVERFLOW if the new file offset
2669// isn't representable in long/off_t.
2670TEST(STDIO_TEST, fseek_overflow_32bit) {
2671 TemporaryFile tf;
Mark Salyzyn68a3bcc2018-11-13 07:35:21 -08002672 FILE* fp = fopen64(tf.path, "w+");
Ryan Prichardbf549862017-11-07 15:30:32 -08002673 ASSERT_EQ(0, ftruncate64(fileno(fp), 0x2'0000'0000));
2674
2675 // Bionic implements overflow checking for SEEK_CUR, but glibc doesn't.
2676#if defined(__BIONIC__) && !defined(__LP64__)
2677 ASSERT_EQ(0, fseek(fp, 0x7fff'ffff, SEEK_SET));
2678 ASSERT_EQ(-1, fseek(fp, 1, SEEK_CUR));
2679 ASSERT_EQ(EOVERFLOW, errno);
2680#endif
2681
2682 // Neither Bionic nor glibc implement the overflow checking for SEEK_END.
2683 // (Aside: FreeBSD's libc is an example of a libc that checks both SEEK_CUR
2684 // and SEEK_END -- many C libraries check neither.)
2685 ASSERT_EQ(0, fseek(fp, 0, SEEK_END));
2686 ASSERT_EQ(0x2'0000'0000, ftello64(fp));
2687
2688 fclose(fp);
2689}
Elliott Hughesf1a38382018-08-22 15:38:07 -07002690
2691TEST(STDIO_TEST, dev_std_files) {
2692 // POSIX only mentions /dev/stdout, but we should have all three (http://b/31824379).
2693 char path[PATH_MAX];
Christopher Ferris2c4ec7e2018-08-23 11:17:55 -07002694 ssize_t length = readlink("/dev/stdin", path, sizeof(path));
2695 ASSERT_LT(0, length);
2696 ASSERT_EQ("/proc/self/fd/0", std::string(path, length));
2697
2698 length = readlink("/dev/stdout", path, sizeof(path));
2699 ASSERT_LT(0, length);
2700 ASSERT_EQ("/proc/self/fd/1", std::string(path, length));
2701
2702 length = readlink("/dev/stderr", path, sizeof(path));
2703 ASSERT_LT(0, length);
2704 ASSERT_EQ("/proc/self/fd/2", std::string(path, length));
Elliott Hughesf1a38382018-08-22 15:38:07 -07002705}
Ryan Prichardc485cdb2019-04-30 14:47:34 -07002706
2707TEST(STDIO_TEST, fread_with_locked_file) {
2708 // Reading an unbuffered/line-buffered file from one thread shouldn't block on
2709 // files locked on other threads, even if it flushes some line-buffered files.
2710 FILE* fp1 = fopen("/dev/zero", "r");
2711 ASSERT_TRUE(fp1 != nullptr);
2712 flockfile(fp1);
2713
2714 std::thread([] {
2715 for (int mode : { _IONBF, _IOLBF }) {
2716 FILE* fp2 = fopen("/dev/zero", "r");
2717 ASSERT_TRUE(fp2 != nullptr);
2718 setvbuf(fp2, nullptr, mode, 0);
2719 ASSERT_EQ('\0', fgetc(fp2));
2720 fclose(fp2);
2721 }
2722 }).join();
2723
2724 funlockfile(fp1);
2725 fclose(fp1);
2726}
Elliott Hughes31c73092019-05-07 10:03:02 -07002727
2728TEST(STDIO_TEST, SEEK_macros) {
2729 ASSERT_EQ(0, SEEK_SET);
2730 ASSERT_EQ(1, SEEK_CUR);
2731 ASSERT_EQ(2, SEEK_END);
2732 ASSERT_EQ(3, SEEK_DATA);
2733 ASSERT_EQ(4, SEEK_HOLE);
2734 // So we'll notice if Linux grows another constant in <linux/fs.h>...
2735 ASSERT_EQ(SEEK_MAX, SEEK_HOLE);
2736}
Elliott Hughes05b675e2019-04-17 13:01:06 -07002737
2738TEST(STDIO_TEST, rename) {
2739 TemporaryDir td;
2740 std::string old_path = td.path + "/old"s;
2741 std::string new_path = td.path + "/new"s;
2742
2743 // Create the file, check it exists.
2744 ASSERT_EQ(0, close(creat(old_path.c_str(), 0666)));
2745 struct stat sb;
2746 ASSERT_EQ(0, stat(old_path.c_str(), &sb));
2747 ASSERT_EQ(-1, stat(new_path.c_str(), &sb));
2748
2749 // Rename and check it moved.
2750 ASSERT_EQ(0, rename(old_path.c_str(), new_path.c_str()));
2751 ASSERT_EQ(-1, stat(old_path.c_str(), &sb));
2752 ASSERT_EQ(0, stat(new_path.c_str(), &sb));
2753}
2754
2755TEST(STDIO_TEST, renameat) {
2756 TemporaryDir td;
2757 android::base::unique_fd dirfd{open(td.path, O_PATH)};
2758 std::string old_path = td.path + "/old"s;
2759 std::string new_path = td.path + "/new"s;
2760
2761 // Create the file, check it exists.
2762 ASSERT_EQ(0, close(creat(old_path.c_str(), 0666)));
2763 struct stat sb;
2764 ASSERT_EQ(0, stat(old_path.c_str(), &sb));
2765 ASSERT_EQ(-1, stat(new_path.c_str(), &sb));
2766
2767 // Rename and check it moved.
2768 ASSERT_EQ(0, renameat(dirfd, "old", dirfd, "new"));
2769 ASSERT_EQ(-1, stat(old_path.c_str(), &sb));
2770 ASSERT_EQ(0, stat(new_path.c_str(), &sb));
2771}
2772
2773TEST(STDIO_TEST, renameat2) {
Colin Cross4c5595c2021-08-16 15:51:59 -07002774#if defined(__GLIBC__) || defined(ANDROID_HOST_MUSL)
Colin Cross7da20342021-07-28 11:18:11 -07002775 GTEST_SKIP() << "glibc doesn't have renameat2 until 2.28 and musl doesn't have renameat2";
Elliott Hughes05b675e2019-04-17 13:01:06 -07002776#else
2777 TemporaryDir td;
2778 android::base::unique_fd dirfd{open(td.path, O_PATH)};
2779 std::string old_path = td.path + "/old"s;
2780 std::string new_path = td.path + "/new"s;
2781
2782 // Create the file, check it exists.
2783 ASSERT_EQ(0, close(creat(old_path.c_str(), 0666)));
2784 struct stat sb;
2785 ASSERT_EQ(0, stat(old_path.c_str(), &sb));
2786 ASSERT_EQ(-1, stat(new_path.c_str(), &sb));
2787
2788 // Rename and check it moved.
2789 ASSERT_EQ(0, renameat2(dirfd, "old", dirfd, "new", 0));
2790 ASSERT_EQ(-1, stat(old_path.c_str(), &sb));
2791 ASSERT_EQ(0, stat(new_path.c_str(), &sb));
2792
2793 // After this, both "old" and "new" exist.
2794 ASSERT_EQ(0, close(creat(old_path.c_str(), 0666)));
2795
2796 // Rename and check it moved.
2797 ASSERT_EQ(-1, renameat2(dirfd, "old", dirfd, "new", RENAME_NOREPLACE));
2798 ASSERT_EQ(EEXIST, errno);
2799#endif
2800}
2801
2802TEST(STDIO_TEST, renameat2_flags) {
2803#if defined(__GLIBC__)
2804 GTEST_SKIP() << "glibc doesn't have renameat2 until 2.28";
2805#else
2806 ASSERT_NE(0, RENAME_EXCHANGE);
2807 ASSERT_NE(0, RENAME_NOREPLACE);
2808 ASSERT_NE(0, RENAME_WHITEOUT);
2809#endif
2810}
Elliott Hughes7cebf832020-08-12 14:25:41 -07002811
2812TEST(STDIO_TEST, fdopen_failures) {
2813 FILE* fp;
2814 int fd = open("/proc/version", O_RDONLY);
2815 ASSERT_TRUE(fd != -1);
2816
2817 // Nonsense mode.
2818 errno = 0;
2819 fp = fdopen(fd, "nonsense");
2820 ASSERT_TRUE(fp == nullptr);
2821 ASSERT_EQ(EINVAL, errno);
2822
2823 // Mode that isn't a subset of the fd's actual mode.
2824 errno = 0;
2825 fp = fdopen(fd, "w");
2826 ASSERT_TRUE(fp == nullptr);
2827 ASSERT_EQ(EINVAL, errno);
2828
2829 // Can't set append on the underlying fd.
2830 errno = 0;
2831 fp = fdopen(fd, "a");
2832 ASSERT_TRUE(fp == nullptr);
2833 ASSERT_EQ(EINVAL, errno);
2834
2835 // Bad fd.
2836 errno = 0;
2837 fp = fdopen(-1, "re");
2838 ASSERT_TRUE(fp == nullptr);
2839 ASSERT_EQ(EBADF, errno);
2840
2841 close(fd);
2842}
2843
2844TEST(STDIO_TEST, fmemopen_invalid_mode) {
2845 errno = 0;
2846 FILE* fp = fmemopen(nullptr, 16, "nonsense");
2847 ASSERT_TRUE(fp == nullptr);
2848 ASSERT_EQ(EINVAL, errno);
2849}
2850
2851TEST(STDIO_TEST, fopen_invalid_mode) {
2852 errno = 0;
2853 FILE* fp = fopen("/proc/version", "nonsense");
2854 ASSERT_TRUE(fp == nullptr);
2855 ASSERT_EQ(EINVAL, errno);
2856}
2857
2858TEST(STDIO_TEST, freopen_invalid_mode) {
2859 FILE* fp = fopen("/proc/version", "re");
2860 ASSERT_TRUE(fp != nullptr);
2861
2862 errno = 0;
2863 fp = freopen("/proc/version", "nonsense", fp);
2864 ASSERT_TRUE(fp == nullptr);
2865 ASSERT_EQ(EINVAL, errno);
2866}
2867
2868TEST(STDIO_TEST, asprintf_smoke) {
2869 char* p = nullptr;
2870 ASSERT_EQ(11, asprintf(&p, "hello %s", "world"));
2871 ASSERT_STREQ("hello world", p);
2872 free(p);
2873}
2874
2875TEST(STDIO_TEST, fopen_ENOENT) {
2876 errno = 0;
2877 FILE* fp = fopen("/proc/does-not-exist", "re");
2878 ASSERT_TRUE(fp == nullptr);
2879 ASSERT_EQ(ENOENT, errno);
2880}
Elliott Hughes439ebbd2020-12-04 18:51:42 -08002881
2882static void tempnam_test(bool has_TMPDIR, const char* dir, const char* prefix, const char* re) {
2883 if (has_TMPDIR) {
2884 setenv("TMPDIR", "/my/tmp/dir", 1);
2885 } else {
2886 unsetenv("TMPDIR");
2887 }
2888 char* s1 = tempnam(dir, prefix);
2889 char* s2 = tempnam(dir, prefix);
2890 ASSERT_MATCH(s1, re);
2891 ASSERT_MATCH(s2, re);
2892 ASSERT_STRNE(s1, s2);
2893 free(s1);
2894 free(s2);
2895}
2896
2897TEST(STDIO_TEST, tempnam__system_directory_system_prefix_with_TMPDIR) {
2898 tempnam_test(true, nullptr, nullptr, "^/my/tmp/dir/.*");
2899}
2900
2901TEST(STDIO_TEST, tempnam__system_directory_system_prefix_without_TMPDIR) {
2902 tempnam_test(false, nullptr, nullptr, "^/data/local/tmp/.*");
2903}
2904
2905TEST(STDIO_TEST, tempnam__system_directory_user_prefix_with_TMPDIR) {
2906 tempnam_test(true, nullptr, "prefix", "^/my/tmp/dir/prefix.*");
2907}
2908
2909TEST(STDIO_TEST, tempnam__system_directory_user_prefix_without_TMPDIR) {
2910 tempnam_test(false, nullptr, "prefix", "^/data/local/tmp/prefix.*");
2911}
2912
2913TEST(STDIO_TEST, tempnam__user_directory_system_prefix_with_TMPDIR) {
2914 tempnam_test(true, "/a/b/c", nullptr, "^/my/tmp/dir/.*");
2915}
2916
2917TEST(STDIO_TEST, tempnam__user_directory_system_prefix_without_TMPDIR) {
2918 tempnam_test(false, "/a/b/c", nullptr, "^/a/b/c/.*");
2919}
2920
2921TEST(STDIO_TEST, tempnam__user_directory_user_prefix_with_TMPDIR) {
2922 tempnam_test(true, "/a/b/c", "prefix", "^/my/tmp/dir/prefix.*");
2923}
2924
2925TEST(STDIO_TEST, tempnam__user_directory_user_prefix_without_TMPDIR) {
2926 tempnam_test(false, "/a/b/c", "prefix", "^/a/b/c/prefix.*");
2927}
2928
2929static void tmpnam_test(char* s) {
2930 char s1[L_tmpnam], s2[L_tmpnam];
2931
2932 strcpy(s1, tmpnam(s));
2933 strcpy(s2, tmpnam(s));
2934 ASSERT_MATCH(s1, "/tmp/.*");
2935 ASSERT_MATCH(s2, "/tmp/.*");
2936 ASSERT_STRNE(s1, s2);
2937}
2938
2939TEST(STDIO_TEST, tmpnam) {
2940 tmpnam_test(nullptr);
2941}
2942
2943TEST(STDIO_TEST, tmpnam_buf) {
2944 char buf[L_tmpnam];
2945 tmpnam_test(buf);
2946}
Elliott Hughesf9cfecf2021-02-04 16:58:13 -08002947
2948TEST(STDIO_TEST, freopen_null_filename_mode) {
2949 TemporaryFile tf;
2950 FILE* fp = fopen(tf.path, "r");
2951 ASSERT_TRUE(fp != nullptr);
2952
2953 // "r" = O_RDONLY
2954 char buf[1];
2955 ASSERT_EQ(0, read(fileno(fp), buf, 1));
2956 ASSERT_EQ(-1, write(fileno(fp), "hello", 1));
2957 // "r+" = O_RDWR
2958 fp = freopen(nullptr, "r+", fp);
2959 ASSERT_EQ(0, read(fileno(fp), buf, 1));
2960 ASSERT_EQ(1, write(fileno(fp), "hello", 1));
2961 // "w" = O_WRONLY
2962 fp = freopen(nullptr, "w", fp);
2963 ASSERT_EQ(-1, read(fileno(fp), buf, 1));
2964 ASSERT_EQ(1, write(fileno(fp), "hello", 1));
2965
2966 fclose(fp);
2967}
Elliott Hughesbe78fc92022-07-28 20:58:45 +00002968
Elliott Hughes0cac2912022-08-02 18:25:22 +00002969#if defined(__LP64__)
Elliott Hughesbe78fc92022-07-28 20:58:45 +00002970static int64_t GetTotalRamGiB() {
2971 struct sysinfo si;
2972 sysinfo(&si);
2973 return (static_cast<int64_t>(si.totalram) * si.mem_unit) / 1024 / 1024 / 1024;
2974}
Elliott Hughes0cac2912022-08-02 18:25:22 +00002975#endif
Elliott Hughesbe78fc92022-07-28 20:58:45 +00002976
2977TEST(STDIO_TEST, fread_int_overflow) {
Elliott Hughes0cac2912022-08-02 18:25:22 +00002978#if defined(__LP64__)
Elliott Hughesbe78fc92022-07-28 20:58:45 +00002979 if (GetTotalRamGiB() <= 4) GTEST_SKIP() << "not enough memory";
2980
2981 const size_t too_big_for_an_int = 0x80000000ULL;
2982 std::vector<char> buf(too_big_for_an_int);
2983 std::unique_ptr<FILE, decltype(&fclose)> fp{fopen("/dev/zero", "re"), fclose};
2984 ASSERT_EQ(too_big_for_an_int, fread(&buf[0], 1, too_big_for_an_int, fp.get()));
Elliott Hughes0cac2912022-08-02 18:25:22 +00002985#else
2986 GTEST_SKIP() << "32-bit can't allocate 2GiB";
2987#endif
Elliott Hughesbe78fc92022-07-28 20:58:45 +00002988}
2989
2990TEST(STDIO_TEST, fwrite_int_overflow) {
Elliott Hughes0cac2912022-08-02 18:25:22 +00002991#if defined(__LP64__)
Elliott Hughesbe78fc92022-07-28 20:58:45 +00002992 if (GetTotalRamGiB() <= 4) GTEST_SKIP() << "not enough memory";
2993
2994 const size_t too_big_for_an_int = 0x80000000ULL;
2995 std::vector<char> buf(too_big_for_an_int);
2996 std::unique_ptr<FILE, decltype(&fclose)> fp{fopen("/dev/null", "we"), fclose};
2997 ASSERT_EQ(too_big_for_an_int, fwrite(&buf[0], 1, too_big_for_an_int, fp.get()));
Elliott Hughes0cac2912022-08-02 18:25:22 +00002998#else
2999 GTEST_SKIP() << "32-bit can't allocate 2GiB";
3000#endif
Elliott Hughesbe78fc92022-07-28 20:58:45 +00003001}
Elliott Hughesb813a6a2022-08-01 22:18:40 +00003002
3003TEST(STDIO_TEST, snprintf_b) {
Elliott Hughesb813a6a2022-08-01 22:18:40 +00003004 char buf[BUFSIZ];
3005 EXPECT_EQ(5, snprintf(buf, sizeof(buf), "<%b>", 5));
3006 EXPECT_STREQ("<101>", buf);
3007 EXPECT_EQ(10, snprintf(buf, sizeof(buf), "<%08b>", 5));
3008 EXPECT_STREQ("<00000101>", buf);
3009 EXPECT_EQ(34, snprintf(buf, sizeof(buf), "<%b>", 0xaaaaaaaa));
3010 EXPECT_STREQ("<10101010101010101010101010101010>", buf);
3011 EXPECT_EQ(36, snprintf(buf, sizeof(buf), "<%#b>", 0xaaaaaaaa));
3012 EXPECT_STREQ("<0b10101010101010101010101010101010>", buf);
3013 EXPECT_EQ(3, snprintf(buf, sizeof(buf), "<%#b>", 0));
3014 EXPECT_STREQ("<0>", buf);
Elliott Hughesb813a6a2022-08-01 22:18:40 +00003015}
3016
3017TEST(STDIO_TEST, snprintf_B) {
Elliott Hughesb813a6a2022-08-01 22:18:40 +00003018 char buf[BUFSIZ];
3019 EXPECT_EQ(5, snprintf(buf, sizeof(buf), "<%B>", 5));
3020 EXPECT_STREQ("<101>", buf);
3021 EXPECT_EQ(10, snprintf(buf, sizeof(buf), "<%08B>", 5));
3022 EXPECT_STREQ("<00000101>", buf);
3023 EXPECT_EQ(34, snprintf(buf, sizeof(buf), "<%B>", 0xaaaaaaaa));
3024 EXPECT_STREQ("<10101010101010101010101010101010>", buf);
3025 EXPECT_EQ(36, snprintf(buf, sizeof(buf), "<%#B>", 0xaaaaaaaa));
3026 EXPECT_STREQ("<0B10101010101010101010101010101010>", buf);
3027 EXPECT_EQ(3, snprintf(buf, sizeof(buf), "<%#B>", 0));
3028 EXPECT_STREQ("<0>", buf);
Elliott Hughesb813a6a2022-08-01 22:18:40 +00003029}
3030
3031TEST(STDIO_TEST, swprintf_b) {
Elliott Hughesb813a6a2022-08-01 22:18:40 +00003032 wchar_t buf[BUFSIZ];
3033 EXPECT_EQ(5, swprintf(buf, sizeof(buf), L"<%b>", 5));
3034 EXPECT_EQ(std::wstring(L"<101>"), buf);
3035 EXPECT_EQ(10, swprintf(buf, sizeof(buf), L"<%08b>", 5));
3036 EXPECT_EQ(std::wstring(L"<00000101>"), buf);
3037 EXPECT_EQ(34, swprintf(buf, sizeof(buf), L"<%b>", 0xaaaaaaaa));
3038 EXPECT_EQ(std::wstring(L"<10101010101010101010101010101010>"), buf);
3039 EXPECT_EQ(36, swprintf(buf, sizeof(buf), L"<%#b>", 0xaaaaaaaa));
3040 EXPECT_EQ(std::wstring(L"<0b10101010101010101010101010101010>"), buf);
3041 EXPECT_EQ(3, swprintf(buf, sizeof(buf), L"<%#b>", 0));
3042 EXPECT_EQ(std::wstring(L"<0>"), buf);
Elliott Hughesb813a6a2022-08-01 22:18:40 +00003043}
3044
3045TEST(STDIO_TEST, swprintf_B) {
Elliott Hughesb813a6a2022-08-01 22:18:40 +00003046 wchar_t buf[BUFSIZ];
3047 EXPECT_EQ(5, swprintf(buf, sizeof(buf), L"<%B>", 5));
3048 EXPECT_EQ(std::wstring(L"<101>"), buf);
3049 EXPECT_EQ(10, swprintf(buf, sizeof(buf), L"<%08B>", 5));
3050 EXPECT_EQ(std::wstring(L"<00000101>"), buf);
3051 EXPECT_EQ(34, swprintf(buf, sizeof(buf), L"<%B>", 0xaaaaaaaa));
3052 EXPECT_EQ(std::wstring(L"<10101010101010101010101010101010>"), buf);
3053 EXPECT_EQ(36, swprintf(buf, sizeof(buf), L"<%#B>", 0xaaaaaaaa));
3054 EXPECT_EQ(std::wstring(L"<0B10101010101010101010101010101010>"), buf);
3055 EXPECT_EQ(3, swprintf(buf, sizeof(buf), L"<%#B>", 0));
3056 EXPECT_EQ(std::wstring(L"<0>"), buf);
Elliott Hughesb813a6a2022-08-01 22:18:40 +00003057}
Elliott Hughes1f462de2022-08-05 22:51:05 +00003058
3059TEST(STDIO_TEST, scanf_i_decimal) {
3060 int i;
3061 EXPECT_EQ(1, sscanf("<123789>", "<%i>", &i));
3062 EXPECT_EQ(123789, i);
3063
3064 long long int lli;
3065 char ch;
3066 EXPECT_EQ(2, sscanf("1234567890abcdefg", "%lli%c", &lli, &ch));
3067 EXPECT_EQ(1234567890, lli);
3068 EXPECT_EQ('a', ch);
3069}
3070
3071TEST(STDIO_TEST, scanf_i_hex) {
3072 int i;
3073 EXPECT_EQ(1, sscanf("<0x123abf>", "<%i>", &i));
3074 EXPECT_EQ(0x123abf, i);
3075
3076 long long int lli;
3077 char ch;
3078 EXPECT_EQ(2, sscanf("0x1234567890abcdefg", "%lli%c", &lli, &ch));
3079 EXPECT_EQ(0x1234567890abcdefLL, lli);
3080 EXPECT_EQ('g', ch);
3081}
3082
3083TEST(STDIO_TEST, scanf_i_octal) {
3084 int i;
3085 EXPECT_EQ(1, sscanf("<01234567>", "<%i>", &i));
3086 EXPECT_EQ(01234567, i);
3087
3088 long long int lli;
3089 char ch;
3090 EXPECT_EQ(2, sscanf("010234567890abcdefg", "%lli%c", &lli, &ch));
3091 EXPECT_EQ(010234567, lli);
3092 EXPECT_EQ('8', ch);
3093}
3094
3095TEST(STDIO_TEST, scanf_i_binary) {
3096 int i;
3097 EXPECT_EQ(1, sscanf("<0b101>", "<%i>", &i));
3098 EXPECT_EQ(0b101, i);
3099
3100 long long int lli;
3101 char ch;
3102 EXPECT_EQ(2, sscanf("0b10234567890abcdefg", "%lli%c", &lli, &ch));
3103 EXPECT_EQ(0b10, lli);
3104 EXPECT_EQ('2', ch);
3105}
3106
3107TEST(STDIO_TEST, wscanf_i_decimal) {
3108 int i;
3109 EXPECT_EQ(1, swscanf(L"<123789>", L"<%i>", &i));
3110 EXPECT_EQ(123789, i);
3111
3112 long long int lli;
3113 char ch;
3114 EXPECT_EQ(2, swscanf(L"1234567890abcdefg", L"%lli%c", &lli, &ch));
3115 EXPECT_EQ(1234567890, lli);
3116 EXPECT_EQ('a', ch);
3117}
3118
3119TEST(STDIO_TEST, wscanf_i_hex) {
3120 int i;
3121 EXPECT_EQ(1, swscanf(L"<0x123abf>", L"<%i>", &i));
3122 EXPECT_EQ(0x123abf, i);
3123
3124 long long int lli;
3125 char ch;
3126 EXPECT_EQ(2, swscanf(L"0x1234567890abcdefg", L"%lli%c", &lli, &ch));
3127 EXPECT_EQ(0x1234567890abcdefLL, lli);
3128 EXPECT_EQ('g', ch);
3129}
3130
3131TEST(STDIO_TEST, wscanf_i_octal) {
3132 int i;
3133 EXPECT_EQ(1, swscanf(L"<01234567>", L"<%i>", &i));
3134 EXPECT_EQ(01234567, i);
3135
3136 long long int lli;
3137 char ch;
3138 EXPECT_EQ(2, swscanf(L"010234567890abcdefg", L"%lli%c", &lli, &ch));
3139 EXPECT_EQ(010234567, lli);
3140 EXPECT_EQ('8', ch);
3141}
3142
3143TEST(STDIO_TEST, wscanf_i_binary) {
3144 int i;
3145 EXPECT_EQ(1, swscanf(L"<0b101>", L"<%i>", &i));
3146 EXPECT_EQ(0b101, i);
3147
3148 long long int lli;
3149 char ch;
3150 EXPECT_EQ(2, swscanf(L"0b10234567890abcdefg", L"%lli%c", &lli, &ch));
3151 EXPECT_EQ(0b10, lli);
3152 EXPECT_EQ('2', ch);
3153}
3154
3155TEST(STDIO_TEST, scanf_b) {
Elliott Hughes1f462de2022-08-05 22:51:05 +00003156 int i;
3157 char ch;
3158 EXPECT_EQ(2, sscanf("<1012>", "<%b%c>", &i, &ch));
3159 EXPECT_EQ(0b101, i);
3160 EXPECT_EQ('2', ch);
3161 EXPECT_EQ(1, sscanf("<00000101>", "<%08b>", &i));
3162 EXPECT_EQ(0b00000101, i);
3163 EXPECT_EQ(1, sscanf("<0b1010>", "<%b>", &i));
3164 EXPECT_EQ(0b1010, i);
3165 EXPECT_EQ(2, sscanf("-0b", "%i%c", &i, &ch));
3166 EXPECT_EQ(0, i);
3167 EXPECT_EQ('b', ch);
Elliott Hughes1f462de2022-08-05 22:51:05 +00003168}
3169
3170TEST(STDIO_TEST, swscanf_b) {
Elliott Hughes1f462de2022-08-05 22:51:05 +00003171 int i;
3172 char ch;
3173 EXPECT_EQ(2, swscanf(L"<1012>", L"<%b%c>", &i, &ch));
3174 EXPECT_EQ(0b101, i);
3175 EXPECT_EQ('2', ch);
3176 EXPECT_EQ(1, swscanf(L"<00000101>", L"<%08b>", &i));
3177 EXPECT_EQ(0b00000101, i);
3178 EXPECT_EQ(1, swscanf(L"<0b1010>", L"<%b>", &i));
3179 EXPECT_EQ(0b1010, i);
3180 EXPECT_EQ(2, swscanf(L"-0b", L"%i%c", &i, &ch));
3181 EXPECT_EQ(0, i);
3182 EXPECT_EQ('b', ch);
Elliott Hughes1f462de2022-08-05 22:51:05 +00003183}