Update posix_memalign testing.

Move all tests into stdlib_test.cpp since that's where the definition lives
in bionic.

Add a sweep test and a various size test.

Test: Run new unit tests on glibc and angler.
Change-Id: Ief1301f402bea82ce90240500dd6a01636dbdbae
diff --git a/tests/stdlib_test.cpp b/tests/stdlib_test.cpp
index fc17cde..4c4c102 100644
--- a/tests/stdlib_test.cpp
+++ b/tests/stdlib_test.cpp
@@ -138,15 +138,48 @@
   EXPECT_EQ(795539493, mrand48());
 }
 
-TEST(stdlib, posix_memalign) {
-  void* p;
+TEST(stdlib, posix_memalign_sweep) {
+  void* ptr;
 
-  ASSERT_EQ(0, posix_memalign(&p, 512, 128));
-  ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(p) % 512);
-  free(p);
+  // These should all fail.
+  for (size_t align = 0; align < sizeof(long); align++) {
+    ASSERT_EQ(EINVAL, posix_memalign(&ptr, align, 256))
+        << "Unexpected value at align " << align;
+  }
 
-  // Can't align to a non-power of 2.
-  ASSERT_EQ(EINVAL, posix_memalign(&p, 81, 128));
+  // Verify powers of 2 up to 2048 allocate, and verify that all other
+  // alignment values between the powers of 2 fail.
+  size_t last_align = sizeof(long);
+  for (size_t align = sizeof(long); align <= 2048; align <<= 1) {
+    // Try all of the non power of 2 values from the last until this value.
+    for (size_t fail_align = last_align + 1; fail_align < align; fail_align++) {
+      ASSERT_EQ(EINVAL, posix_memalign(&ptr, fail_align, 256))
+          << "Unexpected success at align " << fail_align;
+    }
+    ASSERT_EQ(0, posix_memalign(&ptr, align, 256))
+        << "Unexpected failure at align " << align;
+    ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(ptr) & (align - 1))
+        << "Did not return a valid aligned ptr " << ptr << " expected alignment " << align;
+    free(ptr);
+    last_align = align;
+  }
+}
+
+TEST(stdlib, posix_memalign_various_sizes) {
+  std::vector<size_t> sizes{1, 4, 8, 256, 1024, 65000, 128000, 256000, 1000000};
+  for (auto size : sizes) {
+    void* ptr;
+    ASSERT_EQ(0, posix_memalign(&ptr, 16, 1))
+        << "posix_memalign failed at size " << size;
+    ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(ptr) & 0xf)
+        << "Pointer not aligned at size " << size << " ptr " << ptr;
+    free(ptr);
+  }
+}
+
+TEST(stdlib, posix_memalign_overflow) {
+  void* ptr;
+  ASSERT_NE(0, posix_memalign(&ptr, 16, SIZE_MAX));
 }
 
 TEST(stdlib, realpath__NULL_filename) {