1 // Copyright (C) 2019 Google LLC
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 #include "icing/util/icu-data-file-helper.h"
16
17 #include <sys/mman.h>
18
19 #include <cstdint>
20 #include <memory>
21
22 #include "icing/text_classifier/lib3/utils/base/status.h"
23 #include "icing/absl_ports/canonical_errors.h"
24 #include "icing/file/filesystem.h"
25 #ifdef CUSTOM_ICU_DAT_FILE
26 #include "unicode/udata.h"
27 #include "unicode/utypes.h"
28 #endif // CUSTOM_ICU_DAT_FILE
29 namespace icing {
30 namespace lib {
31
32 namespace icu_data_file_helper {
33
34 // ICU data file needs to be set up once, it can be shared between different
35 // Icing instances. Setting up the file too many times may cause out-of-memory
36 // segmentation fault errors.
37 bool has_set_up_icu_data_file = false;
38
SetUpIcuDataFile(const std::string & icu_data_file_absolute_path)39 libtextclassifier3::Status SetUpIcuDataFile(
40 const std::string& icu_data_file_absolute_path) {
41 #ifdef CUSTOM_ICU_DAT_FILE
42 if (has_set_up_icu_data_file) {
43 return libtextclassifier3::Status::OK;
44 }
45
46 Filesystem filesystem;
47 int64_t file_size =
48 filesystem.GetFileSize(icu_data_file_absolute_path.c_str());
49 ScopedFd fd(filesystem.OpenForRead(icu_data_file_absolute_path.c_str()));
50 if (!fd.is_valid()) {
51 return absl_ports::InternalError("Unable to open file at provided path");
52 }
53
54 const void* data =
55 mmap(nullptr, file_size, PROT_READ, MAP_PRIVATE, fd.get(), 0);
56
57 UErrorCode status = U_ZERO_ERROR;
58 udata_setCommonData(data, &status);
59
60 if (U_FAILURE(status)) {
61 return absl_ports::InternalError(
62 "Failed to set up ICU data, please check if you have the data file at "
63 "the given path.");
64 }
65
66 has_set_up_icu_data_file = true;
67 #endif // CUSTOM_ICU_DAT_FILE
68 return libtextclassifier3::Status::OK;
69 }
70
71 } // namespace icu_data_file_helper
72
73 } // namespace lib
74 } // namespace icing
75