Debian Codegraph @

src/PluginSegmentation.cpp

raw symbols SCIP
1 /*
2 * Open Chinese Convert
3 *
4 * Copyright 2010-2026 Carbo Kuo and contributors
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * 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, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #include "PluginSegmentation.hpp"
20
21 #include "Exception.hpp"
22 #include "Segmentation.hpp"
23 #include "Segments.hpp"
24 #include "UTF8Util.hpp"
25 #include "plugin/OpenCCPlugin.h"
26
27 #include <cstddef>
28 #include <cstdlib>
29 #include <fstream>
30 #include <memory>
31 #include <mutex>
32 #include <sstream>
33 #include <unordered_map>
34
35 #if defined(_WIN32) || defined(_WIN64)
36 #include "WinUtil.hpp"
37 #else
38 #include <dlfcn.h>
39 #endif
40
41 namespace opencc {
42
43 namespace {
44
45 std::string DirName(const std::string& path) {
46 const std::string::size_type pos = path.find_last_of("/\\");
47 if (pos == std::string::npos) {
48 return "";
49 }
50 return path.substr(0, pos);
51 }
52
53 std::string JoinPath(const std::string& left, const std::string& right) {
54 if (left.empty()) {
55 return right;
56 }
57 const char last = left.back();
58 if (last == '/' || last == '\\') {
59 return left + right;
60 }
61 return left + "/" + right;
62 }
63
64 void AppendUnique(std::vector<std::string>& values, const std::string& value) {
65 if (value.empty()) {
66 return;
67 }
68 for (const std::string& existing : values) {
69 if (existing == value) {
70 return;
71 }
72 }
73 values.push_back(value);
74 }
75
76 bool IsTruthy(const char* value) {
77 if (value == nullptr) {
78 return false;
79 }
80 const std::string text(value);
81 return text == "1" || text == "true" || text == "TRUE" || text == "yes" ||
82 text == "on";
83 }
84
85 bool IsReadableFile(const std::string& path) {
86 #if defined(_WIN32) || defined(_WIN64)
87 const DWORD attributes =
88 GetFileAttributesW(internal::WideFromUtf8(path).c_str());
89 return attributes != INVALID_FILE_ATTRIBUTES &&
90 (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
91 #else
92 std::ifstream ifs(path.c_str(), std::ios::binary);
93 return ifs.is_open();
94 #endif
95 }
96
97 std::vector<std::string> SplitSearchPath(const char* raw) {
98 std::vector<std::string> entries;
99 if (raw == nullptr || *raw == '\0') {
100 return entries;
101 }
102 const char separator =
103 #if defined(_WIN32) || defined(_WIN64)
104 ';';
105 #else
106 ':';
107 #endif
108 std::string path(raw);
109 std::string::size_type start = 0;
110 while (start <= path.size()) {
111 const std::string::size_type end = path.find(separator, start);
112 const std::string entry = path.substr(start, end - start);
113 if (!entry.empty()) {
114 entries.push_back(entry);
115 }
116 if (end == std::string::npos) {
117 break;
118 }
119 start = end + 1;
120 }
121 return entries;
122 }
123
124 #if defined(_WIN32) || defined(_WIN64)
125 using internal::Utf8FromWide;
126 using internal::WideFromUtf8;
127
128 std::string GetCurrentLibraryDirectory() {
129 HMODULE module = nullptr;
130 if (!GetModuleHandleExW(
131 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
132 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
133 reinterpret_cast<LPCWSTR>(&GetCurrentLibraryDirectory), &module)) {
134 return "";
135 }
136 std::wstring buffer(MAX_PATH, L'\0');
137 for (;;) {
138 const DWORD copied = GetModuleFileNameW(module, buffer.data(),
139 static_cast<DWORD>(buffer.size()));
140 if (copied == 0) {
141 return "";
142 }
143 if (copied < buffer.size() - 1) {
144 buffer.resize(copied);
145 return DirName(Utf8FromWide(buffer));
146 }
147 buffer.resize(buffer.size() * 2);
148 }
149 }
150 #else
151 std::string GetCurrentLibraryDirectory() {
152 Dl_info info;
153 if (dladdr(reinterpret_cast<void*>(&GetCurrentLibraryDirectory), &info) == 0 ||
154 info.dli_fname == nullptr) {
155 return "";
156 }
157 return DirName(info.dli_fname);
158 }
159 #endif
160
161 class SharedLibrary {
162 public:
163 explicit SharedLibrary(const std::string& path) {
164 #if defined(_WIN32) || defined(_WIN64)
165 handle_ = LoadLibraryExW(
166 WideFromUtf8(path).c_str(), nullptr,
167 LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
168 if (handle_ == nullptr) {
169 throw Exception("Failed to load plugin library: " + path);
170 }
171 #else
172 handle_ = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
173 if (handle_ == nullptr) {
174 throw Exception("Failed to load plugin library: " + path);
175 }
176 #endif
177 }
178
179 ~SharedLibrary() {
180 #if defined(_WIN32) || defined(_WIN64)
181 if (handle_ != nullptr) {
182 FreeLibrary(handle_);
183 }
184 #else
185 if (handle_ != nullptr) {
186 dlclose(handle_);
187 }
188 #endif
189 }
190
191 void* FindSymbol(const char* symbolName) const {
192 #if defined(_WIN32) || defined(_WIN64)
193 FARPROC symbol = GetProcAddress(handle_, symbolName);
194 if (symbol == nullptr) {
195 throw Exception("Plugin symbol not found: " + std::string(symbolName));
196 }
197 return reinterpret_cast<void*>(symbol);
198 #else
199 dlerror();
200 void* symbol = dlsym(handle_, symbolName);
201 if (symbol == nullptr) {
202 throw Exception("Plugin symbol not found: " + std::string(symbolName));
203 }
204 return symbol;
205 #endif
206 }
207
208 private:
209 #if defined(_WIN32) || defined(_WIN64)
210 HMODULE handle_ = nullptr;
211 #else
212 void* handle_ = nullptr;
213 #endif
214 };
215
216 struct PluginLibrary {
217 std::shared_ptr<SharedLibrary> library;
218 const opencc_segmentation_plugin_v2* descriptor = nullptr;
219 };
220
221 size_t RequiredDescriptorSize() {
222 return offsetof(opencc_segmentation_plugin_v2, free_error) +
223 sizeof(((opencc_segmentation_plugin_v2*)nullptr)->free_error);
224 }
225
226 std::string TakeErrorMessage(const opencc_segmentation_plugin_v2* descriptor,
227 opencc_error_t* error,
228 const std::string& fallback) {
229 if (error == nullptr) {
230 return fallback;
231 }
232 const std::string message =
233 error->message == nullptr ? fallback : std::string(error->message);
234 if (descriptor->free_error != nullptr) {
235 descriptor->free_error(error);
236 }
237 return message;
238 }
239
240 [[noreturn]] void ThrowPluginError(const opencc_segmentation_plugin_v2* descriptor,
241 opencc_error_t* error,
242 const std::string& pluginType,
243 const std::string& fallbackPrefix,
244 const std::string& fallbackMessage) {
245 const std::string message =
246 TakeErrorMessage(descriptor, error, fallbackMessage);
247 throw Exception(fallbackPrefix + " '" + pluginType + "': " + message);
248 }
249
250 SegmentsPtr BuildSegmentsFromLengths(std::string_view text,
251 const opencc_segment_length_array_t& lengths) {
252 SegmentsPtr segments(new Segments);
253 const char* bytes = text.data();
254 const size_t inputSize = text.size();
255 size_t byteOffset = 0;
256
257 for (size_t i = 0; i < lengths.segment_count; i++) {
258 const uint32_t codepointLength = lengths.codepoint_lengths[i];
259 if (codepointLength == 0) {
260 throw Exception("Segmentation plugin returned a zero-length segment.");
261 }
262
263 const size_t segmentStart = byteOffset;
264 for (uint32_t j = 0; j < codepointLength; j++) {
265 if (byteOffset >= inputSize) {
266 throw Exception("Segmentation plugin returned lengths past end of input.");
267 }
268 const size_t charLength = UTF8Util::NextCharLengthNoException(bytes + byteOffset);
269 if (charLength == 0 || byteOffset + charLength > inputSize) {
270 throw Exception("Input text is not valid UTF-8.");
271 }
272 byteOffset += charLength;
273 }
274
275 segments->AddSegment(text.substr(segmentStart, byteOffset - segmentStart));
276 }
277
278 if (byteOffset != inputSize) {
279 throw Exception("Segmentation plugin lengths do not cover the full input. "
280 "Consumed bytes: " + std::to_string(byteOffset) +
281 ", total bytes: " + std::to_string(inputSize) +
282 ", segments: " + std::to_string(lengths.segment_count) + ".");
283 }
284 return segments;
285 }
286
287 class PluginSegmentationAdapter : public Segmentation {
288 public:
289 PluginSegmentationAdapter(std::shared_ptr<PluginLibrary> plugin,
290 opencc_segmentation_handle_t* handle)
291 : plugin_(std::move(plugin)), handle_(handle) {}
292
293 ~PluginSegmentationAdapter() override {
294 if (handle_ != nullptr) {
295 plugin_->descriptor->destroy(handle_);
296 handle_ = nullptr;
297 }
298 }
299
300 SegmentsPtr Segment(std::string_view text) const override {
301 const std::string owned(text);
302 opencc_segment_length_array_t segmentLengths = {};
303 segmentLengths.struct_size = sizeof(segmentLengths);
304 opencc_error_t error = {};
305 error.struct_size = sizeof(error);
306 opencc_segmentation_segment_args_t args = {};
307 args.struct_size = sizeof(args);
308 args.handle = handle_;
309 args.utf8_text = owned.c_str();
310 args.segment_lengths = &segmentLengths;
311 args.error = &error;
312 const int status = plugin_->descriptor->segment(&args);
313
314 struct SegmentLengthGuard {
315 const opencc_segmentation_plugin_v2* desc;
316 opencc_segment_length_array_t* arr;
317 ~SegmentLengthGuard() { desc->free_segment_lengths(arr); }
318 } guard{plugin_->descriptor, &segmentLengths};
319
320 if (status != 0) {
321 ThrowPluginError(plugin_->descriptor, &error,
322 plugin_->descriptor->segmentation_type,
323 "Segmentation plugin failed", "unknown error");
324 }
325 return BuildSegmentsFromLengths(text, segmentLengths);
326 }
327
328 private:
329 std::shared_ptr<PluginLibrary> plugin_;
330 mutable opencc_segmentation_handle_t* handle_ = nullptr;
331 };
332
333 class PluginManager {
334 public:
335 std::shared_ptr<PluginLibrary> LoadByType(const std::string& type) {
336 if (IsTruthy(std::getenv("OPENCC_DISABLE_PLUGINS"))) {
337 throw Exception("Segmentation plugin loading is disabled.");
338 }
339
340 std::lock_guard<std::mutex> lock(mutex_);
341 auto it = cache_.find(type);
342 if (it != cache_.end()) {
343 return it->second;
344 }
345
346 const std::vector<std::string> searchDirs = BuildSearchDirs();
347 const std::vector<std::string> fileNames = GetPluginFileNames(type);
348 std::ostringstream attempted;
349 bool first = true;
350 for (const auto& dir : searchDirs) {
351 std::vector<std::string> matches;
352 for (const auto& fileName : fileNames) {
353 const std::string candidate = JoinPath(dir, fileName);
354 if (!first) {
355 attempted << ", ";
356 }
357 first = false;
358 attempted << candidate;
359 if (IsReadableFile(candidate)) {
360 matches.push_back(candidate);
361 }
362 }
363
364 if (matches.size() > 1) {
365 throw Exception("Multiple segmentation plugin libraries found for '" +
366 type + "' in directory '" + dir +
367 "'. Keep only one matching DLL per plugin type.");
368 }
369 if (matches.empty()) {
370 continue;
371 }
372 try {
373 std::shared_ptr<PluginLibrary> plugin =
374 LoadFromPath(matches.front(), type);
375 cache_[type] = plugin;
376 return plugin;
377 } catch (const Exception&) {
378 }
379 }
380 throw Exception("Segmentation plugin '" + type +
381 "' not found. Searched: " + attempted.str());
382 }
383
384 std::shared_ptr<PluginLibrary> LoadByPath(const std::string& path,
385 const std::string& type) {
386 if (IsTruthy(std::getenv("OPENCC_DISABLE_PLUGINS"))) {
387 throw Exception("Segmentation plugin loading is disabled.");
388 }
389
390 std::lock_guard<std::mutex> lock(mutex_);
391 // Use the explicit path as cache key (not type) to avoid collisions
392 // when the same plugin type is loaded from different library paths.
393 auto it = cache_.find(path);
394 if (it != cache_.end()) {
395 return it->second;
396 }
397 std::shared_ptr<PluginLibrary> plugin = LoadFromPath(path, type);
398 cache_[path] = plugin;
399 return plugin;
400 }
401
402 private:
403 static std::vector<std::string> GetPluginFileNames(const std::string& type) {
404 #if defined(_WIN32) || defined(_WIN64)
405 return {
406 "opencc-" + type + ".dll",
407 "libopencc-" + type + ".dll",
408 "msys-opencc-" + type + ".dll",
409 };
410 #elif defined(__APPLE__)
411 return {"libopencc-" + type + ".dylib"};
412 #else
413 return {"libopencc-" + type + ".so"};
414 #endif
415 }
416
417 static std::vector<std::string> BuildSearchDirs() {
418 std::vector<std::string> dirs =
419 SplitSearchPath(std::getenv("OPENCC_SEGMENTATION_PLUGIN_PATH"));
420 AppendUnique(dirs, PACKAGE_SEGMENTATION_PLUGIN_DIRECTORY);
421
422 const std::string currentLibraryDir = GetCurrentLibraryDirectory();
423 if (!currentLibraryDir.empty()) {
424 #if defined(_WIN32) || defined(_WIN64)
425 AppendUnique(dirs, JoinPath(currentLibraryDir, "plugins"));
426 #else
427 AppendUnique(dirs, JoinPath(currentLibraryDir, "opencc/plugins"));
428 #endif
429 AppendUnique(dirs, currentLibraryDir);
430 }
431 return dirs;
432 }
433
434 static std::shared_ptr<PluginLibrary> LoadFromPath(const std::string& path,
435 const std::string& type) {
436 std::shared_ptr<SharedLibrary> library(new SharedLibrary(path));
437 typedef const opencc_segmentation_plugin_v2* (*EntryPoint)(void);
438 EntryPoint entryPoint = reinterpret_cast<EntryPoint>(
439 library->FindSymbol("opencc_get_segmentation_plugin_v2"));
440 const opencc_segmentation_plugin_v2* descriptor = entryPoint();
441 if (descriptor == nullptr) {
442 throw Exception("Plugin returned null descriptor.");
443 }
444 if (descriptor->struct_size < RequiredDescriptorSize()) {
445 throw Exception("Plugin descriptor is too small.");
446 }
447 if (descriptor->abi_major != OPENCC_SEGMENTATION_PLUGIN_ABI_MAJOR) {
448 throw Exception("Plugin ABI major version mismatch.");
449 }
450 if (descriptor->abi_minor < OPENCC_SEGMENTATION_PLUGIN_ABI_MINOR) {
451 throw Exception("Plugin ABI minor version is older than required by the host.");
452 }
453 if (descriptor->segmentation_type == nullptr ||
454 type != descriptor->segmentation_type) {
455 throw Exception("Plugin type mismatch.");
456 }
457 std::shared_ptr<PluginLibrary> plugin(new PluginLibrary);
458 plugin->library = library;
459 plugin->descriptor = descriptor;
460 return plugin;
461 }
462
463 std::mutex mutex_;
464 std::unordered_map<std::string, std::shared_ptr<PluginLibrary>> cache_;
465 };
466
467 PluginManager& GetPluginManager() {
468 static PluginManager manager;
469 return manager;
470 }
471
472 } // namespace
473
474 SegmentationPtr CreatePluginSegmentation(const std::string& type,
475 const PluginConfigPairs& configPairs) {
476 // Allow explicit plugin library path via __plugin_library config pair,
477 // bypassing search-based discovery (used by language bindings to bundle
478 // plugins as optional packages with deterministic paths).
479 std::string pluginLibraryPath;
480 for (const auto& pair : configPairs) {
481 if (pair.first == "__plugin_library") {
482 pluginLibraryPath = pair.second;
483 break;
484 }
485 }
486 std::shared_ptr<PluginLibrary> plugin =
487 pluginLibraryPath.empty()
488 ? GetPluginManager().LoadByType(type)
489 : GetPluginManager().LoadByPath(pluginLibraryPath, type);
490 std::vector<opencc_kv_pair_t> rawConfig;
491 rawConfig.reserve(configPairs.size());
492 for (const auto& pair : configPairs) {
493 rawConfig.push_back(
494 {sizeof(opencc_kv_pair_t), pair.first.c_str(), pair.second.c_str()});
495 }
496
497 opencc_segmentation_handle_t* handle = nullptr;
498 opencc_error_t error = {};
499 error.struct_size = sizeof(error);
500 opencc_segmentation_create_args_t args = {};
501 args.struct_size = sizeof(args);
502 args.config = rawConfig.empty() ? nullptr : rawConfig.data();
503 args.config_size = rawConfig.size();
504 args.out = &handle;
505 args.error = &error;
506 const int status = plugin->descriptor->create(&args);
507 if (status != 0 || handle == nullptr) {
508 const std::string message =
509 TakeErrorMessage(plugin->descriptor, &error, "unknown error");
510 throw InvalidFormat("Failed to initialize segmentation plugin '" + type +
511 "': " + message);
512 }
513 return SegmentationPtr(new PluginSegmentationAdapter(plugin, handle));
514 }
515
516 } // namespace opencc