size_t UserPatcher::mapAddresses(const char *mapBuf, MapEntry *mapEntries, size_t nentries) {
	if (nentries == 0 || !mapBuf)
		return 0;
	
	size_t nfound = 0;
	const char *ptr = mapBuf;
	while (*ptr) {
		size_t i = 1;
		if (*ptr == '\n') {
			MapEntry *currEntry = nullptr;
			
			for (size_t j = 0; j < nentries; j++) {
				if (!mapEntries[j].filename)
					continue;
				if (!strncmp(&ptr[i], mapEntries[j].filename, mapEntries[j].length)) {
					currEntry = &mapEntries[j];
					i += mapEntries[j].length;
					break;
				}
			}
			
			if (currEntry) {
				const char *text = strstr(&ptr[i], "__TEXT", strlen("__TEXT"));
				if (text) {
					i += strlen("__TEXT");
					const char *arrow = strstr(&ptr[i], "->", strlen("->"));
					if (arrow) {
						currEntry->startTEXT = strtouq(text + strlen("__TEXT") + 1, nullptr, 16);
						currEntry->endTEXT = strtouq(arrow + strlen("->") + 1, nullptr, 16);
						
						const char *data = strstr(&ptr[i], "__DATA", strlen("__DATA"));
						if (data) {
							i += strlen("__DATA");
							arrow = strstr(&ptr[i], "->", strlen("->"));
							if (arrow) {
								currEntry->startDATA = strtouq(data + strlen("__DATA") + 1, nullptr, 16);
								currEntry->endDATA = strtouq(arrow + strlen("->") + 1, nullptr, 16);
							}
						}
						
						nfound++;
					}
				}
			}
		}
		ptr += i;
	}
	
	return nfound;
}
Beispiel #2
0
static int
vfs_getrealpath(const char * path, char * realpath, size_t bufsize, vfs_context_t ctx)
{
	vnode_t vp;
	struct mount *mp = NULL;
	char  *str;
	char ch;
	uint32_t  id;
	ino64_t ino;
	int error;
	int length;

	/* Get file system id and move str to next component. */
	id = strtoul(path, &str, 10);
	if (id == 0 || str[0] != '/') {
		return (EINVAL);
	}
	while (*str == '/') {
		str++;
	}
	ch = *str;

	mp = mount_lookupby_volfsid(id, 1);
	if (mp == NULL) {
		return (EINVAL);  /* unexpected failure */
	}
	/* Check for an alias to a file system root. */
	if (ch == '@' && str[1] == '\0') {
		ino = 2;
		str++;
	} else {
		/* Get file id and move str to next component. */
	    ino = strtouq(str, &str, 10);
	}

	/* Get the target vnode. */
	if (ino == 2) {
		error = VFS_ROOT(mp, &vp, ctx);
	} else {
		error = VFS_VGET(mp, ino, &vp, ctx);
	}
	vfs_unbusy(mp);
	if (error) {
		goto out;
	}
	realpath[0] = '\0';

	/* Get the absolute path to this vnode. */
	error = build_path(vp, realpath, bufsize, &length, 0, ctx);
	vnode_put(vp);

	if (error == 0 && *str != '\0') {
		int attempt = strlcat(realpath, str, MAXPATHLEN);
		if (attempt > MAXPATHLEN){
			error = ENAMETOOLONG;
		}
	}
out:
	return (error);
}
Beispiel #3
0
Bool
StrUtil_StrToSizet(size_t *out,     // OUT: The output value
                   const char *str) // IN : String to parse
{
   char *ptr;

   ASSERT(out);
   ASSERT(str);

   errno = 0;
#if defined VM_X86_64
   ASSERT_ON_COMPILE(sizeof *out == sizeof(uint64));
#   if defined(_WIN32)
   *out = _strtoui64(str, &ptr, 0);
#   elif defined(__FreeBSD__)
   *out = strtouq(str, &ptr, 0);
#   else
   *out = strtoull(str, &ptr, 0);
#   endif
#else
   ASSERT_ON_COMPILE(sizeof *out == sizeof(uint32));
   *out = strtoul(str, &ptr, 0);
#endif

   return *ptr == '\0' && errno != ERANGE;
}
Beispiel #4
0
/*
 * Convert a string to an unsigned quad integer.
 */
uint64_t
__wt_strtouq(const char *nptr, char **endptr, int base)
{
#if defined(HAVE_STRTOUQ)
	return (strtouq(nptr, endptr, base));
#else
	STATIC_ASSERT(sizeof(uint64_t) == sizeof(unsigned long long));

	return (strtoull(nptr, endptr, base));
#endif
}
Beispiel #5
0
/**
 * eva_strtoull:
 * @str: the string to parse a longlong unsigned integer (guint64) from.
 * @endp: optional place to store the character right past
 * the number in @str.  If *endp == @str, then you may assume an error
 * occurred.
 * @base: the assumed base for the number to parse.  eg "2" to
 * parse a binary, "8" for octal, "10" for decimal, "16" for hexidecimal.
 * Also, "0" is autodetects the C-style base.
 *
 * Like strtol, but for 64-bit unsigned integers.
 *
 * returns: the parsed unsigned integer.
 */
