• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "util.h"
18 
19 #include <stdio.h>
20 #include <stdlib.h>
21 
22 #include "libfdt.h"
23 #include "libufdt_sysdeps.h"
24 
load_file_contents(FILE * fp,size_t * len_ptr)25 static char *load_file_contents(FILE *fp, size_t *len_ptr) {
26   // Gets the file size.
27   fseek(fp, 0, SEEK_END);
28   size_t len = ftell(fp);
29   fseek(fp, 0, SEEK_SET);
30 
31   char *buf = malloc(len);
32   if (buf == NULL) {
33     return NULL;
34   }
35 
36   if (fread(buf, len, 1, fp) != 1) {
37     free(buf);
38     return NULL;
39   }
40 
41   if (len_ptr) {
42     *len_ptr = len;
43   }
44 
45   return buf;
46 }
47 
load_file(const char * filename,size_t * len_ptr)48 char *load_file(const char *filename, size_t *len_ptr) {
49   FILE *fp = fopen(filename, "r");
50   if (!fp) {
51     return NULL;
52   }
53 
54   char *buf = load_file_contents(fp, len_ptr);
55 
56   fclose(fp);
57 
58   return buf;
59 }
60 
write_buf_to_file(const char * filename,const void * buf,size_t buf_size)61 int write_buf_to_file(const char *filename,
62                       const void *buf, size_t buf_size) {
63   int ret = 0;
64   FILE *fout = NULL;
65 
66   fout = fopen(filename, "wb");
67   if (!fout) {
68     ret = 1;
69     goto end;
70   }
71   if (fwrite(buf, 1, buf_size, fout) < 1) {
72     ret = 2;
73     goto end;
74   }
75 
76 end:
77   if (fout) fclose(fout);
78 
79   return ret;
80 }
81 
write_fdt_to_file(const char * filename,const void * fdt)82 int write_fdt_to_file(const char *filename, const void *fdt) {
83   return write_buf_to_file(filename, fdt, fdt_totalsize(fdt));
84 }
85