1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // A crazy linker test to:
6 // - Load a library (libfoo_with_static_constructor.so) with the linker.\
7 //
8 // - This shall execute a static constructor that will change the value
9 //   of the TEST_VAR environment variable to "LOADED'.
10 //
11 // - Close the library, this shall execute a static destructor that will
12 //   change the value of TEST_VAR to "UNLOADED'.
13 
14 #include <stdio.h>
15 #include <stdlib.h>
16 
17 #include <crazy_linker.h>
18 
19 #include "test_util.h"
20 
21 typedef void (*FunctionPtr)();
22 
main()23 int main() {
24   crazy_context_t* context = crazy_context_create();
25   crazy_library_t* library;
26 
27   putenv("TEST_VAR=INIT");
28 
29   // DEBUG
30   crazy_context_set_load_address(context, 0x20000000);
31 
32   // Load libfoo.so
33   if (!crazy_library_open(
34            &library, "libfoo_with_static_constructor.so", context)) {
35     Panic("Could not open library: %s\n", crazy_context_get_error(context));
36   }
37 
38   const char* env = getenv("TEST_VAR");
39   if (!env || strcmp(env, "LOADED"))
40     Panic(
41         "Constructors not run when loading libfoo_with_static_constructor.so");
42 
43   // Find the "Foo" symbol.
44   FunctionPtr foo_func;
45   if (!crazy_library_find_symbol(
46            library, "Foo", reinterpret_cast<void**>(&foo_func))) {
47     Panic("Could not find 'Foo' in libfoo.so\n");
48   }
49 
50   // Call it.
51   (*foo_func)();
52 
53   // Close the library.
54   printf("Closing libfoo_with_static_constructor.so\n");
55   crazy_library_close(library);
56 
57   env = getenv("TEST_VAR");
58   if (!env || strcmp(env, "UNLOADED"))
59     Panic(
60         "Destructors not run when unloading libfoo_with_static_constructor.so");
61 
62   crazy_context_destroy(context);
63 
64   return 0;
65 }