1 //
2 //  Copyright 2015 Google, Inc.
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 #define LOG_TAG "hal_util"
18 
19 #include <base/logging.h>
20 #include <base/strings/stringprintf.h>
21 #include <hardware/bluetooth.h>
22 
23 #include <dlfcn.h>
24 #include <errno.h>
25 #include <string.h>
26 
27 #include "btcore/include/hal_util.h"
28 #include "osi/include/log.h"
29 
30 using base::StringPrintf;
31 
32 #define BLUETOOTH_LIBRARY_NAME "libbluetooth.so"
33 
34 #if !defined(STATIC_LIBBLUETOOTH)
hal_util_load_bt_library(const bt_interface_t ** interface)35 int hal_util_load_bt_library(const bt_interface_t** interface) {
36   const char* sym = BLUETOOTH_INTERFACE_STRING;
37   bt_interface_t* itf = nullptr;
38 
39   // Always try to load the default Bluetooth stack on GN builds.
40   void* handle = dlopen(BLUETOOTH_LIBRARY_NAME, RTLD_NOW);
41   if (!handle) {
42     const char* err_str = dlerror();
43     LOG(ERROR) << __func__ << ": failed to load bluetooth library, error="
44                << (err_str ? err_str : "error unknown");
45     goto error;
46   }
47 
48   // Get the address of the bt_interface_t.
49   itf = (bt_interface_t*)dlsym(handle, sym);
50   if (!itf) {
51     LOG(ERROR) << __func__ << ": failed to load symbol from Bluetooth library "
52                << sym;
53     goto error;
54   }
55 
56   // Success.
57   LOG(INFO) << __func__ << " loaded HAL path=" << BLUETOOTH_LIBRARY_NAME
58             << " btinterface=" << itf << " handle=" << handle;
59 
60   *interface = itf;
61   return 0;
62 
63 error:
64   *interface = NULL;
65   if (handle) dlclose(handle);
66 
67   return -EINVAL;
68 }
69 #else
70 extern bt_interface_t bluetoothInterface;
71 
hal_util_load_bt_library(const bt_interface_t ** interface)72 int hal_util_load_bt_library(const bt_interface_t** interface) {
73   *interface = &bluetoothInterface;
74 
75   return 0;
76 }
77 #endif
78