1 /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 #include "tensorflow/core/platform/load_library.h"
17
18 #include <dlfcn.h>
19
20 #include "tensorflow/core/platform/errors.h"
21
22 namespace tensorflow {
23
24 namespace internal {
25
LoadDynamicLibrary(const char * library_filename,void ** handle)26 Status LoadDynamicLibrary(const char* library_filename, void** handle) {
27 *handle = dlopen(library_filename, RTLD_NOW | RTLD_LOCAL);
28 if (!*handle) {
29 // Note that in C++17 std::string_view(nullptr) gives segfault!
30 const char* error_msg = dlerror();
31 return errors::NotFound(error_msg ? error_msg : "(null error message)");
32 }
33 return OkStatus();
34 }
35
GetSymbolFromLibrary(void * handle,const char * symbol_name,void ** symbol)36 Status GetSymbolFromLibrary(void* handle, const char* symbol_name,
37 void** symbol) {
38 // Check that the handle is not NULL to avoid dlsym's RTLD_DEFAULT behavior.
39 if (!handle) {
40 *symbol = nullptr;
41 } else {
42 *symbol = dlsym(handle, symbol_name);
43 }
44 if (!*symbol) {
45 // Note that in C++17 std::string_view(nullptr) gives segfault!
46 const char* error_msg = dlerror();
47 return errors::NotFound(error_msg ? error_msg : "(null error message)");
48 }
49 return OkStatus();
50 }
51
FormatLibraryFileName(const string & name,const string & version)52 string FormatLibraryFileName(const string& name, const string& version) {
53 string filename;
54 #if defined(__APPLE__)
55 if (version.size() == 0) {
56 filename = "lib" + name + ".dylib";
57 } else {
58 filename = "lib" + name + "." + version + ".dylib";
59 }
60 #else
61 if (version.empty()) {
62 filename = "lib" + name + ".so";
63 } else {
64 filename = "lib" + name + ".so" + "." + version;
65 }
66 #endif
67 return filename;
68 }
69
70 } // namespace internal
71
72 } // namespace tensorflow
73