sanitizer_libc.cc revision 88207ab15125e2f1e9b3d541b735b2b8aba9b6d9
1//===-- sanitizer_libc.cc -------------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is shared between AddressSanitizer and ThreadSanitizer
11// run-time libraries. See sanitizer_libc.h for details.
12//===----------------------------------------------------------------------===//
13#include "sanitizer_common.h"
14#include "sanitizer_libc.h"
15
16namespace __sanitizer {
17
18void MiniLibcStub() {
19}
20
21void *internal_memchr(const void *s, int c, uptr n) {
22  const char* t = (char*)s;
23  for (uptr i = 0; i < n; ++i, ++t)
24    if (*t == c)
25      return (void*)t;
26  return 0;
27}
28
29int internal_memcmp(const void* s1, const void* s2, uptr n) {
30  const char* t1 = (char*)s1;
31  const char* t2 = (char*)s2;
32  for (uptr i = 0; i < n; ++i, ++t1, ++t2)
33    if (*t1 != *t2)
34      return *t1 < *t2 ? -1 : 1;
35  return 0;
36}
37
38void *internal_memcpy(void *dest, const void *src, uptr n) {
39  char *d = (char*)dest;
40  char *s = (char*)src;
41  for (uptr i = 0; i < n; ++i)
42    d[i] = s[i];
43  return dest;
44}
45
46void *internal_memset(void* s, int c, uptr n) {
47  // The next line prevents Clang from making a call to memset() instead of the
48  // loop below.
49  // FIXME: building the runtime with -ffreestanding is a better idea. However
50  // there currently are linktime problems due to PR12396.
51  char volatile *t = (char*)s;
52  for (uptr i = 0; i < n; ++i, ++t) {
53    *t = c;
54  }
55  return s;
56}
57
58char* internal_strdup(const char *s) {
59  uptr len = internal_strlen(s);
60  char *s2 = (char*)InternalAlloc(len + 1);
61  internal_memcpy(s2, s, len);
62  s2[len] = 0;
63  return s2;
64}
65
66int internal_strcmp(const char *s1, const char *s2) {
67  while (true) {
68    unsigned c1 = *s1;
69    unsigned c2 = *s2;
70    if (c1 != c2) return (c1 < c2) ? -1 : 1;
71    if (c1 == 0) break;
72    s1++;
73    s2++;
74  }
75  return 0;
76}
77
78char* internal_strchr(const char *s, int c) {
79  while (true) {
80    if (*s == (char)c)
81      return (char*)s;
82    if (*s == 0)
83      return 0;
84    s++;
85  }
86}
87
88char *internal_strrchr(const char *s, int c) {
89  const char *res = 0;
90  for (uptr i = 0; s[i]; i++) {
91    if (s[i] == c) res = s + i;
92  }
93  return (char*)res;
94}
95
96uptr internal_strlen(const char *s) {
97  uptr i = 0;
98  while (s[i]) i++;
99  return i;
100}
101
102char *internal_strncpy(char *dst, const char *src, uptr n) {
103  uptr i;
104  for (i = 0; i < n && src[i]; i++)
105    dst[i] = src[i];
106  for (; i < n; i++)
107    dst[i] = '\0';
108  return dst;
109}
110
111}  // namespace __sanitizer
112