blob: fd52a0fc8f43337b58c394c5d08dfc72931ff4f5 [file] [log] [blame]
Andrew Scull2b5fbad2019-04-05 13:55:56 +01001/*
2 * Copyright 2019 The Hafnium Authors.
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 * https://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 "hf/std.h"
18
19#include "hf/panic.h"
20
21/* Declare unsafe functions locally so they are not available globally. */
22void *memset(void *s, int c, size_t n);
Andrew Sculla1aa2ba2019-04-05 11:49:02 +010023void *memcpy(void *dst, const void *src, size_t n);
Andrew Scull8fbd7ee2019-04-05 14:36:34 +010024void *memmove(void *dst, const void *src, size_t n);
Andrew Scull2b5fbad2019-04-05 13:55:56 +010025
26void memset_s(void *dest, rsize_t destsz, int ch, rsize_t count)
27{
28 if (dest == NULL) {
29 goto fail;
30 }
31
32 if (destsz > RSIZE_MAX || count > RSIZE_MAX) {
33 goto fail;
34 }
35
36 if (count > destsz) {
37 goto fail;
38 }
39
40 memset(dest, ch, count);
41 return;
42
43fail:
44 panic("memset_s failure");
45}
Andrew Sculla1aa2ba2019-04-05 11:49:02 +010046
47void memcpy_s(void *dest, rsize_t destsz, const void *src, rsize_t count)
48{
49 uintptr_t d = (uintptr_t)dest;
50 uintptr_t s = (uintptr_t)src;
51
52 if (dest == NULL || src == NULL) {
53 goto fail;
54 }
55
56 if (destsz > RSIZE_MAX || count > RSIZE_MAX) {
57 goto fail;
58 }
59
60 if (count > destsz) {
61 goto fail;
62 }
63
64 /* Destination overlaps the end of source. */
65 if (d > s && d < (s + count)) {
66 goto fail;
67 }
68
69 /* Source overlaps the end of destination. */
70 if (s > d && s < (d + destsz)) {
71 goto fail;
72 }
73
74 /* TODO: consider wrapping? */
75
76 memcpy(dest, src, count);
77 return;
78
79fail:
80 panic("memcpy_s failure");
81}
Andrew Scull8fbd7ee2019-04-05 14:36:34 +010082
83void memmove_s(void *dest, rsize_t destsz, const void *src, rsize_t count)
84{
85 if (dest == NULL || src == NULL) {
86 goto fail;
87 }
88
89 if (destsz > RSIZE_MAX || count > RSIZE_MAX) {
90 goto fail;
91 }
92
93 if (count > destsz) {
94 goto fail;
95 }
96
97 memmove(dest, src, count);
98 return;
99
100fail:
101 panic("memmove_s failure");
102}