guint64
eva_strtoull (const char *str,
	      char      **endp,
	      int         base)
{
#if HAVE_STRTOUQ
  return strtouq (str, endp, base);
#elif HAVE_STRTOULL
  return strtoull (str, endp, base);
#else
  return strtoul (str, endp, base);
#endif
}
Beispiel #6
0
/*
 * Convert string after @@ (@@ not included) to TID.  Returns 0 on success,
 * EINVAL on failure.
 *
 * If this function fails *ispfs, *tidp, and *localizationp will not
 * be modified.
 */
int
hammer_str_to_tid(const char *str, int *ispfsp,
		  hammer_tid_t *tidp, u_int32_t *localizationp)
{
	hammer_tid_t tid;
	u_int32_t localization;
	char *ptr;
	int ispfs;
	int n;

	/*
	 * Forms allowed for TID:  "0x%016llx"
	 *			   "-1"
	 */
	tid = strtouq(str, &ptr, 0);
	n = ptr - str;
	if (n == 2 && str[0] == '-' && str[1] == '1') {
		/* ok */
	} else if (n == 18 && str[0] == '0' && (str[1] | 0x20) == 'x') {
		/* ok */
	} else {
		return(EINVAL);
	}

	/*
	 * Forms allowed for PFS:  ":%05d"  (i.e. "...:0" would be illegal).
	 */
	str = ptr;
	if (*str == ':') {
		localization = strtoul(str + 1, &ptr, 10) << 16;
		if (ptr - str != 6)
			return(EINVAL);
		str = ptr;
		ispfs = 1;
	} else {
		localization = *localizationp;
		ispfs = 0;
	}

	/*
	 * Any trailing junk invalidates special extension handling.
	 */
	if (*str)
		return(EINVAL);
	*tidp = tid;
	*localizationp = localization;
	*ispfsp = ispfs;
	return(0);
}
Beispiel #7
0
/*
 * Convert an expression of the following forms to a uintmax_t.
 * 	1) A positive decimal number.
 *	2) A positive decimal number followed by a 'b' or 'B' (mult by 512).
 *	3) A positive decimal number followed by a 'k' or 'K' (mult by 1 << 10).
 *	4) A positive decimal number followed by a 'm' or 'M' (mult by 1 << 20).
 *	5) A positive decimal number followed by a 'g' or 'G' (mult by 1 << 30).
 *	5) A positive decimal number followed by a 'w' or 'W' (mult by sizeof int).
 *	6) Two or more positive decimal numbers (with/without [BbKkMmGgWw])
 *	   separated by 'x' or 'X' (also '*' for backwards compatibility),
 *	   specifying the product of the indicated values.
 */
static uintmax_t
get_num(const char *val)
{
	uintmax_t num, mult, prevnum;
	char *expr;

	errno = 0;
	num = strtouq(val, &expr, 0);
	if (errno != 0)				/* Overflow or underflow. */
		err(1, "%s", oper);
	
	if (expr == val)			/* No valid digits. */
		errx(1, "%s: illegal numeric value", oper);

	mult = postfix_to_mult(*expr);

	if (mult != 0) {
		prevnum = num;
		num *= mult;
		/* Check for overflow. */
		if (num / mult != prevnum)
			goto erange;
		expr++;
	}

	switch (*expr) {
		case '\0':
			break;
		case '*':			/* Backward compatible. */
		case 'X':
		case 'x':
			mult = get_num(expr + 1);
			prevnum = num;
			num *= mult;
			if (num / mult == prevnum)
				break;
erange:
			errx(1, "%s: %s", oper, strerror(ERANGE));
		default:
			errx(1, "%s: illegal numeric value", oper);
	}
	return (num);
}
Beispiel #8
0
Bool
StrUtil_StrToUint64(uint64 *out,     // OUT: The output value
                    const char *str) // IN : String to parse
{
   char *ptr;

   ASSERT(out);
   ASSERT(str);

   errno = 0;

#if defined(_WIN32)
   *out = _strtoui64(str, &ptr, 0);
#elif defined(__FreeBSD__)
   *out = strtouq(str, &ptr, 0);
#else
   *out = strtoull(str, &ptr, 0);
#endif

   return ptr[0] == '\0' && errno != ERANGE && errno != EINVAL;
}
inline ir_code s_strtocode(char *val)
{
	ir_code code=0;
	char *endptr;

	errno=0;
#       ifdef LONG_IR_CODE
	code=strtouq(val,&endptr,0);
	if((code==(unsigned long long) -1 && errno==ERANGE) ||
	    strlen(endptr)!=0 || strlen(val)==0)
	{
		logprintf(LOG_ERR,"error in configfile line %d:",line);
		logprintf(LOG_ERR,"\"%s\": must be a valid (unsigned long "
			  "long) number",val);
		parse_error=1;
		return(0);
	}
#       else
	code=strtoul(val,&endptr,0);
	if(code==ULONG_MAX && errno==ERANGE)
	{
		logprintf(LOG_ERR,"error in configfile line %d:",line);
		logprintf(LOG_ERR,"code is out of range");
		logprintf(LOG_ERR,"try compiling lircd with the LONG_IR_CODE "
			  "option");
		parse_error=1;
		return(0);
	}
	else if(strlen(endptr)!=0 || strlen(val)==0)
	{
		logprintf(LOG_ERR,"error in configfile line %d:",line);
		logprintf(LOG_ERR,"\"%s\": must be a valid (unsigned long) "
			  "number",val);
		parse_error=1;
		return(0);
	}
#       endif
	return(code);
}
Beispiel #10
0
/*
 * str2recno --
 *	Convert a string to a record number.
 */
