Пример #1
0
int
jvmti_write_debug_info(void *agent, uint64_t code, const char *file,
		       jvmti_line_info_t *li, int nr_lines)
{
	struct jr_code_debug_info rec;
	size_t sret, len, size, flen;
	uint64_t addr;
	const char *fn = file;
	FILE *fp = agent;
	int i;

	/*
	 * no entry to write
	 */
	if (!nr_lines)
		return 0;

	if (!fp) {
		warnx("jvmti: invalid fd in write_debug_info");
		return -1;
	}

	flen = strlen(file) + 1;

	rec.p.id        = JIT_CODE_DEBUG_INFO;
	size            = sizeof(rec);
	rec.p.timestamp = perf_get_timestamp();
	rec.code_addr   = (uint64_t)(uintptr_t)code;
	rec.nr_entry    = nr_lines;

	/*
	 * on disk source line info layout:
	 * uint64_t : addr
	 * int      : line number
	 * int      : column discriminator
	 * file[]   : source file name
	 */
	size += nr_lines * sizeof(struct debug_entry);
	size += flen * nr_lines;
	rec.p.total_size = size;

	/*
	 * If JVM is multi-threaded, nultiple concurrent calls to agent
	 * may be possible, so protect file writes
	 */
	flockfile(fp);

	sret = fwrite_unlocked(&rec, sizeof(rec), 1, fp);
	if (sret != 1)
		goto error;

	for (i = 0; i < nr_lines; i++) {

		addr = (uint64_t)li[i].pc;
		len  = sizeof(addr);
		sret = fwrite_unlocked(&addr, len, 1, fp);
		if (sret != 1)
			goto error;

		len  = sizeof(li[0].line_number);
		sret = fwrite_unlocked(&li[i].line_number, len, 1, fp);
		if (sret != 1)
			goto error;

		len  = sizeof(li[0].discrim);
		sret = fwrite_unlocked(&li[i].discrim, len, 1, fp);
		if (sret != 1)
			goto error;

		sret = fwrite_unlocked(fn, flen, 1, fp);
		if (sret != 1)
			goto error;
	}
	funlockfile(fp);
	return 0;
error:
	funlockfile(fp);
	return -1;
}
Пример #2
0
static void my_funlockfile(FILE *fp)
{
    return funlockfile(_get_actual_fp(fp));
}
Пример #3
0
ssize_t getseq(char **lineptr, size_t *n, FILE *fp) {
	int result = 0;
	ssize_t cur_len = 0;

	if (lineptr == NULL || n == NULL || fp == NULL)
	{
		errno = EINVAL;
		return -1;
	}

	flockfile (fp);

	if (*lineptr == NULL || *n == 0)
	{
		*n = 120;
		*lineptr = (char *) malloc (*n);
		if (*lineptr == NULL)
		{
			result = -1;
			goto unlock_return;
		}
	}

		int newline = 0;
	for (;;) {
		int i;

		i = getc (fp);
		if (i == EOF)
		{
			result = -1;
			break;
		}

		/* Make enough space for len+1 (for final NUL) bytes.  */
		if (cur_len + 2 >= *n)
		{
			size_t needed = 2 * (cur_len + 1) + 2;   /* Be generous. */
			char *new_lineptr;

			if (needed < cur_len)
			{
				result = -1;
				goto unlock_return;
			}

			new_lineptr = (char *) realloc (*lineptr, needed);
			if (new_lineptr == NULL){
				result = -1;
				goto unlock_return;
			}

			*lineptr = new_lineptr;
			*n = needed;
		}

		(*lineptr)[cur_len] = i;
		cur_len++;

		if (i == '\n') {
			newline = 1;
		}

		if(i == '>' && newline == 1) {
			break;
		}
	}
	(*lineptr)[cur_len] = '\0';
	result = cur_len ? cur_len : result;

	unlock_return:
		funlockfile (fp);
		return result;
}
Пример #4
0
void
cherokee_trace_do_trace (const char *entry, const char *file, int line, const char *func, const char *fmt, ...)
{
	ret_t                  ret;
	char                  *p;
	char                  *lentry;
	char                  *lentry_end;
	va_list                args;
	cherokee_connection_t *conn;
	cherokee_buffer_t     *trace_modules = &trace.modules;
	cherokee_boolean_t     do_log        = false;
	cherokee_buffer_t      entries       = CHEROKEE_BUF_INIT;

	/* Prevents loops
	 */
	if (disabled) {
		return;
	}

	disabled = true;

	/* Return ASAP if nothing is being traced
	 */
	if (cherokee_buffer_is_empty (&trace.modules)) {
		goto out;
	}

	/* Check the connection source, if possible
	 */
	if (trace.from_filter != NULL) {
		conn = CONN (CHEROKEE_THREAD_PROP_GET (thread_connection_ptr));

		/* No conn, no trace entry
		 */
		if (conn == NULL) {
			goto out;
		}

		if (conn->socket.socket < 0) {
			goto out;
		}

		/* Skip the trace if the conn doesn't match
		 */
		ret = cherokee_access_ip_match (trace.from_filter, &conn->socket);
		if (ret != ret_ok) {
			goto out;
		}
	}

	/* Also, check for 'all'
	 */
	p = strstr (trace_modules->buf, "all");
	if (p == NULL) {
		/* Parse the In-code module string
		 */
		cherokee_buffer_add (&entries, entry, strlen(entry));

		for (lentry = entries.buf;;) {
			lentry_end = strchr (lentry, ',');
			if (lentry_end) *lentry_end = '\0';

			/* Check the type
			 */
			p = strstr (trace_modules->buf, lentry);
			if (p) {
				char *tmp = p + strlen(lentry);
				if ((*tmp == '\0') || (*tmp == ',') || (*tmp == ' '))
					do_log = true;
			}

			if ((lentry_end == NULL) || (do_log))
				break;

			lentry = lentry_end + 1;
		}

		/* Return if trace entry didn't match with the configured list
		 */
		if (! do_log) {
			goto out;
		}
	}

	/* Format the message and log it:
	 * 'entries' is not needed at this stage, reuse it
	 */
	cherokee_buffer_clean (&entries);
	if (trace.print_thread) {
		int        len;
		char       tmp[32+1];
		static int longest_len = 0;

		len = snprintf (tmp, 32+1, "%llX", (unsigned long long) CHEROKEE_THREAD_SELF);
		longest_len = MAX (longest_len, len);

		cherokee_buffer_add_str    (&entries, "{0x");
		cherokee_buffer_add_char_n (&entries, '0', longest_len - len);
		cherokee_buffer_add        (&entries, tmp, len);
		cherokee_buffer_add_str    (&entries, "} ");
	}

	if (trace.print_time) {
		cherokee_buffer_add_char (&entries, '[');
		cherokee_buf_add_bogonow (&entries, true);
		cherokee_buffer_add_str  (&entries, "] ");
	}

	cherokee_buffer_add_va (&entries, "%18s:%04d (%30s): ", file, line, func);

	va_start (args, fmt);
	cherokee_buffer_add_va_list (&entries, (char *)fmt, args);
	va_end (args);

	if (trace.use_syslog) {
		cherokee_syslog (LOG_DEBUG, &entries);
	} else {
#ifdef HAVE_FLOCKFILE
		flockfile (stdout);
#endif
		fprintf (stdout, "%s", entries.buf);
#ifdef HAVE_FUNLOCKFILE
		funlockfile (stdout);
#endif
	}

out:
	cherokee_buffer_mrproper (&entries);
	disabled = false;
}
Пример #5
0
TEST(stdio, flockfile_18208568_stderr) {
  // Check that we have a _recursive_ mutex for flockfile.
  flockfile(stderr);
  feof(stderr); // We don't care about the result, but this needs to take the lock.
  funlockfile(stderr);
}
Пример #6
0
ssize_t
getdelim (char **lineptr, size_t *n, int delimiter, FILE *fp)
{
  ssize_t result;
  size_t cur_len = 0;

  if (lineptr == NULL || n == NULL || fp == NULL)
    {
      errno = EINVAL;
      return -1;
    }

  flockfile (fp);

  if (*lineptr == NULL || *n == 0)
    {
      *n = 120;
      *lineptr = (char *) malloc (*n);
      if (*lineptr == NULL)
	{
	  result = -1;
	  goto unlock_return;
	}
    }

  for (;;)
    {
      int i;

      i = getc (fp);
      if (i == EOF)
	{
	  result = -1;
	  break;
	}

      /* Make enough space for len+1 (for final NUL) bytes.  */
      if (cur_len + 1 >= *n)
	{
	  size_t needed_max =
	    SSIZE_MAX < SIZE_MAX ? (size_t) SSIZE_MAX + 1 : SIZE_MAX;
	  size_t needed = 2 * *n + 1;   /* Be generous. */
	  char *new_lineptr;

	  if (needed_max < needed)
	    needed = needed_max;
	  if (cur_len + 1 >= needed)
	    {
	      result = -1;
	      goto unlock_return;
	    }

	  new_lineptr = (char *) realloc (*lineptr, needed);
	  if (new_lineptr == NULL)
	    {
	      result = -1;
	      goto unlock_return;
	    }

	  *lineptr = new_lineptr;
	  *n = needed;
	}

      (*lineptr)[cur_len] = i;
      cur_len++;

      if (i == delimiter)
	break;
    }
  (*lineptr)[cur_len] = '\0';
  result = cur_len ? cur_len : result;

 unlock_return:
  funlockfile (fp);
  return result;
}
Пример #7
0
int ferror(FILE* file) {
    flockfile(file);
    int result = ferror_unlocked(file);
    funlockfile(file);
    return result;
}
Пример #8
0
void VMPI_funlockfile(FILE *stream)
{
    funlockfile(stream);
}
Пример #9
0
static void LockingByCallerHelper(std::atomic<pid_t>* pid) {
  *pid = gettid();
  flockfile(stdout);
  funlockfile(stdout);
}
Пример #10
0
/* IMPLMENTATION */
int main(int argc, char**argv)
{
    char    cmdConcat[PSMCLI_CMD_LEN_MAX]    = {0};
    char    *pCfg                            = CCSP_MSG_BUS_CFG;
    void    *bus_handle                      = NULL;
    int     tmpLen                           = 0;
    int     cmdTableLen                      = sizeof(cmdsTable) / sizeof(cmdsTable_s);
    int     ret                              = 0;
    char    component_id[256]                = {0} ;
    int     local_argc                       = argc;
    char    **local_argv                     = argv;
    int     i                                = 0;

    enable_ccsp_exception_handlers();

    sprintf(prog_name, "PsmCli.pid%d", getpid());

    // check debug print levell
    psmcli_debug_print = psmcli_get_debug_level(psmcli_debug_file_name);

    // save command line
    for(i=0; i<(argc-1) && (strlen(argv[i])+strlen(cmdLine)+2)<=PSMCLI_STRLEN_MAX; i++) {
        strcat(cmdLine, argv[i]);
        strcat(cmdLine, " ");
    }
    if(i == argc-1 && (strlen(argv[i])+strlen(cmdLine)+1)<=PSMCLI_STRLEN_MAX)
        strcat(cmdLine, argv[i]);

#ifdef PSMCLI_TESTING_LOCAL
    // Echo input
    CcspTraceDebug(("<%s>: invocation = '%s'", prog_name, cmdLine));
#endif

    // Check if the number of args is >= 2
    if(argc < 3) {

        help_usage();

        if((argc == 2) && (!strcmp(argv[1], "help"))) {
            exit(0);
        } else {
            exit(CCSP_ERR_INVALID_ARGUMENTS);
        }
    }
    
    // try to set the subsystem prefix
    if (strcmp(argv[1], "nosubsys") == 0)  {
        if(argc < 4) { // must be followed by a cmd
 	    help_usage();
	    exit(CCSP_ERR_INVALID_ARGUMENTS);
        }
        subsys_prefix[0] = '\0';  
        local_argc = argc - 1;
        local_argv = argv + 1;
    }
    else if (strcmp(argv[1], "subsys") == 0) {
        if(argc < 5) { // must be followed by a string and then a cmd
 	    help_usage();
	    exit(CCSP_ERR_INVALID_ARGUMENTS);
        }
        else {
            strncpy(subsys_prefix, argv[2], 256); // truncate if >256
            subsys_prefix[255] = '\0';  // in case it is not terminated
            local_argc = argc - 2;
            local_argv = argv + 2;
        }
    }
    else { // no subsys nor nosubsys specified, use default prefix
        strcpy(subsys_prefix, PSMCLI_SUBSYSTEM_PREFIX_DEFAULT);
        local_argc = argc;
        local_argv = argv;
    }

    // try to get an unique name for the connection
    sprintf(component_id, "%s.pid%d", psmcli_component_id, getpid()); 

    // Assuming the component_id generated with pid is unique, 
    // So skip the checking to increase speed. RTian 6/19/2013
    /*
    {

    // #define PSMCLI_SUBSYSTEM_PREFIX_GEN_RAND_MAX        997     // a prime close to 1000
    // #define PSMCLI_SUBSYSTEM_PREFIX_GEN_NTRY_MAX        20
    // #include <time.h>

        int nTry = 0, ret = 0;

        srand(time(NULL)*getpid());  // seed the random number generator

        do {
            // each section in component id separated by . cannot start with a number!!! 
            sprintf
                (
                    component_id, 
                    "%s.pid%d.sub%d", 
                    psmcli_component_id, 
                    getpid(), 
                    rand()%PSMCLI_SUBSYSTEM_PREFIX_GEN_RAND_MAX
                ); 
        
            // check if the id is in use already
            ret = psmcli_bus_name_in_use(component_id, pCfg); 
            if(ret < 0 || ret == 1) { nTry++; }
            else break;  // if(ret == 0)

        } while (nTry < PSMCLI_SUBSYSTEM_PREFIX_GEN_NTRY_MAX);

        if (nTry == PSMCLI_SUBSYSTEM_PREFIX_GEN_NTRY_MAX)  
            CcspTraceWarning(("<%s> Error: cannot generate unique id.  Id to be used is %s\n", prog_name, component_id));
    }
    */

    //    CcspTraceDebug(("<%s>: unique component_id = %s\n", prog_name, component_id));

    // Connect to  Dbus and get bus_handle
    // we begin the initiation of dbus    
#ifdef DBUS_INIT_SYNC_MODE
    ret = CCSP_Message_Bus_Init_Synced(component_id, 
                                       pCfg, 
                                       &bus_handle, 
                                       (CCSP_MESSAGE_BUS_MALLOC)Ansc_AllocateMemory_Callback, 
                                       Ansc_FreeMemory_Callback);
#else
    ret = CCSP_Message_Bus_Init(component_id, 
                                pCfg, 
                                &bus_handle, 
                                (CCSP_MESSAGE_BUS_MALLOC)Ansc_AllocateMemory_Callback, 
                                Ansc_FreeMemory_Callback);
#endif
    
    if ( ret == -1 )
    {
        // Dbus connection error
        // Comment below
        CcspTraceWarning(("<%s> Error: DBUS connection error, returned %d,  exitting w/ %d = CCSP_MESSAGE_BUS_CANNOT_CONNECT\n", 
                        prog_name, ret, CCSP_MESSAGE_BUS_CANNOT_CONNECT));
        exit(CCSP_MESSAGE_BUS_CANNOT_CONNECT);
    }

    //    CcspTraceDebug(("<%s>: Message_Bus_Init ok.\n", prog_name));

    // Check if commands are "get -e" or "getdetail -e"
    if((strlen(local_argv[2]) == strlen("-e")) && 
       (!strncmp(local_argv[2], "-e", strlen("-e")))) {
    	// "get -e" or "getdetail -e" command
    	tmpLen = strlen(local_argv[1]);
        
    	// Concatenate command and option
    	if(tmpLen <= (PSMCLI_CMD_LEN_MAX - strlen(" -e"))) {
            strcpy(cmdConcat, local_argv[1]);
            strcat(cmdConcat, " -e"); 
            cmdConcat[PSMCLI_CMD_LEN_MAX-1] = '\0';
            
            i = 0;
            // Search command jumop tables
            while(i < cmdTableLen) {
                if(!strncmp(cmdsTable[i].cmd, cmdConcat, PSMCLI_CMD_LEN_MAX)) {
                    flockfile(stdout);
                    ret = cmdsTable[i].process_cmd(local_argc, (char const * const *)local_argv, bus_handle);
                    funlockfile(stdout);
                    break;
                }
                i++;
            }
            
            if(i == cmdTableLen) {
                CcspTraceWarning(("<%s>: unknown cmd %s, exiting with %d = CCSP_INVALID_PSMCLI_CMD\n", 
                                prog_name, cmdConcat, CCSP_INVALID_PSMCLI_CMD));
                ret = CCSP_INVALID_PSMCLI_CMD;
                goto  EXIT;
            }
            
    	} else {
            CcspTraceWarning(("<%s> Error: Invalid command usage, exiting w/ %d = CCSP_ERR_INVALID_ARGUMENTS\n", 
                            prog_name, CCSP_ERR_INVALID_ARGUMENTS));
            ret = CCSP_ERR_INVALID_ARGUMENTS;
            goto  EXIT;
    	}
        // Check for other commands - get, getdetail, set, setdetail, del
    } else {
    	
    	// Search commands jump table
    	i = 0;
    	while(i < cmdTableLen) {
            if(!strncmp(cmdsTable[i].cmd, local_argv[1], PSMCLI_CMD_LEN_MAX)) {
                flockfile(stdout);
                ret = cmdsTable[i].process_cmd(local_argc, (char const * const *)local_argv, bus_handle);
                funlockfile(stdout);
                break;
            }
            i++;
    	}
        
    	if(i == cmdTableLen) {
            CcspTraceWarning(("<%s>: unknown cmd %s, exiting with %d = CCSP_INVALID_PSMCLI_CMD\n", 
                            prog_name, local_argv[1], CCSP_INVALID_PSMCLI_CMD));
            ret = CCSP_INVALID_PSMCLI_CMD;
            goto  EXIT;
    	}
    }

EXIT:
    CCSP_Message_Bus_Exit(bus_handle);

#ifdef PSMCLI_TESTING_LOCAL
    // Echo return value
    CcspTraceDebug(("<%s>: final return value = %d\n", prog_name, ret));
#endif

    exit(ret);
    // return ret;
}
Пример #11
0
/* Allocate and load a matrix from the given file (or stdin if NULL) */
CMATRIX *
cm_load(const char *fname, int nrows, int ncols, int dtype)
{
	FILE	*fp = stdin;
	CMATRIX	*cm;

	if (fname == NULL)
		fname = "<stdin>";
	else if ((fp = fopen(fname, "r")) == NULL) {
		sprintf(errmsg, "cannot open file '%s'", fname);
		error(SYSTEM, errmsg);
	}
#ifdef getc_unlocked
	flockfile(fp);
#endif
	if (dtype != DTascii)
		SET_FILE_BINARY(fp);		/* doesn't really work */
	if (!dtype | !ncols) {			/* expecting header? */
		char	*err = cm_getheader(&dtype, &nrows, &ncols, fp);
		if (err != NULL)
			error(USER, err);
		if (ncols <= 0)
			error(USER, "unspecified number of columns");
	}
	switch (dtype) {
	case DTascii:
	case DTfloat:
	case DTdouble:
		break;
	default:
		error(USER, "unexpected data type in cm_load()");
	}
	if (nrows <= 0) {			/* don't know length? */
		int	guessrows = 147;	/* usually big enough */
		if ((dtype != DTascii) & (fp != stdin)) {
			long	startpos = ftell(fp);
			if (fseek(fp, 0L, SEEK_END) == 0) {
				long	endpos = ftell(fp);
				long	elemsiz = 3*(dtype==DTfloat ?
					    sizeof(float) : sizeof(double));

				if ((endpos - startpos) % (ncols*elemsiz)) {
					sprintf(errmsg,
					"improper length for binary file '%s'",
							fname);
					error(USER, errmsg);
				}
				guessrows = (endpos - startpos)/(ncols*elemsiz);
				if (fseek(fp, startpos, SEEK_SET) < 0) {
					sprintf(errmsg,
						"fseek() error on file '%s'",
							fname);
					error(SYSTEM, errmsg);
				}
				nrows = guessrows;	/* we're confident */
			}
		}
		cm = cm_alloc(guessrows, ncols);
	} else
		cm = cm_alloc(nrows, ncols);
	if (cm == NULL)					/* XXX never happens */
		return(NULL);
	if (dtype == DTascii) {				/* read text file */
		int	maxrow = (nrows > 0 ? nrows : 32000);
		int	r, c;
		for (r = 0; r < maxrow; r++) {
		    if (r >= cm->nrows)			/* need more space? */
			cm = cm_resize(cm, 2*cm->nrows);
		    for (c = 0; c < ncols; c++) {
		        COLORV	*cv = cm_lval(cm,r,c);
			if (fscanf(fp, COLSPEC, cv, cv+1, cv+2) != 3)
				if ((nrows <= 0) & (r > 0) & !c) {
					cm = cm_resize(cm, maxrow=r);
					break;
				} else
					goto EOFerror;
		    }
		}
		while ((c = getc(fp)) != EOF)
			if (!isspace(c)) {
				sprintf(errmsg,
				"unexpected data at end of ascii file %s",
						fname);
				error(WARNING, errmsg);
				break;
			}
	} else {					/* read binary file */
		if (sizeof(COLOR) == cm_elem_size[dtype]) {
			int	nread = 0;
			do {				/* read all we can */
				nread += fread(cm->cmem + 3*nread,
						sizeof(COLOR),
						cm->nrows*cm->ncols - nread,
						fp);
				if (nrows <= 0) {	/* unknown length */
					if (nread == cm->nrows*cm->ncols)
							/* need more space? */
						cm = cm_resize(cm, 2*cm->nrows);
					else if (nread && !(nread % cm->ncols))
							/* seem to be  done */
						cm = cm_resize(cm, nread/cm->ncols);
					else		/* ended mid-row */
						goto EOFerror;
				} else if (nread < cm->nrows*cm->ncols)
					goto EOFerror;
			} while (nread < cm->nrows*cm->ncols);

		} else if (dtype == DTdouble) {
			double	dc[3];			/* load from double */
			COLORV	*cvp = cm->cmem;
			int	n = nrows*ncols;

			if (n <= 0)
				goto not_handled;
			while (n--) {
				if (fread(dc, sizeof(double), 3, fp) != 3)
					goto EOFerror;
				copycolor(cvp, dc);
				cvp += 3;
			}
		} else /* dtype == DTfloat */ {
			float	fc[3];			/* load from float */
			COLORV	*cvp = cm->cmem;
			int	n = nrows*ncols;

			if (n <= 0)
				goto not_handled;
			while (n--) {
				if (fread(fc, sizeof(float), 3, fp) != 3)
					goto EOFerror;
				copycolor(cvp, fc);
				cvp += 3;
			}
		}
		if (fgetc(fp) != EOF) {
				sprintf(errmsg,
				"unexpected data at end of binary file %s",
						fname);
				error(WARNING, errmsg);
		}
	}
	if (fp != stdin)
		fclose(fp);
#ifdef getc_unlocked
	else
		funlockfile(fp);
#endif
	return(cm);
EOFerror:
	sprintf(errmsg, "unexpected EOF reading %s", fname);
	error(USER, errmsg);
not_handled:
	error(INTERNAL, "unhandled data size or length in cm_load()");
	return(NULL);	/* gratis return */
}
Пример #12
0
static const char* remap_file(const char* syscall_name, const char* pathname,
                              char* buffer, usage_t usage) {
  char* pos;
  int debug = EKAM_DEBUG;

  /* Ad-hoc debugging can be accomplished by setting debug = 1 when a particular file pattern
   * is matched. */

  if (debug) {
    fprintf(stderr, "remap for %s (%s): %s\n",
            syscall_name, (usage == READ ? "read" : "write"), pathname);
  }

  init_streams();

  if (strlen(pathname) >= PATH_MAX) {
    /* Too long. */
    if (debug) fprintf(stderr, "  name too long\n");
    errno = ENAMETOOLONG;
    return NULL;
  }

  if (get_cached_result(pathname, buffer, usage)) {
    if (debug) fprintf(stderr, "  cached: %s\n", buffer);
    return buffer;
  }

  flockfile(ekam_call_stream);

  if (strncmp(pathname, TAG_PROVIDER_PREFIX, strlen(TAG_PROVIDER_PREFIX)) == 0) {
    /* A tag reference.  Construct the tag name in |buffer|. */
    strcpy(buffer, pathname + strlen(TAG_PROVIDER_PREFIX));

    if (usage == READ) {
      /* Change first slash to a colon to form a tag.  E.g. "header/foo.h" becomes
       * "header:foo.h". */
      pos = strchr(buffer, '/');
      if (pos == NULL) {
        /* This appears to be a tag type without a name, so it should look like a directory.
         * We can use the current directory.  TODO:  Return some fake empty directory instead. */
        funlockfile(ekam_call_stream);
        strcpy(buffer, ".");
        if (debug) fprintf(stderr, "  is directory\n");
        return buffer;
      }
      *pos = ':';
      canonicalizePath(pos + 1);

      if (strcmp(buffer, "canonical:.") == 0) {
        /* HACK:  Don't try to remap top directory. */
        funlockfile(ekam_call_stream);
        if (debug) fprintf(stderr, "  current directory\n");
        return "src";
      }
    }

    /* Ask ekam to remap the file name. */
    fputs(usage == READ ? "findProvider " : "newProvider ", ekam_call_stream);
    fputs(buffer, ekam_call_stream);
    fputs("\n", ekam_call_stream);
  } else if (strcmp(pathname, TMP) == 0 ||
             strcmp(pathname, VAR_TMP) == 0 ||
             strncmp(pathname, TMP_PREFIX, strlen(TMP_PREFIX)) == 0 ||
             strncmp(pathname, VAR_TMP_PREFIX, strlen(VAR_TMP_PREFIX)) == 0) {
    /* Temp file.  Ignore. */
    funlockfile(ekam_call_stream);
    if (debug) fprintf(stderr, "  temp file: %s\n", pathname);
    return pathname;
  } else {
    if (strncmp(pathname, current_dir, strlen(current_dir)) == 0) {
      /* The app is trying to open files in the current directory by absolute path.  Treat it
       * exactly as if it had used a relative path. */
      pathname = pathname + strlen(current_dir);
    } else if (pathname[0] == '/') {
      /* Absolute path.  Note the access but don't remap. */
      if (usage == WRITE) {
        /* Cannot write to absolute paths. */
        funlockfile(ekam_call_stream);
        errno = EACCES;
        if (debug) fprintf(stderr, "  absolute path, can't write\n");
        return NULL;
      }

      fputs("noteInput ", ekam_call_stream);
      fputs(pathname, ekam_call_stream);
      fputs("\n", ekam_call_stream);
      fflush(ekam_call_stream);
      if (ferror_unlocked(ekam_call_stream)) {
        funlockfile(ekam_call_stream);
        fprintf(stderr, "error: Ekam call stream broken.\n");
        abort();
      }
      cache_result(pathname, pathname, usage);
      funlockfile(ekam_call_stream);
      if (debug) fprintf(stderr, "  absolute path: %s\n", pathname);
      return pathname;
    }

    /* Path in current directory. */
    strcpy(buffer, pathname);
    canonicalizePath(buffer);
    if (strcmp(buffer, ".") == 0) {
      /* HACK:  Don't try to remap current directory. */
      funlockfile(ekam_call_stream);
      if (debug) fprintf(stderr, "  current directory\n");
      return "src";
    } else {
      /* Ask ekam to remap the file name. */
      fputs(usage == READ ? "findInput " : "newOutput ", ekam_call_stream);
      fputs(buffer, ekam_call_stream);
      fputs("\n", ekam_call_stream);
    }
  }

  fflush(ekam_call_stream);
  if (ferror_unlocked(ekam_call_stream)) {
    funlockfile(ekam_call_stream);
    fprintf(stderr, "error: Ekam call stream broken.\n");
    abort();
  }

  /* Carefully lock the return stream then unlock the call stream, so that we know that
   * responses will be received in the correct order. */
  flockfile(ekam_return_stream);
  funlockfile(ekam_call_stream);

  /* Read response from Ekam. */
  if (fgets(buffer, PATH_MAX, ekam_return_stream) == NULL) {
    funlockfile(ekam_return_stream);
    fprintf(stderr, "error: Ekam return stream broken.\n");
    abort();
  }

  /* Done reading. */
  funlockfile(ekam_return_stream);

  /* Remove the trailing newline. */
  pos = strchr(buffer, '\n');
  if (pos == NULL) {
    fprintf(stderr, "error: Path returned from Ekam was too long.\n");
    abort();
  }
  *pos = '\0';

  if (*buffer == '\0') {
    /* Not found. */
    errno = ENOENT;
    if (debug) fprintf(stderr, "  ekam says no such file\n");
    return NULL;
  }

  cache_result(pathname, buffer, usage);

  if (debug) fprintf(stderr, "  remapped to: %s\n", buffer);
  return buffer;
}
Пример #13
0
/* The main test function. */
int main(int argc, char * argv[])
{
	int ret, status;
	pid_t child, ctl;
	pthread_t ch;

	/* Initialize output */
	output_init();

	/* lock the stdout file */
	flockfile(stdout);

	/* Create the child */
	child = fork();

	if (child == -1)
	{
		UNRESOLVED(errno, "Failed to fork");
	}

	/* child */
	if (child == 0)
	{

		ret = pthread_create(&ch, NULL, threaded, NULL);

		if (ret != 0)
		{
			UNRESOLVED(ret, "Failed to create a thread");
		}

		ret = pthread_join(ch, NULL);

		if (ret != 0)
		{
			UNRESOLVED(ret, "Failed to join the thread");
		}

		/* We're done */
		exit(PTS_PASS);
	}

	/* Parent sleeps for a while to create contension in case the file lock is inherited */
	sleep(1);

	funlockfile(stdout);

	/* Parent joins the child */
	ctl = waitpid(child, &status, 0);

	if (ctl != child)
	{
		UNRESOLVED(errno, "Waitpid returned the wrong PID");
	}

	if (!WIFEXITED(status) || (WEXITSTATUS(status) != PTS_PASS))
	{
		FAILED("Child exited abnormally");
	}

	/* Test passed */
#if VERBOSE > 0

	output("Test passed\n");

#endif

	PASSED;
}
Пример #14
0
/* Read one mount table entry from STREAM.  Returns a pointer to storage
   reused on the next call, or null for EOF or error (use feof/ferror to
   check).  */
