atexit_test.cpp revision 39036f655aee275f307b9557270e1364b0c6ef36
1/* 2 * Copyright (C) 2014 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 <dlfcn.h> 20#include <libgen.h> 21#include <limits.h> 22#include <stdio.h> 23#include <stdint.h> 24 25#include <string> 26 27TEST(atexit, dlclose) { 28#if defined(__BIONIC__) 29 std::string atexit_call_sequence; 30 bool valid_this_in_static_dtor = false; 31 void* handle = dlopen("libtest_atexit.so", RTLD_NOW); 32 ASSERT_TRUE(handle != NULL); 33 34 void* sym = dlsym(handle, "register_atexit"); 35 ASSERT_TRUE(sym != NULL); 36 reinterpret_cast<void (*)(std::string*, bool*)>(sym)(&atexit_call_sequence, &valid_this_in_static_dtor); 37 38 ASSERT_EQ(0, dlclose(handle)); 39 // this test verifies atexit call from atexit handler. as well as the order of calls 40 ASSERT_EQ("Humpty Dumpty sat on a wall", atexit_call_sequence); 41 ASSERT_TRUE(valid_this_in_static_dtor); 42#else // __BIONIC__ 43 GTEST_LOG_(INFO) << "This test does nothing."; 44#endif // __BIONIC__ 45} 46 47class TestMainStaticDtorClass { 48 public: 49 TestMainStaticDtorClass() { 50 expected_this = this; 51 } 52 53 ~TestMainStaticDtorClass() { 54 if (this != expected_this) { 55 fprintf(stderr, "\nerror: static d-tor called with incorrect this pointer: %p, expected: %p\n", this, expected_this); 56 } else { 57 fprintf(stderr, "6"); 58 } 59 } 60 private: 61 static const TestMainStaticDtorClass* expected_this; 62}; 63 64const TestMainStaticDtorClass* TestMainStaticDtorClass::expected_this = NULL; 65 66static void atexit_func5() { 67 fprintf(stderr, "5"); 68} 69 70static void atexit_func4() { 71 fprintf(stderr, "4"); 72} 73 74static void atexit_func3() { 75 fprintf(stderr, "3"); 76 atexit(atexit_func4); 77} 78 79static void atexit_func2() { 80 fprintf(stderr, "2"); 81} 82 83static void atexit_func1() { 84 fprintf(stderr, "1"); 85} 86 87static void atexit_main() { 88 // This should result in "123456" output to stderr 89 static TestMainStaticDtorClass static_obj; 90 atexit(atexit_func5); 91 atexit(atexit_func3); 92 atexit(atexit_func2); 93 atexit(atexit_func1); 94 exit(0); 95} 96 97TEST(atexit, exit) { 98 ASSERT_EXIT(atexit_main(), testing::ExitedWithCode(0), "123456"); 99} 100 101