Andrew Scull | 2b5fbad | 2019-04-05 13:55:56 +0100 | [diff] [blame] | 1 | /* |
| 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. */ |
| 22 | void *memset(void *s, int c, size_t n); |
Andrew Scull | a1aa2ba | 2019-04-05 11:49:02 +0100 | [diff] [blame^] | 23 | void *memcpy(void *dst, const void *src, size_t n); |
Andrew Scull | 2b5fbad | 2019-04-05 13:55:56 +0100 | [diff] [blame] | 24 | |
| 25 | void memset_s(void *dest, rsize_t destsz, int ch, rsize_t count) |
| 26 | { |
| 27 | if (dest == NULL) { |
| 28 | goto fail; |
| 29 | } |
| 30 | |
| 31 | if (destsz > RSIZE_MAX || count > RSIZE_MAX) { |
| 32 | goto fail; |
| 33 | } |
| 34 | |
| 35 | if (count > destsz) { |
| 36 | goto fail; |
| 37 | } |
| 38 | |
| 39 | memset(dest, ch, count); |
| 40 | return; |
| 41 | |
| 42 | fail: |
| 43 | panic("memset_s failure"); |
| 44 | } |
Andrew Scull | a1aa2ba | 2019-04-05 11:49:02 +0100 | [diff] [blame^] | 45 | |
| 46 | void memcpy_s(void *dest, rsize_t destsz, const void *src, rsize_t count) |
| 47 | { |
| 48 | uintptr_t d = (uintptr_t)dest; |
| 49 | uintptr_t s = (uintptr_t)src; |
| 50 | |
| 51 | if (dest == NULL || src == NULL) { |
| 52 | goto fail; |
| 53 | } |
| 54 | |
| 55 | if (destsz > RSIZE_MAX || count > RSIZE_MAX) { |
| 56 | goto fail; |
| 57 | } |
| 58 | |
| 59 | if (count > destsz) { |
| 60 | goto fail; |
| 61 | } |
| 62 | |
| 63 | /* Destination overlaps the end of source. */ |
| 64 | if (d > s && d < (s + count)) { |
| 65 | goto fail; |
| 66 | } |
| 67 | |
| 68 | /* Source overlaps the end of destination. */ |
| 69 | if (s > d && s < (d + destsz)) { |
| 70 | goto fail; |
| 71 | } |
| 72 | |
| 73 | /* TODO: consider wrapping? */ |
| 74 | |
| 75 | memcpy(dest, src, count); |
| 76 | return; |
| 77 | |
| 78 | fail: |
| 79 | panic("memcpy_s failure"); |
| 80 | } |