struct mntent *
__getmntent_r (FILE *stream, struct mntent *mp, char *buffer, int bufsiz)
{
  char *cp;
  char *head;

  flockfile (stream);
  do
    {
      char *end_ptr;

      if (__fgets_unlocked (buffer, bufsiz, stream) == NULL)
	{
	  funlockfile (stream);
	  return NULL;
	}

      end_ptr = strchr (buffer, '\n');
      if (end_ptr != NULL)	/* chop newline */
	{
	  /* Do not walk past the start of buffer if it's all whitespace.  */
	  while (end_ptr != buffer
		 && (end_ptr[-1] == ' ' || end_ptr[-1] == '\t'))
            end_ptr--;
	  *end_ptr = '\0';
	}
      else
	{
	  /* Not the whole line was read.  Do it now but forget it.  */
	  char tmp[1024];
	  while (__fgets_unlocked (tmp, sizeof tmp, stream) != NULL)
	    if (strchr (tmp, '\n') != NULL)
	      break;
	}

      head = buffer + strspn (buffer, " \t");
      /* skip empty lines and comment lines:  */
    }
  while (head[0] == '\0' || head[0] == '#');

  cp = __strsep (&head, " \t");
  mp->mnt_fsname = cp != NULL ? decode_name (cp) : (char *) "";
  if (head)
    head += strspn (head, " \t");
  cp = __strsep (&head, " \t");
  mp->mnt_dir = cp != NULL ? decode_name (cp) : (char *) "";
  if (head)
    head += strspn (head, " \t");
  cp = __strsep (&head, " \t");
  mp->mnt_type = cp != NULL ? decode_name (cp) : (char *) "";
  if (head)
    head += strspn (head, " \t");
  cp = __strsep (&head, " \t");
  mp->mnt_opts = cp != NULL ? decode_name (cp) : (char *) "";
  switch (head ? sscanf (head, " %d %d ", &mp->mnt_freq, &mp->mnt_passno) : 0)
    {
    case 0:
      mp->mnt_freq = 0;
    case 1:
      mp->mnt_passno = 0;
    case 2:
      break;
    }
  funlockfile (stream);

  return mp;
}
Пример #15
0
/* fparseln():
 *	Read a line from a file parsing continuations ending in \
 *	and eliminating trailing newlines, or comments starting with
 *	the comment char.
 */
