1 //
2 //
3 // Copyright 2015 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 
19 #include <grpc/support/port_platform.h>
20 
21 #include "src/core/lib/iomgr/load_file.h"
22 
23 #include <errno.h>
24 #include <string.h>
25 
26 #include <grpc/support/alloc.h>
27 #include <grpc/support/log.h>
28 #include <grpc/support/string_util.h>
29 
30 #include "src/core/lib/gpr/string.h"
31 #include "src/core/lib/gprpp/crash.h"
32 #include "src/core/lib/iomgr/block_annotate.h"
33 
grpc_load_file(const char * filename,int add_null_terminator,grpc_slice * output)34 grpc_error_handle grpc_load_file(const char* filename, int add_null_terminator,
35                                  grpc_slice* output) {
36   unsigned char* contents = nullptr;
37   size_t contents_size = 0;
38   grpc_slice result = grpc_empty_slice();
39   FILE* file;
40   size_t bytes_read = 0;
41   grpc_error_handle error;
42 
43   GRPC_SCHEDULING_START_BLOCKING_REGION;
44   file = fopen(filename, "rb");
45   if (file == nullptr) {
46     error = GRPC_OS_ERROR(errno, "fopen");
47     goto end;
48   }
49   fseek(file, 0, SEEK_END);
50   // Converting to size_t on the assumption that it will not fail
51   contents_size = static_cast<size_t>(ftell(file));
52   fseek(file, 0, SEEK_SET);
53   contents = static_cast<unsigned char*>(
54       gpr_malloc(contents_size + (add_null_terminator ? 1 : 0)));
55   bytes_read = fread(contents, 1, contents_size, file);
56   if (bytes_read < contents_size) {
57     gpr_free(contents);
58     error = GRPC_OS_ERROR(errno, "fread");
59     GPR_ASSERT(ferror(file));
60     goto end;
61   }
62   if (add_null_terminator) {
63     contents[contents_size++] = 0;
64   }
65   result = grpc_slice_new(contents, contents_size, gpr_free);
66 
67 end:
68   *output = result;
69   if (file != nullptr) fclose(file);
70   if (!error.ok()) {
71     grpc_error_handle error_out = grpc_error_set_str(
72         GRPC_ERROR_CREATE_REFERENCING("Failed to load file", &error, 1),
73         grpc_core::StatusStrProperty::kFilename, filename);
74     error = error_out;
75   }
76   GRPC_SCHEDULING_END_BLOCKING_REGION_NO_EXEC_CTX;
77   return error;
78 }
79