static int
str2recno(WT_SESSION_IMPL *session, const char *p, uint64_t *recnop)
{
	uint64_t recno;
	char *endptr;

	/*
	 * strtouq takes lots of things like hex values, signs and so on and so
	 * forth -- none of them are OK with us.  Check the string starts with
	 * digit, that turns off the special processing.
	 */
	if (!isdigit(p[0]))
		goto format;

	errno = 0;
	recno = strtouq(p, &endptr, 0);
	if (recno == ULLONG_MAX && errno == ERANGE)
		WT_RET_MSG(session, ERANGE, "%s: invalid record number", p);
	if (endptr[0] != '\0')
format:		WT_RET_MSG(session, EINVAL, "%s: invalid record number", p);

	*recnop = recno;
	return (0);
}
Beispiel #11
0
/*
 * Parse a name into a MIB entry.
 * Lookup and print out the MIB entry if it exists.
 * Set a new value if requested.
 */
static void
parse(const char *string)
{
	size_t len;
	int i, j;
	void *newval = NULL;
	int intval;
	unsigned int uintval;
	long longval;
	unsigned long ulongval;
	size_t newsize = 0;
	quad_t quadval;
	u_quad_t uquadval;
	int mib[CTL_MAXNAME];
	char *cp, fmt[BUFSIZ];
	const char *name;
	char *name_allocated = NULL;
	u_int kind;

	if ((cp = strchr(string, '=')) != NULL) {
		if ((name_allocated = malloc(cp - string + 1)) == NULL)
			err(1, "malloc failed");
		strlcpy(name_allocated, string, cp - string + 1);
		name = name_allocated;
		
		while (isspace(*++cp))
			;

		newval = cp;
		newsize = strlen(cp);
	} else {
		name = string;
	}

	len = CTL_MAXNAME;
	if (sysctlnametomib(name, mib, &len) < 0) {
		if (errno == ENOENT) {
			errx(1, "unknown oid '%s'", name);
		} else {
			err(1, "sysctlnametomib(\"%s\")", name);
		}
	}

	if (oidfmt(mib, len, fmt, &kind))
		err(1, "couldn't find format of oid '%s'", name);

	if (newval == NULL) {
		if ((kind & CTLTYPE) == CTLTYPE_NODE) {
			sysctl_all(mib, len);
		} else {
			i = show_var(mib, len);
			if (!i && !bflag)
				putchar('\n');
		}
	} else {
		if ((kind & CTLTYPE) == CTLTYPE_NODE)
			errx(1, "oid '%s' isn't a leaf node", name);

		if (!(kind&CTLFLAG_WR))
			errx(1, "oid '%s' is read only", name);
	
		switch (kind & CTLTYPE) {
			case CTLTYPE_INT:
				if (!(strcmp(fmt, "IK") == 0)) {
					if (!set_IK(newval, &intval))
						errx(1, "invalid value '%s'",
						    (char *)newval);
				} else
					intval = (int) strtol(newval, NULL, 0);
				newval = &intval;
				newsize = sizeof(intval);
				break;
			case CTLTYPE_UINT:
				uintval = (int) strtoul(newval, NULL, 0);
				newval = &uintval;
				newsize = sizeof uintval;
				break;
			case CTLTYPE_LONG:
				longval = strtol(newval, NULL, 0);
				newval = &longval;
				newsize = sizeof longval;
				break;
			case CTLTYPE_ULONG:
				ulongval = strtoul(newval, NULL, 0);
				newval = &ulongval;
				newsize = sizeof ulongval;
				break;
			case CTLTYPE_STRING:
				break;
			case CTLTYPE_QUAD:
				quadval = strtoq(newval, NULL, 0);
				newval = &quadval;
				newsize = sizeof(quadval);
				break;
			case CTLTYPE_UQUAD:
				uquadval = strtouq(newval, NULL, 0);
				newval = &uquadval;
				newsize = sizeof(uquadval);
				break;
			case CTLTYPE_OPAQUE:
				if (strcmp(fmt, "T,dev_t") == 0 ||
				    strcmp(fmt, "T,udev_t") == 0
				) {
					set_T_dev_t((char*)newval, &newval,
						    &newsize);
					break;
				}
				/* FALLTHROUGH */
			default:
				errx(1, "oid '%s' is type %d,"
					" cannot set that", name,
					kind & CTLTYPE);
		}

		i = show_var(mib, len);
		if (sysctl(mib, len, 0, 0, newval, newsize) == -1) {
			if (!i && !bflag)
				putchar('\n');
			switch (errno) {
			case EOPNOTSUPP:
				errx(1, "%s: value is not available", 
					string);
			case ENOTDIR:
				errx(1, "%s: specification is incomplete", 
					string);
			case ENOMEM:
				errx(1, "%s: type is unknown to this program", 
					string);
			default:
				warn("%s", string);
				return;
			}
		}
		if (!bflag)
			printf(" -> ");
		i = nflag;
		nflag = 1;
		j = show_var(mib, len);
		if (!j && !bflag)
			putchar('\n');
		nflag = i;
	}

	if (name_allocated != NULL)
		free(name_allocated);
}
Beispiel #12
0
int
vsscanf(const char *inp, char const *fmt0, va_list ap)
{
	int inr;
	const u_char *fmt = (const u_char *)fmt0;
	int c;			/* character from format, or conversion */
	size_t width;		/* field width, or 0 */
	char *p;		/* points into all kinds of strings */
	int n;			/* handy integer */
	int flags;		/* flags as defined above */
	char *p0;		/* saves original value of p when necessary */
	int nassigned;		/* number of fields assigned */
	int nconversions;	/* number of conversions */
	int nread;		/* number of characters consumed from fp */
	int base;		/* base argument to conversion function */
	char ccltab[256];	/* character class table for %[...] */
	char buf[BUF];		/* buffer for numeric conversions */

	/* `basefix' is used to avoid `if' tests in the integer scanner */
	static short basefix[17] =
		{ 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

	inr = strlen(inp);
	
	nassigned = 0;
	nconversions = 0;
	nread = 0;
	base = 0;		/* XXX just to keep gcc happy */
	for (;;) {
		c = *fmt++;
		if (c == 0)
			return (nassigned);
		if (isspace(c)) {
			while (inr > 0 && isspace(*inp))
				nread++, inr--, inp++;
			continue;
		}
		if (c != '%')
			goto literal;
		width = 0;
		flags = 0;
		/*
		 * switch on the format.  continue if done;
		 * break once format type is derived.
		 */
again:		c = *fmt++;
		switch (c) {
		case '%':
literal:
			if (inr <= 0)
				goto input_failure;
			if (*inp != c)
				goto match_failure;
			inr--, inp++;
			nread++;
			continue;

		case '*':
			flags |= SUPPRESS;
			goto again;
		case 'l':
			if (flags & LONG) {
				flags &= ~LONG;
				flags |= LONGLONG;
			} else
				flags |= LONG;
			goto again;
		case 'q':
			flags |= LONGLONG;	/* not quite */
			goto again;
		case 'h':
			if (flags & SHORT) {
				flags &= ~SHORT;
				flags |= SHORTSHORT;
			} else
				flags |= SHORT;
			goto again;

		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			width = width * 10 + c - '0';
			goto again;

		/*
		 * Conversions.
		 */
		case 'd':
			c = CT_INT;
			base = 10;
			break;

		case 'i':
			c = CT_INT;
			base = 0;
			break;

		case 'o':
			c = CT_INT;
			flags |= UNSIGNED;
			base = 8;
			break;

		case 'u':
			c = CT_INT;
			flags |= UNSIGNED;
			base = 10;
			break;

		case 'X':
		case 'x':
			flags |= PFXOK;	/* enable 0x prefixing */
			c = CT_INT;
			flags |= UNSIGNED;
			base = 16;
			break;

		case 's':
			c = CT_STRING;
			break;

		case '[':
			fmt = __sccl(ccltab, fmt);
			flags |= NOSKIP;
			c = CT_CCL;
			break;

		case 'c':
			flags |= NOSKIP;
			c = CT_CHAR;
			break;

		case 'p':	/* pointer format is like hex */
			flags |= POINTER | PFXOK;
			c = CT_INT;
			flags |= UNSIGNED;
			base = 16;
			break;

		case 'n':
			nconversions++;
			if (flags & SUPPRESS)	/* ??? */
				continue;
			if (flags & SHORTSHORT)
				*va_arg(ap, char *) = nread;
			else if (flags & SHORT)
				*va_arg(ap, short *) = nread;
			else if (flags & LONG)
				*va_arg(ap, long *) = nread;
			else if (flags & LONGLONG)
				*va_arg(ap, long long *) = nread;
			else
				*va_arg(ap, int *) = nread;
			continue;
		}

		/*
		 * We have a conversion that requires input.
		 */
		if (inr <= 0)
			goto input_failure;

		/*
		 * Consume leading white space, except for formats
		 * that suppress this.
		 */
		if ((flags & NOSKIP) == 0) {
			while (isspace(*inp)) {
				nread++;
				if (--inr > 0)
					inp++;
				else 
					goto input_failure;
			}
			/*
			 * Note that there is at least one character in
			 * the buffer, so conversions that do not set NOSKIP
			 * can no longer result in an input failure.
			 */
		}

		/*
		 * Do the conversion.
		 */
		switch (c) {

		case CT_CHAR:
			/* scan arbitrary characters (sets NOSKIP) */
			if (width == 0)
				width = 1;
			if (flags & SUPPRESS) {
				size_t sum = 0;
				for (;;) {
					if ((n = inr) < (int)width) {
						sum += n;
						width -= n;
						inp += n;
						if (sum == 0)
							goto input_failure;
						break;
					} else {
						sum += width;
						inr -= width;
						inp += width;
						break;
					}
				}
				nread += sum;
			} else {
				bcopy(inp, va_arg(ap, char *), width);
				inr -= width;
				inp += width;
				nread += width;
				nassigned++;
			}
			nconversions++;
			break;

		case CT_CCL:
			/* scan a (nonempty) character class (sets NOSKIP) */
			if (width == 0)
				width = (size_t)~0;	/* `infinity' */
			/* take only those things in the class */
			if (flags & SUPPRESS) {
				n = 0;
				while (ccltab[(unsigned char)*inp]) {
					n++, inr--, inp++;
					if (--width == 0)
						break;
					if (inr <= 0) {
						if (n == 0)
							goto input_failure;
						break;
					}
				}
				if (n == 0)
					goto match_failure;
			} else {
				p0 = p = va_arg(ap, char *);
				while (ccltab[(unsigned char)*inp]) {
					inr--;
					*p++ = *inp++;
					if (--width == 0)
						break;
					if (inr <= 0) {
						if (p == p0)
							goto input_failure;
						break;
					}
				}
				n = p - p0;
				if (n == 0)
					goto match_failure;
				*p = 0;
				nassigned++;
			}
			nread += n;
			nconversions++;
			break;

		case CT_STRING:
			/* like CCL, but zero-length string OK, & no NOSKIP */
			if (width == 0)
				width = (size_t)~0;
			if (flags & SUPPRESS) {
				n = 0;
				while (!isspace(*inp)) {
					n++, inr--, inp++;
					if (--width == 0)
						break;
					if (inr <= 0)
						break;
				}
				nread += n;
			} else {
				p0 = p = va_arg(ap, char *);
				while (!isspace(*inp)) {
					inr--;
					*p++ = *inp++;
					if (--width == 0)
						break;
					if (inr <= 0)
						break;
				}
				*p = 0;
				nread += p - p0;
				nassigned++;
			}
			nconversions++;
			continue;

		case CT_INT:
			/* scan an integer as if by the conversion function */
#ifdef hardway
			if (width == 0 || width > sizeof(buf) - 1)
				width = sizeof(buf) - 1;
#else
			/* size_t is unsigned, hence this optimisation */
			if (--width > sizeof(buf) - 2)
				width = sizeof(buf) - 2;
			width++;
#endif
			flags |= SIGNOK | NDIGITS | NZDIGITS;
			for (p = buf; width; width--) {
				c = *inp;
				/*
				 * Switch on the character; `goto ok'
				 * if we accept it as a part of number.
				 */
				switch (c) {

				/*
				 * The digit 0 is always legal, but is
				 * special.  For %i conversions, if no
				 * digits (zero or nonzero) have been
				 * scanned (only signs), we will have
				 * base==0.  In that case, we should set
				 * it to 8 and enable 0x prefixing.
				 * Also, if we have not scanned zero digits
				 * before this, do not turn off prefixing
				 * (someone else will turn it off if we
				 * have scanned any nonzero digits).
				 */
				case '0':
					if (base == 0) {
						base = 8;
						flags |= PFXOK;
					}
					if (flags & NZDIGITS)
					    flags &= ~(SIGNOK|NZDIGITS|NDIGITS);
					else
					    flags &= ~(SIGNOK|PFXOK|NDIGITS);
					goto ok;

				/* 1 through 7 always legal */
				case '1': case '2': case '3':
				case '4': case '5': case '6': case '7':
					base = basefix[base];
					flags &= ~(SIGNOK | PFXOK | NDIGITS);
					goto ok;

				/* digits 8 and 9 ok iff decimal or hex */
				case '8': case '9':
					base = basefix[base];
					if (base <= 8)
						break;	/* not legal here */
					flags &= ~(SIGNOK | PFXOK | NDIGITS);
					goto ok;

				/* letters ok iff hex */
				case 'A': case 'B': case 'C':
				case 'D': case 'E': case 'F':
				case 'a': case 'b': case 'c':
				case 'd': case 'e': case 'f':
					/* no need to fix base here */
					if (base <= 10)
						break;	/* not legal here */
					flags &= ~(SIGNOK | PFXOK | NDIGITS);
					goto ok;

				/* sign ok only as first character */
				case '+': case '-':
					if (flags & SIGNOK) {
						flags &= ~SIGNOK;
						goto ok;
					}
					break;

				/* x ok iff flag still set & 2nd char */
				case 'x': case 'X':
					if (flags & PFXOK && p == buf + 1) {
						base = 16;	/* if %i */
						flags &= ~PFXOK;
						goto ok;
					}
					break;
				}

				/*
				 * If we got here, c is not a legal character
				 * for a number.  Stop accumulating digits.
				 */
				break;
		ok:
				/*
				 * c is legal: store it and look at the next.
				 */
				*p++ = c;
				if (--inr > 0)
					inp++;
				else 
					break;		/* end of input */
			}
			/*
			 * If we had only a sign, it is no good; push
			 * back the sign.  If the number ends in `x',
			 * it was [sign] '0' 'x', so push back the x
			 * and treat it as [sign] '0'.
			 */
			if (flags & NDIGITS) {
				if (p > buf) {
					inp--;
					inr++;
				}
				goto match_failure;
			}
			c = ((u_char *)p)[-1];
			if (c == 'x' || c == 'X') {
				--p;
				inp--;
				inr++;
			}
			if ((flags & SUPPRESS) == 0) {
				u_quad_t res;

				*p = 0;
				if ((flags & UNSIGNED) == 0)
				    res = strtoq(buf, (char **)NULL, base);
				else
				    res = strtouq(buf, (char **)NULL, base);
				if (flags & POINTER)
					*va_arg(ap, void **) =
						(void *)(uintptr_t)res;
				else if (flags & SHORTSHORT)
					*va_arg(ap, char *) = res;
				else if (flags & SHORT)
					*va_arg(ap, short *) = res;
				else if (flags & LONG)
					*va_arg(ap, long *) = res;
				else if (flags & LONGLONG)
					*va_arg(ap, long long *) = res;
				else
					*va_arg(ap, int *) = res;
				nassigned++;
			}
			nread += p - buf;
			nconversions++;
			break;

		}
	}
input_failure:
	return (nconversions != 0 ? nassigned : -1);
match_failure:
	return (nassigned);
}
Beispiel #13
0
int
main(int argc, char *argv[])
{
	u_int64_t val;
	int ch;
	char *p, buf[100];		/* > max number of digits. */

	if (pledge("stdio", NULL) == -1)
		err(1, "pledge");

	while ((ch = getopt(argc, argv, "h")) != -1) {
		switch (ch) {
		case 'h':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	/* No args supplied, read numbers from stdin. */
	if (argc == 0) {
		for (;;) {
			if (fgets(buf, sizeof(buf), stdin) == NULL) {
				if (ferror(stdin))
					err(1, "stdin");
				return 0;
			}
			buf[strcspn(buf, "\n")] = '\0';
			for (p = buf; isblank((unsigned char)*p); ++p)
				;
			if (*p == '\0')
				continue;
			if (*p == '-')
				errx(1, "negative numbers aren't permitted.");
			errno = 0;
			val = strtouq(buf, &p, 10);
			if (errno)
				err(1, "%s", buf);
			for (; isblank((unsigned char)*p); ++p)
				;
			if (*p != '\0')
				errx(1, "%s: illegal numeric format.", buf);
			pr_fact(val);
		}
	/* Factor the arguments. */
	} else {
		for (; *argv != NULL; ++argv) {
			if (argv[0][0] == '-')
				errx(1, "negative numbers aren't permitted.");
			errno = 0;
			val = strtouq(argv[0], &p, 10);
			if (errno)
				err(1, "%s", argv[0]);
			if (*p != '\0')
				errx(1, "%s: illegal numeric format.", argv[0]);
			pr_fact(val);
		}
	}
	return 0;
}
Beispiel #14
0
static void
set(char *t, NODE *ip)
{
	int type;
	char *kw, *val = NULL;
	struct group *gr;
	struct passwd *pw;
	void *m;
	int value;
	u_int32_t fset, fclr;
	char *ep;
	size_t len;

	for (; (kw = strtok(t, "= \t\n")); t = NULL) {
		ip->flags |= type = parsekey(kw, &value);
		if (value && (val = strtok(NULL, " \t\n")) == NULL)
			error("missing value");
		switch(type) {
		case F_CKSUM:
			ip->cksum = strtoul(val, &ep, 10);
			if (*ep)
				error("invalid checksum %s", val);
			break;
		case F_MD5:
			ip->md5digest = strdup(val);
			if (!ip->md5digest)
				error("%s", strerror(errno));
			break;
		case F_FLAGS:
			if (!strcmp(val, "none")) {
				ip->file_flags = 0;
				break;
			}
			if (strtofflags(&val, &fset, &fclr))
				error("%s", strerror(errno));
			ip->file_flags = fset;
			break; 
		case F_GID:
			ip->st_gid = strtoul(val, &ep, 10);
			if (*ep)
				error("invalid gid %s", val);
			break;
		case F_GNAME:
			if ((gr = getgrnam(val)) == NULL)
			    error("unknown group %s", val);
			ip->st_gid = gr->gr_gid;
			break;
		case F_IGN:
			/* just set flag bit */
			break;
		case F_MODE:
			if ((m = setmode(val)) == NULL)
				error("invalid file mode %s", val);
			ip->st_mode = getmode(m, 0);
			free(m);
			break;
		case F_NLINK:
			ip->st_nlink = strtoul(val, &ep, 10);
			if (*ep)
				error("invalid link count %s", val);
			break;
		case F_RMD160:
			ip->rmd160digest = strdup(val);
			if (!ip->rmd160digest)
				error("%s", strerror(errno));
			break;
		case F_SHA1:
			ip->sha1digest = strdup(val);
			if (!ip->sha1digest)
				error("%s", strerror(errno));
			break;
		case F_SIZE:
			ip->st_size = strtouq(val, &ep, 10);
			if (*ep)
				error("invalid size %s", val);
			break;
		case F_SLINK:
			len = strlen(val) + 1;
			if ((ip->slink = malloc(len)) == NULL)
				error("%s", strerror(errno));
			if (strunvis(ip->slink, val) == -1) {
				fprintf(stderr,
				    "mtree: filename (%s) encoded incorrectly\n", val);
				strlcpy(ip->slink, val, len);
			}
			break;
		case F_TIME:
			ip->st_mtimespec.tv_sec = strtoul(val, &ep, 10);
			if (*ep != '.')
				error("invalid time %s", val);
			val = ep + 1;
			ip->st_mtimespec.tv_nsec = strtoul(val, &ep, 10);
			if (*ep)
				error("invalid time %s", val);
			break;
		case F_TYPE:
			switch(*val) {
			case 'b':
				if (!strcmp(val, "block"))
					ip->type = F_BLOCK;
				break;
			case 'c':
				if (!strcmp(val, "char"))
					ip->type = F_CHAR;
				break;
			case 'd':
				if (!strcmp(val, "dir"))
					ip->type = F_DIR;
				break;
			case 'f':
				if (!strcmp(val, "file"))
					ip->type = F_FILE;
				if (!strcmp(val, "fifo"))
					ip->type = F_FIFO;
				break;
			case 'l':
				if (!strcmp(val, "link"))
					ip->type = F_LINK;
				break;
			case 's':
				if (!strcmp(val, "socket"))
					ip->type = F_SOCK;
				break;
			default:
				error("unknown file type %s", val);
			}
			break;
		case F_UID:
			ip->st_uid = strtoul(val, &ep, 10);
			if (*ep)
				error("invalid uid %s", val);
			break;
		case F_UNAME:
			if ((pw = getpwnam(val)) == NULL)
			    error("unknown user %s", val);
			ip->st_uid = pw->pw_uid;
			break;
		}
	}
}
Beispiel #15
0
int osm_db_restore(IN osm_db_domain_t * p_domain)
{

	osm_log_t *p_log = p_domain->p_db->p_log;
	osm_db_domain_imp_t *p_domain_imp =
	    (osm_db_domain_imp_t *) p_domain->p_domain_imp;
	FILE *p_file;
	int status;
	char sLine[OSM_DB_MAX_LINE_LEN];
	boolean_t before_key;
	char *p_first_word, *p_rest_of_line, *p_last;
	char *p_key = NULL;
	char *p_prev_val, *p_accum_val = NULL;
	char *endptr = NULL;
	unsigned int line_num;

	OSM_LOG_ENTER(p_log);

	/* take the lock on the domain */
	cl_spinlock_acquire(&p_domain_imp->lock);

	/* open the file - read mode */
	p_file = fopen(p_domain_imp->file_name, "r");

	if (!p_file) {
		OSM_LOG(p_log, OSM_LOG_ERROR, "ERR 6103: "
			"Failed to open the db file:%s\n",
			p_domain_imp->file_name);
		status = 1;
		goto Exit;
	}

	/* parse the file allocating new hash tables as required */
	/*
	   states:
	   before_key (0) -> in_key (1)

	   before_key: if a word on the first byte - it is the key. state=in_key
	   the rest of the line is start of the value.
	   in_key: unless the line is empty - add it (with newlines) to the value.
	   if empty: state=before_key
	 */
	status = 0;
	before_key = TRUE;
	line_num = 0;
	/* if we got to EOF in the middle of a key we add a last newline */
	while ((fgets(sLine, OSM_DB_MAX_LINE_LEN, p_file) != NULL) ||
	       ((before_key == FALSE) && strcpy(sLine, "\n"))
	    ) {
		line_num++;
		if (before_key) {
			if ((sLine[0] != ' ') && (sLine[0] != '\t')
			    && (sLine[0] != '\n')) {
				/* we got a new key */
				before_key = FALSE;

				/* handle the key */
				p_first_word =
				    strtok_r(sLine, " \t\n", &p_last);
				if (!p_first_word) {
					OSM_LOG(p_log, OSM_LOG_ERROR, "ERR 6104: "
						"Failed to get key from line:%u : %s (file:%s)\n",
						line_num, sLine,
						p_domain_imp->file_name);
					status = 1;
					goto EndParsing;
				}
				if (strlen(p_first_word) > OSM_DB_MAX_GUID_LEN) {
					OSM_LOG(p_log, OSM_LOG_ERROR, "ERR 610A: "
						"Illegal key from line:%u : %s (file:%s)\n",
						line_num, sLine,
						p_domain_imp->file_name);
					status = 1;
					goto EndParsing;
				}

				p_key =
				    (char *)malloc(sizeof(char) *
						   (strlen(p_first_word) + 1));
				strcpy(p_key, p_first_word);

				p_rest_of_line = strtok_r(NULL, "\n", &p_last);
				if (p_rest_of_line != NULL) {
					p_accum_val =
					    (char *)malloc(sizeof(char) *
							   (strlen
							    (p_rest_of_line) +
							    1));
					strcpy(p_accum_val, p_rest_of_line);
				} else {
					p_accum_val = (char *)malloc(2);
					strcpy(p_accum_val, "\0");
				}
			} else if (sLine[0] != '\n') {
				OSM_LOG(p_log, OSM_LOG_ERROR, "ERR 6105: "
					"How did we get here? line:%u : %s (file:%s)\n",
					line_num, sLine,
					p_domain_imp->file_name);
				status = 1;
				goto EndParsing;
			}
		} /* before key */
		else {
			/* we already have a key */

			if (sLine[0] == '\n') {
				/* got an end of key */
				before_key = TRUE;

				/* make sure the key was not previously used */
				if (st_lookup(p_domain_imp->p_hash,
					      (st_data_t) p_key,
					      (void *) & p_prev_val)) {
					OSM_LOG(p_log, OSM_LOG_ERROR, "ERR 6106: "
						"Key:%s already exists in:%s with value:%s."
						" Removing it\n",
						p_key,
						p_domain_imp->file_name,
						p_prev_val);
				} else {
					p_prev_val = NULL;
				}

				OSM_LOG(p_log, OSM_LOG_DEBUG,
					"Got key:%s value:%s\n", p_key,
					p_accum_val);

				/* check that the key is a number */
				if (!strtouq(p_key, &endptr, 0)
				    && *endptr != '\0') {
					OSM_LOG(p_log, OSM_LOG_ERROR, "ERR 610B: "
						"Key:%s is invalid\n", p_key);
				} else {
					/* store our key and value */
					st_insert(p_domain_imp->p_hash,
						  (st_data_t) p_key,
						  (st_data_t) p_accum_val);
				}
			} else {
				/* accumulate into the value */
				p_prev_val = p_accum_val;
				p_accum_val =
				    (char *)malloc(strlen(p_prev_val) +
						   strlen(sLine) + 1);
				strcpy(p_accum_val, p_prev_val);
				free(p_prev_val);
				strcat(p_accum_val, sLine);
			}
		}		/* in key */
	}			/* while lines or last line */

EndParsing:
	fclose(p_file);

Exit:
	cl_spinlock_release(&p_domain_imp->lock);
	OSM_LOG_EXIT(p_log);
	return status;
}
Beispiel #16
0
BOOLEAN
DepositValue(
    IN PCHAR   AsciiValue,
    IN ULONG   Address
    )

/*++

Routine Description:

    This routine writes the converted value to the specified
    address. DataSize is set to the size of the data to be written.

Arguments:

    AsciiValue - Supplies a pointer to a string that contains an hexadecimal
                 value.
    Address     - Supplies the address where the value is to be written to.

Return Value:

    TRUE if the value is successfully converted.
    FALSE otherwise.

--*/

{
//    ULONG   Value;
    ULONGLONG   Value;
    PCHAR   Terminator;

    //
    // Convert value to integer
    //

    Value = strtouq(AsciiValue,&Terminator,16);

    if (*Terminator != '\0') {

            //
            // Not the whole string was converted.
            //

            FwPrint(Terminator);
            FwPrint(MON_INVALID_VALUE_MSG);
            return FALSE;

    } else {
        //
        // Store the value.
        //
        switch (DataSize) {
            case    BYTE:*(PUCHAR)Address = (UCHAR)Value;
                         break;
            case    HALF:*(PUSHORT)Address = (USHORT)Value;
                         break;
            case    MON_LONGWORD:*(PULONG)Address = (ULONG)Value;
                         break;
	    case    MON_QUAD:*(PULONGLONG)Address = (ULONGLONG)Value;
		             break;
        }
    }
    return TRUE;
}