char *
fparseln(FILE *fp, size_t *size, size_t *lineno, const char str[3], int flags)
{
	static const char dstr[3] = { '\\', '\\', '#' };

	ssize_t	s;
	size_t len, ptrlen;
	char   *buf;
	char   *ptr, *cp;
	int	cnt;
	char	esc, con, nl, com;

	_DIAGASSERT(fp != NULL);

	len = 0;
	buf = NULL;
	ptrlen = 0;
	ptr = NULL;
	cnt = 1;

	if (str == NULL)
		str = dstr;

	esc = str[0];
	con = str[1];
	com = str[2];
	/*
	 * XXX: it would be cool to be able to specify the newline character,
	 * getdelim(3) does let us, but supporting it would diverge from BSDs.
	 */
	nl  = '\n';

	flockfile(fp);

	while (cnt) {
		cnt = 0;

		if (lineno)
			(*lineno)++;

		s = getline(&ptr, &ptrlen, fp);
		if (s < 0)
			break;

		if (s && com) {		/* Check and eliminate comments */
			for (cp = ptr; cp < ptr + s; cp++)
				if (*cp == com && !isescaped(ptr, cp, esc)) {
					s = cp - ptr;
					cnt = s == 0 && buf == NULL;
					break;
				}
		}

		if (s && nl) { 		/* Check and eliminate newlines */
			cp = &ptr[s - 1];

			if (*cp == nl)
				s--;	/* forget newline */
		}

		if (s && con) {		/* Check and eliminate continuations */
			cp = &ptr[s - 1];

			if (*cp == con && !isescaped(ptr, cp, esc)) {
				s--;	/* forget continuation char */
				cnt = 1;
			}
		}

		if (s == 0) {
			/*
			 * nothing to add, skip realloc except in case
			 * we need a minimal buf to return an empty line
			 */
			if (cnt || buf != NULL)
				continue;
		}

		if ((cp = realloc(buf, len + s + 1)) == NULL) {
			funlockfile(fp);
			free(buf);
			free(ptr);
			return NULL;
		}
		buf = cp;

		(void) memcpy(buf + len, ptr, s);
		len += s;
		buf[len] = '\0';
	}

	funlockfile(fp);
	free(ptr);

	if ((flags & FPARSELN_UNESCALL) != 0 && esc && buf != NULL &&
	    strchr(buf, esc) != NULL) {
		ptr = cp = buf;
		while (cp[0] != '\0') {
			int skipesc;

			while (cp[0] != '\0' && cp[0] != esc)
				*ptr++ = *cp++;
			if (cp[0] == '\0' || cp[1] == '\0')
				break;

			skipesc = 0;
			if (cp[1] == com)
				skipesc += (flags & FPARSELN_UNESCCOMM);
			if (cp[1] == con)
				skipesc += (flags & FPARSELN_UNESCCONT);
			if (cp[1] == esc)
				skipesc += (flags & FPARSELN_UNESCESC);
			if (cp[1] != com && cp[1] != con && cp[1] != esc)
				skipesc = (flags & FPARSELN_UNESCREST);

			if (skipesc)
				cp++;
			else
				*ptr++ = *cp++;
			*ptr++ = *cp++;
		}
		*ptr = '\0';
		len = strlen(buf);
	}

	if (size)
		*size = len;
	return buf;
}
Пример #16
0
char *
getpass (const char *prompt)
{
  FILE *tty;
  FILE *in, *out;
  struct termios s, t;
  bool tty_changed = false;
  static char *buf;
  static size_t bufsize;
  ssize_t nread;

  /* Try to write to and read from the terminal if we can.
     If we can't open the terminal, use stderr and stdin.  */

  tty = fopen ("/dev/tty", "w+");
  if (tty == NULL)
    {
      in = stdin;
      out = stderr;
    }
  else
    {
      /* We do the locking ourselves.  */
      __fsetlocking (tty, FSETLOCKING_BYCALLER);

      out = in = tty;
    }

  flockfile (out);

  /* Turn echoing off if it is on now.  */
# if HAVE_TCGETATTR
  if (tcgetattr (fileno (in), &t) == 0)
    {
      /* Save the old one. */
      s = t;
      /* Tricky, tricky. */
      t.c_lflag &= ~(ECHO | ISIG);
      tty_changed = (tcsetattr (fileno (in), TCSAFLUSH | TCSASOFT, &t) == 0);
    }
# endif

  /* Write the prompt.  */
  fputs_unlocked (prompt, out);
  fflush_unlocked (out);

  /* Read the password.  */
  nread = getline (&buf, &bufsize, in);

  /* According to the C standard, input may not be followed by output
     on the same stream without an intervening call to a file
     positioning function.  Suppose in == out; then without this fseek
     call, on Solaris, HP-UX, AIX, OSF/1, the previous input gets
     echoed, whereas on IRIX, the following newline is not output as
     it should be.  POSIX imposes similar restrictions if fileno (in)
     == fileno (out).  The POSIX restrictions are tricky and change
     from POSIX version to POSIX version, so play it safe and invoke
     fseek even if in != out.  */
  fseeko (out, 0, SEEK_CUR);

  if (buf != NULL)
    {
      if (nread < 0)
        buf[0] = '\0';
      else if (buf[nread - 1] == '\n')
        {
          /* Remove the newline.  */
          buf[nread - 1] = '\0';
          if (tty_changed)
            {
              /* Write the newline that was not echoed.  */
              putc_unlocked ('\n', out);
            }
        }
    }

  /* Restore the original setting.  */
# if HAVE_TCSETATTR
  if (tty_changed)
    tcsetattr (fileno (in), TCSAFLUSH | TCSASOFT, &s);
# endif

  funlockfile (out);

  call_fclose (tty);

  return buf;
}
Пример #17
0
inline void liberabloqueos(){
    sigrelse(SIGUSR1);
    funlockfile(stdout);
    sigprocmask(SIG_UNBLOCK, &allsignals, NULL);
}
Пример #18
0
/**
 * The thread created by the student.
 * @param     p
 *                 A struct thread_param object cast to void *
 * @return    A pointer to an int containing the number of solutions found
 *            cast to a void *.
 */
