Home | History | Annotate | Download | only in libs
      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 <dlfcn.h>
     18 #include <stdint.h>
     19 #include <stdio.h>
     20 #include <stdlib.h>
     21 
     22 static uintptr_t g_flag = 0;
     23 
     24 static void __attribute__((constructor)) init_flag() {
     25   g_flag = reinterpret_cast<uintptr_t>(dlsym(RTLD_DEFAULT, "dlsym"));
     26 }
     27 
     28 static const char* is_ctor_called() __attribute__ ((ifunc("is_ctor_called_ifun")));
     29 
     30 extern "C" const char* foo() __attribute__ ((ifunc ("foo_ifunc")));
     31 
     32 // Static linker creates GLOBAL/IFUNC symbol and JUMP_SLOT relocation type for plt segment
     33 extern "C" const char* is_ctor_called_jump_slot() __attribute__ ((ifunc("is_ctor_called_ifun")));
     34 
     35 extern "C" const char* is_ctor_called_irelative() {
     36   // Call internal ifunc-resolved function with IRELATIVE reloc
     37   return is_ctor_called();
     38 }
     39 
     40 extern "C" const char* return_true() {
     41   return "true";
     42 }
     43 
     44 extern "C" const char* return_false() {
     45   return "false";
     46 }
     47 
     48 extern "C" const char* f1() {
     49   return "unset";
     50 }
     51 
     52 extern "C" const char* f2() {
     53   return "set";
     54 }
     55 
     56 typedef const char* (*fn_ptr)();
     57 
     58 extern "C" fn_ptr is_ctor_called_ifun() {
     59   return g_flag == 0 ? return_false : return_true;
     60 }
     61 
     62 extern "C" fn_ptr foo_ifunc() {
     63    char* choice = getenv("IFUNC_CHOICE");
     64    return choice == NULL ? f1 : f2;
     65 }
     66 
     67 extern "C" const char* foo_library() {
     68    return foo();
     69 }
     70