xref: /aosp_15_r20/external/boringssl/src/tool/file.cc (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
1 /* Copyright (c) 2017, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include <openssl/bytestring.h>
16 
17 #include <errno.h>
18 #include <stdio.h>
19 #include <string.h>
20 
21 #include <algorithm>
22 #include <vector>
23 
24 #include "internal.h"
25 
26 
ReadAll(std::vector<uint8_t> * out,FILE * file)27 bool ReadAll(std::vector<uint8_t> *out, FILE *file) {
28   out->clear();
29 
30   constexpr size_t kMaxSize = 1024 * 1024;
31   size_t len = 0;
32   out->resize(128);
33 
34   for (;;) {
35     len += fread(out->data() + len, 1, out->size() - len, file);
36 
37     if (feof(file)) {
38       out->resize(len);
39       return true;
40     }
41     if (ferror(file)) {
42       return false;
43     }
44 
45     if (len == out->size()) {
46       if (out->size() == kMaxSize) {
47         fprintf(stderr, "Input too large.\n");
48         return false;
49       }
50       size_t cap = std::min(out->size() * 2, kMaxSize);
51       out->resize(cap);
52     }
53   }
54 }
55 
WriteToFile(const std::string & path,bssl::Span<const uint8_t> in)56 bool WriteToFile(const std::string &path, bssl::Span<const uint8_t> in) {
57   ScopedFILE file(fopen(path.c_str(), "wb"));
58   if (!file) {
59     fprintf(stderr, "Failed to open '%s': %s\n", path.c_str(), strerror(errno));
60     return false;
61   }
62   if (fwrite(in.data(), in.size(), 1, file.get()) != 1) {
63     fprintf(stderr, "Failed to write to '%s': %s\n", path.c_str(),
64             strerror(errno));
65     return false;
66   }
67   return true;
68 }
69