void* thread(void* p)
{
	struct thread_param * param = (struct thread_param *) p;
	struct resuse resuse;
	int rows[num_queens];
	int column;

	// star collecting resource information about this thread
	resuse_start(&resuse, RESUSE_SCOPE_THREAD);

	// print debug information
	dprintf("Thread %d Starting\n", param->thread_num);

	while(1) {
		/* Obtain the mutex for the next column */
		int err = pthread_mutex_lock(&nc_mutex);
		if (err) {
			fprintf(stderr, "ERR: pthread_mutex_lock returned %d\n", err);
			exit(1);
		}

		/* Take the next column */
		column = next_column; 

		/* Decrement the next column */
		next_column--;

		/* NOTE: Even though it *looks* atomic,
		 * local = global++ is anything but.
		 * Without the mutex, two threads
		 * could end up grabbing
		 * the same column, then
		 * both incrementing it and
		 * skipping a column, or any
		 * other sort of weirdness.
		 */

		/* Release mutex */
		err = pthread_mutex_unlock(&nc_mutex);
		if (err) {
			fprintf(stderr, "ERR: pthread_mutex_lock returned %d\n", err);
			exit(1);
		}

		if (column < 0) {
			break;
		}

		dprintf("Thread %d kicking off column %d\n", param->thread_num, column);

		rows[0] = param->thread_num;
		queens_helper(rows, 1, &(param->solution_count));

		dprintf("Thread %d finished column %d, looking for new work...\n", param->thread_num, column);

	}
	// print debug information
	dprintf("Thread %d Finished, found %d solutions\n", param->thread_num, 
					param->solution_count);

	// finish collecting resource information about this thread
	resuse_end(&resuse);

	// print the resource information to stdout
	flockfile(stdout);
	fprintf(stdout, "Thread %02d: ", param->thread_num);
	resuse_fprint(stdout, resuse_fmt, &resuse);
	fflush(stdout);
	funlockfile(stdout);

	// return the number of solutions this thread found
	return (void*) &param->solution_count;
}
/* Read one mount table entry from STREAM.  Returns a pointer to storage
   reused on the next call, or null for EOF or error (use feof/ferror to
   check).  */
