• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 gRPC authors.
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 "src/core/util/load_file.h"
16 
17 #include <errno.h>
18 #include <grpc/slice.h>
19 #include <grpc/support/alloc.h>
20 #include <grpc/support/port_platform.h>
21 #include <stdio.h>
22 #include <string.h>
23 
24 #include "absl/cleanup/cleanup.h"
25 #include "absl/status/status.h"
26 #include "absl/strings/str_cat.h"
27 
28 namespace grpc_core {
29 
30 // Loads the content of a file into a slice. add_null_terminator will add a NULL
31 // terminator if true.
32 // This API is NOT thread-safe and requires proper synchronization when used by
33 // multiple threads, especially when they can happen to be reading from the same
34 // file.
LoadFile(const std::string & filename,bool add_null_terminator)35 absl::StatusOr<Slice> LoadFile(const std::string& filename,
36                                bool add_null_terminator) {
37   unsigned char* contents = nullptr;
38   size_t contents_size = 0;
39   FILE* file;
40   size_t bytes_read = 0;
41   absl::Status error = absl::OkStatus();
42   auto sock_cleanup = absl::MakeCleanup([&file]() -> void {
43     if (file != nullptr) {
44       fclose(file);
45     }
46   });
47 
48   file = fopen(filename.c_str(), "rb");
49   if (file == nullptr) {
50     error = absl::InternalError(
51         absl::StrCat("Failed to load file: ", filename,
52                      " due to error(fdopen): ", strerror(errno)));
53     return error;
54   }
55   fseek(file, 0, SEEK_END);
56   // Converting to size_t on the assumption that it will not fail.
57   contents_size = static_cast<size_t>(ftell(file));
58   fseek(file, 0, SEEK_SET);
59   contents = static_cast<unsigned char*>(
60       gpr_malloc(contents_size + (add_null_terminator ? 1 : 0)));
61   bytes_read = fread(contents, 1, contents_size, file);
62   if (bytes_read < contents_size) {
63     gpr_free(contents);
64     error = absl::InternalError(
65         absl::StrCat("Failed to load file: ", filename,
66                      " due to error(fread): ", strerror(errno)));
67     return error;
68   }
69   if (add_null_terminator) {
70     contents[contents_size++] = 0;
71   }
72   return Slice(grpc_slice_new(contents, contents_size, gpr_free));
73 }
74 
75 }  // namespace grpc_core
76