Ejemplo n.º 1
0
/**
 * External logger function
 * @param level log level
 * @param fmt as printf format string
 * @param ... as printf variable argument
 */
void fnc_log(int level, const char *fmt, ...) {
    va_list vl;
    va_start(vl, fmt);
    fnc_vlog(level, fmt, vl);
    va_end(vl);
}
Ejemplo n.º 2
0
/**
**  Generate a list of files within a specified directory
**
**  @param dirname  Directory to read.
**  @param fl       Filelist pointer.
**
**  @return the number of entries added to FileList.
*/
int ReadDataDirectory(const char *dirname, std::vector<FileList> &fl)
{
	struct stat st;
	char buffer[PATH_MAX];
	char *filename;

	strcpy_s(buffer, sizeof(buffer), dirname);
	int n = strlen(buffer);
	if (!n || buffer[n - 1] != '/') {
		buffer[n++] = '/';
		buffer[n] = 0;
	}
	char *np = buffer + n;

#ifndef USE_WIN32
	DIR *dirp = opendir(dirname);
	struct dirent *dp;

	if (dirp) {
		while ((dp = readdir(dirp)) != NULL) {
			filename = dp->d_name;
#else
	strcat_s(buffer, sizeof(buffer), "*.*");
	struct _finddata_t fileinfo;
	long hFile = _findfirst(buffer, &fileinfo);
	if (hFile != -1L) {
		do {
			filename = fileinfo.name;
#endif
			if (strcmp(filename, ".") == 0) {
				continue;
			}
			if (strcmp(filename, "..") == 0) {
				continue;
			}
			strcpy_s(np, sizeof(buffer) - (np - buffer), filename);
			if (stat(buffer, &st) == 0) {
				int isdir = S_ISDIR(st.st_mode);
				if (isdir || S_ISREG(st.st_mode)) {
					FileList nfl;

					if (isdir) {
						nfl.name = np;
					} else {
						nfl.name = np;
						nfl.type = 1;
					}
					// sorted instertion
					fl.insert(std::lower_bound(fl.begin(), fl.end(), nfl), nfl);
				}
			}
#ifndef USE_WIN32
		}
		closedir(dirp);
#else
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
#endif
	}
	return fl.size();
}

void FileWriter::printf(const char *format, ...)
{
	// FIXME: hardcoded size
	char buf[1024];

	va_list ap;
	va_start(ap, format);
	buf[sizeof(buf) - 1] = '\0';
	vsnprintf(buf, sizeof(buf) - 1, format, ap);
	va_end(ap);
	write(buf, strlen(buf));
}
Ejemplo n.º 3
0
void __ast_string_field_ptr_build_va(struct ast_string_field_mgr *mgr,
	struct ast_string_field_pool **pool_head, ast_string_field *ptr,
	const char *format, va_list ap)
{
	size_t needed;
	size_t available;
	size_t space = (*pool_head)->size - (*pool_head)->used;
	int res;
	ssize_t grow;
	char *target;
	va_list ap2;

	/* if the field already has space allocated, try to reuse it;
	   otherwise, try to use the empty space at the end of the current
	   pool
	*/
	if (*ptr != __ast_string_field_empty) {
		target = (char *) *ptr;
		available = AST_STRING_FIELD_ALLOCATION(*ptr);
		if (*ptr == mgr->last_alloc) {
			available += space;
		}
	} else {
		/* pool->used is always a multiple of ast_alignof(ast_string_field_allocation)
		 * so we don't need to re-align anything here.
		 */
		target = (*pool_head)->base + (*pool_head)->used + ast_alignof(ast_string_field_allocation);
		if (space > ast_alignof(ast_string_field_allocation)) {
			available = space - ast_alignof(ast_string_field_allocation);
		} else {
			available = 0;
		}
	}

	va_copy(ap2, ap);
	res = vsnprintf(target, available, format, ap2);
	va_end(ap2);

	if (res < 0) {
		/* Are we out of memory? */
		return;
	}
	if (res == 0) {
		__ast_string_field_release_active(*pool_head, *ptr);
		*ptr = __ast_string_field_empty;
		return;
	}
	needed = (size_t)res + 1; /* NUL byte */

	if (needed > available) {
		/* the allocation could not be satisfied using the field's current allocation
		   (if it has one), or the space available in the pool (if it does not). allocate
		   space for it, adding a new string pool if necessary.
		*/
		if (!(target = (char *) __ast_string_field_alloc_space(mgr, pool_head, needed))) {
			return;
		}
		vsprintf(target, format, ap);
		va_end(ap); /* XXX va_end without va_start? */
		__ast_string_field_release_active(*pool_head, *ptr);
		*ptr = target;
	} else if (*ptr != target) {
		/* the allocation was satisfied using available space in the pool, but not
		   using the space already allocated to the field
		*/
		__ast_string_field_release_active(*pool_head, *ptr);
		mgr->last_alloc = *ptr = target;
	        ast_assert(needed < (ast_string_field_allocation)-1);
		AST_STRING_FIELD_ALLOCATION(target) = (ast_string_field_allocation)needed;
		(*pool_head)->used += ast_make_room_for(needed, ast_string_field_allocation);
		(*pool_head)->active += needed;
	} else if ((grow = (needed - AST_STRING_FIELD_ALLOCATION(*ptr))) > 0) {
		/* the allocation was satisfied by using available space in the pool *and*
		   the field was the last allocated field from the pool, so it grew
		*/
		AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
		(*pool_head)->used += ast_align_for(grow, ast_string_field_allocation);
		(*pool_head)->active += grow;
	}
}
Ejemplo n.º 4
0
NORETURN multi_server_main(int argc, char **argv, MULTI_SERVER_FN service,...)
{
    const char *myname = "multi_server_main";
    VSTREAM *stream = 0;
    char   *root_dir = 0;
    char   *user_name = 0;
    int     debug_me = 0;
    int     daemon_mode = 1;
    char   *service_name = basename(argv[0]);
    int     delay;
    int     c;
    int     fd;
    va_list ap;
    MAIL_SERVER_INIT_FN pre_init = 0;
    MAIL_SERVER_INIT_FN post_init = 0;
    MAIL_SERVER_LOOP_FN loop = 0;
    int     key;
    char   *transport = 0;

#if 0
    char   *lock_path;
    VSTRING *why;

#endif
    int     alone = 0;
    int     zerolimit = 0;
    WATCHDOG *watchdog;
    char   *oname_val;
    char   *oname;
    char   *oval;
    const char *err;
    char   *generation;
    int     msg_vstream_needed = 0;
    int     redo_syslog_init = 0;
    const char *dsn_filter_title;
    const char **dsn_filter_maps;

    /*
     * Process environment options as early as we can.
     */
    if (getenv(CONF_ENV_VERB))
        msg_verbose = 1;
    if (getenv(CONF_ENV_DEBUG))
        debug_me = 1;

    /*
     * Don't die when a process goes away unexpectedly.
     */
    signal(SIGPIPE, SIG_IGN);

    /*
     * Don't die for frivolous reasons.
     */
#ifdef SIGXFSZ
    signal(SIGXFSZ, SIG_IGN);
#endif

    /*
     * May need this every now and then.
     */
    var_procname = mystrdup(basename(argv[0]));
    set_mail_conf_str(VAR_PROCNAME, var_procname);

    /*
     * Initialize logging and exit handler. Do the syslog first, so that its
     * initialization completes before we enter the optional chroot jail.
     */
    msg_syslog_init(mail_task(var_procname), LOG_PID, LOG_FACILITY);
    if (msg_verbose)
        msg_info("daemon started");

    /*
     * Check the Postfix library version as soon as we enable logging.
     */
    MAIL_VERSION_CHECK;

    /*
     * Initialize from the configuration file. Allow command-line options to
     * override compiled-in defaults or configured parameter values.
     */
    mail_conf_suck();

    /*
     * After database open error, continue execution with reduced
     * functionality.
     */
    dict_allow_surrogate = 1;

    /*
     * Pick up policy settings from master process. Shut up error messages to
     * stderr, because no-one is going to see them.
     */
    opterr = 0;
    while ((c = GETOPT(argc, argv, "cdDi:lm:n:o:s:St:uvVz")) > 0) {
        switch (c) {
        case 'c':
            root_dir = "setme";
            break;
        case 'd':
            daemon_mode = 0;
            break;
        case 'D':
            debug_me = 1;
            break;
        case 'i':
            mail_conf_update(VAR_MAX_IDLE, optarg);
            break;
        case 'l':
            alone = 1;
            break;
        case 'm':
            mail_conf_update(VAR_MAX_USE, optarg);
            break;
        case 'n':
            service_name = optarg;
            break;
        case 'o':
            oname_val = mystrdup(optarg);
            if ((err = split_nameval(oname_val, &oname, &oval)) != 0)
                msg_fatal("invalid \"-o %s\" option value: %s", optarg, err);
            mail_conf_update(oname, oval);
            if (strcmp(oname, VAR_SYSLOG_NAME) == 0)
                redo_syslog_init = 1;
            myfree(oname_val);
            break;
        case 's':
            if ((socket_count = atoi(optarg)) <= 0)
                msg_fatal("invalid socket_count: %s", optarg);
            break;
        case 'S':
            stream = VSTREAM_IN;
            break;
        case 'u':
            user_name = "setme";
            break;
        case 't':
            transport = optarg;
            break;
        case 'v':
            msg_verbose++;
            break;
        case 'V':
            if (++msg_vstream_needed == 1)
                msg_vstream_init(mail_task(var_procname), VSTREAM_ERR);
            break;
        case 'z':
            zerolimit = 1;
            break;
        default:
            msg_fatal("invalid option: %c", c);
            break;
        }
    }

    /*
     * Initialize generic parameters.
     */
    mail_params_init();
    if (redo_syslog_init)
        msg_syslog_init(mail_task(var_procname), LOG_PID, LOG_FACILITY);

    /*
     * Register higher-level dictionaries and initialize the support for
     * dynamically-loaded dictionarles.
     */
    mail_dict_init();

    /*
     * If not connected to stdin, stdin must not be a terminal.
     */
    if (daemon_mode && stream == 0 && isatty(STDIN_FILENO)) {
        msg_vstream_init(var_procname, VSTREAM_ERR);
        msg_fatal("do not run this command by hand");
    }

    /*
     * Application-specific initialization.
     */
    va_start(ap, service);
    while ((key = va_arg(ap, int)) != 0) {
        switch (key) {
        case MAIL_SERVER_INT_TABLE:
            get_mail_conf_int_table(va_arg(ap, CONFIG_INT_TABLE *));
            break;
        case MAIL_SERVER_LONG_TABLE:
            get_mail_conf_long_table(va_arg(ap, CONFIG_LONG_TABLE *));
            break;
        case MAIL_SERVER_STR_TABLE:
            get_mail_conf_str_table(va_arg(ap, CONFIG_STR_TABLE *));
            break;
        case MAIL_SERVER_BOOL_TABLE:
            get_mail_conf_bool_table(va_arg(ap, CONFIG_BOOL_TABLE *));
            break;
        case MAIL_SERVER_TIME_TABLE:
            get_mail_conf_time_table(va_arg(ap, CONFIG_TIME_TABLE *));
            break;
        case MAIL_SERVER_RAW_TABLE:
            get_mail_conf_raw_table(va_arg(ap, CONFIG_RAW_TABLE *));
            break;
        case MAIL_SERVER_NINT_TABLE:
            get_mail_conf_nint_table(va_arg(ap, CONFIG_NINT_TABLE *));
            break;
        case MAIL_SERVER_NBOOL_TABLE:
            get_mail_conf_nbool_table(va_arg(ap, CONFIG_NBOOL_TABLE *));
            break;
        case MAIL_SERVER_PRE_INIT:
            pre_init = va_arg(ap, MAIL_SERVER_INIT_FN);
            break;
        case MAIL_SERVER_POST_INIT:
            post_init = va_arg(ap, MAIL_SERVER_INIT_FN);
            break;
        case MAIL_SERVER_LOOP:
            loop = va_arg(ap, MAIL_SERVER_LOOP_FN);
            break;
        case MAIL_SERVER_EXIT:
            multi_server_onexit = va_arg(ap, MAIL_SERVER_EXIT_FN);
            break;
        case MAIL_SERVER_PRE_ACCEPT:
            multi_server_pre_accept = va_arg(ap, MAIL_SERVER_ACCEPT_FN);
            break;
        case MAIL_SERVER_PRE_DISCONN:
            multi_server_pre_disconn = va_arg(ap, MAIL_SERVER_DISCONN_FN);
            break;
        case MAIL_SERVER_IN_FLOW_DELAY:
            multi_server_in_flow_delay = 1;
            break;
        case MAIL_SERVER_SOLITARY:
            if (stream == 0 && !alone)
                msg_fatal("service %s requires a process limit of 1",
                          service_name);
            break;
        case MAIL_SERVER_UNLIMITED:
            if (stream == 0 && !zerolimit)
                msg_fatal("service %s requires a process limit of 0",
                          service_name);
            break;
        case MAIL_SERVER_PRIVILEGED:
            if (user_name)
                msg_fatal("service %s requires privileged operation",
                          service_name);
            break;
        case MAIL_SERVER_BOUNCE_INIT:
            dsn_filter_title = va_arg(ap, const char *);
            dsn_filter_maps = va_arg(ap, const char **);
            bounce_client_init(dsn_filter_title, *dsn_filter_maps);
            break;
        default:
            msg_panic("%s: unknown argument type: %d", myname, key);
        }
    }
    va_end(ap);

    if (root_dir)
        root_dir = var_queue_dir;
    if (user_name)
        user_name = var_mail_owner;

    /*
     * Can options be required?
     */
    if (stream == 0) {
        if (transport == 0)
            msg_fatal("no transport type specified");
        if (strcasecmp(transport, MASTER_XPORT_NAME_INET) == 0)
            multi_server_accept = multi_server_accept_inet;
        else if (strcasecmp(transport, MASTER_XPORT_NAME_UNIX) == 0)
            multi_server_accept = multi_server_accept_local;
#ifdef MASTER_XPORT_NAME_PASS
        else if (strcasecmp(transport, MASTER_XPORT_NAME_PASS) == 0)
            multi_server_accept = multi_server_accept_pass;
#endif
        else
            msg_fatal("unsupported transport type: %s", transport);
    }

    /*
     * Retrieve process generation from environment.
     */
    if ((generation = getenv(MASTER_GEN_NAME)) != 0) {
        if (!alldig(generation))
            msg_fatal("bad generation: %s", generation);
        OCTAL_TO_UNSIGNED(multi_server_generation, generation);
        if (msg_verbose)
            msg_info("process generation: %s (%o)",
                     generation, multi_server_generation);
    }

    /*
     * Optionally start the debugger on ourself.
     */
    if (debug_me)
        debug_process();

    /*
     * Traditionally, BSD select() can't handle multiple processes selecting
     * on the same socket, and wakes up every process in select(). See TCP/IP
     * Illustrated volume 2 page 532. We avoid select() collisions with an
     * external lock file.
     */

    /*
     * XXX Can't compete for exclusive access to the listen socket because we
     * also have to monitor existing client connections for service requests.
     */
#if 0
    if (stream == 0 && !alone) {
        lock_path = concatenate(DEF_PID_DIR, "/", transport,
                                ".", service_name, (char *) 0);
        why = vstring_alloc(1);
        if ((multi_server_lock = safe_open(lock_path, O_CREAT | O_RDWR, 0600,
                                           (struct stat *) 0, -1, -1, why)) == 0)
            msg_fatal("open lock file %s: %s", lock_path, vstring_str(why));
        close_on_exec(vstream_fileno(multi_server_lock), CLOSE_ON_EXEC);
        myfree(lock_path);
        vstring_free(why);
    }
#endif

    /*
     * Set up call-back info.
     */
    multi_server_service = service;
    multi_server_name = service_name;
    multi_server_argv = argv + optind;

    /*
     * Run pre-jail initialization.
     */
    if (chdir(var_queue_dir) < 0)
        msg_fatal("chdir(\"%s\"): %m", var_queue_dir);
    if (pre_init)
        pre_init(multi_server_name, multi_server_argv);

    /*
     * Optionally, restrict the damage that this process can do.
     */
    resolve_local_init();
    tzset();
    chroot_uid(root_dir, user_name);

    /*
     * Run post-jail initialization.
     */
    if (post_init)
        post_init(multi_server_name, multi_server_argv);

    /*
     * Are we running as a one-shot server with the client connection on
     * standard input? If so, make sure the output is written to stdout so as
     * to satisfy common expectation.
     */
    if (stream != 0) {
        vstream_control(stream,
                        CA_VSTREAM_CTL_DOUBLE,
                        CA_VSTREAM_CTL_WRITE_FD(STDOUT_FILENO),
                        CA_VSTREAM_CTL_END);
        service(stream, multi_server_name, multi_server_argv);
        vstream_fflush(stream);
        multi_server_exit();
    }

    /*
     * Running as a semi-resident server. Service connection requests.
     * Terminate when we have serviced a sufficient number of clients, when
     * no-one has been talking to us for a configurable amount of time, or
     * when the master process terminated abnormally.
     */
    if (var_idle_limit > 0)
        event_request_timer(multi_server_timeout, (void *) 0, var_idle_limit);
    for (fd = MASTER_LISTEN_FD; fd < MASTER_LISTEN_FD + socket_count; fd++) {
        event_enable_read(fd, multi_server_accept, CAST_INT_TO_VOID_PTR(fd));
        close_on_exec(fd, CLOSE_ON_EXEC);
    }
    event_enable_read(MASTER_STATUS_FD, multi_server_abort, (void *) 0);
    close_on_exec(MASTER_STATUS_FD, CLOSE_ON_EXEC);
    close_on_exec(MASTER_FLOW_READ, CLOSE_ON_EXEC);
    close_on_exec(MASTER_FLOW_WRITE, CLOSE_ON_EXEC);
    watchdog = watchdog_create(var_daemon_timeout, (WATCHDOG_FN) 0, (void *) 0);

    /*
     * The event loop, at last.
     */
    while (var_use_limit == 0 || use_count < var_use_limit || client_count > 0) {
        if (multi_server_lock != 0) {
            watchdog_stop(watchdog);
            if (myflock(vstream_fileno(multi_server_lock), INTERNAL_LOCK,
                        MYFLOCK_OP_EXCLUSIVE) < 0)
                msg_fatal("select lock: %m");
        }
        watchdog_start(watchdog);
        delay = loop ? loop(multi_server_name, multi_server_argv) : -1;
        event_loop(delay);
    }
    multi_server_exit();
}
Ejemplo n.º 5
0
int
ACE_Process_Options::setenv (const ACE_TCHAR *variable_name,
                             const ACE_TCHAR *format, ...)
{
  // To address the potential buffer overflow,
  // we now allocate the buffer on heap with a variable size.
  size_t const buflen = ACE_OS::strlen (variable_name) + ACE_OS::strlen (format) + 2;
  ACE_TCHAR *newformat = 0;
  ACE_NEW_RETURN (newformat, ACE_TCHAR[buflen], -1);
  ACE_Auto_Basic_Array_Ptr<ACE_TCHAR> safe_newformat (newformat);

  // Add in the variable name.
  ACE_OS::sprintf (safe_newformat.get (),
                   ACE_TEXT ("%s=%s"),
                   variable_name,
                   format);

  // Start varargs.
  va_list argp;
  va_start (argp, format);

  // Add the rest of the varargs.
  size_t tmp_buflen = DEFAULT_COMMAND_LINE_BUF_LEN > buflen
                      ? static_cast<size_t> (DEFAULT_COMMAND_LINE_BUF_LEN) : buflen;
  int retval = 0;

  ACE_TCHAR *stack_buf = 0;
  ACE_NEW_RETURN (stack_buf, ACE_TCHAR[tmp_buflen], -1);
  ACE_Auto_Basic_Array_Ptr<ACE_TCHAR> safe_stack_buf (stack_buf);

  do
    {
      retval = ACE_OS::vsnprintf (safe_stack_buf.get (), tmp_buflen, safe_newformat.get (), argp);
      if (retval > ACE_Utils::truncate_cast<int> (tmp_buflen))
        {
          tmp_buflen *= 2;
          ACE_NEW_RETURN (stack_buf, ACE_TCHAR[tmp_buflen], -1);
          safe_stack_buf.reset (stack_buf);
        }
      else
        break;
    }
  while (1);

  if (retval == -1)
    {
      // In case that vsnprintf is not supported,
      // e.g., LynxOS and VxWorks 5, we have to
      // fall back to vsprintf.
      if (errno == ENOTSUP)
        {
          // ALERT: Since we have to use vsprintf here, there is still a chance that
          // the stack_buf overflows, i.e., the length of the resulting string
          // can still possibly go beyond the allocated stack_buf.
          retval = ACE_OS::vsprintf (safe_stack_buf.get (), safe_newformat.get (), argp);
          if (retval == -1)
            // vsprintf is failed.
            return -1;
        }
      else
        // vsnprintf is failed.
        return -1;
    }

  // End varargs.
  va_end (argp);

  // Append the string to our environment buffer.
  if (this->setenv_i (safe_stack_buf.get (),
                      ACE_OS::strlen (safe_stack_buf.get ())) == -1)
    return -1;

#if defined (ACE_WIN32)
  if (inherit_environment_)
    this->inherit_environment ();
#endif /* ACE_WIN32 */

  return 0;
}
Ejemplo n.º 6
0
void I_Error (char *error, ...)
{
    va_list argptr;
    atexit_listentry_t *entry;
    boolean exit_gui_popup;

    if (already_quitting)
    {
        fprintf(stderr, "Warning: recursive call to I_Error detected.\n");
        exit(-1);
    }
    else
    {
        already_quitting = true;
    }
    
    // Message first.
    va_start(argptr, error);
    //fprintf(stderr, "\nError: ");
    vfprintf(stderr, error, argptr);
    fprintf(stderr, "\n\n");
    va_end(argptr);
    fflush(stderr);

    // Shutdown. Here might be other errors.

    entry = exit_funcs;

    while (entry != NULL)
    {
        if (entry->run_on_error)
        {
            entry->func();
        }

        entry = entry->next;
    }

    exit_gui_popup = !M_ParmExists("-nogui");

#ifdef _WIN32
    // On Windows, pop up a dialog box with the error message.

    if (exit_gui_popup)
    {
        char msgbuf[512];
        wchar_t wmsgbuf[512];

        va_start(argptr, error);
        memset(msgbuf, 0, sizeof(msgbuf));
        M_vsnprintf(msgbuf, sizeof(msgbuf), error, argptr);
        va_end(argptr);

        MultiByteToWideChar(CP_ACP, 0,
                            msgbuf, strlen(msgbuf) + 1,
                            wmsgbuf, sizeof(wmsgbuf));

        MessageBoxW(NULL, wmsgbuf, L"", MB_OK);
    }
#endif

#ifdef __MACOSX__
    if (exit_gui_popup && !I_ConsoleStdout())
    {
        CFStringRef message;
        char msgbuf[512];
	int i;

        va_start(argptr, error);
        memset(msgbuf, 0, sizeof(msgbuf));
        M_vsnprintf(msgbuf, sizeof(msgbuf), error, argptr);
        va_end(argptr);

	// The CoreFoundation message box wraps text lines, so replace
	// newline characters with spaces so that multiline messages
	// are continuous.

	for (i = 0; msgbuf[i] != '\0'; ++i)
        {
            if (msgbuf[i] == '\n')
            {
                msgbuf[i] = ' ';
            }
        }

        message = CFStringCreateWithCString(NULL, msgbuf,
                                            kCFStringEncodingUTF8);

        CFUserNotificationDisplayNotice(0,
                                        kCFUserNotificationCautionAlertLevel,
                                        NULL,
                                        NULL,
                                        NULL,
                                        CFSTR(PACKAGE_STRING),
                                        message,
                                        NULL);
    }
#endif

    // abort();

    exit(-1);
}
Ejemplo n.º 7
0
static void
test0(const char *type, ...)
{
	char buf[512];
	CONV_RESULT cr;
	int rc;
	TDS_INT result_type;
	int done_flags;
	va_list ap;
	struct {
		const char *value;
		const char *result;
	} data[10];
	int num_data = 0, i_row;

	sprintf(buf, "CREATE TABLE #tmp(a %s)", type);
	exec_query(buf);

        va_start(ap, type);
	for (;;) {
		const char * value = va_arg(ap, const char *);
		const char * result;
		if (!value)
			break;
		result = va_arg(ap, const char *);
		if (!result)
			result = value;
		data[num_data].value = value;
		data[num_data].result = result;
		sprintf(buf, "INSERT INTO #tmp VALUES(CONVERT(%s,'%s'))", type, value);
		exec_query(buf);
		++num_data;
	}
        va_end(ap);

	assert(num_data > 0);

	/* execute it */
	rc = tds_submit_query(tds, "SELECT * FROM #tmp");
	if (rc != TDS_SUCCESS) {
		fprintf(stderr, "tds_submit_query() failed\n");
		exit(1);
	}

	if (tds_process_tokens(tds, &result_type, NULL, TDS_TOKEN_RESULTS) != TDS_SUCCESS) {
		fprintf(stderr, "tds_process_tokens() failed\n");
		exit(1);
	}

	if (result_type != TDS_ROWFMT_RESULT) {
		fprintf(stderr, "expected row fmt() failed\n");
		exit(1);
	}

	if (tds_process_tokens(tds, &result_type, NULL, TDS_TOKEN_RESULTS) != TDS_SUCCESS) {
		fprintf(stderr, "tds_process_tokens() failed\n");
		exit(1);
	}

	if (result_type != TDS_ROW_RESULT) {
		fprintf(stderr, "expected row result() failed\n");
		exit(1);
	}

	i_row = 0;
	while ((rc = tds_process_tokens(tds, &result_type, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW|TDS_RETURN_COMPUTE)) == TDS_SUCCESS && (result_type == TDS_ROW_RESULT || result_type == TDS_COMPUTE_RESULT)) {

		TDSCOLUMN *curcol = tds->current_results->columns[0];
		TDS_CHAR *src = (TDS_CHAR *) curcol->column_data;
		int conv_type = tds_get_conversion_type(curcol->column_type, curcol->column_size);

		assert(i_row < num_data);

		if (is_blob_col(curcol)) {
			TDSBLOB *blob = (TDSBLOB *) src;

			src = blob->textvalue;
		}

		if (tds_convert(test_context, conv_type, src, curcol->column_cur_size, SYBVARCHAR, &cr) < 0) {
			fprintf(stderr, "Error converting\n");
			g_result = 1;
		} else {
			if (strcmp(data[i_row].result, cr.c) != 0) {
				fprintf(stderr, "Failed! Is \n%s\nShould be\n%s\n", cr.c, data[i_row].result);
				g_result = 1;
			}
			free(cr.c);
		}
		++i_row;
	}

	if (rc != TDS_NO_MORE_RESULTS && rc != TDS_SUCCESS) {
		fprintf(stderr, "tds_process_tokens() unexpected return\n");
		exit(1);
	}

	while ((rc = tds_process_tokens(tds, &result_type, &done_flags, TDS_TOKEN_RESULTS)) == TDS_SUCCESS) {
		switch (result_type) {
		case TDS_NO_MORE_RESULTS:
			return;

		case TDS_DONE_RESULT:
		case TDS_DONEPROC_RESULT:
		case TDS_DONEINPROC_RESULT:
			if (!(done_flags & TDS_DONE_ERROR))
				break;

		default:
			fprintf(stderr, "tds_process_tokens() unexpected result_type\n");
			exit(1);
			break;
		}
	}

	exec_query("DROP TABLE #tmp");
}
Ejemplo n.º 8
0
void class_addmethod(t_class *c, t_method fn, t_symbol *sel,
    t_atomtype arg1, ...)
{
    va_list ap;
    t_methodentry *m;
    t_atomtype argtype = arg1;
    int nargs;
    
    va_start(ap, arg1);
        /* "signal" method specifies that we take audio signals but
        that we don't want automatic float to signal conversion.  This
        is obsolete; you should now use the CLASS_MAINSIGNALIN macro. */
    if (sel == &s_signal)
    {
        if (c->c_floatsignalin)
            post("warning: signal method overrides class_mainsignalin");
        c->c_floatsignalin = -1;
    }
        /* check for special cases.  "Pointer" is missing here so that
        pd_objectmaker's pointer method can be typechecked differently.  */
    if (sel == &s_bang)
    {
        if (argtype) goto phooey;
        class_addbang(c, fn);
    }
    else if (sel == &s_float)
    {
        if (argtype != A_FLOAT || va_arg(ap, t_atomtype)) goto phooey;
        class_doaddfloat(c, fn);
    }
    else if (sel == &s_symbol)
    {
        if (argtype != A_SYMBOL || va_arg(ap, t_atomtype)) goto phooey;
        class_addsymbol(c, fn);
    }
    else if (sel == &s_blob) /* MP 20070106 blob type */
    {
        post("class_addmethod: %p", fn);
        if (argtype != A_BLOB || va_arg(ap, t_atomtype)) goto phooey;
        class_addblob(c, fn);
    }
    else if (sel == &s_list)
    {
        if (argtype != A_GIMME) goto phooey;
        class_addlist(c, fn);
    }
    else if (sel == &s_anything)
    {
        if (argtype != A_GIMME) goto phooey;
        class_addanything(c, fn);
    }
    else
    {
        /* Pd-extended doesn't use the aliasing automagic
        int i;
        for (i = 0; i < c->c_nmethod; i++)
            if (c->c_methods[i].me_name == sel)
        {
            char nbuf[80];
            snprintf(nbuf, 80, "%s_aliased", sel->s_name);
            c->c_methods[i].me_name = gensym(nbuf);
            if (c == pd_objectmaker)
                post("warning: class '%s' overwritten; old one renamed '%s'",
                    sel->s_name, nbuf);
            else post("warning: old method '%s' for class '%s' renamed '%s'",
                sel->s_name, c->c_name->s_name, nbuf);
        }
        */
        c->c_methods = t_resizebytes(c->c_methods,
            c->c_nmethod * sizeof(*c->c_methods),
            (c->c_nmethod + 1) * sizeof(*c->c_methods));
        m = c->c_methods +  c->c_nmethod;
        c->c_nmethod++;
        m->me_name = sel;
        m->me_fun = (t_gotfn)fn;
        nargs = 0;
        while (argtype != A_NULL && nargs < MAXPDARG)
        {
            m->me_arg[nargs++] = argtype;
            argtype = va_arg(ap, t_atomtype);
        }
        if (argtype != A_NULL)
            error("%s_%s: only 5 arguments are typecheckable; use A_GIMME",
                c->c_name->s_name, sel->s_name);
        va_end(ap);
        m->me_arg[nargs] = A_NULL;
    }
    return;
phooey:
    bug("class_addmethod: %s_%s: bad argument types\n",
        c->c_name->s_name, sel->s_name);
}
Ejemplo n.º 9
0
void fmt_fmt(int put(int c, void *), void *cl, const char *fmt, ...){
	va_list ap;
	va_start(ap, fmt);
	fmt_vfmt(put, cl, fmt, ap);
	va_end(ap);
}
Ejemplo n.º 10
0
void CLogFile::WriteMessage(const char* string, ...) {
    va_list args;
    va_start(args, string);
    Write("#00FF00",string,args);
    va_end(args);
}
Ejemplo n.º 11
0
t_class *class_new(t_symbol *s, t_newmethod newmethod, t_method freemethod,
    size_t size, int flags, t_atomtype type1, ...)
{
    va_list ap;
    t_atomtype vec[MAXPDARG+1], *vp = vec;
    int count = 0;
    t_class *c;
    int typeflag = flags & CLASS_TYPEMASK;
    if (!typeflag) typeflag = CLASS_PATCHABLE;
    *vp = type1;

    va_start(ap, type1);
    while (*vp)
    {
        if (count == MAXPDARG)
        {
            error("class %s: sorry: only %d args typechecked; use A_GIMME",
                s->s_name, MAXPDARG);
            break;
        }
        vp++;
        count++;
        *vp = va_arg(ap, t_atomtype);
    }
    va_end(ap);
    if (pd_objectmaker && newmethod)
    {
            /* add a "new" method by the name specified by the object */
        class_addmethod(pd_objectmaker, (t_method)newmethod, s,
            vec[0], vec[1], vec[2], vec[3], vec[4], vec[5]);
        if (class_loadsym)
        {
                /* if we're loading an extern it might have been invoked by a
                longer file name; in this case, make this an admissible name
                too. */
            char *loadstring = class_loadsym->s_name,
                l1 = strlen(s->s_name), l2 = strlen(loadstring);
            if (l2 > l1 && !strcmp(s->s_name, loadstring + (l2 - l1)))
                class_addmethod(pd_objectmaker, (t_method)newmethod,
                    class_loadsym,
                    vec[0], vec[1], vec[2], vec[3], vec[4], vec[5]);
        }
    }
    c = (t_class *)t_getbytes(sizeof(*c));
    c->c_name = c->c_helpname = s;
    c->c_size = size;
    c->c_methods = t_getbytes(0);
    c->c_nmethod = 0;
    c->c_freemethod = (t_method)freemethod;
    c->c_bangmethod = pd_defaultbang;
    c->c_pointermethod = pd_defaultpointer;
    c->c_floatmethod = pd_defaultfloat;
    c->c_symbolmethod = pd_defaultsymbol;
    c->c_blobmethod = pd_defaultblob; /* MP 20061226 blob type */
    c->c_listmethod = pd_defaultlist;
    c->c_anymethod = pd_defaultanything;
    c->c_wb = (typeflag == CLASS_PATCHABLE ? &text_widgetbehavior : 0);
    c->c_pwb = 0;
    c->c_firstin = ((flags & CLASS_NOINLET) == 0);
    c->c_patchable = (typeflag == CLASS_PATCHABLE);
    c->c_gobj = (typeflag >= CLASS_GOBJ);
    c->c_drawcommand = 0;
    c->c_floatsignalin = 0;
    c->c_externdir = class_extern_dir;
    c->c_savefn = (typeflag == CLASS_PATCHABLE ? text_save : class_nosavefn);
#if 0 
    post("class: %s", c->c_name->s_name);
#endif
    classtable_register(c);
//    post("class: %s", c->c_name->s_name);
    return (c);
}
Ejemplo n.º 12
0
Archivo: vm.c Proyecto: hiromu/picrin
int
pic_get_args(pic_state *pic, const char *format, ...)
{
  char c;
  int i = 1, argc = pic->ci->argc;
  va_list ap;
  bool opt = false;

  va_start(ap, format);
  while ((c = *format++)) {
    switch (c) {
    default:
      if (argc <= i && ! opt) {
	pic_error(pic, "wrong number of arguments");
      }
      break;
    case '|':
      break;
    }

    /* in order to run out of all arguments passed to this function
       (i.e. do va_arg for each argument), optional argument existence
       check is done in every case closure */

    switch (c) {
    case '|':
      opt = true;
      break;
    case 'o':
      {
	pic_value *p;

	p = va_arg(ap, pic_value*);
	if (i < argc) {
	  *p = GET_OPERAND(pic,i);
	  i++;
	}
      }
      break;
    case 'f':
      {
	double *f;

	f = va_arg(ap, double *);
	if (i < argc) {
	  pic_value v;

	  v = GET_OPERAND(pic, i);
	  switch (pic_type(v)) {
	  case PIC_TT_FLOAT:
	    *f = pic_float(v);
	    break;
	  case PIC_TT_INT:
	    *f = pic_int(v);
	    break;
	  default:
	    pic_error(pic, "pic_get_args: expected float or int");
	  }
	  i++;
	}
      }
      break;
    case 'F':
      {
	double *f;
	bool *e;

	f = va_arg(ap, double *);
	e = va_arg(ap, bool *);
	if (i < argc) {
	  pic_value v;

	  v = GET_OPERAND(pic, i);
	  switch (pic_type(v)) {
	  case PIC_TT_FLOAT:
	    *f = pic_float(v);
	    *e = false;
	    break;
	  case PIC_TT_INT:
	    *f = pic_int(v);
	    *e = true;
	    break;
	  default:
	    pic_error(pic, "pic_get_args: expected float or int");
	  }
	  i++;
	}
      }
      break;
    case 'I':
      {
	int *k;
	bool *e;

	k = va_arg(ap, int *);
	e = va_arg(ap, bool *);
	if (i < argc) {
	  pic_value v;

	  v = GET_OPERAND(pic, i);
	  switch (pic_type(v)) {
	  case PIC_TT_FLOAT:
	    *k = (int)pic_float(v);
	    *e = false;
	    break;
	  case PIC_TT_INT:
	    *k = pic_int(v);
	    *e = true;
	    break;
	  default:
	    pic_error(pic, "pic_get_args: expected float or int");
	  }
	  i++;
	}
      }
      break;
    case 'i':
      {
	int *k;

	k = va_arg(ap, int *);
	if (i < argc) {
	  pic_value v;

	  v = GET_OPERAND(pic, i);
	  switch (pic_type(v)) {
	  case PIC_TT_FLOAT:
	    *k = (int)pic_float(v);
	    break;
	  case PIC_TT_INT:
	    *k = pic_int(v);
	    break;
	  default:
	    pic_error(pic, "pic_get_args: expected int");
	  }
	  i++;
	}
      }
      break;
    case 's':
      {
	pic_value str;
	char **cstr;
	size_t *len;

	cstr = va_arg(ap, char **);
	len = va_arg(ap, size_t *);
	if (i < argc) {
	  str = GET_OPERAND(pic,i);
	  if (! pic_str_p(str)) {
	    pic_error(pic, "pic_get_args: expected string");
	  }
	  *cstr = pic_str_ptr(str)->str;
	  *len = pic_str_ptr(str)->len;
	  i++;
	}
      }
      break;
    case 'v':
      {
	struct pic_vector **vec;
	pic_value v;

	vec = va_arg(ap, struct pic_vector **);
	if (i < argc) {
	  v = GET_OPERAND(pic,i);
	  if (pic_vec_p(v)) {
	    *vec = pic_vec_ptr(v);
	  }
	  else {
	    pic_error(pic, "pic_get_args: expected vector");
	  }
	  i++;
	}
      }
      break;
    case 'b':
      {
	struct pic_blob **b;
	pic_value v;

	b = va_arg(ap, struct pic_blob **);
	if (i < argc) {
	  v = GET_OPERAND(pic,i);
	  if (pic_blob_p(v)) {
	    *b = pic_blob_ptr(v);
	  }
	  else {
	    pic_error(pic, "pic_get_args: expected bytevector");
	  }
	  i++;
	}
      }
      break;
    default:
      {
	pic_error(pic, "pic_get_args: invalid argument specifier given");
      }
    }
  }
  if (argc > i) {
    pic_error(pic, "wrong number of arguments");
  }
  va_end(ap);
  return i;
}
Ejemplo n.º 13
0
void WOLog(int level, const char *format, ...)
{
   FILE *log;
   va_list ap;
   int do_it;
#if defined(TIMESTAMP_LOG_MESSAGES)
   struct tm *t;
   time_t now;
   char timestamp[64];
#endif

   if (level < baselevel)
      return;

   if (! initialized )
	   return;

   do_it = shouldLog();
   if ( do_it ) {
      /*
       * plenty of people have complained that we need to timestamp
       * the log entries.  the problem is that mktime & friends aren't
       * reentrant.
       */
#if defined(TIMESTAMP_LOG_MESSAGES)
      WA_lock(logMutex);
      time(&now);
      t = localtime(&now);
      strftime(timestamp, sizeof(timestamp), "%d-%b-%Y %T - ", t);
      WA_unlock(logMutex);
#endif
      log = fopen(logPath, "a+");
      if (log != NULL) {
#if defined(TIMESTAMP_LOG_MESSAGES)
         fprintf(log, timestamp);
#endif
         fprintf(log,"%s: ", WOLogLevel[level]);
         va_start(ap, format);
         vfprintf(log, format, ap);
         va_end(ap);
         fprintf(log,"\n");
         fclose(log);
      }else{
// TODO - figure out how to report this for other web servers
#if defined(APACHE)
         ap_log_error(APLOG_MARK, APLOG_ERR, 0, _webobjects_server, "Failed to append to log file '%s'.  This can occur when the file is not writable by the child httpd process.  A workaround is to change the ownership of the file to match the child httpd process.", logPath);
#endif
      }
   }


   /*
    *	if the error is serious, include it into the server's log
    */
#if	defined(Netscape) || defined(APACHE) || defined(IIS)
   if (level == WO_ERR) {
      String *str;
      str = str_create(NULL, 128);
      va_start(ap,format);
      str_vappendf(str, format, ap);
      va_end(ap);
#if defined(Netscape)
      log_error(0,"WebObjects",NULL,NULL,str->text);
#elif defined(APACHE)
      ap_log_error(APLOG_MARK, APLOG_ERR, 0, _webobjects_server, "%s", str->text);
#elif defined(IIS)
      /*
       *	again, we're stymied because we don't have a ptr to the
       *	server struct
       * /
       {
          LPDWORD len = strlen(logstr);
          ServerSupportFunction(p->ConnID, HSE_APPEND_LOG_PARAMETER,
                                str->text, &len, (LPDWORD)NULL);
       }
       */
#endif
      str_free(str);
   }
#endif
}
Ejemplo n.º 14
0
static void
logprint(uint32_t flags, char *message, ...)
{
	va_list args;
	char buf[1024];
	int do_always = ((flags & (SC_IF_VERBOSE | SC_IF_ISATTY)) == 0);
	int do_ifverb = (flags & SC_IF_VERBOSE) && verbose;
	int do_ifisatty = (flags & SC_IF_ISATTY) && interactive;
	int code;
	static int logprint_raised = 0;

	if (do_always || do_ifverb || do_ifisatty) {
		va_start(args, message);
		/*LINTED: E_SEC_PRINTF_VAR_FMT*/
		(void) vsnprintf(buf, sizeof (buf), message, args);
		(void) fprintf(stderr, "%s: %s\n", progname, buf);
		if (!interactive) {
			switch (flags & (SC_SL_NONE | SC_SL_ERR | SC_SL_WARN)) {
			case SC_SL_ERR:
				/*LINTED: E_SEC_PRINTF_VAR_FMT*/
				syslog(LOG_ERR, buf);
				break;

			case SC_SL_WARN:
				/*LINTED: E_SEC_PRINTF_VAR_FMT*/
				syslog(LOG_WARNING, buf);
				break;

			default:
				break;
			}
		}
		va_end(args);
	}

	switch (flags & _SC_ALLEXIT) {
	case 0:
		return;

	case SC_EXIT_OK:
		code = 0;
		break;

	case SC_EXIT_PEND:
		/*
		 * Raise an ireport saying why we are exiting.  Do not
		 * raise if run as savecore -m.  If something in the
		 * raise_event codepath calls logprint avoid recursion.
		 */
		if (!mflag && logprint_raised++ == 0)
			raise_event(SC_EVENT_SAVECORE_FAILURE, buf);
		code = 2;
		break;

	case SC_EXIT_FM:
		code = 3;
		break;

	case SC_EXIT_ERR:
	default:
		if (!mflag && logprint_raised++ == 0)
			raise_event(SC_EVENT_SAVECORE_FAILURE, buf);
		code = 1;
		break;
	}

	exit(code);
}
Ejemplo n.º 15
0
int hb_vsnprintf( char * buffer, size_t bufsize, const char * format, va_list ap )
{
   va_list args;
   size_t size;
   char c;

#ifndef __NO_ARGPOS__
   const char * fmt_start = format;
   v_param argbuf[ _ARGBUF_SIZE ];
   v_paramlst params;

   params.size = _ARGBUF_SIZE;
   params.maxarg = 0;
   params.arglst = argbuf;
#endif


#ifndef __NO_ARGPOS__
   do
   {
      params.repeat = HB_FALSE;
      if( params.maxarg > 0 )
      {
         va_copy( args, ap );
         va_arg_fill( &params, args );
         va_end( args );
      }
      format = fmt_start;
#endif
      va_copy( args, ap );
      size = 0;

      do
      {
         c = *format++;
         if( c == '%' )
         {
            const char * pattern = format;

            c = *format++;
            if( c != 0 && c != '%' )
            {
               /* decode pattern */
               v_param argval;
               int param = 0, flags = 0, width = -1, precision = -1, length,
                   value, stop = 0;

               /* parameter position */
               if( c >= '0' && c <= '9' )
               {
                  c = get_decimal( c, &format, &value );
                  if( c == '$' )
                     param = value;
                  else
                     format = pattern;
                  c = *format++;
               }

               /* flags */
               while( ! stop )
               {
                  switch( c )
                  {
                     case '#':
                        flags |= _F_ALTERNATE;
                        c = *format++;
                        break;
                     case '0':
                        flags |= _F_ZEROPADED;
                        c = *format++;
                        break;
                     case '-':
                        flags |= _F_LEFTADJUSTED;
                        c = *format++;
                        break;
                     case ' ':
                        flags |= _F_SPACE;
                        c = *format++;
                        break;
                     case '+':
                        flags |= _F_SIGN;
                        c = *format++;
                        break;
#ifdef _SUSV2_COMPAT_
                     case '\'':  /* group with locale thousands' grouping characters */
                        c = *format++;
                        break;
#endif
                     default:
                        stop = 1;
                        break;
                  }
               }

               /* field width */
               if( c == '*' )
               {
                  c = *format++;
                  if( c >= '0' && c <= '9' )
                  {
                     c = get_decimal( c, &format, &value );
                     if( c == '$' )
                     {
                        width = va_arg_n( args, _x_int, value );
                        c = *format++;
                     }
                     /* else error, wrong format */
                  }
                  else
                     width = va_arg_n( args, _x_int, 0 );
               }
               else if( c >= '0' && c <= '9' )
                  c = get_decimal( c, &format, &width );

               /* precision */
               if( c == '.' )
               {
                  precision = 0;
                  c = *format++;
                  if( c == '*' )
                  {
                     c = *format++;
                     if( c >= '0' && c <= '9' )
                     {
                        c = get_decimal( c, &format, &value );
                        if( c == '$' )
                        {
                           precision = va_arg_n( args, _x_int, value );
                           c = *format++;
                        }
                        /* else error, wrong format */
                     }
                     else
                        precision = va_arg_n( args, _x_int, 0 );
                  }
                  else if( c >= '0' && c <= '9' )
                     c = get_decimal( c, &format, &precision );
               }

               /* length modifier */
               switch( c )
               {
                  case 'h':
                     c = *format++;
                     if( c == 'h' )
                     {
                        length = _L_CHAR_;
                        c = *format++;
                     }
                     else
                        length = _L_SHORT_;
                     break;
                  case 'l':
                     c = *format++;
                     if( c == 'l' )
                     {
                        length = _L_LONGLONG_;
                        c = *format++;
                     }
                     else
                        length = _L_LONG_;
                     break;
                  case 'L':
                     length = _L_LONGDOUBLE_;
                     c = *format++;
                     break;
                  case 'j':
                     length = _L_INTMAX_;
                     c = *format++;
                     break;
                  case 'z':
                     length = _L_SIZE_;
                     c = *format++;
                     break;
                  case 't':
                     length = _L_PTRDIFF_;
                     c = *format++;
                     break;
                  case 'I':   /* MS-Windows extension */
                     if( format[ 0 ] == '6' && format[ 1 ] == '4' )
                     {
                        length = _L_LONGLONG_;
                        format += 2;
                        c = *format++;
                        break;
                     }
                     else if( format[ 0 ] == '1' && format[ 1 ] == '6' )
                     {
                        length = _L_SHORT_;
                        format += 2;
                        c = *format++;
                        break;
                     }
                     else if( format[ 0 ] == '3' && format[ 1 ] == '2' )
                     {
                        format += 2;
                        c = *format++;
                     }
                     /* fallthrough */
                  default:
                     length = _L_UNDEF_;
                     break;
               }

               /* conversion specifier */
               switch( c )
               {
#ifndef __NO_DOUBLE__
                  case 'a':
                  case 'A':
                  case 'e':
                  case 'E':
                  case 'g':
                  case 'G':
                     /* redirect above conversion to 'f' or 'F' type to keep
                      * valid parameters order
                      */
                     c = ( c == 'a' || c == 'e' || c == 'g' ) ? 'f' : 'F';
                     /* fallthrough */
                  case 'f':   /* double decimal notation */
                  case 'F':   /* double decimal notation */
                     if( length == _L_LONGDOUBLE_ )
                     {
                        argval.value.as_x_long_dbl = va_arg_n( args, _x_long_dbl, param );
                        HB_NUMTYPEL( value, argval.value.as_x_long_dbl );
                     }
                     else
                     {
                        double d = va_arg_n( args, _x_double, param );
                        HB_NUMTYPE( value, d );
                        argval.value.as_x_long_dbl = ( _x_long_dbl )
                           ( ( value & ( _HB_NUM_NAN | _HB_NUM_PINF | _HB_NUM_NINF ) ) == 0 ? d : 0 );
                     }
                     if( value & _HB_NUM_NAN )
                        size = put_str( buffer, bufsize, size,
                                        c == 'f' ?
                                        ( ( flags & _F_SIGN ) ? "+nan": "nan" ) :
                                        ( ( flags & _F_SIGN ) ? "+NAN": "NAN" ) ,
                                        flags, width, -1 );
                     else if( value & _HB_NUM_PINF )
                        size = put_str( buffer, bufsize, size,
                                        c == 'f' ?
                                        ( ( flags & _F_SIGN ) ? "+inf": "inf" ) :
                                        ( ( flags & _F_SIGN ) ? "+INF": "INF" ),
                                        flags, width, -1 );
                     else if( value & _HB_NUM_NINF )
                        size = put_str( buffer, bufsize, size,
                                        c == 'f' ? "-inf" : "-INF",
                                        flags, width, -1 );
                     else
                        size = put_dbl( buffer, bufsize, size, argval.value.as_x_long_dbl,
                                        flags, width, precision );
                     continue;
#endif
                  case 'd':
                  case 'i':   /* signed int decimal conversion */
                     if( length == _L_CHAR_ )
                        argval.value.as_x_intmax_t = ( unsigned char ) va_arg_n( args, _x_int, param );
                     else if( length == _L_SHORT_ )
                        argval.value.as_x_intmax_t = ( unsigned short ) va_arg_n( args, _x_int, param );
                     else if( length == _L_LONG_ )
                        argval.value.as_x_intmax_t = va_arg_n( args, _x_long, param );
                     else if( length == _L_LONGLONG_ )
                        argval.value.as_x_intmax_t = va_arg_n( args, _x_longlong, param );
                     else if( length == _L_INTMAX_ )
                        argval.value.as_x_intmax_t = va_arg_n( args, _x_intmax_t, param );
                     else if( length == _L_SIZE_ )
                        argval.value.as_x_intmax_t = va_arg_n( args, _x_size_t, param );
                     else if( length == _L_PTRDIFF_ )
                        argval.value.as_x_intmax_t = va_arg_n( args, _x_ptrdiff_t, param );
                     else
                        argval.value.as_x_intmax_t = va_arg_n( args, _x_int, param );
                     value = argval.value.as_x_intmax_t < 0;
                     argval.value.as_x_uintmax_t = value ? -argval.value.as_x_intmax_t :
                                                            argval.value.as_x_intmax_t;
                     size = put_dec( buffer, bufsize, size, argval.value.as_x_uintmax_t,
                                     flags, width, precision, value );
                     continue;
                  case 'o':   /* unsigned int octal conversion */
                  case 'u':   /* unsigned int decimal conversion */
                  case 'x':   /* unsigned int hexadecimal conversion */
                  case 'X':   /* unsigned int hexadecimal conversion */
                     if( length == _L_CHAR_ )
                        argval.value.as_x_uintmax_t = ( unsigned char ) va_arg_n( args, _x_int, param );
                     else if( length == _L_SHORT_ )
                        argval.value.as_x_uintmax_t = ( unsigned short ) va_arg_n( args, _x_int, param );
                     else if( length == _L_LONG_ )
                        argval.value.as_x_uintmax_t = va_arg_n( args, _x_ulong, param );
                     else if( length == _L_LONGLONG_ )
                        argval.value.as_x_uintmax_t = va_arg_n( args, _x_ulonglong, param );
                     else if( length == _L_INTMAX_ )
                        argval.value.as_x_uintmax_t = va_arg_n( args, _x_uintmax_t, param );
                     else if( length == _L_SIZE_ )
                        argval.value.as_x_uintmax_t = va_arg_n( args, _x_size_t, param );
                     else if( length == _L_PTRDIFF_ )
                        argval.value.as_x_uintmax_t = va_arg_n( args, _x_ptrdiff_t, param );
                     else
                        argval.value.as_x_uintmax_t = va_arg_n( args, _x_uint, param );

                     if( c == 'o' )
                        size = put_octal( buffer, bufsize, size, argval.value.as_x_uintmax_t,
                                          flags, width, precision );
                     else if( c == 'u' )
                        size = put_dec( buffer, bufsize, size, argval.value.as_x_uintmax_t,
                                        flags & ~( _F_SPACE | _F_SIGN ),
                                        width, precision, 0 );
                     else
                        size = put_hex( buffer, bufsize, size, argval.value.as_x_uintmax_t,
                                        flags, width, precision, c == 'X' );
                     continue;
                  case 'p':   /* void * pointer */
                     argval.value.as_x_ptr = va_arg_n( args, _x_ptr, param );
                     if( argval.value.as_x_ptr )
                        size = put_hex( buffer, bufsize, size, ( HB_PTRUINT ) argval.value.as_x_ptr,
                                        flags | _F_ALTERNATE, width, precision, 0 );
                     else
                        size = put_str( buffer, bufsize, size, "(nil)",
                                        flags, width, -1 );
                     continue;
                  case 'c':   /* signed int casted to unsigned char */
                     if( ( flags & _F_LEFTADJUSTED ) == 0 )
                     {
                        while( --width > 0 )
                        {
                           if( size < bufsize )
                              buffer[ size ] = ' ';
                           ++size;
                        }
                     }
                     c = ( unsigned char ) va_arg_n( args, _x_int, param );
                     if( size < bufsize )
                        buffer[ size ] = c;
                     ++size;
                     while( --width > 0 )
                     {
                        if( size < bufsize )
                           buffer[ size ] = ' ';
                        ++size;
                     }
                     continue;
                  case 's':   /* const char * */
                     if( length == _L_LONG_ )
                     {
                        argval.value.as_x_wstr = va_arg_n( args, _x_wstr, param );
                        size = put_wstr( buffer, bufsize, size, argval.value.as_x_wstr,
                                         flags, width, precision );
                     }
                     else
                     {
                        argval.value.as_x_str = va_arg_n( args, _x_str, param );
                        size = put_str( buffer, bufsize, size, argval.value.as_x_str,
                                        flags, width, precision );
                     }
                     continue;
                  case 'n':   /* store current result size in int * arg */
                     /* This is very danger feature in *printf() functions
                      * family very often used by hackers to create buffer
                      * overflows. It can also cause unintentional memory
                      * corruption by programmers typo in pattern so if it's
                      * not strictly necessary it's good to disable it.
                      */
                     *( va_arg_n( args, _x_intptr, param ) ) = ( int ) size;
                     continue;
                  case '%':   /* store % consuming arguments % */
                     break;
                  default:    /* error, wrong format, store pattern */
                     format = pattern;
                     c = '%';
                     break;
               }
            }
         }

         /* ISO C99 defines that when size is 0 and buffer is NULL we should
          * return number of characters that would have been written in case
          * the output string has been large enough without trailing 0.
          * Many implementations always returns number of characters necessary
          * to hold the string even if the above condition is not true so the
          * returned value can be used to check if buffer was large enough
          * and if not to allocate bigger buffer. Let's do the same.
          */
         if( size < bufsize )
            buffer[ size ] = c;
         ++size;
      }
      while( c != 0 );

      va_end( args );

#ifndef __NO_ARGPOS__
   }
   while( params.repeat );

   if( params.arglst != argbuf )
      hb_xfree( params.arglst );
#endif

   /* always set trailing \0 !!! */
   if( bufsize )
      buffer[ bufsize - 1 ] = 0;

   return ( int ) ( size - 1 );
}
Ejemplo n.º 16
0
void fmt_print(const char *fmt, ...){
	va_list ap;
	va_start(ap, fmt);
	fmt_vfmt(outc, stdout, fmt, ap);
	va_end(ap);
}
Ejemplo n.º 17
0
/**
 * Emit a log message. This function is the variable argument list equivalent
 * to vlc_Log().
 */
void vlc_vaLog (vlc_object_t *obj, int type, const char *module,
                const char *format, va_list args)
{
    if (obj != NULL && obj->i_flags & OBJECT_FLAGS_QUIET)
        return;

    /* Get basename from the module filename */
    char *p = strrchr(module, '/');
    if (p != NULL)
        module = p;
    p = strchr(module, '.');

    size_t modlen = (p != NULL) ? (p - module) : 1;
    char modulebuf[modlen + 1];
    if (p != NULL)
    {
        memcpy(modulebuf, module, modlen);
        modulebuf[modlen] = '\0';
        module = modulebuf;
    }

    /* C locale to get error messages in English in the logs */
    locale_t c = newlocale (LC_MESSAGES_MASK, "C", (locale_t)0);
    locale_t locale = uselocale (c);

#ifndef __GLIBC__
    /* Expand %m to strerror(errno) - only once */
    char buf[strlen(format) + 2001], *ptr;
    strcpy (buf, format);
    ptr = (char*)buf;
    format = (const char*) buf;

    for( ;; )
    {
        ptr = strchr( ptr, '%' );
        if( ptr == NULL )
            break;

        if( ptr[1] == 'm' )
        {
            char errbuf[2001];
            size_t errlen;

#ifndef _WIN32
            strerror_r( errno, errbuf, 1001 );
#else
            int sockerr = WSAGetLastError( );
            if( sockerr )
            {
                strncpy( errbuf, net_strerror( sockerr ), 1001 );
                WSASetLastError( sockerr );
            }
            if ((sockerr == 0)
             || (strcmp ("Unknown network stack error", errbuf) == 0))
                strncpy( errbuf, strerror( errno ), 1001 );
#endif
            errbuf[1000] = 0;

            /* Escape '%' from the error string */
            for( char *percent = strchr( errbuf, '%' );
                 percent != NULL;
                 percent = strchr( percent + 2, '%' ) )
            {
                memmove( percent + 1, percent, strlen( percent ) + 1 );
            }

            errlen = strlen( errbuf );
            memmove( ptr + errlen, ptr + 2, strlen( ptr + 2 ) + 1 );
            memcpy( ptr, errbuf, errlen );
            break; /* Only once, so we don't overflow */
        }

        /* Looks for conversion specifier... */
        do
            ptr++;
        while( *ptr && ( strchr( "diouxXeEfFgGaAcspn%", *ptr ) == NULL ) );
        if( *ptr )
            ptr++; /* ...and skip it */
    }
#endif

    /* Fill message information fields */
    vlc_log_t msg;

    msg.i_object_id = (uintptr_t)obj;
    msg.psz_object_type = (obj != NULL) ? obj->psz_object_type : "generic";
    msg.psz_module = module;
    msg.psz_header = NULL;

    for (vlc_object_t *o = obj; o != NULL; o = o->p_parent)
        if (o->psz_header != NULL)
        {
            msg.psz_header = o->psz_header;
            break;
        }

    /* Pass message to the callback */
    libvlc_priv_t *priv = obj ? libvlc_priv (obj->p_libvlc) : NULL;

#ifdef _WIN32
    va_list ap;

    va_copy (ap, args);
    Win32DebugOutputMsg (priv ? &priv->log.verbose : NULL, type, &msg, format, ap);
    va_end (ap);
#endif

    if (priv) {
        vlc_rwlock_rdlock (&priv->log.lock);
        priv->log.cb (priv->log.opaque, type, &msg, format, args);
        vlc_rwlock_unlock (&priv->log.lock);
    }

    uselocale (locale);
    freelocale (c);
}
Ejemplo n.º 18
0
void fmt_fprint(FILE *stream, const char *fmt, ...){
	va_list ap;
	va_start(ap, fmt);
	fmt_vfmt(outc, stdout, fmt, ap);
	va_end(ap);
}
Ejemplo n.º 19
0
static int 
TargetCall(WsXmlDocH doc, PyObject* instance, 
                 const char* opname, int nargs, ...)
{
    va_list vargs; 
    PyObject *pyargs = NULL; 
    PyObject *pyfunc = NULL; 
    PyObject *result = NULL; 
    WsmanStatus status;
    wsman_status_init(&status);

    pyargs = PyTuple_New(nargs); 
    pyfunc = PyObject_GetAttrString(instance, opname); 
    if (pyfunc == NULL)
    {
        PyErr_Print(); 
        PyErr_Clear(); 
        char* str = fmtstr("Python module does not contain \"%s\"", opname); 
        debug("%s", str); 
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;

        free(str); 
        goto cleanup; 
    }
    if (! PyCallable_Check(pyfunc))
    {
        char* str = fmtstr("Python module attribute \"%s\" is not callable", 
                opname); 
        debug("%s", str); 
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        free(str); 
        goto cleanup; 
    }
    
    va_start(vargs, nargs); 
    int i; 
    for (i = 0; i < nargs; ++i)
    {
        PyObject* arg = va_arg(vargs, PyObject*); 
        if (arg == NULL)
        {
            arg = Py_None; 
            Py_IncRef(arg); 
        }
        PyTuple_SET_ITEM(pyargs, i, arg); 
    }
    va_end(vargs); 
    result = PyObject_CallObject(pyfunc, pyargs);
    if (PyErr_Occurred())
    {
        status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
        PyErr_Clear(); 
        goto cleanup; 
    }

    if (! PyTuple_Check(result) || 
            (PyTuple_Size(result) != 2 && PyTuple_Size(result) != 1))
    {
        TARGET_THREAD_BEGIN_ALLOW;
        status.fault_msg = fmtstr("Python function \"%s\" didn't return a two-tuple", opname); 
	status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
        TARGET_THREAD_END_ALLOW; 
        goto cleanup; 
    }
    PyObject* code = PyTuple_GetItem(result, 0);
    PyObject* detail = Py_None; 
    if (PyTuple_Size(result) == 2)
    {
        detail = PyTuple_GetItem(result, 1); 
    }

    if (! PyInt_Check(code) || (! PyInt_Check(detail) && detail != Py_None))
    {
        TARGET_THREAD_BEGIN_ALLOW;
        status.fault_msg = fmtstr("Python function \"%s\" didn't return a {<int>, <int>) two-tuple", opname); 
	status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
        TARGET_THREAD_END_ALLOW; 
        goto cleanup; 
    }
    status.fault_code = PyInt_AsLong(code); 
    if (detail == Py_None)
    {
	status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
    }
    else
    {
        status.fault_detail_code = PyInt_AsLong(detail);
    }
cleanup:
    if (status.fault_code != WSMAN_RC_OK)
      wsman_generate_fault( doc, status.fault_code, status.fault_detail_code, status.fault_msg );
    Py_DecRef(pyargs);
    Py_DecRef(pyfunc);
    Py_DecRef(result);
 
    return status.fault_code != WSMAN_RC_OK; 
}
Ejemplo n.º 20
0
void *g_html_special(struct g_part *p, int c, ...)
{
	va_list l;
	unsigned char *t;
	struct form_control *fc;
	struct frameset_param *fsp;
	struct frame_param *fp;
	struct image_description *im;
	struct g_object_tag *tag;
	struct refresh_param *rp;
	struct hr_param *hr;
	va_start(l, c);
	switch (c) {
		case SP_TAG:
			t = va_arg(l, unsigned char *);
			va_end(l);
			/*html_tag(p->data, t, X(p->cx), Y(p->cy));*/
			tag = mem_calloc(sizeof(struct g_object_tag) + strlen(t) + 1);
			tag->mouse_event = g_dummy_mouse;
			tag->draw = g_dummy_draw;
			tag->destruct = g_tag_destruct;
			strcpy(tag->name, t);
			flush_pending_text_to_line(p);
			add_object_to_line(p, &p->line, (struct g_object *)tag);
			break;
		case SP_CONTROL:
			fc = va_arg(l, struct form_control *);
			va_end(l);
			g_html_form_control(p, fc);
			break;
		case SP_TABLE:
			va_end(l);
			return convert_table;
		case SP_USED:
			va_end(l);
			return (void *)(my_intptr_t)!!p->data;
		case SP_FRAMESET:
			fsp = va_arg(l, struct frameset_param *);
			va_end(l);
			return create_frameset(p->data, fsp);
		case SP_FRAME:
			fp = va_arg(l, struct frame_param *);
			va_end(l);
			create_frame(fp);
			break;
		case SP_SCRIPT:
			t = va_arg(l, unsigned char *);
			va_end(l);
			if (p->data) process_script(p->data, t);
			break;
		case SP_IMAGE:
			im = va_arg(l, struct image_description *);
			va_end(l);
			do_image(p, im);
			break;
		case SP_NOWRAP:
			va_end(l);
			break;
		case SP_REFRESH:
			rp = va_arg(l, struct refresh_param *);
			va_end(l);
			html_process_refresh(p->data, rp->url, rp->time);
			break;
		case SP_SET_BASE:
			t = va_arg(l, unsigned char *);
			va_end(l);
			if (p->data) set_base(p->data, t);
			break;
		case SP_HR:
			hr = va_arg(l, struct hr_param *);
			va_end(l);
			g_hr(p, hr);
			break;
		default:
			va_end(l);
			internal("html_special: unknown code %d", c);
	}
	return NULL;
}
Ejemplo n.º 21
0
/**
 * gedit_utils_get_ui_objects:
 * @filename: the path to the gtk builder file
 * @root_objects: a NULL terminated list of root objects to load or NULL to
 *                load all objects
 * @error_widget: a pointer were a #GtkLabel
 * @object_name: the name of the first object
 * @...: a pointer were the first object is returned, followed by more
 *       name / object pairs and terminated by NULL.
 *
 * This function gets the requested objects from a GtkBuilder ui file. In case
 * of error it returns FALSE and sets error_widget to a GtkLabel containing
 * the error message to display.
 *
 * Returns FALSE if an error occurs, TRUE on success.
 */
gboolean
gedit_utils_get_ui_objects (const gchar  *filename,
			    gchar       **root_objects,
			    GtkWidget   **error_widget,
			    const gchar  *object_name,
			    ...)
{

	GtkBuilder *builder;
	va_list args;
	const gchar *name;
	GError *error = NULL;
	gchar *filename_markup;
	gboolean ret = TRUE;

	g_return_val_if_fail (filename != NULL, FALSE);
	g_return_val_if_fail (error_widget != NULL, FALSE);
	g_return_val_if_fail (object_name != NULL, FALSE);

	filename_markup = g_markup_printf_escaped ("<i>%s</i>", filename);
	*error_widget = NULL;

	builder = gtk_builder_new ();
	
	if (root_objects != NULL)
	{
		gtk_builder_add_objects_from_file (builder, 
						   filename, 
						   root_objects, 
						   &error);
	}
	else
	{
		gtk_builder_add_from_file (builder,
					   filename,
					   &error);
	}

	if (error != NULL)
	{
		*error_widget = handle_builder_error (_("Unable to open ui file %s. Error: %s"),
						      filename_markup,
						      error->message);
		g_error_free (error);
		g_free (filename_markup);
		g_object_unref (builder);

		return FALSE;
	}

	va_start (args, object_name);
	for (name = object_name; name; name = va_arg (args, const gchar *) )
	{
		GObject **gobj;

		gobj = va_arg (args, GObject **);
		*gobj = gtk_builder_get_object (builder, name);

		if (!*gobj)
		{
			*error_widget = handle_builder_error (_("Unable to find the object '%s' inside file %s."), 
							      name, 
							      filename_markup),
			ret = FALSE;
			break;
		}

		/* we return a new ref for the root objects,
		 * the others are already reffed by their parent root object */
		if (root_objects != NULL)
		{
			gint i;

			for (i = 0; root_objects[i] != NULL; ++i)
			{
				if ((strcmp (name, root_objects[i]) == 0))
				{
					g_object_ref (*gobj);
				}
			}
		}
	}
	va_end (args);

	g_free (filename_markup);
	g_object_unref (builder);

	return ret;
}
Ejemplo n.º 22
0
void TxtLogger::logSync(unsigned insid, unsigned short sync,
                        unsigned turn, 
                        timespec time1, 
                        timespec time2, timespec sched_time, 
                        bool after, ...) {
  assert(sync >= syncfunc::first_sync && sync < syncfunc::num_syncs
    && "trying to log unknown synchronization operation!");

//  if(!syncfunc::isSync(sync))
//  {
    if (sync == syncfunc::tern_thread_begin
      || sync == syncfunc::tern_thread_end)    //  for tests, i need to know the thread_mapping
    {
      va_list args;
      va_start(args, after);
      ouf << syncfunc::getName(sync)
          << " 0x" << hex << insid << dec
          << ' ' << turn
          << " " << dec << time1.tv_sec << ":"
          << setfill('0') << setw(9) << time1.tv_nsec
          << " " << dec << time2.tv_sec << ":"
          << setfill('0') << setw(9) << time2.tv_nsec
          << " " << dec << sched_time.tv_sec << ":"
          << setfill('0') << setw(9) << sched_time.tv_nsec
          << ' ' << tid
          << hex << " 0x" << va_arg(args, uint64_t) << dec;
      va_end(args);
      ouf << "\n";
      ouf.flush();
      return;
    }
//    return;
//  }
  // YJF: why ignore prog_begin/end and thread_begin/end?
  const char *suffix = "";
  if(NumRecordsForSync(sync) == 2)
    suffix = (after?"_second":"_first");

  ouf << syncfunc::getName(sync) << suffix
      << " 0x" << hex << setfill('0') << setw(8) << insid << dec
      << ' ' << turn
      << " " << dec << time1.tv_sec << ":"
      << setfill('0') << setw(9) << time1.tv_nsec
      << " " << dec << time2.tv_sec << ":"
      << setfill('0') << setw(9) << time2.tv_nsec
      << " " << dec << sched_time.tv_sec << ":"
      << setfill('0') << setw(9) << sched_time.tv_nsec
      << ' ' << tid;

  va_list args;
  va_start(args, after);

  switch(sync) {
    // log nothing, mostly for sched point. 
  case syncfunc::accept4:
  case syncfunc::recv:
  case syncfunc::recvfrom:
  case syncfunc::recvmsg:
  case syncfunc::select:
  case syncfunc::poll:
  case syncfunc::bind:
  case syncfunc::listen:
  case syncfunc::getsockopt:
  case syncfunc::setsockopt:
  case syncfunc::pipe:
  case syncfunc::fcntl:
  case syncfunc::shutdown:
  case syncfunc::gethostbyname:
  case syncfunc::gethostbyname_r:
  case syncfunc::getaddrinfo:
  case syncfunc::freeaddrinfo:
  case syncfunc::gethostbyaddr:
  case syncfunc::inet_ntoa:
  case syncfunc::strtok:
  case syncfunc::epoll_wait:
  case syncfunc::epoll_create:
  case syncfunc::epoll_ctl:
  case syncfunc::sigwait:
  case syncfunc::fgets:
  case syncfunc::kill:
  case syncfunc::fork:
  case syncfunc::execv:
  case syncfunc::sched_yield:
  case syncfunc::wait:
  case syncfunc::waitpid:
  case syncfunc::tern_idle:
  case syncfunc::tern_non_det_start:
  case syncfunc::tern_non_det_end:
    break;
    // log one sync var (common case)
  case syncfunc::pthread_mutex_init:
  case syncfunc::pthread_mutex_destroy:
  case syncfunc::pthread_mutex_lock:
  case syncfunc::pthread_mutex_unlock:
  case syncfunc::pthread_barrier_wait:
  case syncfunc::pthread_barrier_destroy:
  case syncfunc::pthread_cond_signal:
  case syncfunc::pthread_cond_broadcast:
  case syncfunc::sem_wait:
  case syncfunc::sem_init:
  case syncfunc::sem_post:
  case syncfunc::pthread_join:
  case syncfunc::pthread_detach:
  case syncfunc::sleep:
  case syncfunc::usleep:
  case syncfunc::nanosleep:
  case syncfunc::pthread_rwlock_rdlock:
  case syncfunc::pthread_rwlock_wrlock:
  case syncfunc::tern_lineup_start:
  case syncfunc::tern_lineup_end:
  case syncfunc::tern_lineup_destroy:
    ouf << hex << " 0x" << va_arg(args, uint64_t) << dec;
    break;

    // log two sync vars for cond_*wait
  case syncfunc::pthread_mutex_timedlock:
  case syncfunc::pthread_cond_wait:
  case syncfunc::pthread_barrier_init:
  case syncfunc::pthread_create:
  case syncfunc::pthread_mutex_trylock:
  case syncfunc::sem_trywait:
  case syncfunc::sem_timedwait:
  case syncfunc::pthread_rwlock_tryrdlock:  //  rwlock, ret
  case syncfunc::pthread_rwlock_trywrlock:
  case syncfunc::pthread_rwlock_unlock:  //  rwlock, ret
    {
      //  notice "<<" operator is expanded from right to left.
      uint64_t a = va_arg(args, uint64_t);
      uint64_t b = va_arg(args, uint64_t);

    ouf << hex
        << " 0x" << a
        << " 0x" << b
        << dec;
    }
    break;
    // log three sync vars
  case syncfunc::pthread_cond_timedwait:  //  cv, mu, ret
  case syncfunc::read:  //  sig, fd, ret
  case syncfunc::fread:  //  sig, ptr, size
  case syncfunc::pread:  //  sig, fd, ret
  case syncfunc::accept:  //  sock(ret), from_port, to_port
  case syncfunc::write: //  sig, fd, ret
  case syncfunc::pwrite: //  sig, fd, ret
  case syncfunc::tern_lineup_init:
    {
      //  notice "<<" operator is explained from right to left.
      uint64_t a = va_arg(args, uint64_t);
      uint64_t b = va_arg(args, uint64_t);
      uint64_t c = va_arg(args, uint64_t);

    ouf << hex
        << " 0x" << a
        << " 0x" << b
        << " 0x" << c
        << dec;
    }
    break;
  case syncfunc::connect: //  fd, from_port, to_port, ret
    {
      //  notice "<<" operator is explained from right to left.
      uint64_t a = va_arg(args, uint64_t);
      uint64_t b = va_arg(args, uint64_t);
      uint64_t c = va_arg(args, uint64_t);
      uint64_t d = va_arg(args, uint64_t);

    ouf << hex
        << " 0x" << a
        << " 0x" << b
        << " 0x" << c
        << " 0x" << d
        << dec;
    }
    break;

  default:
    cerr << "sync " << syncfunc::getName(sync) << " is not yet handled!\n";
    assert(0);
  }

  va_end(args);
  ouf << "\n";
  ouf.flush();
}
Ejemplo n.º 23
0
   SpiceInt mini_c ( SpiceInt n,  ... ) 

/*

-Brief_I/O
 
   Variable  I/O  Description 
   --------  ---  -------------------------------------------------- 
   n          I   The number of integer values to compare.
   ...        I   The numbers to be compared, separated by commas.
    
-Detailed_Input
 
   n              is the number of integer values in the set 
                  whose minimum is to be determined.  
   
   ...            represents a variable argument list.  The number of 
                  integer values supplied must be that indicated by n.  
                  The values are separated by commas.
                  
                  Section 5.2.4.1 of the ANSI C Standard, titled
                  "Translation Limits," specifies that argument lists
                  containing at least 31 items must be supported.  In
                  the interest of portability, no more than 30 
                  integer values should be supplied.
   
-Detailed_Output
 
   The function returns the minimum of the set of input integers.
 
-Parameters
 
   None. 
 
-Exceptions
 
   Error free.
   
   1) If n is less than 1, the value 0 is returned.
   
   2) If the number of integer values supplied does not match
      the argument n, the action of this routine is not defined.
      
   3) If the number of integer values supplied exceeds 30,
      the action of this routine is not defined.
    
-Files
 
   None. 
 
-Particulars

   None.
 
-Examples
 
   1) Find the minimum of four integer values.
   
      #include "SpiceUsr.h"
           .
           .
           .
           
      SpiceInt                min;
      SpiceInt                a;
      SpiceInt                b;
      SpiceInt                c;
      SpiceInt                d;
           .
           .
           .
           
      min = mini_c ( 4, a, b, c, d );
      
   
-Restrictions
 
   1) The ANSI C Standard specifies that argument lists containing 31
      actual arguments must be supported.  Larger sets of values may
      not be handled properly by this routine. 
 
-Literature_References
 
   1) "American National Standard for Programming Languages---C."
      Section 5.4.2.1, "Translation Limits," p. 13.
      Published by American National Standards Institute,
      11 West 42nd St., New York, NY 10035. Copyright 1990.
      
-Author_and_Institution
 
   N.J. Bachman   (JPL) 
 
-Version
 
   -CSPICE Version 1.0.1, 11-NOV-2006 (EDW)

      Added "None." text to Particulars section, required for
      API doc script (cspicehtml.pl) integrity checks.

   -CSPICE Version 1.0.0, 29-MAR-1999 (NJB)

-Index_Entries
 
   minimum of integer values 
 
-&
*/

{ /* Begin mini_c */

   /*
   Local variables
   */
   
   SpiceInt                next;
   SpiceInt                retval;
   
   SpiceInt                i;


   /*
   ap is the argument pointer.  Its type va_list is declared in the
   header stdarg.h.
   */

   va_list                 ap;
   
   
   
   /*
   If there are no values to compare, return zero.  
   */
 
   if ( n < 1 )
   {
      return ( 0 );
   }
   
   /*
   Initialize the argument pointer with the last named argument, namely
   n.
   */
   
   va_start ( ap, n );
   
   
   /*
   Initialize the minimum with the first value.
   */
   
   retval = va_arg ( ap, int );
   
   
   /*
   Now compute a running minimum of the values, if there are more.
   
   By the way, we capture the argument in the variable next rather than
   make the va_arg call as a MinVal argument, because the MinVal macro
   would make the va_arg call twice.
   */ 
   
   for ( i = 1;  i < n;  i++ )
   {
      next   =  va_arg ( ap,     int  );
      retval =  MinVal ( retval, next );
   }
   
   
   /*
   Terminate the argument fetching process.
   */
   
   va_end ( ap );
   
   
   /*
   Return the value we've found.
   */
   
   return ( retval );
   
   
} /* End mini_c */
Ejemplo n.º 24
0
Archivo: msg.c Proyecto: UNGLinux/Obase
/*
 * msgq --
 *	Display a message.
 *
 * PUBLIC: void msgq(SCR *, mtype_t, const char *, ...);
 */
void
msgq(SCR *sp, mtype_t mt, const char *fmt, ...)
{
#ifndef NL_ARGMAX
#define	__NL_ARGMAX	20		/* Set to 9 by System V. */
	struct {
		const char *str;	/* String pointer. */
		size_t	 arg;		/* Argument number. */
		size_t	 prefix;	/* Prefix string length. */
		size_t	 skip;		/* Skipped string length. */
		size_t	 suffix;	/* Suffix string length. */
	} str[__NL_ARGMAX];
#endif
	static int reenter;		/* STATIC: Re-entrancy check. */
	GS *gp;
	size_t blen, len, mlen, nlen;
	const char *p;
	char *bp, *mp;
#ifndef NL_ARGMAX
	size_t cnt1, cnt2, soff;
	CHAR_T ch;
	const char *t, *u;
	char *rbp, *s_rbp;
#endif
        va_list ap;

	/*
	 * !!!
	 * It's possible to enter msg when there's no screen to hold the
	 * message.  If sp is NULL, ignore the special cases and put the
	 * message out to stderr.
	 */
	if (sp == NULL) {
		gp = NULL;
		if (mt == M_BERR)
			mt = M_ERR;
		else if (mt == M_VINFO)
			mt = M_INFO;
	} else {
		gp = sp->gp;
		switch (mt) {
		case M_BERR:
			if (F_ISSET(sp, SC_VI) && !O_ISSET(sp, O_VERBOSE)) {
				F_SET(gp, G_BELLSCHED);
				return;
			}
			mt = M_ERR;
			break;
		case M_VINFO:
			if (!O_ISSET(sp, O_VERBOSE))
				return;
			mt = M_INFO;
			/* FALLTHROUGH */
		case M_INFO:
			if (F_ISSET(sp, SC_EX_SILENT))
				return;
			break;
		case M_ERR:
		case M_SYSERR:
			break;
		default:
			abort();
		}
	}

	/*
	 * It's possible to reenter msg when it allocates space.  We're
	 * probably dead anyway, but there's no reason to drop core.
	 *
	 * XXX
	 * Yes, there's a race, but it should only be two instructions.
	 */
	if (reenter++)
		return;

	/* Get space for the message. */
	nlen = 1024;
	if (0) {
retry:		FREE_SPACE(sp, bp, blen);
		nlen *= 2;
	}
	bp = NULL;
	blen = 0;
	GET_SPACE_GOTO(sp, bp, blen, nlen);

	/*
	 * Error prefix.
	 *
	 * mp:	 pointer to the current next character to be written
	 * mlen: length of the already written characters
	 * blen: total length of the buffer
	 */
#define	REM	(blen - mlen)
	mp = bp;
	mlen = 0;
	if (mt == M_SYSERR) {
		p = msg_cat(sp, "020|Error: ", &len);
		if (REM < len)
			goto retry;
		memcpy(mp, p, len);
		mp += len;
		mlen += len;
	}

	/*
	 * If we're running an ex command that the user didn't enter, display
	 * the file name and line number prefix.
	 */
	if ((mt == M_ERR || mt == M_SYSERR) &&
	    sp != NULL && gp != NULL && gp->if_name != NULL) {
		for (p = gp->if_name; *p != '\0'; ++p) {
			len = snprintf(mp, REM, "%s", KEY_NAME(sp, *p));
			mp += len;
			if ((mlen += len) > blen)
				goto retry;
		}
		len = snprintf(mp, REM, ", %d: ", gp->if_lno);
		mp += len;
		if ((mlen += len) > blen)
			goto retry;
	}

	/* If nothing to format, we're done. */
	if (fmt == NULL)
		goto nofmt;
	fmt = msg_cat(sp, fmt, NULL);

#ifndef NL_ARGMAX
	/*
	 * Nvi should run on machines that don't support the numbered argument
	 * specifications (%[digit]*$).  We do this by reformatting the string
	 * so that we can hand it to vsnprintf(3) and it will use the arguments
	 * in the right order.  When vsnprintf returns, we put the string back
	 * into the right order.  It's undefined, according to SVID III, to mix
	 * numbered argument specifications with the standard style arguments,
	 * so this should be safe.
	 *
	 * In addition, we also need a character that is known to not occur in
	 * any vi message, for separating the parts of the string.  As callers
	 * of msgq are responsible for making sure that all the non-printable
	 * characters are formatted for printing before calling msgq, we use a
	 * random non-printable character selected at terminal initialization
	 * time.  This code isn't fast by any means, but as messages should be
	 * relatively short and normally have only a few arguments, it won't be
	 * too bad.  Regardless, nobody has come up with any other solution.
	 *
	 * The result of this loop is an array of pointers into the message
	 * string, with associated lengths and argument numbers.  The array
	 * is in the "correct" order, and the arg field contains the argument
	 * order.
	 */
	for (p = fmt, soff = 0; soff < __NL_ARGMAX;) {
		for (t = p; *p != '\0' && *p != '%'; ++p);
		if (*p == '\0')
			break;
		++p;
		if (!isdigit(*p)) {
			if (*p == '%')
				++p;
			continue;
		}
		for (u = p; isdigit(*++p););
		if (*p != '$')
			continue;

		/* Up to, and including the % character. */
		str[soff].str = t;
		str[soff].prefix = u - t;

		/* Up to, and including the $ character. */
		str[soff].arg = atoi(u);
		str[soff].skip = (p - u) + 1;
		if (str[soff].arg >= __NL_ARGMAX)
			goto ret;

		/* Up to, and including the conversion character. */
		for (u = p; (ch = *++p) != '\0';)
			if (isalpha(ch) &&
			    strchr("diouxXfeEgGcspn", ch) != NULL)
				break;
		str[soff].suffix = p - u;
		if (ch != '\0')
			++p;
		++soff;
	}

	/* If no magic strings, we're done. */
	if (soff == 0)
		goto format;

	 /* Get space for the reordered strings. */
	if ((rbp = malloc(nlen)) == NULL)
		goto ret;
	s_rbp = rbp;

	/*
	 * Reorder the strings into the message string based on argument
	 * order.
	 *
	 * !!!
	 * We ignore arguments that are out of order, i.e. if we don't find
	 * an argument, we continue.  Assume (almost certainly incorrectly)
	 * that whoever created the string knew what they were doing.
	 *
	 * !!!
	 * Brute force "sort", but since we don't expect more than one or two
	 * arguments in a string, the setup cost of a fast sort will be more
	 * expensive than the loop.
	 */
	for (cnt1 = 1; cnt1 <= soff; ++cnt1)
		for (cnt2 = 0; cnt2 < soff; ++cnt2)
			if (cnt1 == str[cnt2].arg) {
				memmove(s_rbp, str[cnt2].str, str[cnt2].prefix);
				memmove(s_rbp + str[cnt2].prefix,
				    str[cnt2].str + str[cnt2].prefix +
				    str[cnt2].skip, str[cnt2].suffix);
				s_rbp += str[cnt2].prefix + str[cnt2].suffix;
				*s_rbp++ =
				    gp == NULL ? DEFAULT_NOPRINT : gp->noprint;
				break;
			}
	*s_rbp = '\0';
	fmt = rbp;

format:
#endif
	/* Format the arguments into the string. */
        va_start(ap, fmt);
	len = vsnprintf(mp, REM, fmt, ap);
	va_end(ap);
	if (len >= nlen)
		goto retry;

#ifndef NL_ARGMAX
	if (soff == 0)
		goto nofmt;

	/*
	 * Go through the resulting string, and, for each separator character
	 * separated string, enter its new starting position and length in the
	 * array.
	 */
	for (p = t = mp, cnt1 = 1,
	    ch = gp == NULL ? DEFAULT_NOPRINT : gp->noprint; *p != '\0'; ++p)
		if (*p == ch) {
			for (cnt2 = 0; cnt2 < soff; ++cnt2)
				if (str[cnt2].arg == cnt1)
					break;
			str[cnt2].str = t;
			str[cnt2].prefix = p - t;
			t = p + 1;
			++cnt1;
		}

	/*
	 * Reorder the strings once again, putting them back into the
	 * message buffer.
	 *
	 * !!!
	 * Note, the length of the message gets decremented once for
	 * each substring, when we discard the separator character.
	 */
	for (s_rbp = rbp, cnt1 = 0; cnt1 < soff; ++cnt1) {
		memmove(rbp, str[cnt1].str, str[cnt1].prefix);
		rbp += str[cnt1].prefix;
		--len;
	}
	memmove(mp, s_rbp, rbp - s_rbp);

	/* Free the reordered string memory. */
	free(s_rbp);
#endif

nofmt:	mp += len;
	if ((mlen += len) > blen)
		goto retry;
	if (mt == M_SYSERR) {
		len = snprintf(mp, REM, ": %s", strerror(errno));
		mp += len;
		if ((mlen += len) > blen)
			goto retry;
		mt = M_ERR;
	}

	/* Add trailing newline. */
	if ((mlen += 1) > blen)
		goto retry;
	*mp = '\n';

	if (sp != NULL)
		(void)ex_fflush(sp);
	if (gp != NULL)
		gp->scr_msg(sp, mt, bp, mlen);
	else
		(void)fprintf(stderr, "%.*s", (int)mlen, bp);

	/* Cleanup. */
	FREE_SPACE(sp, bp, blen);
alloc_err:
	reenter = 0;
}
Ejemplo n.º 25
0
int er_default_printf(char *format,...) {
  int ret;
  va_list ap; va_start(ap,format); ret=(*er_vprintf)(format,ap); va_end(ap);
  return ret;
}
Ejemplo n.º 26
0
void StringAppendF(std::string* dst, const char* format, ...) {
    va_list ap;
    va_start(ap, format);
    StringAppendV(dst, format, ap);
    va_end(ap);
}
int opus_multistream_decoder_ctl(OpusMSDecoder *st, int request, ...)
{
   va_list ap;
   int coupled_size, mono_size;
   char *ptr;
   int ret = OPUS_OK;

   va_start(ap, request);

   coupled_size = opus_decoder_get_size(2);
   mono_size = opus_decoder_get_size(1);
   ptr = (char*)st + align(sizeof(OpusMSDecoder));
   switch (request)
   {
       case OPUS_GET_BANDWIDTH_REQUEST:
       case OPUS_GET_SAMPLE_RATE_REQUEST:
       case OPUS_GET_GAIN_REQUEST:
       case OPUS_GET_LAST_PACKET_DURATION_REQUEST:
       {
          OpusDecoder *dec;
          /* For int32* GET params, just query the first stream */
          opus_int32 *value = va_arg(ap, opus_int32*);
          dec = (OpusDecoder*)ptr;
          ret = opus_decoder_ctl(dec, request, value);
       }
       break;
       case OPUS_GET_FINAL_RANGE_REQUEST:
       {
          int s;
          opus_uint32 *value = va_arg(ap, opus_uint32*);
          opus_uint32 tmp;
          if (!value)
          {
             goto bad_arg;
          }
          *value = 0;
          for (s=0;s<st->layout.nb_streams;s++)
          {
             OpusDecoder *dec;
             dec = (OpusDecoder*)ptr;
             if (s < st->layout.nb_coupled_streams)
                ptr += align(coupled_size);
             else
                ptr += align(mono_size);
             ret = opus_decoder_ctl(dec, request, &tmp);
             if (ret != OPUS_OK) break;
             *value ^= tmp;
          }
       }
       break;
       case OPUS_RESET_STATE:
       {
          int s;
          for (s=0;s<st->layout.nb_streams;s++)
          {
             OpusDecoder *dec;

             dec = (OpusDecoder*)ptr;
             if (s < st->layout.nb_coupled_streams)
                ptr += align(coupled_size);
             else
                ptr += align(mono_size);
             ret = opus_decoder_ctl(dec, OPUS_RESET_STATE);
             if (ret != OPUS_OK)
                break;
          }
       }
       break;
       case OPUS_MULTISTREAM_GET_DECODER_STATE_REQUEST:
       {
          int s;
          opus_int32 stream_id;
          OpusDecoder **value;
          stream_id = va_arg(ap, opus_int32);
          if (stream_id<0 || stream_id >= st->layout.nb_streams)
             ret = OPUS_BAD_ARG;
          value = va_arg(ap, OpusDecoder**);
          if (!value)
          {
             goto bad_arg;
          }
          for (s=0;s<stream_id;s++)
          {
             if (s < st->layout.nb_coupled_streams)
                ptr += align(coupled_size);
             else
                ptr += align(mono_size);
          }
          *value = (OpusDecoder*)ptr;
       }
       break;
       case OPUS_SET_GAIN_REQUEST:
       {
          int s;
          /* This works for int32 params */
          opus_int32 value = va_arg(ap, opus_int32);
          for (s=0;s<st->layout.nb_streams;s++)
          {
             OpusDecoder *dec;

             dec = (OpusDecoder*)ptr;
             if (s < st->layout.nb_coupled_streams)
                ptr += align(coupled_size);
             else
                ptr += align(mono_size);
             ret = opus_decoder_ctl(dec, request, value);
             if (ret != OPUS_OK)
                break;
          }
       }
       break;
       default:
          ret = OPUS_UNIMPLEMENTED;
       break;
   }

   va_end(ap);
   return ret;
bad_arg:
   va_end(ap);
   return OPUS_BAD_ARG;
}
Ejemplo n.º 28
0
/* Write string, similar to nputs, but with embedded formatting (#[]). */
void
screen_write_cnputs(struct screen_write_ctx *ctx,
    ssize_t maxlen, struct grid_cell *gc, int utf8flag, const char *fmt, ...)
{
	struct grid_cell	 lgc;
	struct utf8_data	 utf8data;
	va_list			 ap;
	char			*msg;
	u_char 			*ptr, *last;
	size_t			 left, size = 0;

	va_start(ap, fmt);
	xvasprintf(&msg, fmt, ap);
	va_end(ap);

	memcpy(&lgc, gc, sizeof lgc);

	ptr = msg;
	while (*ptr != '\0') {
		if (ptr[0] == '#' && ptr[1] == '[') {
			ptr += 2;
			last = ptr + strcspn(ptr, "]");
			if (*last == '\0') {
				/* No ]. Not much point in doing anything. */
				break;
			}
			*last = '\0';

			style_parse(gc, &lgc, ptr);
			ptr = last + 1;
			continue;
		}

		if (utf8flag && *ptr > 0x7f && utf8_open(&utf8data, *ptr)) {
			ptr++;

			left = strlen(ptr);
			if (left < utf8data.size - 1)
				break;
			while (utf8_append(&utf8data, *ptr))
				ptr++;
			ptr++;

			if (maxlen > 0 &&
			    size + utf8data.width > (size_t) maxlen) {
				while (size < (size_t) maxlen) {
					screen_write_putc(ctx, gc, ' ');
					size++;
				}
				break;
			}
			size += utf8data.width;

			grid_cell_set(&lgc, &utf8data);
			screen_write_cell(ctx, &lgc);
		} else {
			if (maxlen > 0 && size + 1 > (size_t) maxlen)
				break;

			size++;
			screen_write_putc(ctx, &lgc, *ptr);
			ptr++;
		}
	}

	free(msg);
}
Ejemplo n.º 29
0
void ble_send_message(uint8 msgid,...)            
{
    uint32 i;
    uint32 u32;
    uint16 u16;
    uint8  u8;
    struct ble_cmd_packet packet;
    uint8 *b=(uint8 *)&packet.payload;
            
    uint8 *hw;
    uint8 *data_ptr=0;
    uint16 data_len=0;
    va_list va;
    va_start(va,msgid);
    
    i=apis[msgid].params;
    packet.header=apis[msgid].hdr;
    while(i)
    {
    
        switch(i&0xF)
        {
        
            case 7:/*int32*/
            case 6:/*uint32*/
                u32=va_arg(va,uint32);
                *b++=u32&0xff;u32>>=8;
                *b++=u32&0xff;u32>>=8;
                *b++=u32&0xff;u32>>=8;
                *b++=u32&0xff;
                break;
            case 5:/*int16*/
            case 4:/*uint16*/
                u16=va_arg(va,unsigned);
                *b++=u16&0xff;u16>>=8;
                *b++=u16&0xff;
                break;
            case 3:/*int8*/
            case 2:/*uint8*/
                u8=va_arg(va,int);
                *b++=u8&0xff;
            break;     
            
            case 9:/*string*/
            case 8:/*uint8 array*/
                data_len=va_arg(va,int);
                *b++=data_len;        
                
                u16=data_len+packet.header.lolen;
                packet.header.lolen=u16&0xff;
                packet.header.type_hilen|=u16>>8;
                 
                data_ptr=va_arg(va,uint8*);
            break;
            case 10:/*hwaddr*/
                hw=va_arg(va,uint8*);
                *b++=*hw++;
                *b++=*hw++;
                *b++=*hw++;
                *b++=*hw++;
                *b++=*hw++;
                *b++=*hw++;
            break;
            case 11:/*uint16 array*/
                data_len=va_arg(va,int);
                *b++=data_len&0xff;        
                *b++=data_len>>8;        
                
                u16=data_len+packet.header.lolen;
                packet.header.lolen=u16&0xff;
                packet.header.type_hilen|=u16>>8;
                 
                data_ptr=va_arg(va,uint8*);
            break;
        }
        i=i>>4;
    }
    va_end(va);
        if(bglib_output)bglib_output(sizeof(struct ble_header)+apis[msgid].hdr.lolen,(uint8*)&packet,data_len,(uint8*)data_ptr);
}
Ejemplo n.º 30
0
int parse_env_file(
                const char *fname,
                const char *separator, ...) {

        int r = 0;
        char *contents = NULL, *p;

        assert(fname);
        assert(separator);

        if ((r = read_full_file(fname, &contents, NULL)) < 0)
                return r;

        p = contents;
        for (;;) {
                const char *key = NULL;

                p += strspn(p, separator);
                p += strspn(p, WHITESPACE);

                if (!*p)
                        break;

                if (!strchr(COMMENTS, *p)) {
                        va_list ap;
                        char **value;

                        va_start(ap, separator);
                        while ((key = va_arg(ap, char *))) {
                                size_t n;
                                char *v;

                                value = va_arg(ap, char **);

                                n = strlen(key);
                                if (!strneq(p, key, n) ||
                                    p[n] != '=')
                                        continue;

                                p += n + 1;
                                n = strcspn(p, separator);

                                if (n >= 2 &&
                                    strchr(QUOTES, p[0]) &&
                                    p[n-1] == p[0])
                                        v = strndup(p+1, n-2);
                                else
                                        v = strndup(p, n);

                                if (!v) {
                                        r = -ENOMEM;
                                        va_end(ap);
                                        goto fail;
                                }

                                if (v[0] == '\0') {
                                        /* return empty value strings as NULL */
                                        free(v);
                                        v = NULL;
                                }

                                free(*value);
                                *value = v;

                                p += n;

                                r ++;
                                break;
                        }
                        va_end(ap);
                }

                if (!key)
                        p += strcspn(p, separator);
        }