diff options
author | wm4 <wm4@nowhere> | 2014-07-01 23:10:38 +0200 |
---|---|---|
committer | wm4 <wm4@nowhere> | 2014-07-01 23:11:08 +0200 |
commit | 9a210ca2d50e02bf045866bbb2f44a33a3c48cd9 (patch) | |
tree | 9f685c66c9d3b2e968416c7f60d30ea56ab1f9bb /misc/ctype.h | |
parent | 0208ad4f3b4d2331b8242bb6fb12a9a4475ccae6 (diff) | |
download | mpv-9a210ca2d50e02bf045866bbb2f44a33a3c48cd9.tar.bz2 mpv-9a210ca2d50e02bf045866bbb2f44a33a3c48cd9.tar.xz |
Audit and replace all ctype.h uses
Something like "char *s = ...; isdigit(s[0]);" triggers undefined
behavior, because char can be signed, and thus s[0] can be a negative
value. The is*() functions require unsigned char _or_ EOF. EOF is a
special value outside of unsigned char range, thus the argument to the
is*() functions can't be a char.
This undefined behavior can actually trigger crashes if the
implementation of these functions e.g. uses lookup tables, which are
then indexed with out-of-range values.
Replace all <ctype.h> uses with our own custom mp_is*() functions added
with misc/ctype.h. As a bonus, these functions are locale-independent.
(Although currently, we _require_ C locale for other reasons.)
Diffstat (limited to 'misc/ctype.h')
-rw-r--r-- | misc/ctype.h | 19 |
1 files changed, 19 insertions, 0 deletions
diff --git a/misc/ctype.h b/misc/ctype.h new file mode 100644 index 0000000000..cbff799285 --- /dev/null +++ b/misc/ctype.h @@ -0,0 +1,19 @@ +#ifndef MP_CTYPE_H_ +#define MP_CTYPE_H_ + +// Roughly follows C semantics, but doesn't account for EOF, allows char as +// parameter, and is locale independent (always uses "C" locale). + +static inline int mp_isprint(char c) { return (unsigned char)c >= 32; } +static inline int mp_isspace(char c) { return c == ' ' || c == '\f' || c == '\n' || + c == '\r' || c == '\t' || c =='\v'; } +static inline int mp_isupper(char c) { return c >= 'A' && c <= 'Z'; } +static inline int mp_islower(char c) { return c >= 'a' && c <= 'z'; } +static inline int mp_isdigit(char c) { return c >= '0' && c <= '9'; } +static inline int mp_isalpha(char c) { return mp_isupper(c) || mp_islower(c); } +static inline int mp_isalnum(char c) { return mp_isalpha(c) || mp_isdigit(c); } + +static inline char mp_tolower(char c) { return mp_isupper(c) ? c - 'A' + 'a' : c; } +static inline char mp_toupper(char c) { return mp_islower(c) ? c - 'a' + 'A' : c; } + +#endif |