radare2/libr/util/name.c

101 lines
2.0 KiB
C
Raw Normal View History

/* radare - LGPL - Copyright 2009-2019 - pancake */
#include <r_util.h>
2020-04-07 12:07:40 +00:00
R_API bool r_name_validate_char(const char ch) {
2018-04-11 08:25:22 +00:00
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (IS_DIGIT(ch))) {
2016-07-12 20:15:19 +00:00
return true;
2018-04-11 08:25:22 +00:00
}
switch (ch) {
2015-01-02 01:10:20 +00:00
case ':':
case '.':
case '_':
2016-07-12 20:15:19 +00:00
return true;
}
2016-07-12 20:15:19 +00:00
return false;
}
2020-04-07 12:07:40 +00:00
R_API bool r_name_check(const char *name) {
/* Cannot start by number */
2018-04-11 08:25:22 +00:00
if (!name || !*name || IS_DIGIT (*name)) {
2016-07-12 20:15:19 +00:00
return false;
2018-04-11 08:25:22 +00:00
}
/* Cannot contain non-alphanumeric chars + [:._] */
2018-04-11 08:25:22 +00:00
for (; *name != '\0'; name++) {
if (!r_name_validate_char (*name)) {
2016-07-12 20:15:19 +00:00
return false;
2018-04-11 08:25:22 +00:00
}
}
2016-07-12 20:15:19 +00:00
return true;
}
static inline bool is_special_char (char *name) {
const char n = *name;
return (n == 'b' || n == 'f' || n == 'n' || n == 'r' || n == 't' || n == 'v' || n == 'a');
}
2020-04-07 12:07:40 +00:00
R_API bool r_name_filter(char *name, int maxlen) {
size_t i, len;
2018-04-11 08:25:22 +00:00
if (!name) {
2020-04-07 12:07:40 +00:00
return false;
2018-04-11 08:25:22 +00:00
}
2015-12-08 12:24:21 +00:00
if (maxlen < 0) {
maxlen = strlen (name);
}
r_str_trim (name);
char *oname = name;
2015-12-08 12:24:21 +00:00
for (i = 0; *name; name++, i++) {
if (maxlen && i > maxlen) {
*name = '\0';
break;
}
if (!r_name_validate_char (*name) && *name != '\\') {
*name = '_';
2015-12-08 12:24:21 +00:00
// r_str_ccpy (name, name+1, 0);
//name--;
}
}
while (i > 0) {
if (*(name - 1) == '\\' && is_special_char (name)) {
*name = '_';
*(name - 1) = '_';
}
if (*name == '\\') {
*name = '_';
}
name--;
i--;
}
if (*name == '\\') {
*name = '_';
}
// trimming trailing and leading underscores
len = strlen (name);
for (; len > 0 && *(name + len - 1) == '_'; len--) {
;
}
2017-12-19 14:18:00 +00:00
if (!len) { // name consists only of underscores
return r_name_check (oname);
}
for (i = 0; *(name + i) == '_'; i++, len--) {
;
}
memmove (name, name + i, len);
*(name + len) = '\0';
return r_name_check (oname);
}
R_API char *r_name_filter2(const char *name) {
2020-04-07 12:07:40 +00:00
size_t i;
2018-04-11 08:25:22 +00:00
while (!IS_PRINTABLE (*name)) {
name++;
2018-04-11 08:25:22 +00:00
}
char *res = strdup (name);
2015-12-08 12:24:21 +00:00
for (i = 0; res[i]; i++) {
if (!r_name_validate_char (res[i])) {
res[i] = '_';
}
}
return res;
}