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