comparison lib/lib.c @ 1638:184c98250cc5 draft

strtol() doesn't return error indicator for overflow, it just sets errno. So add estrtol() (which clears errno first), and xstrtol() (which error_exit()s on overflow).
author Rob Landley <rob@landley.net>
date Thu, 01 Jan 2015 16:28:51 -0600
parents 45fb262230c9
children 10922d83392a
comparison
equal deleted inserted replaced
1637:2c86e2cc1fd7 1638:184c98250cc5
231 free(cwd); 231 free(cwd);
232 232
233 return rlist; 233 return rlist;
234 } 234 }
235 235
236 long estrtol(char *str, char **end, int base)
237 {
238 errno = 0;
239
240 return strtol(str, end, base);
241 }
242
243 long xstrtol(char *str, char **end, int base)
244 {
245 long l = estrtol(str, end, base);
246
247 if (errno) perror_exit("%s", str);
248
249 return l;
250 }
251
236 // atol() with the kilo/mega/giga/tera/peta/exa extensions. 252 // atol() with the kilo/mega/giga/tera/peta/exa extensions.
237 // (zetta and yotta don't fit in 64 bits.) 253 // (zetta and yotta don't fit in 64 bits.)
238 long atolx(char *numstr) 254 long atolx(char *numstr)
239 { 255 {
240 char *c, *suffixes="cbkmgtpe", *end; 256 char *c, *suffixes="cbkmgtpe", *end;
241 long val = strtol(numstr, &c, 0); 257 long val;
242 258
259 val = xstrtol(numstr, &c, 0);
243 if (*c) { 260 if (*c) {
244 if (c != numstr && (end = strchr(suffixes, tolower(*c)))) { 261 if (c != numstr && (end = strchr(suffixes, tolower(*c)))) {
245 int shift = end-suffixes-2; 262 int shift = end-suffixes-2;
246 if (shift >= 0) val *= 1024L<<(shift*10); 263 if (shift >= 0) val *= 1024L<<(shift*10);
247 } else { 264 } else {
683 { 700 {
684 int i; 701 int i;
685 702
686 if (pidstr) { 703 if (pidstr) {
687 char *s; 704 char *s;
688 i = strtol(pidstr, &s, 10); 705
689 if (!*s) return i; 706 i = estrtol(pidstr, &s, 10);
707 if (!errno && !*s) return i;
690 708
691 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3; 709 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
692 } 710 }
693 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++) 711 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
694 if (!pidstr) xputs(signames[i].name); 712 if (!pidstr) xputs(signames[i].name);
713 *s, *str = modestr; 731 *s, *str = modestr;
714 mode_t extrabits = mode & ~(07777); 732 mode_t extrabits = mode & ~(07777);
715 733
716 // Handle octal mode 734 // Handle octal mode
717 if (isdigit(*str)) { 735 if (isdigit(*str)) {
718 mode = strtol(str, &s, 8); 736 mode = estrtol(str, &s, 8);
719 if (*s || (mode & ~(07777))) goto barf; 737 if (errno || *s || (mode & ~(07777))) goto barf;
720 738
721 return mode | extrabits; 739 return mode | extrabits;
722 } 740 }
723 741
724 // Gaze into the bin of permission... 742 // Gaze into the bin of permission...