struct mntent *
__getmntent_r (FILE *stream, struct mntent *mp, char *buffer, int bufsiz)
{
  char *cp;
  char *head;

#ifndef __WIN32__
  flockfile (stream);
  do
    {
      char *end_ptr;

      if (fgets_unlocked (buffer, bufsiz, stream) == NULL)
	{
	  funlockfile (stream);
	  return NULL;
	}

      end_ptr = strchr (buffer, '\n');
      if (end_ptr != NULL)	/* chop newline */
	*end_ptr = '\0';
      else
	{
	  /* Not the whole line was read.  Do it now but forget it.  */
	  char tmp[1024];
	  while (fgets_unlocked (tmp, sizeof tmp, stream) != NULL)
	    if (strchr (tmp, '\n') != NULL)
	      break;
	}

      head = buffer + strspn (buffer, " \t");
      /* skip empty lines and comment lines:  */
    }
  while (head[0] == '\0' || head[0] == '#');
#else /* __WIN32__ */
  struct statfsx64 buf;
  if (!strcmp(rootlist, NotSet)) {
//	fprintf(stderr, "rootlist0\n");
	rootlist = getrootdirs(rootlist);
  }
  /* skip the rootdirs that are not mounted */
  while ( (statfsx64 (rootlist, &buf) < 0)) { //(access (rootlist, F_OK) < 0) ||
//    fprintf(stderr, "rootlist < 0: %s\n", rootlist);
	if (rootlist[0] == 0)
    	return NULL;
	else
		rootlist = strchr (rootlist, 0) + 1;	
  }
//  fprintf(stderr, "rootlist: %s\n", rootlist);
//  fprintf(stderr, "buf.f_mntonname: %s\n", buf.f_mntonname);
//  fprintf(stderr, "buf.f_mntfromname: %s\n", buf.f_mntfromname);
//  fprintf(stderr, "buf.f_mntfromname: %s\n", buf.f_mntfromname);
//  fprintf(stderr, "buf.f_fstypename: %s\n", buf.f_fstypename);
  mp->mnt_fsname = buf.f_mntonname;
  mp->mnt_dir = buf.f_mntfromname;
  mp->mnt_type = buf.f_fstypename;
  mp->mnt_opts = MNTOPT_RW;
  __addmntentstr(buffer, mp);
//  fprintf(stderr, "mp->mnt_fsname: %s\n", mp->mnt_fsname);
//  fprintf(stderr, "mp->mnt_dir: %s\n", mp->mnt_dir);
//  fprintf(stderr, "mp->mnt_type: %s\n", mp->mnt_type);
//  fprintf(stderr, "mp->mnt_opts: %s\n", mp->mnt_opts);
  head = buffer + strspn (buffer, " \t");
  rootlist = strchr (rootlist, 0) + 1;
#endif /* __WIN32 */

  cp = __strsep (&head, " \t");
  mp->mnt_fsname = cp != NULL ? decode_name (cp) : (char *) "";
  if (head)
    head += strspn (head, " \t");
  cp = __strsep (&head, " \t");
  mp->mnt_dir = cp != NULL ? decode_name (cp) : (char *) "";
  if (head)
    head += strspn (head, " \t");
  cp = __strsep (&head, " \t");
  mp->mnt_type = cp != NULL ? decode_name (cp) : (char *) "";
  if (head)
    head += strspn (head, " \t");
  cp = __strsep (&head, " \t");
  mp->mnt_opts = cp != NULL ? decode_name (cp) : (char *) "";
  switch (head ? sscanf (head, " %d %d ", &mp->mnt_freq, &mp->mnt_passno) : 0)
    {
    case 0:
      mp->mnt_freq = 0;
    case 1:
      mp->mnt_passno = 0;
    case 2:
      break;
    }
  funlockfile (stream);
 
  return mp;
}
Пример #20
0
gint
gtk_read_line (FILE *stream, GString *str)
{
  gboolean quoted = FALSE;
  gboolean comment = FALSE;
  int n_read = 0;
  int lines = 1;

  flockfile (stream);

  g_string_truncate (str, 0);

  while (1)
    {
      int c;

      c = getc_unlocked (stream);

      if (c == EOF)
        {
          if (quoted)
            g_string_append_c (str, '\\');

          goto done;
        }
      else
        n_read++;

      if (quoted)
        {
          quoted = FALSE;

          switch (c)
            {
            case '#':
              g_string_append_c (str, '#');
              break;
            case '\r':
            case '\n':
              {
                int next_c = getc_unlocked (stream);

                if (!(next_c == EOF ||
                      (c == '\r' && next_c == '\n') ||
                      (c == '\n' && next_c == '\r')))
                  ungetc (next_c, stream);

                lines++;

                break;
              }
            default:
              g_string_append_c (str, '\\');
              g_string_append_c (str, c);
            }
        }
      else
        {
          switch (c)
            {
            case '#':
              comment = TRUE;
              break;
            case '\\':
              if (!comment)
                quoted = TRUE;
              break;
            case '\n':
              {
                int next_c = getc_unlocked (stream);

                if (!(c == EOF ||
                      (c == '\r' && next_c == '\n') ||
                      (c == '\n' && next_c == '\r')))
                  ungetc (next_c, stream);

                goto done;
              }
            default:
              if (!comment)
               g_string_append_c (str, c);
            }
        }
    }

 done:
  funlockfile (stream);

  return (n_read > 0) ? lines : 0;
}
Пример #21
0
/*****************************************************************************
 * PrintMsg: output a standard message item to stderr
 *****************************************************************************
 * Print a message to stderr, with colour formatting if needed.
 *****************************************************************************/
