1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20/*!
21 * \file system_library.cc
22 * \brief Create library module that directly get symbol from the system lib.
23 */
24#include <tvm/runtime/c_backend_api.h>
25#include <tvm/runtime/memory.h>
26#include <tvm/runtime/registry.h>
27
28#include <mutex>
29
30#include "library_module.h"
31
32namespace tvm {
33namespace runtime {
34
35class SystemLibrary : public Library {
36 public:
37 SystemLibrary() = default;
38
39 void* GetSymbol(const char* name) final {
40 std::lock_guard<std::mutex> lock(mutex_);
41 auto it = tbl_.find(name);
42 if (it != tbl_.end()) {
43 return it->second;
44 } else {
45 return nullptr;
46 }
47 }
48
49 void RegisterSymbol(const std::string& name, void* ptr) {
50 std::lock_guard<std::mutex> lock(mutex_);
51 auto it = tbl_.find(name);
52 if (it != tbl_.end() && ptr != it->second) {
53 LOG(WARNING) << "SystemLib symbol " << name << " get overriden to a different address " << ptr
54 << "->" << it->second;
55 }
56 tbl_[name] = ptr;
57 }
58
59 static const ObjectPtr<SystemLibrary>& Global() {
60 static auto inst = make_object<SystemLibrary>();
61 return inst;
62 }
63
64 private:
65 // Internal mutex
66 std::mutex mutex_;
67 // Internal symbol table
68 std::unordered_map<std::string, void*> tbl_;
69};
70
71TVM_REGISTER_GLOBAL("runtime.SystemLib").set_body_typed([]() {
72 static auto mod = CreateModuleFromLibrary(SystemLibrary::Global());
73 return mod;
74});
75} // namespace runtime
76} // namespace tvm
77
78int TVMBackendRegisterSystemLibSymbol(const char* name, void* ptr) {
79 tvm::runtime::SystemLibrary::Global()->RegisterSymbol(name, ptr);
80 return 0;
81}
82