1 /*
2 * Copyright (C) 2016 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_symlink_support.h"
18
19 #include <gtest/gtest.h>
20
21 #include <dlfcn.h>
22 #include <libgen.h>
23 #include <link.h>
24 #include <unistd.h>
25
26 #include <android-base/strings.h>
27
28 #include <algorithm>
29 #include <string>
30 #include <vector>
31
32 static const constexpr char* source_file_name = "libdlext_test.so";
33 static const constexpr char* symlink_name_prefix = "libdlext_test_";
34
dl_callback(struct dl_phdr_info * info,size_t,void * data)35 static int dl_callback(struct dl_phdr_info *info, size_t /* size */, void *data) {
36 // The case when path is not absolute and is equal to source_file_name
37 // is disregarded intentionally since in bionic dlpi_name should always
38 // be realpath to a shared object.
39 const std::string suffix = std::string("/") + source_file_name;
40
41 // TODO (dimitry): remove this check once fake libdl.so is gone
42 if (info->dlpi_name == nullptr) {
43 // This is linker imposing as libdl.so - skip it
44 return 0;
45 }
46
47 if (android::base::EndsWith(info->dlpi_name, suffix)) {
48 std::string* path = reinterpret_cast<std::string*>(data);
49 *path = info->dlpi_name;
50 return 1; // found
51 }
52
53 return 0;
54 }
55
create_dlfcn_test_symlink(const char * suffix,std::string * result)56 void create_dlfcn_test_symlink(const char* suffix, std::string* result) {
57 void* handle = dlopen(source_file_name, RTLD_NOW);
58 std::string source_file_path;
59
60 ASSERT_TRUE(handle != nullptr) << dlerror();
61 ASSERT_TRUE(dl_iterate_phdr(dl_callback, &source_file_path) == 1)
62 << "dl_phdr_info for \"" << source_file_name << "\" was not found.";
63
64 dlclose(handle);
65 std::vector<char> buf;
66 std::copy(source_file_path.begin(), source_file_path.end(), std::back_inserter(buf));
67 buf.push_back('\0');
68
69 std::string path_dir = dirname(&buf[0]);
70 std::string link_path = path_dir + "/" + symlink_name_prefix + suffix + ".so";
71
72 ASSERT_TRUE(symlink(source_file_path.c_str(), link_path.c_str()) == 0) << strerror(errno);
73 *result = link_path;
74 }
75
remove_dlfcn_test_symlink(const std::string & path)76 void remove_dlfcn_test_symlink(const std::string& path) {
77 ASSERT_TRUE(unlink(path.c_str()) == 0) << strerror(errno);
78 }
79