1 /*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <libgen.h>
20 #include <limits.h>
21 #include <math.h>
22 #include <pthread.h>
23 #include <stdint.h>
24 #include <stdlib.h>
25 #include <sys/types.h>
26 #include <sys/wait.h>
27 #include <unistd.h>
28
29 #include <limits>
30 #include <string>
31
32 #include <android-base/file.h>
33 #include <android-base/macros.h>
34 #include <gtest/gtest.h>
35
36 #include "BionicDeathTest.h"
37 #include "math_data_test.h"
38 #include "utils.h"
39
40 using namespace std::string_literals;
41
42 template <typename T = int (*)(char*)>
43 class GenericTemporaryFile {
44 public:
GenericTemporaryFile(T mk_fn=mkstemp)45 explicit GenericTemporaryFile(T mk_fn = mkstemp) : mk_fn_(mk_fn) {
46 // Since we might be running on the host or the target, and if we're
47 // running on the host we might be running under bionic or glibc,
48 // let's just try both possible temporary directories and take the
49 // first one that works.
50 init("/data/local/tmp");
51 if (fd == -1) {
52 init("/tmp");
53 }
54 }
55
~GenericTemporaryFile()56 ~GenericTemporaryFile() {
57 close(fd);
58 unlink(path);
59 }
60
61 int fd;
62 char path[1024];
63
64 private:
65 T mk_fn_;
66
init(const char * tmp_dir)67 void init(const char* tmp_dir) {
68 snprintf(path, sizeof(path), "%s/TemporaryFile-XXXXXX", tmp_dir);
69 fd = mk_fn_(path);
70 }
71
72 DISALLOW_COPY_AND_ASSIGN(GenericTemporaryFile);
73 };
74
75 typedef GenericTemporaryFile<> MyTemporaryFile;
76
77 // The random number generator tests all set the seed, get four values, reset the seed and check
78 // that they get the first two values repeated, and then reset the seed and check two more values
79 // to rule out the possibility that we're just going round a cycle of four values.
80 // TODO: factor this out.
81
TEST(stdlib,drand48)82 TEST(stdlib, drand48) {
83 srand48(0x01020304);
84 EXPECT_DOUBLE_EQ(0.65619299195623526, drand48());
85 EXPECT_DOUBLE_EQ(0.18522597229772941, drand48());
86 EXPECT_DOUBLE_EQ(0.42015087072844537, drand48());
87 EXPECT_DOUBLE_EQ(0.061637783047395089, drand48());
88 srand48(0x01020304);
89 EXPECT_DOUBLE_EQ(0.65619299195623526, drand48());
90 EXPECT_DOUBLE_EQ(0.18522597229772941, drand48());
91 srand48(0x01020304);
92 EXPECT_DOUBLE_EQ(0.65619299195623526, drand48());
93 EXPECT_DOUBLE_EQ(0.18522597229772941, drand48());
94 }
95
TEST(stdlib,erand48)96 TEST(stdlib, erand48) {
97 const unsigned short seed[3] = { 0x330e, 0xabcd, 0x1234 };
98 unsigned short xsubi[3];
99 memcpy(xsubi, seed, sizeof(seed));
100 EXPECT_DOUBLE_EQ(0.39646477376027534, erand48(xsubi));
101 EXPECT_DOUBLE_EQ(0.84048536941142515, erand48(xsubi));
102 EXPECT_DOUBLE_EQ(0.35333609724524351, erand48(xsubi));
103 EXPECT_DOUBLE_EQ(0.44658343479654405, erand48(xsubi));
104 memcpy(xsubi, seed, sizeof(seed));
105 EXPECT_DOUBLE_EQ(0.39646477376027534, erand48(xsubi));
106 EXPECT_DOUBLE_EQ(0.84048536941142515, erand48(xsubi));
107 memcpy(xsubi, seed, sizeof(seed));
108 EXPECT_DOUBLE_EQ(0.39646477376027534, erand48(xsubi));
109 EXPECT_DOUBLE_EQ(0.84048536941142515, erand48(xsubi));
110 }
111
TEST(stdlib,lcong48)112 TEST(stdlib, lcong48) {
113 unsigned short p[7] = { 0x0102, 0x0304, 0x0506, 0x0708, 0x090a, 0x0b0c, 0x0d0e };
114 lcong48(p);
115 EXPECT_EQ(1531389981, lrand48());
116 EXPECT_EQ(1598801533, lrand48());
117 EXPECT_EQ(2080534853, lrand48());
118 EXPECT_EQ(1102488897, lrand48());
119 lcong48(p);
120 EXPECT_EQ(1531389981, lrand48());
121 EXPECT_EQ(1598801533, lrand48());
122 lcong48(p);
123 EXPECT_EQ(1531389981, lrand48());
124 EXPECT_EQ(1598801533, lrand48());
125 }
126
TEST(stdlib,lrand48)127 TEST(stdlib, lrand48) {
128 srand48(0x01020304);
129 EXPECT_EQ(1409163720, lrand48());
130 EXPECT_EQ(397769746, lrand48());
131 EXPECT_EQ(902267124, lrand48());
132 EXPECT_EQ(132366131, lrand48());
133 srand48(0x01020304);
134 EXPECT_EQ(1409163720, lrand48());
135 EXPECT_EQ(397769746, lrand48());
136 srand48(0x01020304);
137 EXPECT_EQ(1409163720, lrand48());
138 EXPECT_EQ(397769746, lrand48());
139 }
140
TEST(stdlib,random)141 TEST(stdlib, random) {
142 srandom(0x01020304);
143 EXPECT_EQ(55436735, random());
144 EXPECT_EQ(1399865117, random());
145 EXPECT_EQ(2032643283, random());
146 EXPECT_EQ(571329216, random());
147 srandom(0x01020304);
148 EXPECT_EQ(55436735, random());
149 EXPECT_EQ(1399865117, random());
150 srandom(0x01020304);
151 EXPECT_EQ(55436735, random());
152 EXPECT_EQ(1399865117, random());
153 }
154
TEST(stdlib,rand)155 TEST(stdlib, rand) {
156 srand(0x01020304);
157 EXPECT_EQ(55436735, rand());
158 EXPECT_EQ(1399865117, rand());
159 EXPECT_EQ(2032643283, rand());
160 EXPECT_EQ(571329216, rand());
161 srand(0x01020304);
162 EXPECT_EQ(55436735, rand());
163 EXPECT_EQ(1399865117, rand());
164 srand(0x01020304);
165 EXPECT_EQ(55436735, rand());
166 EXPECT_EQ(1399865117, rand());
167 }
168
TEST(stdlib,mrand48)169 TEST(stdlib, mrand48) {
170 srand48(0x01020304);
171 EXPECT_EQ(-1476639856, mrand48());
172 EXPECT_EQ(795539493, mrand48());
173 EXPECT_EQ(1804534249, mrand48());
174 EXPECT_EQ(264732262, mrand48());
175 srand48(0x01020304);
176 EXPECT_EQ(-1476639856, mrand48());
177 EXPECT_EQ(795539493, mrand48());
178 srand48(0x01020304);
179 EXPECT_EQ(-1476639856, mrand48());
180 EXPECT_EQ(795539493, mrand48());
181 }
182
TEST(stdlib,jrand48_distribution)183 TEST(stdlib, jrand48_distribution) {
184 const int iterations = 4096;
185 const int pivot_low = 1536;
186 const int pivot_high = 2560;
187
188 unsigned short xsubi[3];
189 int bits[32] = {};
190
191 for (int iter = 0; iter < iterations; ++iter) {
192 long rand_val = jrand48(xsubi);
193 for (int bit = 0; bit < 32; ++bit) {
194 bits[bit] += (static_cast<unsigned long>(rand_val) >> bit) & 0x01;
195 }
196 }
197
198 // Check that bit probability is uniform
199 for (int bit = 0; bit < 32; ++bit) {
200 EXPECT_TRUE((pivot_low <= bits[bit]) && (bits[bit] <= pivot_high));
201 }
202 }
203
TEST(stdlib,mrand48_distribution)204 TEST(stdlib, mrand48_distribution) {
205 const int iterations = 4096;
206 const int pivot_low = 1536;
207 const int pivot_high = 2560;
208
209 int bits[32] = {};
210
211 for (int iter = 0; iter < iterations; ++iter) {
212 long rand_val = mrand48();
213 for (int bit = 0; bit < 32; ++bit) {
214 bits[bit] += (static_cast<unsigned long>(rand_val) >> bit) & 0x01;
215 }
216 }
217
218 // Check that bit probability is uniform
219 for (int bit = 0; bit < 32; ++bit) {
220 EXPECT_TRUE((pivot_low <= bits[bit]) && (bits[bit] <= pivot_high));
221 }
222 }
223
TEST(stdlib,posix_memalign_sweep)224 TEST(stdlib, posix_memalign_sweep) {
225 SKIP_WITH_HWASAN;
226 void* ptr;
227
228 // These should all fail.
229 for (size_t align = 0; align < sizeof(long); align++) {
230 ASSERT_EQ(EINVAL, posix_memalign(&ptr, align, 256))
231 << "Unexpected value at align " << align;
232 }
233
234 // Verify powers of 2 up to 2048 allocate, and verify that all other
235 // alignment values between the powers of 2 fail.
236 size_t last_align = sizeof(long);
237 for (size_t align = sizeof(long); align <= 2048; align <<= 1) {
238 // Try all of the non power of 2 values from the last until this value.
239 for (size_t fail_align = last_align + 1; fail_align < align; fail_align++) {
240 ASSERT_EQ(EINVAL, posix_memalign(&ptr, fail_align, 256))
241 << "Unexpected success at align " << fail_align;
242 }
243 ASSERT_EQ(0, posix_memalign(&ptr, align, 256))
244 << "Unexpected failure at align " << align;
245 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(ptr) & (align - 1))
246 << "Did not return a valid aligned ptr " << ptr << " expected alignment " << align;
247 free(ptr);
248 last_align = align;
249 }
250 }
251
TEST(stdlib,posix_memalign_various_sizes)252 TEST(stdlib, posix_memalign_various_sizes) {
253 std::vector<size_t> sizes{1, 4, 8, 256, 1024, 65000, 128000, 256000, 1000000};
254 for (auto size : sizes) {
255 void* ptr;
256 ASSERT_EQ(0, posix_memalign(&ptr, 16, 1))
257 << "posix_memalign failed at size " << size;
258 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(ptr) & 0xf)
259 << "Pointer not aligned at size " << size << " ptr " << ptr;
260 free(ptr);
261 }
262 }
263
TEST(stdlib,posix_memalign_overflow)264 TEST(stdlib, posix_memalign_overflow) {
265 SKIP_WITH_HWASAN;
266 void* ptr;
267 ASSERT_NE(0, posix_memalign(&ptr, 16, SIZE_MAX));
268 }
269
TEST(stdlib,aligned_alloc_sweep)270 TEST(stdlib, aligned_alloc_sweep) {
271 SKIP_WITH_HWASAN;
272 // Verify powers of 2 up to 2048 allocate, and verify that all other
273 // alignment values between the powers of 2 fail.
274 size_t last_align = 1;
275 for (size_t align = 1; align <= 2048; align <<= 1) {
276 // Try all of the non power of 2 values from the last until this value.
277 for (size_t fail_align = last_align + 1; fail_align < align; fail_align++) {
278 ASSERT_TRUE(aligned_alloc(fail_align, fail_align) == nullptr)
279 << "Unexpected success at align " << fail_align;
280 ASSERT_EQ(EINVAL, errno) << "Unexpected errno at align " << fail_align;
281 }
282 void* ptr = aligned_alloc(align, 2 * align);
283 ASSERT_TRUE(ptr != nullptr) << "Unexpected failure at align " << align;
284 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(ptr) & (align - 1))
285 << "Did not return a valid aligned ptr " << ptr << " expected alignment " << align;
286 free(ptr);
287 last_align = align;
288 }
289 }
290
TEST(stdlib,aligned_alloc_overflow)291 TEST(stdlib, aligned_alloc_overflow) {
292 SKIP_WITH_HWASAN;
293 ASSERT_TRUE(aligned_alloc(16, SIZE_MAX) == nullptr);
294 }
295
TEST(stdlib,aligned_alloc_size_not_multiple_of_alignment)296 TEST(stdlib, aligned_alloc_size_not_multiple_of_alignment) {
297 SKIP_WITH_HWASAN;
298
299 ASSERT_TRUE(aligned_alloc(2048, 1) == nullptr);
300 ASSERT_TRUE(aligned_alloc(4, 3) == nullptr);
301 ASSERT_TRUE(aligned_alloc(4, 7) == nullptr);
302 ASSERT_TRUE(aligned_alloc(16, 8) == nullptr);
303 }
304
TEST(stdlib,realpath__NULL_filename)305 TEST(stdlib, realpath__NULL_filename) {
306 errno = 0;
307 // Work around the compile-time error generated by FORTIFY here.
308 const char* path = nullptr;
309 char* p = realpath(path, nullptr);
310 ASSERT_TRUE(p == nullptr);
311 ASSERT_EQ(EINVAL, errno);
312 }
313
TEST(stdlib,realpath__empty_filename)314 TEST(stdlib, realpath__empty_filename) {
315 errno = 0;
316 char* p = realpath("", nullptr);
317 ASSERT_TRUE(p == nullptr);
318 ASSERT_EQ(ENOENT, errno);
319 }
320
TEST(stdlib,realpath__ENOENT)321 TEST(stdlib, realpath__ENOENT) {
322 errno = 0;
323 char* p = realpath("/this/directory/path/almost/certainly/does/not/exist", nullptr);
324 ASSERT_TRUE(p == nullptr);
325 ASSERT_EQ(ENOENT, errno);
326 }
327
TEST(stdlib,realpath__ELOOP)328 TEST(stdlib, realpath__ELOOP) {
329 TemporaryDir td;
330 std::string link = std::string(td.path) + "/loop";
331 ASSERT_EQ(0, symlink(link.c_str(), link.c_str()));
332
333 errno = 0;
334 char* p = realpath(link.c_str(), nullptr);
335 ASSERT_TRUE(p == nullptr);
336 ASSERT_EQ(ELOOP, errno);
337 }
338
TEST(stdlib,realpath__component_after_non_directory)339 TEST(stdlib, realpath__component_after_non_directory) {
340 errno = 0;
341 char* p = realpath("/dev/null/.", nullptr);
342 ASSERT_TRUE(p == nullptr);
343 ASSERT_EQ(ENOTDIR, errno);
344
345 errno = 0;
346 p = realpath("/dev/null/..", nullptr);
347 ASSERT_TRUE(p == nullptr);
348 ASSERT_EQ(ENOTDIR, errno);
349 }
350
TEST(stdlib,realpath)351 TEST(stdlib, realpath) {
352 // Get the name of this executable.
353 char executable_path[PATH_MAX];
354 int rc = readlink("/proc/self/exe", executable_path, sizeof(executable_path));
355 ASSERT_NE(rc, -1);
356 executable_path[rc] = '\0';
357
358 char buf[PATH_MAX + 1];
359 char* p = realpath("/proc/self/exe", buf);
360 ASSERT_STREQ(executable_path, p);
361
362 p = realpath("/proc/self/exe", nullptr);
363 ASSERT_STREQ(executable_path, p);
364 free(p);
365 }
366
TEST(stdlib,realpath__dot)367 TEST(stdlib, realpath__dot) {
368 char* p = realpath("/proc/./version", nullptr);
369 ASSERT_STREQ("/proc/version", p);
370 free(p);
371 }
372
TEST(stdlib,realpath__dot_dot)373 TEST(stdlib, realpath__dot_dot) {
374 char* p = realpath("/dev/../proc/version", nullptr);
375 ASSERT_STREQ("/proc/version", p);
376 free(p);
377 }
378
TEST(stdlib,realpath__deleted)379 TEST(stdlib, realpath__deleted) {
380 TemporaryDir td;
381
382 // Create a file "A".
383 std::string A_path = td.path + "/A"s;
384 ASSERT_TRUE(android::base::WriteStringToFile("test\n", A_path));
385
386 // Get an O_PATH fd for it.
387 android::base::unique_fd fd(open(A_path.c_str(), O_PATH));
388 ASSERT_NE(fd, -1);
389
390 // Create a file "A (deleted)".
391 android::base::unique_fd fd2(open((td.path + "/A (deleted)"s).c_str(),
392 O_CREAT | O_TRUNC | O_WRONLY, 0644));
393 ASSERT_NE(fd2, -1);
394
395 // Delete "A".
396 ASSERT_EQ(0, unlink(A_path.c_str()));
397
398 // Now realpath() on the O_PATH fd, and check we *don't* get "A (deleted)".
399 std::string path = android::base::StringPrintf("/proc/%d/fd/%d", static_cast<int>(getpid()),
400 fd.get());
401 errno = 0;
402 char* result = realpath(path.c_str(), nullptr);
403 ASSERT_EQ(nullptr, result) << result;
404 ASSERT_EQ(ENOENT, errno);
405 free(result);
406 }
407
TEST(stdlib,qsort)408 TEST(stdlib, qsort) {
409 struct s {
410 char name[16];
411 static int comparator(const void* lhs, const void* rhs) {
412 return strcmp(reinterpret_cast<const s*>(lhs)->name, reinterpret_cast<const s*>(rhs)->name);
413 }
414 };
415 s entries[3];
416 strcpy(entries[0].name, "charlie");
417 strcpy(entries[1].name, "bravo");
418 strcpy(entries[2].name, "alpha");
419
420 qsort(entries, 3, sizeof(s), s::comparator);
421 ASSERT_STREQ("alpha", entries[0].name);
422 ASSERT_STREQ("bravo", entries[1].name);
423 ASSERT_STREQ("charlie", entries[2].name);
424
425 qsort(entries, 3, sizeof(s), s::comparator);
426 ASSERT_STREQ("alpha", entries[0].name);
427 ASSERT_STREQ("bravo", entries[1].name);
428 ASSERT_STREQ("charlie", entries[2].name);
429 }
430
TestBug57421_child(void * arg)431 static void* TestBug57421_child(void* arg) {
432 pthread_t main_thread = reinterpret_cast<pthread_t>(arg);
433 pthread_join(main_thread, nullptr);
434 char* value = getenv("ENVIRONMENT_VARIABLE");
435 if (value == nullptr) {
436 setenv("ENVIRONMENT_VARIABLE", "value", 1);
437 }
438 return nullptr;
439 }
440
TestBug57421_main()441 static void TestBug57421_main() {
442 pthread_t t;
443 ASSERT_EQ(0, pthread_create(&t, nullptr, TestBug57421_child, reinterpret_cast<void*>(pthread_self())));
444 pthread_exit(nullptr);
445 }
446
447 // Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
448 // run this test (which exits normally) in its own process.
449
450 class stdlib_DeathTest : public BionicDeathTest {};
451
TEST_F(stdlib_DeathTest,getenv_after_main_thread_exits)452 TEST_F(stdlib_DeathTest, getenv_after_main_thread_exits) {
453 // https://code.google.com/p/android/issues/detail?id=57421
454 ASSERT_EXIT(TestBug57421_main(), ::testing::ExitedWithCode(0), "");
455 }
456
TEST(stdlib,mkostemp64)457 TEST(stdlib, mkostemp64) {
458 MyTemporaryFile tf([](char* path) { return mkostemp64(path, O_CLOEXEC); });
459 AssertCloseOnExec(tf.fd, true);
460 }
461
TEST(stdlib,mkostemp)462 TEST(stdlib, mkostemp) {
463 MyTemporaryFile tf([](char* path) { return mkostemp(path, O_CLOEXEC); });
464 AssertCloseOnExec(tf.fd, true);
465 }
466
TEST(stdlib,mkstemp64)467 TEST(stdlib, mkstemp64) {
468 MyTemporaryFile tf(mkstemp64);
469 struct stat64 sb;
470 ASSERT_EQ(0, fstat64(tf.fd, &sb));
471 ASSERT_EQ(O_LARGEFILE, fcntl(tf.fd, F_GETFL) & O_LARGEFILE);
472 }
473
TEST(stdlib,mkstemp)474 TEST(stdlib, mkstemp) {
475 MyTemporaryFile tf(mkstemp);
476 struct stat sb;
477 ASSERT_EQ(0, fstat(tf.fd, &sb));
478 }
479
TEST(stdlib,system)480 TEST(stdlib, system) {
481 int status;
482
483 status = system("exit 0");
484 ASSERT_TRUE(WIFEXITED(status));
485 ASSERT_EQ(0, WEXITSTATUS(status));
486
487 status = system("exit 1");
488 ASSERT_TRUE(WIFEXITED(status));
489 ASSERT_EQ(1, WEXITSTATUS(status));
490 }
491
TEST(stdlib,atof)492 TEST(stdlib, atof) {
493 ASSERT_DOUBLE_EQ(1.23, atof("1.23"));
494 }
495
496 template <typename T>
CheckStrToFloat(T fn (const char * s,char ** end))497 static void CheckStrToFloat(T fn(const char* s, char** end)) {
498 FpUlpEq<0, T> pred;
499
500 EXPECT_PRED_FORMAT2(pred, 9.0, fn("9.0", nullptr));
501 EXPECT_PRED_FORMAT2(pred, 9.0, fn("0.9e1", nullptr));
502 EXPECT_PRED_FORMAT2(pred, 9.0, fn("0x1.2p3", nullptr));
503
504 const char* s = " \t\v\f\r\n9.0";
505 char* p;
506 EXPECT_PRED_FORMAT2(pred, 9.0, fn(s, &p));
507 EXPECT_EQ(s + strlen(s), p);
508
509 EXPECT_TRUE(isnan(fn("+nan", nullptr)));
510 EXPECT_TRUE(isnan(fn("nan", nullptr)));
511 EXPECT_TRUE(isnan(fn("-nan", nullptr)));
512
513 EXPECT_TRUE(isnan(fn("+nan(0xff)", nullptr)));
514 EXPECT_TRUE(isnan(fn("nan(0xff)", nullptr)));
515 EXPECT_TRUE(isnan(fn("-nan(0xff)", nullptr)));
516
517 EXPECT_TRUE(isnan(fn("+nanny", &p)));
518 EXPECT_STREQ("ny", p);
519 EXPECT_TRUE(isnan(fn("nanny", &p)));
520 EXPECT_STREQ("ny", p);
521 EXPECT_TRUE(isnan(fn("-nanny", &p)));
522 EXPECT_STREQ("ny", p);
523
524 EXPECT_EQ(0, fn("muppet", &p));
525 EXPECT_STREQ("muppet", p);
526 EXPECT_EQ(0, fn(" muppet", &p));
527 EXPECT_STREQ(" muppet", p);
528
529 EXPECT_EQ(std::numeric_limits<T>::infinity(), fn("+inf", nullptr));
530 EXPECT_EQ(std::numeric_limits<T>::infinity(), fn("inf", nullptr));
531 EXPECT_EQ(-std::numeric_limits<T>::infinity(), fn("-inf", nullptr));
532
533 EXPECT_EQ(std::numeric_limits<T>::infinity(), fn("+infinity", nullptr));
534 EXPECT_EQ(std::numeric_limits<T>::infinity(), fn("infinity", nullptr));
535 EXPECT_EQ(-std::numeric_limits<T>::infinity(), fn("-infinity", nullptr));
536
537 EXPECT_EQ(std::numeric_limits<T>::infinity(), fn("+infinitude", &p));
538 EXPECT_STREQ("initude", p);
539 EXPECT_EQ(std::numeric_limits<T>::infinity(), fn("infinitude", &p));
540 EXPECT_STREQ("initude", p);
541 EXPECT_EQ(-std::numeric_limits<T>::infinity(), fn("-infinitude", &p));
542 EXPECT_STREQ("initude", p);
543
544 // Check case-insensitivity.
545 EXPECT_EQ(std::numeric_limits<T>::infinity(), fn("InFiNiTy", nullptr));
546 EXPECT_TRUE(isnan(fn("NaN", nullptr)));
547 }
548
TEST(stdlib,strtod)549 TEST(stdlib, strtod) {
550 CheckStrToFloat(strtod);
551 }
552
TEST(stdlib,strtof)553 TEST(stdlib, strtof) {
554 CheckStrToFloat(strtof);
555 }
556
TEST(stdlib,strtold)557 TEST(stdlib, strtold) {
558 CheckStrToFloat(strtold);
559 }
560
TEST(stdlib,strtof_2206701)561 TEST(stdlib, strtof_2206701) {
562 ASSERT_EQ(0.0f, strtof("7.0064923216240853546186479164495e-46", nullptr));
563 ASSERT_EQ(1.4e-45f, strtof("7.0064923216240853546186479164496e-46", nullptr));
564 }
565
TEST(stdlib,strtod_largest_subnormal)566 TEST(stdlib, strtod_largest_subnormal) {
567 // This value has been known to cause javac and java to infinite loop.
568 // http://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/
569 ASSERT_EQ(2.2250738585072014e-308, strtod("2.2250738585072012e-308", nullptr));
570 ASSERT_EQ(2.2250738585072014e-308, strtod("0.00022250738585072012e-304", nullptr));
571 ASSERT_EQ(2.2250738585072014e-308, strtod("00000002.2250738585072012e-308", nullptr));
572 ASSERT_EQ(2.2250738585072014e-308, strtod("2.225073858507201200000e-308", nullptr));
573 ASSERT_EQ(2.2250738585072014e-308, strtod("2.2250738585072012e-00308", nullptr));
574 ASSERT_EQ(2.2250738585072014e-308, strtod("2.22507385850720129978001e-308", nullptr));
575 ASSERT_EQ(-2.2250738585072014e-308, strtod("-2.2250738585072012e-308", nullptr));
576 }
577
TEST(stdlib,quick_exit)578 TEST(stdlib, quick_exit) {
579 pid_t pid = fork();
580 ASSERT_NE(-1, pid) << strerror(errno);
581
582 if (pid == 0) {
583 quick_exit(99);
584 }
585
586 AssertChildExited(pid, 99);
587 }
588
589 static int quick_exit_status = 0;
590
quick_exit_1(void)591 static void quick_exit_1(void) {
592 ASSERT_EQ(quick_exit_status, 0);
593 quick_exit_status = 1;
594 }
595
quick_exit_2(void)596 static void quick_exit_2(void) {
597 ASSERT_EQ(quick_exit_status, 1);
598 }
599
not_run(void)600 static void not_run(void) {
601 FAIL();
602 }
603
TEST(stdlib,at_quick_exit)604 TEST(stdlib, at_quick_exit) {
605 pid_t pid = fork();
606 ASSERT_NE(-1, pid) << strerror(errno);
607
608 if (pid == 0) {
609 ASSERT_EQ(at_quick_exit(quick_exit_2), 0);
610 ASSERT_EQ(at_quick_exit(quick_exit_1), 0);
611 atexit(not_run);
612 quick_exit(99);
613 }
614
615 AssertChildExited(pid, 99);
616 }
617
TEST(unistd,_Exit)618 TEST(unistd, _Exit) {
619 pid_t pid = fork();
620 ASSERT_NE(-1, pid) << strerror(errno);
621
622 if (pid == 0) {
623 _Exit(99);
624 }
625
626 AssertChildExited(pid, 99);
627 }
628
TEST(stdlib,pty_smoke)629 TEST(stdlib, pty_smoke) {
630 // getpt returns a pty with O_RDWR|O_NOCTTY.
631 int fd = getpt();
632 ASSERT_NE(-1, fd);
633
634 // grantpt is a no-op.
635 ASSERT_EQ(0, grantpt(fd));
636
637 // ptsname_r should start "/dev/pts/".
638 char name_r[128];
639 ASSERT_EQ(0, ptsname_r(fd, name_r, sizeof(name_r)));
640 name_r[9] = 0;
641 ASSERT_STREQ("/dev/pts/", name_r);
642
643 close(fd);
644 }
645
TEST(stdlib,posix_openpt)646 TEST(stdlib, posix_openpt) {
647 int fd = posix_openpt(O_RDWR|O_NOCTTY|O_CLOEXEC);
648 ASSERT_NE(-1, fd);
649 close(fd);
650 }
651
TEST(stdlib,ptsname_r_ENOTTY)652 TEST(stdlib, ptsname_r_ENOTTY) {
653 errno = 0;
654 char buf[128];
655 ASSERT_EQ(ENOTTY, ptsname_r(STDOUT_FILENO, buf, sizeof(buf)));
656 ASSERT_EQ(ENOTTY, errno);
657 }
658
TEST(stdlib,ptsname_r_EINVAL)659 TEST(stdlib, ptsname_r_EINVAL) {
660 int fd = getpt();
661 ASSERT_NE(-1, fd);
662 errno = 0;
663 char* buf = nullptr;
664 ASSERT_EQ(EINVAL, ptsname_r(fd, buf, 128));
665 ASSERT_EQ(EINVAL, errno);
666 close(fd);
667 }
668
TEST(stdlib,ptsname_r_ERANGE)669 TEST(stdlib, ptsname_r_ERANGE) {
670 int fd = getpt();
671 ASSERT_NE(-1, fd);
672 errno = 0;
673 char buf[1];
674 ASSERT_EQ(ERANGE, ptsname_r(fd, buf, sizeof(buf)));
675 ASSERT_EQ(ERANGE, errno);
676 close(fd);
677 }
678
TEST(stdlib,ttyname)679 TEST(stdlib, ttyname) {
680 int fd = getpt();
681 ASSERT_NE(-1, fd);
682
683 // ttyname returns "/dev/ptmx" for a pty.
684 ASSERT_STREQ("/dev/ptmx", ttyname(fd));
685
686 close(fd);
687 }
688
TEST(stdlib,ttyname_r)689 TEST(stdlib, ttyname_r) {
690 int fd = getpt();
691 ASSERT_NE(-1, fd);
692
693 // ttyname_r returns "/dev/ptmx" for a pty.
694 char name_r[128];
695 ASSERT_EQ(0, ttyname_r(fd, name_r, sizeof(name_r)));
696 ASSERT_STREQ("/dev/ptmx", name_r);
697
698 close(fd);
699 }
700
TEST(stdlib,ttyname_r_ENOTTY)701 TEST(stdlib, ttyname_r_ENOTTY) {
702 int fd = open("/dev/null", O_WRONLY);
703 errno = 0;
704 char buf[128];
705 ASSERT_EQ(ENOTTY, ttyname_r(fd, buf, sizeof(buf)));
706 ASSERT_EQ(ENOTTY, errno);
707 close(fd);
708 }
709
TEST(stdlib,ttyname_r_EINVAL)710 TEST(stdlib, ttyname_r_EINVAL) {
711 int fd = getpt();
712 ASSERT_NE(-1, fd);
713 errno = 0;
714 char* buf = nullptr;
715 ASSERT_EQ(EINVAL, ttyname_r(fd, buf, 128));
716 ASSERT_EQ(EINVAL, errno);
717 close(fd);
718 }
719
TEST(stdlib,ttyname_r_ERANGE)720 TEST(stdlib, ttyname_r_ERANGE) {
721 int fd = getpt();
722 ASSERT_NE(-1, fd);
723 errno = 0;
724 char buf[1];
725 ASSERT_EQ(ERANGE, ttyname_r(fd, buf, sizeof(buf)));
726 ASSERT_EQ(ERANGE, errno);
727 close(fd);
728 }
729
TEST(stdlib,unlockpt_ENOTTY)730 TEST(stdlib, unlockpt_ENOTTY) {
731 int fd = open("/dev/null", O_WRONLY);
732 errno = 0;
733 ASSERT_EQ(-1, unlockpt(fd));
734 ASSERT_EQ(ENOTTY, errno);
735 close(fd);
736 }
737
TEST(stdlib,getsubopt)738 TEST(stdlib, getsubopt) {
739 char* const tokens[] = {
740 const_cast<char*>("a"),
741 const_cast<char*>("b"),
742 const_cast<char*>("foo"),
743 nullptr
744 };
745 std::string input = "a,b,foo=bar,a,unknown";
746 char* subopts = &input[0];
747 char* value = nullptr;
748
749 ASSERT_EQ(0, getsubopt(&subopts, tokens, &value));
750 ASSERT_EQ(nullptr, value);
751 ASSERT_EQ(1, getsubopt(&subopts, tokens, &value));
752 ASSERT_EQ(nullptr, value);
753 ASSERT_EQ(2, getsubopt(&subopts, tokens, &value));
754 ASSERT_STREQ("bar", value);
755 ASSERT_EQ(0, getsubopt(&subopts, tokens, &value));
756 ASSERT_EQ(nullptr, value);
757
758 ASSERT_EQ(-1, getsubopt(&subopts, tokens, &value));
759 }
760
TEST(stdlib,mblen)761 TEST(stdlib, mblen) {
762 // "If s is a null pointer, mblen() shall return a non-zero or 0 value, if character encodings,
763 // respectively, do or do not have state-dependent encodings." We're always UTF-8.
764 EXPECT_EQ(0, mblen(nullptr, 1));
765
766 ASSERT_STREQ("C.UTF-8", setlocale(LC_ALL, "C.UTF-8"));
767
768 // 1-byte UTF-8.
769 EXPECT_EQ(1, mblen("abcdef", 6));
770 // 2-byte UTF-8.
771 EXPECT_EQ(2, mblen("\xc2\xa2" "cdef", 6));
772 // 3-byte UTF-8.
773 EXPECT_EQ(3, mblen("\xe2\x82\xac" "def", 6));
774 // 4-byte UTF-8.
775 EXPECT_EQ(4, mblen("\xf0\xa4\xad\xa2" "ef", 6));
776
777 // Illegal over-long sequence.
778 ASSERT_EQ(-1, mblen("\xf0\x82\x82\xac" "ef", 6));
779
780 // "mblen() shall ... return 0 (if s points to the null byte)".
781 EXPECT_EQ(0, mblen("", 1));
782 }
783
784 template <typename T>
CheckStrToInt(T fn (const char * s,char ** end,int base))785 static void CheckStrToInt(T fn(const char* s, char** end, int base)) {
786 char* end_p;
787
788 // Negative base => invalid.
789 errno = 0;
790 ASSERT_EQ(T(0), fn("123", &end_p, -1));
791 ASSERT_EQ(EINVAL, errno);
792
793 // Base 1 => invalid (base 0 means "please guess").
794 errno = 0;
795 ASSERT_EQ(T(0), fn("123", &end_p, 1));
796 ASSERT_EQ(EINVAL, errno);
797
798 // Base > 36 => invalid.
799 errno = 0;
800 ASSERT_EQ(T(0), fn("123", &end_p, 37));
801 ASSERT_EQ(EINVAL, errno);
802
803 // If we see "0x" *not* followed by a hex digit, we shouldn't swallow the 'x'.
804 ASSERT_EQ(T(0), fn("0xy", &end_p, 16));
805 ASSERT_EQ('x', *end_p);
806
807 if (std::numeric_limits<T>::is_signed) {
808 // Minimum (such as -128).
809 std::string min{std::to_string(std::numeric_limits<T>::min())};
810 end_p = nullptr;
811 errno = 0;
812 ASSERT_EQ(std::numeric_limits<T>::min(), fn(min.c_str(), &end_p, 0));
813 ASSERT_EQ(0, errno);
814 ASSERT_EQ('\0', *end_p);
815 // Too negative (such as -129).
816 min.back() = (min.back() + 1);
817 end_p = nullptr;
818 errno = 0;
819 ASSERT_EQ(std::numeric_limits<T>::min(), fn(min.c_str(), &end_p, 0));
820 ASSERT_EQ(ERANGE, errno);
821 ASSERT_EQ('\0', *end_p);
822 }
823
824 // Maximum (such as 127).
825 std::string max{std::to_string(std::numeric_limits<T>::max())};
826 end_p = nullptr;
827 errno = 0;
828 ASSERT_EQ(std::numeric_limits<T>::max(), fn(max.c_str(), &end_p, 0));
829 ASSERT_EQ(0, errno);
830 ASSERT_EQ('\0', *end_p);
831 // Too positive (such as 128).
832 max.back() = (max.back() + 1);
833 end_p = nullptr;
834 errno = 0;
835 ASSERT_EQ(std::numeric_limits<T>::max(), fn(max.c_str(), &end_p, 0));
836 ASSERT_EQ(ERANGE, errno);
837 ASSERT_EQ('\0', *end_p);
838
839 // In case of overflow, strto* leaves us pointing past the end of the number,
840 // not at the digit that overflowed.
841 end_p = nullptr;
842 errno = 0;
843 ASSERT_EQ(std::numeric_limits<T>::max(),
844 fn("99999999999999999999999999999999999999999999999999999abc", &end_p, 0));
845 ASSERT_EQ(ERANGE, errno);
846 ASSERT_STREQ("abc", end_p);
847 if (std::numeric_limits<T>::is_signed) {
848 end_p = nullptr;
849 errno = 0;
850 ASSERT_EQ(std::numeric_limits<T>::min(),
851 fn("-99999999999999999999999999999999999999999999999999999abc", &end_p, 0));
852 ASSERT_EQ(ERANGE, errno);
853 ASSERT_STREQ("abc", end_p);
854 }
855 }
856
TEST(stdlib,strtol_smoke)857 TEST(stdlib, strtol_smoke) {
858 CheckStrToInt(strtol);
859 }
860
TEST(stdlib,strtoll_smoke)861 TEST(stdlib, strtoll_smoke) {
862 CheckStrToInt(strtoll);
863 }
864
TEST(stdlib,strtoul_smoke)865 TEST(stdlib, strtoul_smoke) {
866 CheckStrToInt(strtoul);
867 }
868
TEST(stdlib,strtoull_smoke)869 TEST(stdlib, strtoull_smoke) {
870 CheckStrToInt(strtoull);
871 }
872
TEST(stdlib,strtoimax_smoke)873 TEST(stdlib, strtoimax_smoke) {
874 CheckStrToInt(strtoimax);
875 }
876
TEST(stdlib,strtoumax_smoke)877 TEST(stdlib, strtoumax_smoke) {
878 CheckStrToInt(strtoumax);
879 }
880
TEST(stdlib,abs)881 TEST(stdlib, abs) {
882 ASSERT_EQ(INT_MAX, abs(-INT_MAX));
883 ASSERT_EQ(INT_MAX, abs(INT_MAX));
884 }
885
TEST(stdlib,labs)886 TEST(stdlib, labs) {
887 ASSERT_EQ(LONG_MAX, labs(-LONG_MAX));
888 ASSERT_EQ(LONG_MAX, labs(LONG_MAX));
889 }
890
TEST(stdlib,llabs)891 TEST(stdlib, llabs) {
892 ASSERT_EQ(LLONG_MAX, llabs(-LLONG_MAX));
893 ASSERT_EQ(LLONG_MAX, llabs(LLONG_MAX));
894 }
895
TEST(stdlib,getloadavg)896 TEST(stdlib, getloadavg) {
897 double load[3];
898
899 // The second argument should have been size_t.
900 ASSERT_EQ(-1, getloadavg(load, -1));
901 ASSERT_EQ(-1, getloadavg(load, INT_MIN));
902
903 // Zero is a no-op.
904 ASSERT_EQ(0, getloadavg(load, 0));
905
906 // The Linux kernel doesn't support more than 3 (but you can ask for fewer).
907 ASSERT_EQ(1, getloadavg(load, 1));
908 ASSERT_EQ(2, getloadavg(load, 2));
909 ASSERT_EQ(3, getloadavg(load, 3));
910 ASSERT_EQ(3, getloadavg(load, 4));
911 ASSERT_EQ(3, getloadavg(load, INT_MAX));
912
913 // Read /proc/loadavg and check that it's "close enough".
914 double expected[3];
915 std::unique_ptr<FILE, decltype(&fclose)> fp{fopen("/proc/loadavg", "re"), fclose};
916 ASSERT_EQ(3, fscanf(fp.get(), "%lf %lf %lf", &expected[0], &expected[1], &expected[2]));
917 load[0] = load[1] = load[2] = nan("");
918 ASSERT_EQ(3, getloadavg(load, 3));
919
920 // Check that getloadavg(3) at least overwrote the NaNs.
921 ASSERT_FALSE(isnan(load[0]));
922 ASSERT_FALSE(isnan(load[1]));
923 ASSERT_FALSE(isnan(load[2]));
924 // And that the difference between /proc/loadavg and getloadavg(3) is "small".
925 ASSERT_TRUE(fabs(expected[0] - load[0]) < 0.5) << expected[0] << ' ' << load[0];
926 ASSERT_TRUE(fabs(expected[1] - load[1]) < 0.5) << expected[1] << ' ' << load[1];
927 ASSERT_TRUE(fabs(expected[2] - load[2]) < 0.5) << expected[2] << ' ' << load[2];
928 }
929
TEST(stdlib,getprogname)930 TEST(stdlib, getprogname) {
931 #if defined(__GLIBC__)
932 GTEST_SKIP() << "glibc doesn't have getprogname()";
933 #else
934 // You should always have a name.
935 ASSERT_TRUE(getprogname() != nullptr);
936 // The name should never have a slash in it.
937 ASSERT_TRUE(strchr(getprogname(), '/') == nullptr);
938 #endif
939 }
940
TEST(stdlib,setprogname)941 TEST(stdlib, setprogname) {
942 #if defined(__GLIBC__)
943 GTEST_SKIP() << "glibc doesn't have setprogname()";
944 #else
945 // setprogname() only takes the basename of what you give it.
946 setprogname("/usr/bin/muppet");
947 ASSERT_STREQ("muppet", getprogname());
948 #endif
949 }
950