xref: /optee_os/core/kernel/tee_misc.c (revision 54e0470881add603f773fa48b8d26a78571815bb)
1 /*
2  * Copyright (c) 2014, STMicroelectronics International N.V.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright notice,
9  * this list of conditions and the following disclaimer.
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright notice,
12  * this list of conditions and the following disclaimer in the documentation
13  * and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
19  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25  * POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <kernel/tee_common.h>
29 #include <kernel/chip_services.h>
30 #include <kernel/tee_misc.h>
31 #include <mm/core_memprot.h>
32 #include <mm/tee_mmu_defs.h>
33 
34 
35 #include <kernel/tee_common_otp.h>
36 #include <kernel/tee_core_trace.h>
37 
38 static uint8_t tee_b2hs_add_base(uint8_t in)
39 {
40 	if (in > 9)
41 		return in + 55;
42 	else
43 		return in + 48;
44 }
45 
46 static int tee_hs2b_rem_base(uint8_t in, uint8_t *out)
47 {
48 	if (in < 48 || in > 70 || (in > 57 && in < 65))
49 		return -1;
50 
51 	if (in < 58)
52 		*out = in - 48;
53 	else
54 		*out = in - 55;
55 
56 	return 0;
57 }
58 
59 uint32_t tee_b2hs(uint8_t *b, uint8_t *hs, uint32_t blen, uint32_t hslen)
60 {
61 	uint32_t i = 0;
62 
63 	if (blen * 2 + 1 > hslen)
64 		return 0;
65 
66 	for (; i < blen; i++) {
67 		hs[i * 2 + 1] = tee_b2hs_add_base(b[i] & 0xf);
68 		hs[i * 2] = tee_b2hs_add_base(b[i] >> 4);
69 	}
70 	hs[blen * 2] = 0;
71 
72 	return blen * 2;
73 }
74 
75 uint32_t tee_hs2b(uint8_t *hs, uint8_t *b, uint32_t hslen, uint32_t blen)
76 {
77 	uint32_t i = 0;
78 	uint32_t len = TEE_HS2B_BBUF_SIZE(hslen);
79 	uint8_t hi;
80 	uint8_t lo;
81 
82 	if (len > blen)
83 		return 0;
84 
85 	for (; i < len; i++) {
86 		if (tee_hs2b_rem_base(hs[i * 2], &hi))
87 			return 0;
88 		if (tee_hs2b_rem_base(hs[i * 2 + 1], &lo))
89 			return 0;
90 		b[i] = (hi << 4) + lo;
91 	}
92 
93 	return len;
94 }
95