| 1 | /* |
| 2 | * Copyright 2026 LiveKit, 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 | #include "jetson_runtime_loader.h" |
| 18 | |
| 19 | #include <dlfcn.h> |
| 20 | |
| 21 | #include <string> |
| 22 | |
| 23 | namespace { |
| 24 | |
| 25 | void* TryLoad(const std::string& name) { |
| 26 | // Same flags the implib-generated loaders would use themselves. |
| 27 | return dlopen(name.c_str(), RTLD_LAZY | RTLD_GLOBAL); |
| 28 | } |
| 29 | |
| 30 | void* LoadWithFallbacks(const char* lib_name) { |
| 31 | // L4T puts its userspace libraries in a vendor directory that is normally |
| 32 | // in ld.so.conf, but not always in minimal/containerized rootfs setups: |
| 33 | // R34+ uses .../nvidia, older releases used .../tegra. |
| 34 | static const char* const kNvidiaLibDirs[] = { |
| 35 | "/usr/lib/aarch64-linux-gnu/nvidia/", |
| 36 | "/usr/lib/aarch64-linux-gnu/tegra/", |
| 37 | }; |
| 38 | |
| 39 | const std::string name(lib_name); |
| 40 | if (void* handle = TryLoad(name)) { |
| 41 | return handle; |
| 42 | } |
| 43 | for (const char* dir : kNvidiaLibDirs) { |
| 44 | if (void* handle = TryLoad(dir + name)) { |
| 45 | return handle; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | // The stubs bake in the SONAME of the library they were generated from |
| 50 | // (e.g. libnvbufsurface.so.1.0.0); if an L4T release changes the version |
| 51 | // suffix, fall back to the unversioned dev name. |
| 52 | const size_t so_pos = name.rfind(".so."); |
| 53 | if (so_pos != std::string::npos) { |
| 54 | const std::string unversioned = name.substr(0, so_pos + 3); |
| 55 | if (void* handle = TryLoad(unversioned)) { |
| 56 | return handle; |
| 57 | } |
| 58 | for (const char* dir : kNvidiaLibDirs) { |
| 59 | if (void* handle = TryLoad(dir + unversioned)) { |
| 60 | return handle; |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | return nullptr; |
| 66 | } |
| 67 | |
| 68 | } // namespace |
| 69 | |
| 70 | extern "C" void* lk_jetson_dlopen(const char* lib_name) { |
| 71 | return LoadWithFallbacks(lib_name); |
| 72 | } |
| 73 | |
| 74 | extern "C" int lk_jetson_runtime_libs_available(void) { |
| 75 | static const bool available = |
| 76 | LoadWithFallbacks("libnvbufsurface.so.1.0.0") != nullptr && |
| 77 | LoadWithFallbacks("libv4l2.so.0") != nullptr; |
| 78 | return available ? 1 : 0; |
| 79 | } |