static void PrintMsg ( vlc_object_t *p_this, const msg_item_t *p_item )
{
#   define COL(x,y)  "\033[" #x ";" #y "m"
#   define RED     COL(31,1)
#   define GREEN   COL(32,1)
#   define YELLOW  COL(0,33)
#   define WHITE   COL(0,1)
#   define GRAY    "\033[0m"
    static const char msgtype[4][9] = { "", " error", " warning", " debug" };
    static const char msgcolor[4][8] = { WHITE, RED, YELLOW, GRAY };

    libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
    int type = p_item->i_type;

    if (priv->i_verbose < 0 || priv->i_verbose < (type - VLC_MSG_ERR))
        return;

    const char *objtype = p_item->psz_object_type;
    msg_bank_t *bank = priv->msg_bank;
    void * val = vlc_dictionary_value_for_key (&bank->enabled_objects,
                                               p_item->psz_module);
    if( val == kObjectPrintingDisabled )
        return;
    if( val == kObjectPrintingEnabled )
        /* Allowed */;
    else
    {
        val = vlc_dictionary_value_for_key (&bank->enabled_objects,
                                            objtype);
        if( val == kObjectPrintingDisabled )
            return;
        if( val == kObjectPrintingEnabled )
            /* Allowed */;
        else if( !bank->all_objects_enabled )
            return;
    }

    /* Send the message to stderr */
    FILE *stream = stderr;
    int canc = vlc_savecancel ();

    flockfile (stream);
    fprintf (stream, priv->b_color ? "["GREEN"%p"GRAY"] " : "[%p] ",
            (void *)p_item->i_object_id);
    if (p_item->psz_header != NULL)
        utf8_fprintf (stream, "[%s] ", p_item->psz_header);
    utf8_fprintf (stream, "%s %s%s: ", p_item->psz_module, objtype,
                  msgtype[type]);
    if (priv->b_color)
        fputs (msgcolor[type], stream);
    fputs (p_item->psz_msg, stream);
    if (priv->b_color)
        fputs (GRAY, stream);
    putc_unlocked ('\n', stream);
#if defined (WIN32) || defined (__OS2__)
    fflush (stream);
#endif
    funlockfile (stream);
#ifdef ANDROID
    int level[] = {ANDROID_LOG_INFO, ANDROID_LOG_ERROR, ANDROID_LOG_WARN, ANDROID_LOG_DEBUG};
    __android_log_print(
        level[p_item->i_type],
        "faplayer",
        p_item->psz_header ? "[%p][%s] %s %s: %s" : "[%p]%s%s %s: %s",
        (void *) p_item->i_object_id,
        p_item->psz_header ? p_item->psz_header : "",
        p_item->psz_module,
        p_item->psz_object_type,
        p_item->psz_msg
    );
#endif
    vlc_restorecancel (canc);
}
Пример #22
0
Файл: tap.c Проект: abw/nanbox
/*
 * Generate a test result.
 *
 * ok -- boolean, indicates whether or not the test passed.
 * test_name -- the name of the test, may be NULL
 * test_comment -- a comment to print afterwards, may be NULL
 */
