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/iomgr/block_annotate.h"
32
grpc_load_file(const char * filename,int add_null_terminator,grpc_slice * output)33 grpc_error* grpc_load_file(const char* filename, int add_null_terminator,
34 grpc_slice* output) {
35 unsigned char* contents = nullptr;
36 size_t contents_size = 0;
37 grpc_slice result = grpc_empty_slice();
38 FILE* file;
39 size_t bytes_read = 0;
40 grpc_error* error = GRPC_ERROR_NONE;
41
42 GRPC_SCHEDULING_START_BLOCKING_REGION;
43 file = fopen(filename, "rb");
44 if (file == nullptr) {
45 error = GRPC_OS_ERROR(errno, "fopen");
46 goto end;
47 }
48 fseek(file, 0, SEEK_END);
49 /* Converting to size_t on the assumption that it will not fail */
50 contents_size = static_cast<size_t>(ftell(file));
51 fseek(file, 0, SEEK_SET);
52 contents = static_cast<unsigned char*>(
53 gpr_malloc(contents_size + (add_null_terminator ? 1 : 0)));
54 bytes_read = fread(contents, 1, contents_size, file);
55 if (bytes_read < contents_size) {
56 error = GRPC_OS_ERROR(errno, "fread");
57 GPR_ASSERT(ferror(file));
58 goto end;
59 }
60 if (add_null_terminator) {
61 contents[contents_size++] = 0;
62 }
63 result = grpc_slice_new(contents, contents_size, gpr_free);
64
65 end:
66 *output = result;
67 if (file != nullptr) fclose(file);
68 if (error != GRPC_ERROR_NONE) {
69 grpc_error* error_out =
70 grpc_error_set_str(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
71 "Failed to load file", &error, 1),
72 GRPC_ERROR_STR_FILENAME,
73 grpc_slice_from_copied_string(
74 filename)); // TODO(ncteisen), always static?
75 GRPC_ERROR_UNREF(error);
76 error = error_out;
77 }
78 GRPC_SCHEDULING_END_BLOCKING_REGION_NO_EXEC_CTX;
79 return error;
80 }
81