blob: bd9da5bbc867d4446f6283d9142f6709050bab61 [file] [log] [blame]
Heinrich Schuchardtf51a2262019-01-20 08:20:30 +01001// SPDX-License-Identifier: GPL-2.0+
2/*
3 * Library for freestanding binary
4 *
5 * Copyright 2019, Heinrich Schuchardt <xypron.glpk@gmx.de>
6 *
7 * GCC requires that freestanding programs provide memcpy(), memmove(),
8 * memset(), and memcmp().
9 */
10
11#include <common.h>
12
13/**
14 * memcmp() - compare memory areas
15 *
16 * @s1: pointer to first area
17 * @s2: pointer to second area
18 * @n: number of bytes to compare
19 * Return: 0 if both memory areas are the same, otherwise the sign of the
20 * result value is the same as the sign of the difference between
21 * the first differing pair of bytes taken as u8.
22 */
23int memcmp(const void *s1, const void *s2, size_t n)
24{
25 const u8 *pos1 = s1;
26 const u8 *pos2 = s2;
27
28 for (; n; --n) {
29 if (*pos1 != *pos2)
30 return *pos1 - *pos2;
31 ++pos1;
32 ++pos2;
33 }
34 return 0;
35}
36
37/**
38 * memcpy() - copy memory area
39 *
40 * @dest: destination buffer
41 * @src: source buffer
42 * @n: number of bytes to copy
43 * Return: pointer to destination buffer
44 */
45void *memmove(void *dest, const void *src, size_t n)
46{
47 u8 *d = dest;
48 const u8 *s = src;
49
50 if (d >= s) {
51 for (; n; --n)
52 *d++ = *s++;
53 } else {
54 d += n;
55 s += n;
56 for (; n; --n)
57 *--d = *--s;
58 }
59 return dest;
60}
61
62/**
63 * memcpy() - copy memory area
64 *
65 * @dest: destination buffer
66 * @src: source buffer
67 * @n: number of bytes to copy
68 * Return: pointer to destination buffer
69 */
70void *memcpy(void *dest, const void *src, size_t n)
71{
72 return memmove(dest, src, n);
73}
74
75/**
76 * memset() - fill memory with a constant byte
77 *
78 * @s: destination buffer
79 * @c: byte value
80 * @n: number of bytes to set
81 * Return: pointer to destination buffer
82 */
83void *memset(void *s, int c, size_t n)
84{
85 u8 *d = s;
86
87 for (; n; --n)
88 *d++ = c;
89 return s;
90}