unsigned int
_gen_result(int ok, const char *func, char *file, unsigned int line, 
        char *test_name, ...)
{
    va_list ap;
    char *local_test_name = NULL;
    char *c;
    int name_is_digits;
    
    LOCK;

    test_count++;

    /* Start by taking the test name and performing any printf()
       expansions on it */
    if(test_name != NULL) {
        va_start(ap, test_name);
        dud = vasprintf(&local_test_name, test_name, ap);
        va_end(ap);

        /* Make sure the test name contains more than digits
           and spaces.  Emit an error message and exit if it
           does */
        if(local_test_name) {
            name_is_digits = 1;
            for(c = local_test_name; *c != '\0'; c++) {
                if(!isdigit(*c) && !isspace(*c)) {
                    name_is_digits = 0;
                    break;
                }
            }

            if(name_is_digits) {
                diag("    You named your test '%s'.  You shouldn't use numbers for your test names.", local_test_name);
                diag("    Very confusing.");
            }
        }
    }

    if (ok) {
        printf("%sok %d", PASS_COL, test_count);
    }
    else {
        printf("%snot ok %d", todo ? SKIP_COL : FAIL_COL, test_count);
        failures++;
    }

    if(test_name != NULL) {
        printf(" - ");

        /* Print the test name, escaping any '#' characters it
           might contain */
        if(local_test_name != NULL) {
            flockfile(stdout);
            for(c = local_test_name; *c != '\0'; c++) {
                if(*c == '#')
                    fputc('\\', stdout);
                fputc((int)*c, stdout);
            }
            funlockfile(stdout);
        } else {    /* vasprintf() failed, use a fixed message */
            printf("%s", todo_msg_fixed);
        }
    }

    /* If we're in a todo_start() block then flag the test as being
       TODO.  todo_msg should contain the message to print at this
       point.  If it's NULL then asprintf() failed, and we should
       use the fixed message.

       This is not counted as a failure, so decrement the counter if
       the test failed. */
    if(todo) {
        printf(" # TODO %s", todo_msg ? todo_msg : todo_msg_fixed);
        if(!ok)
            failures--;
    }

    printf("%s\n", TERM_COL);

    if(!ok)
        diag("    Failed %stest (%s:%s() at line %d)", 
             todo ? "(TODO) " : "", file, func, line);

    free(local_test_name);

    UNLOCK;

    /* We only care (when testing) that ok is positive, but here we
       specifically only want to return 1 or 0 */
    return ok ? 1 : 0;
}
Пример #23
0
void swift::_swift_stdlib_funlockfile_stdout() {
  funlockfile(stdout);
}
Пример #24
0
/* Read up to (and including) a DELIMITER from FP into *LINEPTR (and
   NUL-terminate it).  *LINEPTR is a pointer returned from malloc (or
   NULL), pointing to *N characters of space.  It is realloc'ed as
   necessary.  Returns the number of characters read (not including
   the null terminator), or -1 on error or EOF.  */
