• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/testing/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 #include "unicode/udata.h"
26 #include "unicode/utypes.h"
27 
28 namespace icing {
29 namespace lib {
30 
31 namespace icu_data_file_helper {
32 
33 // ICU data file needs to be set up once, it can be shared between different
34 // Icing instances. Setting up the file too many times may cause out-of-memory
35 // segmentation fault errors.
36 bool has_set_up_icu_data_file = false;
37 
SetUpICUDataFile(const std::string & icu_data_file_absolute_path)38 libtextclassifier3::Status SetUpICUDataFile(
39     const std::string& icu_data_file_absolute_path) {
40   if (has_set_up_icu_data_file) {
41     return libtextclassifier3::Status::OK;
42   }
43 
44   Filesystem filesystem;
45   int64_t file_size =
46       filesystem.GetFileSize(icu_data_file_absolute_path.c_str());
47   ScopedFd fd(filesystem.OpenForRead(icu_data_file_absolute_path.c_str()));
48   if (!fd.is_valid()) {
49     return absl_ports::InternalError("Unable to open file at provided path");
50   }
51 
52   const void* data =
53       mmap(nullptr, file_size, PROT_READ, MAP_PRIVATE, fd.get(), 0);
54 
55   UErrorCode status = U_ZERO_ERROR;
56   udata_setCommonData(data, &status);
57 
58   if (U_FAILURE(status)) {
59     return absl_ports::InternalError(
60         "Failed to set up ICU data, please check if you have the data file at "
61         "the given path.");
62   }
63 
64   has_set_up_icu_data_file = true;
65 
66   return libtextclassifier3::Status::OK;
67 }
68 
69 }  // namespace icu_data_file_helper
70 
71 }  // namespace lib
72 }  // namespace icing
73