hc
2024-08-12 233ab1bd4c5697f5cdec94e60206e8c6ac609b4c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// SPDX-License-Identifier: GPL-2.0+
/*
 * Handles a buffer that can be allocated and freed
 *
 * Copyright 2021 Google LLC
 * Written by Simon Glass <sjg@chromium.org>
 */
 
#include <common.h>
#include <abuf.h>
#include <malloc.h>
#include <mapmem.h>
#include <linux/string.h>
 
void abuf_set(struct abuf *abuf, void *data, size_t size)
{
   abuf_uninit(abuf);
   abuf->data = data;
   abuf->size = size;
}
 
void abuf_map_sysmem(struct abuf *abuf, ulong addr, size_t size)
{
   abuf_set(abuf, map_sysmem(addr, size), size);
}
 
bool abuf_realloc(struct abuf *abuf, size_t new_size)
{
   void *ptr;
 
   if (!new_size) {
       /* easy case, just need to uninit, freeing any allocation */
       abuf_uninit(abuf);
       return true;
   } else if (abuf->alloced) {
       /* currently allocated, so need to reallocate */
       ptr = realloc(abuf->data, new_size);
       if (!ptr)
           return false;
       abuf->data = ptr;
       abuf->size = new_size;
       return true;
   } else if (new_size <= abuf->size) {
       /*
        * not currently alloced and new size is no larger. Just update
        * it. Data is lost off the end if new_size < abuf->size
        */
       abuf->size = new_size;
       return true;
   } else {
       /* not currently allocated and new size is larger. Alloc and
        * copy in data. The new space is not inited.
        */
       ptr = memdup(abuf->data, new_size);
       if (!ptr)
           return false;
       abuf->data = ptr;
       abuf->size = new_size;
       abuf->alloced = true;
       return true;
   }
}
 
void *abuf_uninit_move(struct abuf *abuf, size_t *sizep)
{
   void *ptr;
 
   if (sizep)
       *sizep = abuf->size;
   if (!abuf->size)
       return NULL;
   if (abuf->alloced) {
       ptr = abuf->data;
   } else {
       ptr = memdup(abuf->data, abuf->size);
       if (!ptr)
           return NULL;
   }
   /* Clear everything out so there is no record of the data */
   abuf_init(abuf);
 
   return ptr;
}
 
void abuf_init_set(struct abuf *abuf, void *data, size_t size)
{
   abuf_init(abuf);
   abuf_set(abuf, data, size);
}
 
void abuf_init_move(struct abuf *abuf, void *data, size_t size)
{
   abuf_init_set(abuf, data, size);
   abuf->alloced = true;
}
 
void abuf_uninit(struct abuf *abuf)
{
   if (abuf->alloced)
       free(abuf->data);
   abuf_init(abuf);
}
 
void abuf_init(struct abuf *abuf)
{
   abuf->data = NULL;
   abuf->size = 0;
   abuf->alloced = false;
}