ssize_t getdelim(char **lineptr, size_t *n, int delimiter, FILE *fp)
{
  ssize_t result;
  size_t cur_len = 0;

  if ((lineptr == NULL) || (n == NULL) || (fp == NULL)) {
      errno = EINVAL;
      return -1;
  }

  flockfile(fp);

  if ((*lineptr == NULL) || (*n == 0)) {
      char *new_lineptr;
      *n = 120;
      new_lineptr = (char *)realloc(*lineptr, *n);
      if (new_lineptr == NULL) {
          result = -1;
          goto unlock_return;
	  }
      *lineptr = new_lineptr;
  }

  for (;;) {
      int i;

      i = getc_maybe_unlocked(fp);
      if (i == EOF) {
          result = -1;
          break;
	  }

      /* Make enough space for len+1 (for final NUL) bytes.  */
      if (cur_len + 1 >= *n) {
          size_t needed_max =
            ((SSIZE_MAX < SIZE_MAX) ? ((size_t)SSIZE_MAX + 1) : SIZE_MAX);
          size_t needed = ((2 * *n) + 1); /* Be generous. */
          char *new_lineptr;

          if (needed_max < needed) {
			  needed = needed_max;
		  }
          if ((cur_len + 1) >= needed) {
              result = -1;
              errno = EOVERFLOW;
              goto unlock_return;
		  }

          new_lineptr = (char *)realloc(*lineptr, needed);
          if (new_lineptr == NULL) {
              result = -1;
              goto unlock_return;
		  }

          *lineptr = new_lineptr;
          *n = needed;
	  }

      (*lineptr)[cur_len] = (char)i;
      cur_len++;

      if (i == delimiter) {
		  break;
	  }
  }
  (*lineptr)[cur_len] = '\0';
  result = (ssize_t)(cur_len ? cur_len : (size_t)result);

 unlock_return:
  funlockfile(fp); /* does NOT set errno */

  return result;
}
Пример #25
0
static int
do_test (void)
{
  const char blah[] = "BLAH";
  char buf[strlen (blah) + 1];
  FILE *fp, *f;
  const char *cp;
  char *wp;

  if ((fp = fdopen (fd, "w+")) == NULL)
    exit (1);

  flockfile (fp);

  f = fp;
  cp = blah;
  /* These tests deliberately use fwrite_unlocked with the size
     argument specified as 0, which results in "division by zero"
     warnings from the expansion of that macro (in code that is not
     evaluated for a size of 0).  This applies to the tests of
     fread_unlocked below as well.  */
  DIAG_PUSH_NEEDS_COMMENT;
  DIAG_IGNORE_NEEDS_COMMENT (4.9, "-Wdiv-by-zero");
  if (ftello (fp) != 0
      || fwrite_unlocked (blah, blah - blah, strlen (blah), f++) != 0
      || f != fp + 1
      || fwrite_unlocked ("", 5.0, 0, --f) != 0
      || f != fp
      || fwrite_unlocked (cp++, 16, 0.25, fp) != 0
      || cp != blah + 1
      || fwrite_unlocked (--cp, 0.25, 16, fp) != 0
      || cp != blah
      || fwrite_unlocked (blah, 0, -0.0, fp) != 0
      || ftello (fp) != 0)
    {
      puts ("One of fwrite_unlocked tests failed");
      exit (1);
    }
  DIAG_POP_NEEDS_COMMENT;

  if (fwrite_unlocked (blah, 1, strlen (blah) - 2, fp) != strlen (blah) - 2)
    {
      puts ("Could not write string into file");
      exit (1);
    }

  if (putc_unlocked ('A' + 0x1000000, fp) != 'A')
    {
      puts ("putc_unlocked failed");
      exit (1);
    }

  f = fp;
  cp = blah + strlen (blah) - 1;
  if (putc_unlocked (*cp++, f++) != 'H'
      || f != fp + 1
      || cp != strchr (blah, '\0'))
    {
      puts ("fputc_unlocked failed");
      exit (1);
    }

  if (ftello (fp) != (off_t) strlen (blah))
    {
      printf ("Failed to write %zd bytes to temporary file", strlen (blah));
      exit (1);
    }

  rewind (fp);

  f = fp;
  wp = buf;
  memset (buf, ' ', sizeof (buf));
  /* See explanation above.  */
  DIAG_PUSH_NEEDS_COMMENT;
  DIAG_IGNORE_NEEDS_COMMENT (4.9, "-Wdiv-by-zero");
  if (ftello (fp) != 0
      || fread_unlocked (buf, buf - buf, strlen (blah), f++) != 0
      || f != fp + 1
      || fread_unlocked (buf, 5.0, 0, --f) != 0
      || f != fp
      || fread_unlocked (wp++, 16, 0.25, fp) != 0
      || wp != buf + 1
      || fread_unlocked (--wp, 0.25, 16, fp) != 0
      || wp != buf
      || fread_unlocked (buf, 0, -0.0, fp) != 0
      || ftello (fp) != 0
      || memcmp (buf, "     ", sizeof (buf)) != 0)
    {
      puts ("One of fread_unlocked tests failed");
      exit (1);
    }
  DIAG_POP_NEEDS_COMMENT;

  if (fread_unlocked (buf, 1, strlen (blah) - 2, fp) != strlen (blah) - 2)
    {
      puts ("Could not read string from file");
      exit (1);
    }

  if (getc_unlocked (fp) != 'A')
    {
      puts ("getc_unlocked failed");
      exit (1);
    }

  f = fp;
  if (fgetc_unlocked (f++) != 'H'
      || f != fp + 1
      || fgetc_unlocked (--f) != EOF
      || f != fp)
    {
      puts ("fgetc_unlocked failed");
      exit (1);
    }

  if (ftello (fp) != (off_t) strlen (blah))
    {
      printf ("Failed to read %zd bytes from temporary file", strlen (blah));
      exit (1);
    }

  funlockfile (fp);
  fclose (fp);

  return 0;
}