1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2017-2020, Linaro Limited
4  */
5 
6 #include <pkcs11_ta.h>
7 #include <stddef.h>
8 #include <stdlib.h>
9 #include <string.h>
10 
11 #include "ck_helpers.h"
12 #include "local_utils.h"
13 #include "serializer.h"
14 
init_serial_object(struct serializer * obj)15 CK_RV init_serial_object(struct serializer *obj)
16 {
17 	struct pkcs11_object_head head = { 0 };
18 
19 	memset(obj, 0, sizeof(*obj));
20 
21 	return serialize_buffer(obj, &head, sizeof(head));
22 }
23 
finalize_serial_object(struct serializer * obj)24 void finalize_serial_object(struct serializer *obj)
25 {
26 	struct pkcs11_object_head head = { 0 };
27 
28 	head.attrs_size = obj->size - sizeof(head);
29 	head.attrs_count = obj->item_count;
30 	memcpy(obj->buffer, &head, sizeof(head));
31 }
32 
release_serial_object(struct serializer * obj)33 void release_serial_object(struct serializer *obj)
34 {
35 	free(obj->buffer);
36 	obj->buffer = NULL;
37 }
38 
39 /**
40  * serialize - append data in a serialized buffer
41  *
42  * Serialize data in provided buffer.
43  * Ensure 64byte alignment of appended data in the buffer.
44  */
serialize(char ** bstart,size_t * blen,void * data,size_t len)45 static CK_RV serialize(char **bstart, size_t *blen, void *data, size_t len)
46 {
47 	size_t nlen = *blen + len;
48 	char *buf = realloc(*bstart, nlen);
49 
50 	if (!buf)
51 		return CKR_HOST_MEMORY;
52 
53 	memcpy(buf + *blen, data, len);
54 
55 	*blen = nlen;
56 	*bstart = buf;
57 
58 	return CKR_OK;
59 }
60 
serialize_buffer(struct serializer * obj,void * data,size_t size)61 CK_RV serialize_buffer(struct serializer *obj, void *data, size_t size)
62 {
63 	return serialize(&obj->buffer, &obj->size, data, size);
64 }
65 
serialize_32b(struct serializer * obj,uint32_t data)66 CK_RV serialize_32b(struct serializer *obj, uint32_t data)
67 {
68 	return serialize_buffer(obj, &data, sizeof(data));
69 }
70 
serialize_ck_ulong(struct serializer * obj,CK_ULONG data)71 CK_RV serialize_ck_ulong(struct serializer *obj, CK_ULONG data)
72 {
73 	uint32_t data32 = data;
74 
75 	return serialize_buffer(obj, &data32, sizeof(data32));
76 }
77