Пример #1
0
ErrorStack TpccLoadTask::load_tables() {
  CHECK_ERROR(load_customers());
  CHECK_ERROR(load_orders_data());
  return kRetOk;
}
Пример #2
0
/** string_match_splitter()
 *  Splitter Function to assign portions of the file to each thread
 */
void string_match_splitter(void *data_in)
{
	key1_final = (char*)malloc(strlen(key1) + 1);
	key2_final = (char*)malloc(strlen(key2) + 1);
	key3_final = (char*)malloc(strlen(key3) + 1);
	key4_final = (char*)malloc(strlen(key4) + 1);

	compute_hashes(key1, key1_final);
	compute_hashes(key2, key2_final);
	compute_hashes(key3, key3_final);
	compute_hashes(key4, key4_final);

    pthread_attr_t attr;
    pthread_t * tid;
    int i, num_procs;

    CHECK_ERROR((num_procs = sysconf(_SC_NPROCESSORS_ONLN)) <= 0);
    printf("THe number of processors is %d\n", num_procs);

    str_data_t * data = (str_data_t *)data_in; 

    /* Check whether the various terms exist */
    assert(data_in);

    tid = (pthread_t *)MALLOC(num_procs * sizeof(pthread_t));

    /* Thread must be scheduled systemwide */
    pthread_attr_init(&attr);
    pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);

    int req_bytes = data->keys_file_len / num_procs;

    str_map_data_t *map_data = (str_map_data_t*)malloc(sizeof(str_map_data_t) 
                                                                                        * num_procs);
    map_args_t* out = (map_args_t*)malloc(sizeof(map_args_t) * num_procs);

    for(i=0; i<num_procs; i++)
    {
	    map_data[i].encrypt_file = data->encrypt_file;
	    map_data[i].keys_file = data->keys_file + data->bytes_comp;
	    map_data[i].TID = i;
	    	    
	    /* Assign the required number of bytes */	    
	    int available_bytes = data->keys_file_len - data->bytes_comp;
	    if(available_bytes < 0)
		    available_bytes = 0;

	    out[i].length = (req_bytes < available_bytes)? req_bytes:available_bytes;
	    out[i].data = &(map_data[i]);


	    char* final_ptr = map_data[i].keys_file + out[i].length;
	    int counter = data->bytes_comp + out[i].length;

		 /* make sure we end at a word */
	    while(counter <= data->keys_file_len && *final_ptr != '\n'
			 && *final_ptr != '\r' && *final_ptr != '\0')
	    {
		    counter++;
		    final_ptr++;
	    }
	    if(*final_ptr == '\r')
		    counter+=2;
	    else if(*final_ptr == '\n')
		    counter++;

	    out[i].length = counter - data->bytes_comp;
	    data->bytes_comp = counter;
	    CHECK_ERROR(pthread_create(&tid[i], &attr, string_match_map, 
	                                                                    (void*)(&(out[i]))) != 0);
    }

    /* Barrier, wait for all threads to finish */
    for (i = 0; i < num_procs; i++)
    {
        int ret_val;
        CHECK_ERROR(pthread_join(tid[i], (void **)(void*)&ret_val) != 0);
	  CHECK_ERROR(ret_val != 0);
    }
    pthread_attr_destroy(&attr);
    free(tid);
    free(key1_final);
    free(key2_final);
    free(key3_final);
    free(key4_final);
    free(out);
    free(map_data);
}
Пример #3
0
int main(int argc, char *argv[]) {
      
   int i, j;
   int fd;
   char *fdata;
   struct stat finfo;
   char * fname;
   pthread_t *pid;
   pthread_attr_t attr;
   thread_arg_t *arg;
   int red[256];
   int green[256];
   int blue[256];
   int num_procs;
   int num_per_thread;
   int excess;


   // Make sure a filename is specified
   if (argv[1] == NULL) {
      printf("USAGE: %s <bitmap filename>\n", argv[0]);
      exit(1);
   }
   
   fname = argv[1];
   
   // Read in the file
   CHECK_ERROR((fd = open(fname, O_RDONLY)) < 0);
   // Get the file info (for file length)
   CHECK_ERROR(fstat(fd, &finfo) < 0);
   // Memory map the file
   CHECK_ERROR((fdata = mmap(0, finfo.st_size + 1, 
      PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)) == NULL);
   
   if ((fdata[0] != 'B') || (fdata[1] != 'M')) {
      printf("File is not a valid bitmap file. Exiting\n");
      exit(1);
   }
   
   test_endianess();    // will set the variable "swap"
   
   unsigned short *bitsperpixel = (unsigned short *)(&(fdata[BITS_PER_PIXEL_POS]));
   if (swap) {
      swap_bytes((char *)(bitsperpixel), sizeof(*bitsperpixel));
   }
   if (*bitsperpixel != 24) {    // ensure its 3 bytes per pixel
      printf("Error: Invalid bitmap format - ");
      printf("This application only accepts 24-bit pictures. Exiting\n");
      exit(1);
   }
   
   unsigned short *data_pos = (unsigned short *)(&(fdata[IMG_DATA_OFFSET_POS]));
   if (swap) {
      swap_bytes((char *)(data_pos), sizeof(*data_pos));
   }
   
   int imgdata_bytes = (int)finfo.st_size - (int)(*(data_pos));
   int num_pixels = ((int)finfo.st_size - (int)(*(data_pos))) / 3;
   printf("This file has %d bytes of image data, %d pixels\n", imgdata_bytes,
                                                            num_pixels);

   printf("Starting pthreads histogram\n");
   

   memset(&(red[0]), 0, sizeof(int) * 256);
   memset(&(green[0]), 0, sizeof(int) * 256);
   memset(&(blue[0]), 0, sizeof(int) * 256);
   
   /* Set a global scope */
   pthread_attr_init(&attr);
   pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
   
   CHECK_ERROR((num_procs = sysconf(_SC_NPROCESSORS_ONLN)) <= 0);
   num_per_thread = num_pixels / num_procs;
   excess = num_pixels % num_procs;
   
   CHECK_ERROR( (pid = (pthread_t *)malloc(sizeof(pthread_t) * num_procs)) == NULL);
   CHECK_ERROR( (arg = (thread_arg_t *)calloc(sizeof(thread_arg_t), num_procs)) == NULL);
   
   /* Assign portions of the image to each thread */
   long curr_pos = (long)(*data_pos);
   for (i = 0; i < num_procs; i++) {
      arg[i].data = (unsigned char *)fdata;
      arg[i].data_pos = curr_pos;
      arg[i].data_len = num_per_thread;
      if (excess > 0) {
         arg[i].data_len++;
         excess--;
      }
      
      arg[i].data_len *= 3;   // 3 bytes per pixel
      curr_pos += arg[i].data_len;
      
      pthread_create(&(pid[i]), &attr, calc_hist, (void *)(&(arg[i])));   
   }
   
   for (i = 0; i < num_procs; i++) {
      pthread_join(pid[i] , NULL);   
   }
   
   for (i = 0; i < num_procs; i++) {
      for (j = 0; j < 256; j++) {
         red[j] += arg[i].red[j];
         green[j] += arg[i].green[j];
         blue[j] += arg[i].blue[j];
      }
   }

   dprintf("\n\nBlue\n");
   dprintf("----------\n\n");
   for (i = 0; i < 256; i++) {
      dprintf("%d - %d\n", i, blue[i]);        
   }

   dprintf("\n\nGreen\n");
   dprintf("----------\n\n");
   for (i = 0; i < 256; i++) {
      dprintf("%d - %d\n", i, green[i]);        
   }
   
   dprintf("\n\nRed\n");
   dprintf("----------\n\n");
   for (i = 0; i < 256; i++) {
      dprintf("%d - %d\n", i, red[i]);        
   }

   CHECK_ERROR(munmap(fdata, finfo.st_size + 1) < 0);
   CHECK_ERROR(close(fd) < 0);
   
   free(pid);
   for(i = 0; i < num_procs; i++) {
      free(arg[i].red);
      free(arg[i].green);
      free(arg[i].blue);
   }
   free(arg);
   pthread_attr_destroy(&attr);
   
   return 0;
}
Пример #4
0
/* Monitor for the child process */
static int
child_monitor (subprocess_t * p,
	       int stdin_pipe[2], int stdout_pipe[2], int stderr_pipe[2])
{
  int ret = RETURN_SUCCESS;

  /* Set the limits on the process */
  if (p->limits != NULL)
    {
      /* Setting the rlimits */
      struct rlimit limit;

      /* Setting a limit on the memory */
      if (p->limits->memory > 0)
	{
	  CHECK_ERROR ((getrlimit (RLIMIT_AS, &limit) == -1),
		       "getting memory limit failed");

	  limit.rlim_cur = p->limits->memory;

	  CHECK_ERROR ((setrlimit (RLIMIT_AS, &limit) == -1),
		       "setting memory limit failed");
	}

      /* Setting a limit on file size */
      if (p->limits->fsize > 0)
	{
	  CHECK_ERROR ((getrlimit (RLIMIT_FSIZE, &limit) == -1),
		       "getting file size limit failed");

	  limit.rlim_cur = p->limits->fsize;

	  CHECK_ERROR ((setrlimit (RLIMIT_FSIZE, &limit) == -1),
		       "setting file size limit failed");
	}

      /* Setting a limit on file descriptor number */
      if (p->limits->fd > 0)
	{
	  CHECK_ERROR ((getrlimit (RLIMIT_NOFILE, &limit) == -1),
		       "getting maximum fd number limit failed");

	  limit.rlim_cur = p->limits->fd;

	  CHECK_ERROR ((setrlimit (RLIMIT_NOFILE, &limit) == -1),
		       "setting maximum fd number limit failed");
	}

      /* Setting a limit on process number */
      if (p->limits->proc > 0)
	{
	  CHECK_ERROR ((getrlimit (RLIMIT_NPROC, &limit) == -1),
		       "getting maximum process number limit failed");

	  limit.rlim_cur = p->limits->proc;

	  CHECK_ERROR ((setrlimit (RLIMIT_NPROC, &limit) == -1),
		       "setting maximum process number limit failed");
	}

      /* Setting a syscall tracer on the process */
      if (p->limits->syscalls[0] > 0)
	{
	  CHECK_ERROR ((ptrace (PTRACE_TRACEME, 0, NULL, NULL) == -1),
		       "ptrace failed");
	}
    }

  /* Setting i/o handlers */
  CHECK_ERROR ((close (stdin_pipe[1]) == -1), "close(stdin[1]) failed");
  CHECK_ERROR ((dup2 (stdin_pipe[0], STDIN_FILENO) == -1),
	       "dup(stdin) failed");
  CHECK_ERROR ((close (stdin_pipe[0]) == -1), "close(stdin[0]) failed");

  CHECK_ERROR ((close (stdout_pipe[0]) == -1), "close(stdout[0]) failed");
  CHECK_ERROR ((dup2 (stdout_pipe[1], STDOUT_FILENO) == -1),
	       "dup(stdout) failed");
  CHECK_ERROR ((close (stdout_pipe[1]) == -1), "close(stdout[1]) failed");

  CHECK_ERROR ((close (stderr_pipe[0]) == -1), "close(stderr[0]) failed");
  CHECK_ERROR ((dup2 (stderr_pipe[1], STDERR_FILENO) == -1),
	       "dup(stderr) failed");
  CHECK_ERROR ((close (stderr_pipe[1]) == -1), "close(stderr[1]) failed");

  /* Run the command line */
  CHECK_ERROR((execve (p->argv[0], p->argv, p->envp) == -1),
	      "execve failed");

  if (false)
  fail:
    ret = RETURN_FAILURE;

  return ret;
}
Пример #5
0
bool rlimit_expect_stdout (subprocess_t * p, char * pattern, int timeout)
{
  regex_t regex;
  bool result = false;
  int new_expect_stdout = 0;
  struct timespec start_time, current_time;

  struct timespec tick;
  tick.tv_sec = 0;
  tick.tv_nsec = 100;

  /* Getting start time */
  CHECK_ERROR ((clock_gettime (CLOCK_MONOTONIC, &start_time) == -1),
	       "getting start time failed");

  /* Getting the regular expression compiled */
  int error = regcomp(&regex, pattern, REG_EXTENDED | REG_NOSUB);
  char * str = &(p->stdout_buffer[p->expect_stdout]);

  /* Dealing with errors (if any) */
  if (error != 0)
    {
      char msgbuf[128];
      regerror(error, &regex, msgbuf, sizeof(msgbuf));

      CHECK_ERROR(true, msgbuf);
    }

  /* Main loop: Wait until the pattern appears or the timeout is hit */
  do
    {
      /* Wait a tick */
      nanosleep (&tick, NULL);

      if (!p->stdout_buffer)
	continue;

      /* Get future expect_stdout (avoiding increase after search) */
      new_expect_stdout = strlen (p->stdout_buffer);

      /* Searching for pattern */
      if (regexec(&regex, str, (size_t) 0, NULL, 0) == 0)
	{
	  result = true;
	  break;
	}

      /* Getting current time */
      CHECK_ERROR ((clock_gettime (CLOCK_MONOTONIC, &current_time) == -1),
	       "getting current time failed");
    }
  while (((current_time.tv_sec - start_time.tv_sec) < timeout) &&
	 (p->status < TERMINATED));

  /* Setting expect_stdout to the new value */
  p->expect_stdout = new_expect_stdout;

 fail:
  regfree(&regex);

  return result;
}
Пример #6
0
static void * gio_fopen (const char * filename, const char * mode)
{
    GError * error = 0;

    FileData * data = malloc (sizeof (FileData));
    memset (data, 0, sizeof (FileData));

    data->file = g_file_new_for_uri (filename);

    switch (mode[0])
    {
    case 'r':
        if (strchr (mode, '+'))
        {
            data->iostream = (GIOStream *) g_file_open_readwrite (data->file, 0, & error);
            CHECK_ERROR ("open", filename);
            data->istream = g_io_stream_get_input_stream (data->iostream);
            data->ostream = g_io_stream_get_output_stream (data->iostream);
            data->seekable = (GSeekable *) data->iostream;
        }
        else
        {
            data->istream = (GInputStream *) g_file_read (data->file, 0, & error);
            CHECK_ERROR ("open", filename);
            data->seekable = (GSeekable *) data->istream;
        }
        break;
    case 'w':
        if (strchr (mode, '+'))
        {
            data->iostream = (GIOStream *) g_file_replace_readwrite (data->file, 0, 0, 0, 0, & error);
            CHECK_ERROR ("open", filename);
            data->istream = g_io_stream_get_input_stream (data->iostream);
            data->ostream = g_io_stream_get_output_stream (data->iostream);
            data->seekable = (GSeekable *) data->iostream;
        }
        else
        {
            data->ostream = (GOutputStream *) g_file_replace (data->file, 0, 0, 0, 0, & error);
            CHECK_ERROR ("open", filename);
            data->seekable = (GSeekable *) data->ostream;
        }
        break;
    case 'a':
        if (strchr (mode, '+'))
        {
            gio_error ("Cannot open %s: GIO does not support read-and-append mode.", filename);
            goto FAILED;
        }
        else
        {
            data->ostream = (GOutputStream *) g_file_append_to (data->file, 0, 0, & error);
            CHECK_ERROR ("open", filename);
            data->seekable = (GSeekable *) data->ostream;
        }
        break;
    default:
        gio_error ("Cannot open %s: invalid mode.", filename);
        goto FAILED;
    }

    return data;

FAILED:
    free (data);
    return 0;
}
Пример #7
0
subprocess_t *
rlimit_subprocess_create (int argc, char **argv, char **envp)
{
  subprocess_t *p = malloc (sizeof (subprocess_t));
  /* Handling 'out of memory' */
  CHECK_ERROR ((p == NULL), "subprocess allocation failed");

  /* Initializing the command line arguments */
  p->argc = argc;

  /* Copy argv */
  p->argv = malloc ((argc + 1) * sizeof (char *));
  /* Handling 'out of memory' */
  if (p->argv == NULL)
    {
      free (p);
      p = NULL;
      CHECK_ERROR (true, "subprocess allocation failed");
    }

  for (int i = 0; i < argc; i++)
    {
      p->argv[i] = malloc ((strlen (argv[i]) + 1) * sizeof (char));
      /* Handling 'out of memory' */
      if (p->argv[i] == NULL)
	{
	  while (i >= 0)
	    free (p->argv[i--]);
	  free (p->argv);
	  free (p);
	  p = NULL;
	  CHECK_ERROR (true, "subprocess allocation failed");
	}

      memcpy (p->argv[i], argv[i], strlen(argv[i]) + 1);
    }
  p->argv[argc] = NULL;

  /* Copy envp */
  if (!envp)			/* Handling the case 'envp == NULL' */
    {
      p->envp = NULL;
    }
  else
    {
      int envp_size = 0;
      while (envp[envp_size++]);

      p->envp = malloc ((envp_size + 1) * sizeof (char *));
      /* Handling 'out of memory' */
      if (p->envp == NULL)
	{
	  for (int i = 0; p->argv[i] != NULL; i++)
	    free (p->argv[i]);
	  free (p->argv);
	  free (p);
	  p = NULL;
	  CHECK_ERROR (true, "subprocess allocation failed");
	}

      for (int i = 0; i < envp_size; i++)
	{
	  p->envp[i] = malloc (strlen (envp[i] + 1) * sizeof (char));
	  /* Handling 'out of memory' */
	  if (p->envp[i] == NULL)
	    {
	      for (int i = 0; p->argv[i] != NULL; i++)
		free (p->argv[i]);
	      free (p->argv);
	      while (i >= 0)
		free (p->envp[i--]);
	      free (p->envp);
	      free (p);
	      p = NULL;
	      CHECK_ERROR (true, "subprocess allocation failed");
	    }

	  memcpy (p->envp[i], envp[i], strlen(envp[i]) + 1);
	}
      p->envp[envp_size] = NULL;
    }

  /* Initializing retval and status */
  p->status = READY;
  p->retval = 0;

  /* Initializing the i/o handlers to NULL */
  p->stdin = NULL;
  p->stdout = NULL;
  p->stderr = NULL;

  p->stdin_buffer = NULL;
  p->stdout_buffer = NULL;
  p->stderr_buffer = NULL;

  /* Initializing the limits and profile to default */

  p->real_time_usec = 0;
  p->user_time_usec = 0;
  p->sys_time_usec = 0;
  p->memory_kbytes = 0;

  p->limits = NULL;

  /* Initializing the private fields */
  p->expect_stdout  = 0;
  p->expect_stderr = 0;

  p->monitor = malloc (sizeof (pthread_t));
  CHECK_ERROR ((p->monitor == NULL), "p->monitor allocation failed");

  pthread_mutex_init (&(p->write_mutex), NULL);

fail:
  return p;
}
Пример #8
0
int main(int argc, char **argv)
{
    if (argc != 4) {
        printf("usage: %s <server-address> <server-port> <phase[-1 - 6]>\n",
                argv[0]);
        return EXIT_FAILURE;
    }
    int start_phase = atoi(argv[3]);

    bool res;

    test_state_t *state = NULL;
    rvm_cfg_t *cfg;
    if(start_phase >= 0) {
        /* Try to recover from server */
        cfg = initialize_rvm(argv[1], argv[2], true,
                create_rmem_layer);

        /* Recover the state (if any) */
        state = (test_state_t*)rvm_get_usr_data(cfg);
    } else {
        /* Starting from scratch */
        cfg = initialize_rvm(argv[1], argv[2], false,
                create_rmem_layer);
        CHECK_ERROR(cfg == NULL, ("Failed to initialize rvm\n"));

        state = NULL;
    }

    rvm_txid_t txid;
    /*====================================================================
     * TX 0 - Allocate and Initialize Arrays
     *===================================================================*/
    /* If state is NULL then we are starting from scratch or recovering from
       an early error */
    if(state == NULL) {
        LOG(1,("Phase 0:\n"));
        TX_START;

        /* Allocate a "state" structure to test pointers */
        state = (test_state_t*)rvm_alloc(cfg, sizeof(test_state_t));
        CHECK_ERROR(state == NULL, ("FAILURE: Couldn't allocate state\n"));

        /* Initialize the arrays */ 
        res = phase0(cfg, state);
        CHECK_ERROR(!res, ("FAILURE: Phase 0 Failure\n"));

        if(start_phase == -1) {
            LOG(1, ("SUCCESS: Phase 0, simulating failure\n"));
            return EXIT_SUCCESS;
        }

        /* End of first txn */
        state->phase = PHASE1;
        TX_COMMIT;
    }

    switch(state->phase) {
    case PHASE1:
        /*====================================================================
         * TX 1 Increment arrays, don't mess with LL
         *===================================================================*/
        LOG(1, ("Phase 1:\n"));
        TX_START;
        
        res = phase1(cfg, state);
        CHECK_ERROR(!res, ("FAILURE: Phase 1 failed\n"));

        /* Simulate Failure */
        if(start_phase == 0) {
            LOG(1, ("SUCCESS: Phase 1, simulating failure\n"));
            return EXIT_SUCCESS;
        }

        state->phase = PHASE2;
        TX_COMMIT;
    
    case PHASE2: //Fallthrough
        /*====================================================================
         * TX 2 Free Arrays
         *===================================================================*/
        LOG(1, ("Phase 2:\n"));
        TX_START;

        res = phase2(cfg, state);
        CHECK_ERROR(!res, ("FAILURE: Phase 2 failed\n"));

        /* Simulate Failure */
        if(start_phase == 1) {
            LOG(1, ("SUCCESS: Phase 2, simulating failure\n"));
            return EXIT_SUCCESS;
        }

        state->phase = PHASE3;
        TX_COMMIT;

    case PHASE3: //Fallthrough
        /*====================================================================
         * TX 3 Fill in Linked list
         *===================================================================*/
        LOG(1, ("Phase 3:\n"));
        TX_START;

        res = phase3(cfg, state);
        CHECK_ERROR(!res, ("FAILURE: Phase 3 failed\n"));

        /* Simulate Failure */
        if(start_phase == 2) {
            LOG(1, ("SUCCESS: Phase 3, simulating failure\n"));
            return EXIT_SUCCESS;
        }

        state->phase = PHASE4;
        TX_COMMIT;

    case PHASE4:
        /*====================================================================
         * TX 4 Free Half the linked list
         *===================================================================*/
        LOG(1, ("Phase 4:\n"));
        TX_START;

        res = phase4(cfg, state);
        CHECK_ERROR(!res, ("FAILURE: Phase 4 failed\n"));

         /* Simulate Failure */
        if(start_phase == 3) {
            LOG(1, ("SUCCESS: Phase 4, simulating failure\n"));
            return EXIT_SUCCESS;
        }

        state->phase = PHASE5;
        TX_COMMIT;

    case PHASE5:
        /*====================================================================
         * TX 5 Re-allocate half of the linked list
         *===================================================================*/
        LOG(1, ("Phase 5:\n"));
        TX_START;

        res = phase5(cfg, state);
        CHECK_ERROR(!res, ("FAILURE: Phase 5 failed\n"));

         /* Simulate Failure */
        if(start_phase == 4) {
            LOG(1, ("SUCCESS: Phase5, simulating failure\n"));
            return EXIT_SUCCESS;
        }

       state->phase = PHASE6;
        TX_COMMIT;

    case PHASE6:
        /*====================================================================
         * TX 6 Free whole linked list
         *===================================================================*/
        LOG(1, ("Phase 6:\n"));
        TX_START;

        res = phase6(cfg, state);
        CHECK_ERROR(!res, ("FAILURE: Phase 6 failed\n"));

        /* Simulate Failure */
        if(start_phase == 5) {
            LOG(1, ("SUCCESS: Phase 6, simulating failure\n"));
            return EXIT_SUCCESS;
        }

        state->phase = DONE;
        TX_COMMIT;

    case DONE:
        res = rvm_cfg_destroy(cfg);
        CHECK_ERROR(!res, ("FAILURE: Failed to destroy rvm state\n"));

        LOG(1, ("SUCCESS: Got through all phases\n"));
        break;

    default:
        LOG(1, ("FAILURE: Corrupted State, tried phase %d\n", state->phase));
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
Пример #9
0
result_t os_base::memoryUsage(v8::Local<v8::Object> &retVal)
{
    size_t rss = 0;

    FILE *f;
    int32_t itmp;
    char ctmp;
    uint32_t utmp;
    size_t page_size = getpagesize();
    char *cbuf;
    int32_t foundExeEnd;
    static char buf[MAXPATHLEN + 1];

    f = fopen("/proc/self/stat", "r");
    if (!f)
        return CHECK_ERROR(LastError());

    /* PID */
    if (fscanf(f, "%d ", &itmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* Exec file */
    cbuf = buf;
    foundExeEnd = 0;
    if (fscanf(f, "%c", cbuf++) == 0)
        goto error;

    while (1)
    {
        if (fscanf(f, "%c", cbuf) == 0)
            goto error;
        if (*cbuf == ')')
        {
            foundExeEnd = 1;
        }
        else if (foundExeEnd && *cbuf == ' ')
        {
            *cbuf = 0;
            break;
        }

        cbuf++;
    }
    /* State */
    if (fscanf(f, "%c ", &ctmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* Parent process */
    if (fscanf(f, "%d ", &itmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* Process group */
    if (fscanf(f, "%d ", &itmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* Session id */
    if (fscanf(f, "%d ", &itmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* TTY */
    if (fscanf(f, "%d ", &itmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* TTY owner process group */
    if (fscanf(f, "%d ", &itmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* Flags */
    if (fscanf(f, "%u ", &utmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* Minor faults (no memory page) */
    if (fscanf(f, "%u ", &utmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* Minor faults, children */
    if (fscanf(f, "%u ", &utmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* Major faults (memory page faults) */
    if (fscanf(f, "%u ", &utmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* Major faults, children */
    if (fscanf(f, "%u ", &utmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* utime */
    if (fscanf(f, "%d ", &itmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* stime */
    if (fscanf(f, "%d ", &itmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* utime, children */
    if (fscanf(f, "%d ", &itmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* stime, children */
    if (fscanf(f, "%d ", &itmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* jiffies remaining in current time slice */
    if (fscanf(f, "%d ", &itmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* 'nice' value */
    if (fscanf(f, "%d ", &itmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* jiffies until next timeout */
    if (fscanf(f, "%u ", &utmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* jiffies until next SIGALRM */
    if (fscanf(f, "%u ", &utmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* start time (jiffies since system boot) */
    if (fscanf(f, "%d ", &itmp) == 0)
        goto error;
    /* coverity[secure_coding] */

    /* Virtual memory size */
    if (fscanf(f, "%u ", &utmp) == 0)
        goto error;
    /* coverity[secure_coding] */

    /* Resident set size */
    if (fscanf(f, "%u ", &utmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    rss = (size_t) utmp * page_size;

    /* rlim */
    if (fscanf(f, "%u ", &utmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* Start of text */
    if (fscanf(f, "%u ", &utmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* End of text */
    if (fscanf(f, "%u ", &utmp) == 0)
        goto error;
    /* coverity[secure_coding] */
    /* Start of stack */
    if (fscanf(f, "%u ", &utmp) == 0)
        goto error;
    /* coverity[secure_coding] */

error:
    fclose(f);

    Isolate* isolate = Isolate::current();
    v8::Local<v8::Object> info = v8::Object::New(isolate->m_isolate);

    v8::HeapStatistics v8_heap_stats;
    isolate->m_isolate->GetHeapStatistics(&v8_heap_stats);
    info->Set(isolate->NewFromUtf8("rss"), v8::Number::New(isolate->m_isolate, (double)rss));
    info->Set(isolate->NewFromUtf8("heapTotal"),
              v8::Number::New(isolate->m_isolate, (double)v8_heap_stats.total_heap_size()));
    info->Set(isolate->NewFromUtf8("heapUsed"),
              v8::Number::New(isolate->m_isolate, (double)v8_heap_stats.used_heap_size()));

    v8::Local<v8::Object> objs;
    object_base::class_info().dump(objs);
    info->Set(isolate->NewFromUtf8("nativeObjects"), objs);

    retVal = info;

    return 0;
}
void OmxDecTestReposition::Run()
{
    switch (iState)
    {
        case StateUnLoaded:
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateUnLoaded IN"));
            OMX_ERRORTYPE Err;
            OMX_BOOL Status;

            //Run this test case only for Audio component currently, exit if video comes
            if (0 == oscl_strcmp(iFormat, "H264") || 0 == oscl_strcmp(iFormat, "M4V")
                    || 0 == oscl_strcmp(iFormat, "WMV") || 0 == oscl_strcmp(iFormat, "H263") || 0 == oscl_strcmp(iFormat, "RV"))
            {
                PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR, (0, "OmxDecTestReposition::Run() - ERROR, This test can't be run for Video component"));
#ifdef PRINT_RESULT
                fprintf(iConsOutFile, "Cannot run this test case for Video Components, Exit\n");
#endif

                iState = StateUnLoaded;
                OsclExecScheduler* sched = OsclExecScheduler::Current();
                sched->StopScheduler();
                break;
            }

            if (!iCallbacks->initCallbacks())
            {
                PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR, (0, "OmxDecTestReposition::Run() - ERROR initCallbacks failed, OUT"));
                StopOnError();
                break;
            }

            ipAppPriv = (AppPrivateType*) oscl_malloc(sizeof(AppPrivateType));
            CHECK_MEM(ipAppPriv, "Component_Handle");
            ipAppPriv->Handle = NULL;

            //Allocate bitstream buffer for AVC component
            if (0 == oscl_strcmp(iFormat, "H264"))
            {
                ipAVCBSO = OSCL_NEW(AVCBitstreamObject, (ipInputFile));
                CHECK_MEM(ipAVCBSO, "Bitstream_Buffer");
            }

            //Allocate bitstream buffer for MPEG4/H263 component
            if (0 == oscl_strcmp(iFormat, "M4V") || 0 == oscl_strcmp(iFormat, "H263"))
            {
                ipBitstreamBuffer = (OMX_U8*) oscl_malloc(BIT_BUFF_SIZE);
                CHECK_MEM(ipBitstreamBuffer, "Bitstream_Buffer")
                ipBitstreamBufferPointer = ipBitstreamBuffer;
            }

            //Allocate bitstream buffer for MP3 component
            if (0 == oscl_strcmp(iFormat, "MP3"))
            {
                ipMp3Bitstream = OSCL_NEW(Mp3BitstreamObject, (ipInputFile));
                CHECK_MEM(ipMp3Bitstream, "Bitstream_Buffer");
            }

            //This should be the first call to the component to load it.
            Err = OMX_MasterInit();
            CHECK_ERROR(Err, "OMX_MasterInit");
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG, (0, "OmxDecTestReposition::Run() - OMX_MasterInit done"));

            Status = PrepareComponent();

            if (OMX_FALSE == Status)
            {
                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG, (0, "OmxDecTestReposition::Run() Error while loading component OUT"));
                iState = StateError;

                if (iInputParameters.inPtr)
                {
                    oscl_free(iInputParameters.inPtr);
                    iInputParameters.inPtr = NULL;
                }

                RunIfNotReady();
                break;
            }


#if PROXY_INTERFACE
            ipThreadSafeHandlerEventHandler = OSCL_NEW(OmxEventHandlerThreadSafeCallbackAO, (this, EVENT_HANDLER_QUEUE_DEPTH, "EventHandlerAO"));
            ipThreadSafeHandlerEmptyBufferDone = OSCL_NEW(OmxEmptyBufferDoneThreadSafeCallbackAO, (this, iInBufferCount, "EmptyBufferDoneAO"));
            ipThreadSafeHandlerFillBufferDone = OSCL_NEW(OmxFillBufferDoneThreadSafeCallbackAO, (this, iOutBufferCount, "FillBufferDoneAO"));

            if ((NULL == ipThreadSafeHandlerEventHandler) ||
                    (NULL == ipThreadSafeHandlerEmptyBufferDone) ||
                    (NULL == ipThreadSafeHandlerFillBufferDone))
            {
                PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR,
                                (0, "OmxDecTestReposition::Run() - Error, ThreadSafe Callback Handler initialization failed, OUT"));

                iState = StateUnLoaded;
                OsclExecScheduler* sched = OsclExecScheduler::Current();
                sched->StopScheduler();
            }
#endif

            if (StateError != iState)
            {
                iState = StateLoaded;
                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateUnLoaded OUT, moving to next state"));
            }

            RunIfNotReady();
        }
        break;

        case StateLoaded:
        {
            OMX_ERRORTYPE Err;
            OMX_U32 ii;

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateLoaded IN"));
            // allocate memory for ipInBuffer
            ipInBuffer = (OMX_BUFFERHEADERTYPE**) oscl_malloc(sizeof(OMX_BUFFERHEADERTYPE*) * iInBufferCount);
            CHECK_MEM(ipInBuffer, "InputBufferHeader");

            ipInputAvail = (OMX_BOOL*) oscl_malloc(sizeof(OMX_BOOL) * iInBufferCount);
            CHECK_MEM(ipInputAvail, "InputBufferFlag");

            /* Initialize all the buffers to NULL */
            for (ii = 0; ii < iInBufferCount; ii++)
            {
                ipInBuffer[ii] = NULL;
            }

            //allocate memory for output buffer
            ipOutBuffer = (OMX_BUFFERHEADERTYPE**) oscl_malloc(sizeof(OMX_BUFFERHEADERTYPE*) * iOutBufferCount);
            CHECK_MEM(ipOutBuffer, "OutputBuffer");

            ipOutReleased = (OMX_BOOL*) oscl_malloc(sizeof(OMX_BOOL) * iOutBufferCount);
            CHECK_MEM(ipOutReleased, "OutputBufferFlag");

            /* Initialize all the buffers to NULL */
            for (ii = 0; ii < iOutBufferCount; ii++)
            {
                ipOutBuffer[ii] = NULL;
            }

            Err = OMX_SendCommand(ipAppPriv->Handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
            CHECK_ERROR(Err, "SendCommand Loaded->Idle");

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                            (0, "OmxDecTestReposition::Run() - Sent State Transition Command from Loaded->Idle"));
            iPendingCommands = 1;

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                            (0, "OmxDecTestReposition::Run() - Allocating %d input and %d output buffers", iInBufferCount, iOutBufferCount));
            //These calls are required because the control of in & out buffer should be with the testapp.
            for (ii = 0; ii < iInBufferCount; ii++)
            {
                Err = OMX_AllocateBuffer(ipAppPriv->Handle, &ipInBuffer[ii], iInputPortIndex, NULL, iInBufferSize);
                CHECK_ERROR(Err, "AllocateBuffer_Input");

                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                (0, "OmxDecTestReposition::Run() - Called AllocateBuffer for buffer index %d on port %d", ii, iInputPortIndex));
                ipInputAvail[ii] = OMX_TRUE;
                ipInBuffer[ii]->nInputPortIndex = iInputPortIndex;
            }

            if (StateError == iState)
            {
                PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR,
                                (0, "OmxDecTestReposition::Run() - AllocateBuffer Error, StateLoaded OUT"));
                RunIfNotReady();
                break;
            }

            for (ii = 0; ii < iOutBufferCount; ii++)
            {
                Err = OMX_AllocateBuffer(ipAppPriv->Handle, &ipOutBuffer[ii], iOutputPortIndex, NULL, iOutBufferSize);
                CHECK_ERROR(Err, "AllocateBuffer_Output");

                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                (0, "OmxDecTestReposition::Run() - Called AllocateBuffer for buffer index %d on port %d", ii, iOutputPortIndex));
                ipOutReleased[ii] = OMX_TRUE;

                ipOutBuffer[ii]->nOutputPortIndex = iOutputPortIndex;
                ipOutBuffer[ii]->nInputPortIndex = 0;
            }
            if (StateError == iState)
            {
                PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR,
                                (0, "OmxDecTestReposition::Run() - AllocateBuffer Error, StateLoaded OUT"));
                RunIfNotReady();
                break;
            }
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateLoaded OUT, Moving to next state"));
        }
        break;

        case StateIdle:
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateIdle IN"));
            OMX_ERRORTYPE Err = OMX_ErrorNone;

            Err = OMX_FillThisBuffer(ipAppPriv->Handle, ipOutBuffer[0]);
            CHECK_ERROR(Err, "FillThisBuffer");

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                            (0, "OmxDecTestReposition::Run() - FillThisBuffer command called for initiating dynamic port reconfiguration"));

            ipOutReleased[0] = OMX_FALSE;

            Err = OMX_SendCommand(ipAppPriv->Handle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
            CHECK_ERROR(Err, "SendCommand Idle->Executing");

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                            (0, "OmxDecTestReposition::Run() - Sent State Transition Command from Idle->Executing"));
            iPendingCommands = 1;

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateIdle OUT"));
        }
        break;

        case StateDecodeHeader:
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                            (0, "OmxDecTestReposition::Run() - StateDecodeHeader IN, Sending configuration input buffers to the component to start dynamic port reconfiguration"));

            if (!iFlagDecodeHeader)
            {
                (*this.*pGetInputFrame)();
                //For AAC component , send one more frame apart from the config frame, so that we can receive the callback
                if (0 == oscl_strcmp(iFormat, "AAC") || 0 == oscl_strcmp(iFormat, "AMR"))
                {
                    (*this.*pGetInputFrame)();
                }
                iFlagDecodeHeader = OMX_TRUE;
                iFrameCount++;

                //Proceed to executing state and if Port settings changed callback comes,
                //then do the dynamic port reconfiguration
                iState = StateExecuting;

                RunIfNotReady();
            }
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateDecodeHeader OUT"));
        }
        break;

        case StateDisablePort:
        {
            OMX_ERRORTYPE Err = OMX_ErrorNone;
            OMX_U32 ii;

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateDisablePort IN"));

            if (!iDisableRun)
            {
                if (!iFlagDisablePort)
                {
                    Err = OMX_SendCommand(ipAppPriv->Handle, OMX_CommandPortDisable, iOutputPortIndex, NULL);
                    CHECK_ERROR(Err, "SendCommand_PortDisable");

                    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                    (0, "OmxDecTestReposition::Run() - Sent Command for OMX_CommandPortDisable on port %d as a part of dynamic port reconfiguration", iOutputPortIndex));

                    iPendingCommands = 1;
                    iFlagDisablePort = OMX_TRUE;
                    RunIfNotReady();
                }
                else
                {
                    //Wait for all the buffers to be returned on output port before freeing them
                    //This wait is required because of the queueing delay in all the Callbacks
                    for (ii = 0; ii < iOutBufferCount; ii++)
                    {
                        if (OMX_FALSE == ipOutReleased[ii])
                        {
                            break;
                        }
                    }

                    if (ii != iOutBufferCount)
                    {
                        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                        (0, "OmxDecTestReposition::Run() - Not all the output buffers returned by component yet, wait for it"));
                        RunIfNotReady();
                        break;
                    }

                    for (ii = 0; ii < iOutBufferCount; ii++)
                    {
                        if (ipOutBuffer[ii])
                        {
                            Err = OMX_FreeBuffer(ipAppPriv->Handle, iOutputPortIndex, ipOutBuffer[ii]);
                            CHECK_ERROR(Err, "FreeBuffer_Output_DynamicReconfig");
                            ipOutBuffer[ii] = NULL;

                            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                            (0, "OmxDecTestReposition::Run() - Called FreeBuffer for buffer index %d on port %d", ii, iOutputPortIndex));
                        }
                    }

                    if (ipOutBuffer)
                    {
                        oscl_free(ipOutBuffer);
                        ipOutBuffer = NULL;
                    }

                    if (ipOutReleased)
                    {
                        oscl_free(ipOutReleased);
                        ipOutReleased = NULL;
                    }

                    if (StateError == iState)
                    {
                        PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR,
                                        (0, "OmxDecTestReposition::Run() - Error occured in this state, StateDisablePort OUT"));
                        RunIfNotReady();
                        break;
                    }
                    iDisableRun = OMX_TRUE;
                }
            }

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateDisablePort OUT"));
        }
        break;

        case StateDynamicReconfig:
        {
            OMX_BOOL Status = OMX_TRUE;

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateDynamicReconfig IN"));

            Status = HandlePortReEnable();
            if (OMX_FALSE == Status)
            {
                PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR,
                                (0, "OmxDecTestReposition::Run() - Error occured in this state, StateDynamicReconfig OUT"));
                iState = StateError;
                RunIfNotReady();
                break;
            }

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateDynamicReconfig OUT"));
        }
        break;

        case StateExecuting:
        {
            OMX_U32 Index;
            OMX_BOOL MoreOutput;
            OMX_ERRORTYPE Err = OMX_ErrorNone;

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateExecuting IN"));

            //After Processing N number of buffers, send the flush command on both the ports
            if ((iFrameCount > TEST_NUM_BUFFERS_TO_PROCESS) && (OMX_FALSE == iRepositionCommandSent))
            {
                OMX_ERRORTYPE Err = OMX_ErrorNone;
                Err = OMX_SendCommand(ipAppPriv->Handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
                CHECK_ERROR(Err, "SendCommand Executing->Idle");

                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                (0, "OmxDecTestReposition::Run() - State transition command send from Executing ->Idle to indicate repositioning of the clip"));

                iPendingCommands = 1;
                iRepositionCommandSent = OMX_TRUE;
            }
            else
            {
                MoreOutput = OMX_TRUE;
                while (MoreOutput)
                {
                    Index = 0;
                    while (OMX_FALSE == ipOutReleased[Index] && Index < iOutBufferCount)
                    {
                        Index++;
                    }

                    if (Index != iOutBufferCount)
                    {
                        //This call is being made only once per frame
                        Err = OMX_FillThisBuffer(ipAppPriv->Handle, ipOutBuffer[Index]);
                        CHECK_ERROR(Err, "FillThisBuffer");
                        //Reset this till u receive the callback for output buffer free
                        ipOutReleased[Index] = OMX_FALSE;

                        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                        (0, "OmxDecTestReposition::Run() - FillThisBuffer command called for output buffer index %d", Index));
                    }
                    else
                    {
                        MoreOutput = OMX_FALSE;
                    }
                } //while (MoreOutput) loop end here


                if (!iStopProcessingInput || (OMX_ErrorInsufficientResources == iStatusExecuting))
                {
                    // find available input buffer
                    Index = 0;
                    while (OMX_FALSE == ipInputAvail[Index] && Index < iInBufferCount)
                    {
                        Index++;
                    }

                    if (Index != iInBufferCount)
                    {
                        iStatusExecuting = (*this.*pGetInputFrame)();
                        iFrameCount++;
                    }
                }
                else if (OMX_FALSE == iEosFlagExecuting)
                {
                    //Only send one successful dummy buffer with flag set to signal EOS
                    Index = 0;
                    while (OMX_FALSE == ipInputAvail[Index] && Index < iInBufferCount)
                    {
                        Index++;
                    }

                    if (Index != iInBufferCount)
                    {
                        ipInBuffer[Index]->nFlags |= OMX_BUFFERFLAG_EOS;
                        ipInBuffer[Index]->nFilledLen = 0;
                        Err = OMX_EmptyThisBuffer(ipAppPriv->Handle, ipInBuffer[Index]);

                        CHECK_ERROR(Err, "EmptyThisBuffer_EOS");

                        ipInputAvail[Index] = OMX_FALSE; // mark unavailable
                        iEosFlagExecuting = OMX_TRUE;

                        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                        (0, "OmxDecTestReposition::Run() - Input buffer sent to the component with OMX_BUFFERFLAG_EOS flag set"));
                    }
                }
                else
                {
                    //nothing to do here
                }

                RunIfNotReady();
            }
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateExecuting OUT"));

        }
        break;

        case StateIntermediate:
        {
            OMX_ERRORTYPE Err = OMX_ErrorNone;
            OMX_BOOL Status;

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG, (0, "OmxDecTestReposition::Run() - Repositioning the stream to the start"));

            Status = ResetStream();

            if (OMX_FALSE == Status)
            {
                iState = StateError;
                RunIfNotReady();
                break;
            }

            //Now resume processing by changing state to Executing again
            Err = OMX_SendCommand(ipAppPriv->Handle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
            CHECK_ERROR(Err, "SendCommand Idle->Executing");

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG, (0, "OmxDecTestReposition::Run() - Resume processing by state transition command from Idle->Executing"));

            iPendingCommands = 1;
        }
        break;


        case StateStopping:
        {
            OMX_ERRORTYPE Err = OMX_ErrorNone;

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateStopping IN"));

            //stop execution by state transition to Idle state.
            if (!iFlagStopping)
            {
                Err = OMX_SendCommand(ipAppPriv->Handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
                CHECK_ERROR(Err, "SendCommand Executing->Idle");

                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                (0, "OmxDecTestReposition::Run() - Sent State Transition Command from Executing->Idle"));

                iPendingCommands = 1;
                iFlagStopping = OMX_TRUE;
            }

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateStopping OUT"));
        }
        break;

        case StateCleanUp:
        {
            OMX_U32 ii;
            OMX_ERRORTYPE Err = OMX_ErrorNone;

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateCleanUp IN"));


            if (!iFlagCleanUp)
            {
                //Added a check here to verify whether all the ip/op buffers are returned back by the component or not
                //in case of Executing->Idle state transition

                if (OMX_FALSE == VerifyAllBuffersReturned())
                {
                    // not all buffers have been returned yet, reschedule
                    RunIfNotReady();
                    break;
                }

                //Destroy the component by state transition to Loaded state
                Err = OMX_SendCommand(ipAppPriv->Handle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
                CHECK_ERROR(Err, "SendCommand Idle->Loaded");

                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                (0, "OmxDecTestReposition::Run() - Sent State Transition Command from Idle->Loaded"));

                iPendingCommands = 1;

                if (ipInBuffer)
                {
                    for (ii = 0; ii < iInBufferCount; ii++)
                    {
                        if (ipInBuffer[ii])
                        {
                            Err = OMX_FreeBuffer(ipAppPriv->Handle, iInputPortIndex, ipInBuffer[ii]);
                            CHECK_ERROR(Err, "FreeBuffer_Input");
                            ipInBuffer[ii] = NULL;

                            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                            (0, "OmxDecTestReposition::Run() - Called FreeBuffer for buffer index %d on port %d", ii, iInputPortIndex));
                        }
                    }

                    oscl_free(ipInBuffer);
                    ipInBuffer = NULL;
                }

                if (ipInputAvail)
                {
                    oscl_free(ipInputAvail);
                    ipInputAvail = NULL;
                }


                if (ipOutBuffer)
                {
                    for (ii = 0; ii < iOutBufferCount; ii++)
                    {
                        if (ipOutBuffer[ii])
                        {
                            Err = OMX_FreeBuffer(ipAppPriv->Handle, iOutputPortIndex, ipOutBuffer[ii]);
                            CHECK_ERROR(Err, "FreeBuffer_Output");
                            ipOutBuffer[ii] = NULL;

                            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                            (0, "OmxDecTestReposition::Run() - Called FreeBuffer for buffer index %d on port %d", ii, iOutputPortIndex));
                        }
                    }
                    oscl_free(ipOutBuffer);
                    ipOutBuffer = NULL;
                }

                if (ipOutReleased)
                {
                    oscl_free(ipOutReleased);
                    ipOutReleased = NULL;
                }

                iFlagCleanUp = OMX_TRUE;
            }

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateCleanUp OUT"));

        }
        break;


        /********* FREE THE HANDLE & CLOSE FILES FOR THE COMPONENT ********/
        case StateStop:
        {
            OMX_U8 TestName[] = "REPOSITIONING_TEST";
            OMX_ERRORTYPE Err = OMX_ErrorNone;

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateStop IN"));

            if (ipAppPriv)
            {
                if (ipAppPriv->Handle)
                {
                    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                    (0, "OmxDecTestReposition::Run() - Free the Component Handle"));

                    Err = OMX_MasterFreeHandle(ipAppPriv->Handle);
                    if (OMX_ErrorNone != Err)
                    {
                        PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR, (0, "OmxDecTestReposition::Run() - FreeHandle Error"));
                        iTestStatus = OMX_FALSE;
                    }
                }
            }

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                            (0, "OmxDecTestReposition::Run() - De-initialize the omx component"));

            Err = OMX_MasterDeinit();
            if (OMX_ErrorNone != Err)
            {
                PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR, (0, "OmxDecTestReposition::Run() - OMX_MasterDeinit Error"));
                iTestStatus = OMX_FALSE;
            }

            if (0 == oscl_strcmp(iFormat, "H264"))
            {
                if (ipAVCBSO)
                {
                    OSCL_DELETE(ipAVCBSO);
                    ipAVCBSO = NULL;
                }
            }

            if (0 == oscl_strcmp(iFormat, "M4V") || 0 == oscl_strcmp(iFormat, "H263"))
            {
                if (ipBitstreamBuffer)
                {
                    oscl_free(ipBitstreamBufferPointer);
                    ipBitstreamBuffer = NULL;
                    ipBitstreamBufferPointer = NULL;
                }
            }

            if (0 == oscl_strcmp(iFormat, "MP3"))
            {
                if (ipMp3Bitstream)
                {
                    OSCL_DELETE(ipMp3Bitstream);
                    ipMp3Bitstream = NULL;
                }
            }

            if (iOutputParameters)
            {
                oscl_free(iOutputParameters);
                iOutputParameters = NULL;
            }

            if (ipAppPriv)
            {
                oscl_free(ipAppPriv);
                ipAppPriv = NULL;
            }

#if PROXY_INTERFACE
            if (ipThreadSafeHandlerEventHandler)
            {
                OSCL_DELETE(ipThreadSafeHandlerEventHandler);
                ipThreadSafeHandlerEventHandler = NULL;
            }

            if (ipThreadSafeHandlerEmptyBufferDone)
            {
                OSCL_DELETE(ipThreadSafeHandlerEmptyBufferDone);
                ipThreadSafeHandlerEmptyBufferDone = NULL;
            }

            if (ipThreadSafeHandlerFillBufferDone)
            {
                OSCL_DELETE(ipThreadSafeHandlerFillBufferDone);
                ipThreadSafeHandlerFillBufferDone = NULL;
            }
#endif

            if (ipOutputFile)
            {
                VerifyOutput(TestName);
            }
            else
            {
                if (OMX_FALSE == iTestStatus)
                {
#ifdef PRINT_RESULT
                    fprintf(iConsOutFile, "%s: Fail \n", TestName);
                    OMX_DEC_TEST(false);
                    iTestCase->TestCompleted();
#endif
                    PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_INFO,
                                    (0, "OmxDecTestReposition::Run() - %s : Fail", TestName));
                }
                else
                {
#ifdef PRINT_RESULT
                    fprintf(iConsOutFile, "%s: Success {Output file not available} \n", TestName);
                    OMX_DEC_TEST(true);
                    iTestCase->TestCompleted();
#endif
                    PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_INFO,
                                    (0, "OmxDecTestReposition::Run() - %s : Success {Output file not available}", TestName));
                }
            }

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateStop OUT"));

            iState = StateUnLoaded;
            OsclExecScheduler* sched = OsclExecScheduler::Current();
            sched->StopScheduler();
        }
        break;

        case StateError:
        {
            //Do all the cleanup's and exit from here
            OMX_U32 ii;

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateError IN"));

            iTestStatus = OMX_FALSE;

            if (ipInBuffer)
            {
                for (ii = 0; ii < iInBufferCount; ii++)
                {
                    if (ipInBuffer[ii])
                    {
                        OMX_FreeBuffer(ipAppPriv->Handle, iInputPortIndex, ipInBuffer[ii]);
                        ipInBuffer[ii] = NULL;

                        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                        (0, "OmxDecTestReposition::Run() - Called FreeBuffer for buffer index %d on port %d", ii, iInputPortIndex));
                    }
                }
                oscl_free(ipInBuffer);
                ipInBuffer = NULL;
            }

            if (ipInputAvail)
            {
                oscl_free(ipInputAvail);
                ipInputAvail = NULL;
            }

            if (ipOutBuffer)
            {
                for (ii = 0; ii < iOutBufferCount; ii++)
                {
                    if (ipOutBuffer[ii])
                    {
                        OMX_FreeBuffer(ipAppPriv->Handle, iOutputPortIndex, ipOutBuffer[ii]);
                        ipOutBuffer[ii] = NULL;

                        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                        (0, "OmxDecTestReposition::Run() - Called FreeBuffer for buffer index %d on port %d", ii, iOutputPortIndex));
                    }
                }
                oscl_free(ipOutBuffer);
                ipOutBuffer = NULL;
            }

            if (ipOutReleased)
            {
                oscl_free(ipOutReleased);
                ipOutReleased = NULL;
            }

            iState = StateStop;
            RunIfNotReady();

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestReposition::Run() - StateError OUT"));

        }
        break;

        default:
        {
            break;
        }
    }
    return ;
}
Пример #11
0
void process_dir_list(long dir_offset, long table_size, long data_size, FILE *infile)
{
    long data_offset = dir_offset + table_size;

    const uint32_t dir_count = get_32_le_seek(dir_offset, infile);
    dir_offset += 4;

    // offset to info on files
    long file_offset = dir_offset;

    // advance file offset to where file info starts
    for (uint32_t i = 0; i < dir_count; i++)
    {
        CHECK_ERROR(file_offset >= data_offset, "read beyond table");
        const uint32_t name_size = get_32_le_seek(file_offset, infile);
        file_offset += 4 + name_size;
    }

    // dirs
    for (uint32_t i = 0; i < dir_count; i++)
    {
        CHECK_ERROR(dir_offset >= data_offset, "read beyond table");

        const uint32_t dir_name_size = get_32_le_seek(dir_offset, infile);
        dir_offset +=4 ;

        dump(infile, stdout, dir_offset, dir_name_size);
        printf("\n");
        dir_offset += dir_name_size;

        if (file_offset == data_offset) break;

        const uint32_t file_count = get_32_le_seek(file_offset, infile);
        file_offset += 4;

        // contents of dir
        for (uint32_t j = 0; j < file_count; j++)
        {
            CHECK_ERROR(file_offset >= data_offset, "read beyond table");
            const uint32_t file_name_size = get_32_le_seek(file_offset, infile);
            file_offset += 4;

            printf("  ");
            dump(infile, stdout, file_offset, file_name_size);
            file_offset += file_name_size;

            CHECK_ERROR(get_32_le_seek(file_offset, infile) != 0, "zernooo");
            const uint32_t offset = get_32_le_seek(file_offset+4, infile)+data_offset;
            const uint32_t size = get_32_le_seek(file_offset+8, infile);
            printf(": offset 0x%"PRIx32" size 0x%"PRIx32"\n",offset,size);
            {
                unsigned char namebuf[file_name_size+1];
                get_bytes_seek(file_offset-file_name_size,infile,namebuf,file_name_size);
                namebuf[file_name_size-1]='\0';
                FILE *outfile = fopen((char*)namebuf,"wb");
                CHECK_ERRNO(outfile == NULL,"fopen");
                dump(infile, outfile, offset+0x38, size-0x38);
                CHECK_ERRNO(fclose(outfile) == EOF,"fclose");
            }
            file_offset += 0xc;
        }
    }
}
Пример #12
0
main(int argc, char *argv[]) {
    GLUquadric *quad;

    glutInit(&argc, argv);
    glutInitWindowSize(winWidth, winHeight);
    glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE);
    (void)glutCreateWindow("locate");
    glutDisplayFunc(redraw);
    glutReshapeFunc(reshape);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(key);
    create_menu();

    glClearColor(0.0f, 0.3f, 0.0f, 0.f);
    /* draw a perspective scene */
    glMatrixMode(GL_PROJECTION);
    glFrustum(-100., 100., -100., 100., 300., 600.); 
    glMatrixMode(GL_MODELVIEW);
    /* look at scene from (0, 0, 450) */
    gluLookAt(0., 0., 450., 0., 0., 0., 0., 1., 0.);
    {
    int i;
    float mat[16];
    glGetFloatv(GL_MODELVIEW_MATRIX, mat);
    for(i = 0; i < 4; i++)
	printf("%f %f %f %f\n", mat[4*i+0], mat[4*i+1], mat[4*i+2], mat[4*i+3]);
    }

    glEnable(GL_DEPTH_TEST);

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_COLOR_MATERIAL);
    
    glCullFace(GL_BACK);
    glReadBuffer(GL_BACK);
    glDisable(GL_DITHER);

    CHECK_ERROR("end of main");

    glNewList(1, GL_COMPILE);
    glutSolidCube(50.f);
    glEndList();

    glNewList(2, GL_COMPILE);
    glutSolidTeapot(50.f);
    glEndList();

    quad = gluNewQuadric();
    gluQuadricTexture(quad, GL_TRUE);

    glNewList(3, GL_COMPILE);
    gluSphere(quad, 70., 20, 20);
    glEndList();

    gluDeleteQuadric(quad);

    glNewList(4, GL_COMPILE);
    glutSolidTorus(20, 50, 20, 20);
    glEndList();

    glNewList(5, GL_COMPILE);
    glPushMatrix();
    glTranslatef(0.f, -80.f, 0.f);
    cylinder(40, 3, 20, 160);
    glTranslatef(0.f, 20.f, 0.f);
    cylinder(40, 3, 60, 20);
    glTranslatef(0.f, 20.f, 0.f);
    cylinder(40, 3, 30, 20);
    glTranslatef(0.f, 60.f, 0.f);
    cylinder(40, 3, 30, 20);
    glTranslatef(0.f, 20.f, 0.f);
    cylinder(40, 3, 60, 20);
    glPopMatrix();
    glEndList();

    glNewList(6, GL_COMPILE);
    glPushMatrix();
    glTranslatef(0.f, -80.f, 0.f);
    cylinder(40, 3, 80, 160);
    glPopMatrix();
    glEndList();

    maxobject = 6;
    {
    GLubyte* tex;
    int texwid, texht, texcomps;
    tex = (GLubyte*)read_texture("../../data/spheremap.rgb", &texwid, &texht, &texcomps);
    glBindTexture(GL_TEXTURE_2D, 1);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texwid, texht, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    free(tex);
    }
    {

    GLubyte tex2[1024];
    int i;
    for(i = 0; i < 1024; i++) {
	if ((i/10)&1)
	    tex2[i] = 0;
	else tex2[i] = 255;
    }
    glBindTexture(GL_TEXTURE_2D, 2);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 1024, 1, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, tex2);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    }

    glutMainLoop();
    return 0;
}
Пример #13
0
int main(int argc, char **argv) {

	pmix_status_t status;
	pmix_proc_t proc;

	sleep(30);

	status = PMIx_Init(&proc, NULL, 0);
	CHECK_ERROR(status, "PMIx_Init()");
	printf("PMIx_Init() succeeded: nspace '%s' rank %d\n", proc.nspace,
		proc.rank);

	if (!PMIx_Initialized()) {
	    printf("PMIx_Initialized() returned false.\n");
	    return -1;
	}
	printf("PMIx_Initialized() returned true.\n");

	sleep(2);

	pmix_value_t val;
	PMIX_VAL_ASSIGN(&val, string, "My test value");
	//PMIX_VAL_SET(&val, string, "My test value");
	status = PMIx_Put(PMIX_GLOBAL, "MyStringKey", &val);
	CHECK_ERROR(status, "PMIx_Put(MyStringKey)");

	sleep(2);

	PMIX_VAL_SET(&val, int, 42);
	status = PMIx_Put(PMIX_GLOBAL, "MyIntKey", &val);
	CHECK_ERROR(status, "PMIx_Put(MyIntKey)");

	sleep(2);

	status = PMIx_Commit();
	CHECK_ERROR(status, "PMIx_Commit()");

	sleep(2);

	pmix_value_t *retval;
	status = PMIx_Get(&proc, "MyStringKey", NULL, 0, &retval);
	CHECK_ERROR(status, "PMIx_Get(MyStringKey)");
	if (retval == NULL) {
	    printf("PMIx_Get(MyStringKey) failed: retval == NULL\n");
	    return -1;
	}
	if (retval->type != PMIX_VAL_TYPE_string) {
	    printf("PMIx_Get(MyStringKey) failed: type == %s\n",
		    PMIx_Data_type_string(retval->type));
	    return -1;
	}
	printf("PMIx_Get(MyStringKey) succeeded: value '%s'\n",
		PMIX_VAL_FIELD_string(retval));

	sleep(2);

	status = PMIx_Get(&proc, "MyIntKey", NULL, 0, &retval);
	CHECK_ERROR(status, "PMIx_Get(MyIntKey)");
	if (retval == NULL) {
	    printf("PMIx_Get(MyIntKey) failed: retval == NULL\n");
	    return -1;
	}
	if (retval->type != PMIX_VAL_TYPE_int) {
	    printf("PMIx_Get(MyIntKey) failed: type == %s\n",
		    PMIx_Data_type_string(retval->type));
	    return -1;
	}
	printf("PMIx_Get(MyIntKey) succeeded: value %d\n",
		PMIX_VAL_FIELD_int(retval));


	sleep(2);

	status = PMIx_Finalize(NULL, 0);
	CHECK_ERROR(status, "PMIx_Finalize()");

    return 0;
}
Пример #14
0
//=============================================================================
// Main Function
//=============================================================================
int 
main( int /* argc */, char* /* argv[] */ )
{
   FlyCaptureError   error;
   FlyCaptureContext context;   

   bool	             bOn;

   unsigned int      uiCurTime     = 0;
   unsigned int      uiLastTime    = 0;
   unsigned int      uiTotalTime   = 0;
   unsigned int      uiSeconds     = 0;
   unsigned int      uiCount	   = 0;
   unsigned int      uiOffset      = 0;

   double            dGrabTime     = 0.0;

   //
   // Create context
   //
   error = ::flycaptureCreateContext( &context );
   CHECK_ERROR( "flycaptureCreateContext()", error );

   //
   // Initialize first camera on the bus.
   //
   error = ::flycaptureInitialize( context, 0 );
   CHECK_ERROR( "flycaptureInitialize()", error );

   //
   // Reset the camera to default factory settings by asserting bit 0
   //
   error = flycaptureSetCameraRegister( context, INITIALIZE, 0x80000000 );
   CHECK_ERROR( "flycaptureSetCameraRegister()", error );

   //
   // Power-up the camera (for cameras that support this feature)
   //
   error = flycaptureSetCameraRegister( context, CAMERA_POWER, 0x80000000 );
   CHECK_ERROR( "flycaptureSetCameraRegister()", error );

   //
   // Enable image timestamping
   //
   error = ::flycaptureGetImageTimestamping( context, &bOn );
   CHECK_ERROR( "flycaptureGetImageTimestamping()", error );

   if( !bOn )
   {
      error = ::flycaptureSetImageTimestamping( context, true );
      CHECK_ERROR( "flycaptureSetImageTimestamping()", error );
   }

   //
   // Query and report on the camera's ability to handle custom image modes.
   //
   bool		  bAvailable;
   unsigned int	  uiMaxImageSizeCols;
   unsigned int	  uiMaxImageSizeRows;
   unsigned int	  uiImageUnitSizeHorz;
   unsigned int	  uiImageUnitSizeVert;
   unsigned int   uiOffsetUnitSizeHorz;
   unsigned int   uiOffsetUnitSizeVert;
   unsigned int   uiPixelFormats;

   error = ::flycaptureQueryCustomImageEx(
      context,
      MODE,
      &bAvailable,
      &uiMaxImageSizeCols,
      &uiMaxImageSizeRows,
      &uiImageUnitSizeHorz,
      &uiImageUnitSizeVert,
      &uiOffsetUnitSizeHorz,
      &uiOffsetUnitSizeVert,
      &uiPixelFormats );
   CHECK_ERROR( "flycaptureQueryCustomImage()", error );

   if( !bAvailable )
   {
      printf( 
         "Warning!  Camera reports that mode %u is not available.\n",
         MODE );
   }

   printf( 
      "Max image pizels: (%u, %u)\n"
      "Image Unit size: (%u, %u)\n"
      "Offset Unit size: (%u, %u)\n"
      "Pixel format bitfield: 0x%08x\n",
      uiMaxImageSizeCols,
      uiMaxImageSizeRows,
      uiImageUnitSizeHorz,
      uiImageUnitSizeVert,
      uiOffsetUnitSizeHorz,
      uiOffsetUnitSizeVert,
      uiPixelFormats );

   if( ( PIXEL_FORMAT & uiPixelFormats ) == 0 )
   {
      printf( 
         "Warning!  "
         "Camera reports that the requested pixel format is not supported!.\n",
         MODE );
   }

   //
   // Start camera using custom image size mode.
   //
   error = ::flycaptureStartCustomImage(
      context, 
      MODE, 
      START_COL, 
      START_ROW, 
      COLS, 
      ROWS, 
      SPEED, 
      PIXEL_FORMAT );
   CHECK_ERROR( "flycaptureStartCustomImage()", error );


   //
   // Grab a series of images, computing the time difference
   // between consecutive images.
   //
   FlyCaptureImage image = { 0 };
   for( int iImage = 0; iImage < IMAGES_TO_GRAB; iImage++ )
   {
      //
      // Grab an image
      //
      error = ::flycaptureGrabImage2( context, &image );
      CHECK_ERROR( "flycaptureGrabImage2()", error );

      //
      // Calculate the time difference between current and last image
      // in order to calculate actual frame rate
      //
      error = ::flycaptureParseImageTimestamp( context,
					       image.pData,
					       &uiSeconds,
					       &uiCount,
					       &uiOffset );
      CHECK_ERROR( "flycaptureParseImageTimestamp()", error );
      
      uiCurTime = (uiSeconds * 8000) + uiCount;
      
      if( iImage == 0 )
      {
	 uiLastTime = uiCurTime;
	 uiTotalTime = 0;
      }
      else
      {
	 uiTotalTime = uiTotalTime + (uiCurTime - uiLastTime);
	 uiLastTime = uiCurTime;
      }
      
      //
      // Print info.
      //
      printf(
	 "Image %03d: %d x %d %d %d %d %d\n",
	 iImage,
	 image.iCols,
	 image.iRows,
	 image.timeStamp.ulSeconds,
	 image.timeStamp.ulMicroSeconds,
	 image.timeStamp.ulCycleSeconds,
	 image.timeStamp.ulCycleCount  );
   }

   // 
   // Convert to a frames per second number
   //
   dGrabTime = (double)(1 / ( ((double)uiTotalTime / (double)8000) 
	       / IMAGES_TO_GRAB ));
   printf("Frame rate: %lfHz\n", dGrabTime );

   //
   // Save the last image to disk
   //
   printf( "Saving last image..." );
   saveFinalImage(context, &image);
   printf( "done\n" );

   //
   // stop the camera and destroy the context.
   //
   ::flycaptureStop( context );
   ::flycaptureDestroyContext( context );

   return 0;
}
Пример #15
0
int main(int argc, char **argv)
{
   
  int num_points; // number of vectors
  int num_means; // number of clusters
  int dim;       // Dimension of each vector
  int grid_size; // size of each dimension of vector space
   int num_procs, curr_point;
   int i;
   pthread_t pid[256];
   pthread_attr_t attr;
   int num_per_thread, excess; 
  
   num_points = DEF_NUM_POINTS;
   num_means = DEF_NUM_MEANS;
   dim = DEF_DIM;
   grid_size = DEF_GRID_SIZE;
   
   {
     int c;
     extern char *optarg;
     extern int optind;
     
     while ((c = getopt(argc, argv, "d:c:p:s:")) != EOF) 
       {
	 switch (c) {
         case 'd':
	   dim = atoi(optarg);
	   break;
         case 'c':
	   num_means = atoi(optarg);
	   break;
         case 'p':
	   num_points = atoi(optarg);
	   break;
         case 's':
	   grid_size = atoi(optarg);
	   break;
         case '?':
	   printf("Usage: %s -d <vector dimension> -c <num clusters> -p <num points> -s <grid size>\n", argv[0]);
	   exit(1);
	 }
       }
   
     if (dim <= 0 || num_means <= 0 || num_points <= 0 || grid_size <= 0) {
       printf("Illegal argument value. All values must be numeric and greater than 0\n");
       exit(1);
     }
   }

   printf("Dimension = %d\n", dim);
   printf("Number of clusters = %d\n", num_means);
   printf("Number of points = %d\n", num_points);
   printf("Size of each dimension = %d\n", grid_size);   
   
   int ** points = (int **)malloc(sizeof(int *) * num_points);
   for (i=0; i<num_points; i++) 
   {
      points[i] = (int *)malloc(sizeof(int) * dim);
   }
   
   dprintf("Generating points\n");
   generate_points(points, num_points, dim, grid_size);
   
   int **means;

   means = (int **)malloc(sizeof(int *) * num_means);
   for (i=0; i<num_means; i++) 
   {
   //   means[i] = (int *)malloc(sizeof(int) * dim);
      means[i] = (int *)malloc(128);
   }
   dprintf("Generating means\n");
   generate_points(means, num_means, dim, grid_size);
 
   int * clusters = (int *)malloc(sizeof(int) * num_points);
   memset(clusters, -1, sizeof(int) * num_points);
   
   
   pthread_attr_init(&attr);
   pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
   CHECK_ERROR((num_procs = sysconf(_SC_NPROCESSORS_ONLN)) <= 0); // FIX ME
   //CHECK_ERROR((num_procs = 4 * sysconf(_SC_NPROCESSORS_ONLN)) <= 0); // FIX ME
      
   //   CHECK_ERROR( (pid = (pthread_t *)malloc(sizeof(pthread_t) * num_procs)) == NULL);


   int modified = true; 
   
   printf("Starting iterative algorithm!!!!!!\n");
   
   /* Create the threads to process the distances between the various
   points and repeat until modified is no longer valid */
   int num_threads;   
   thread_arg arg[256];
   while (modified) 
   {
      num_per_thread = num_points / num_procs;
      excess = num_points % num_procs;
      modified = false;
      dprintf(".");
      curr_point = 0;
      num_threads = 0;
      
      while (curr_point < num_points) {
	//	CHECK_ERROR((arg = (thread_arg *)malloc(sizeof(thread_arg))) == NULL);
         arg[num_threads].start_idx = curr_point;
         arg[num_threads].num_pts = num_per_thread;
	     arg[num_threads].dim = dim;
	     arg[num_threads].num_means = num_means;
	     arg[num_threads].num_points = num_points;
	     arg[num_threads].means = means;
	     arg[num_threads].points = points;
	     arg[num_threads].clusters = clusters;

         if (excess > 0) {
            arg[num_threads].num_pts++;
            excess--;            
         }
         curr_point += arg[num_threads].num_pts;
	     num_threads++;
      }

//	  printf("in this run, num_threads is %d, num_per_thread is %d\n", num_threads, num_per_thread);
      
	  for (i = 0; i < num_threads; i++) {
         CHECK_ERROR((pthread_create(&(pid[i]), &attr, find_clusters,
                                                   (void *)(&arg[i]))) != 0);
	 // EDB - with hierarchical commit we would not have had to
	 // "localize" num_threads.
      }
      
      assert (num_threads == num_procs);
      for (i = 0; i < num_threads; i++) {
	     int m;
	     pthread_join(pid[i], (void *) &m);
	     modified |= m;
      }
      
      num_per_thread = num_means / num_procs;
      excess = num_means % num_procs;
      curr_point = 0;
      num_threads = 0;

      assert (dim <= MAX_DIM);
	//  printf("in this run again, num_threads is %d, num_per_thread is %d\n", num_threads, num_per_thread);

      while (curr_point < num_means) {
	//	CHECK_ERROR((arg = (thread_arg *)malloc(sizeof(thread_arg))) == NULL);
	    arg[num_threads].start_idx = curr_point;
	//	arg[num_threads].sum = (int *)malloc(dim * sizeof(int));
	    arg[num_threads].num_pts = num_per_thread;
	    if (excess > 0) {
	        arg[num_threads].num_pts++;
	        excess--;            
	    }
	    curr_point += arg[num_threads].num_pts;
	    num_threads++;
      }

      for (i = 0; i < num_threads; i++) {
         CHECK_ERROR((pthread_create(&(pid[i]), &attr, calc_means,
                                                   (void *)(&arg[i]))) != 0);
      }

//      printf ("num threads = %d\n", num_threads);
//      printf ("num procs = %d\n", num_procs);

      assert (num_threads == num_procs);
      for (i = 0; i < num_threads; i++) {
		pthread_join(pid[i], NULL);
	 //	 free (arg[i].sum);
      }
      
   }
   
      
   dprintf("\n\nFinal means:\n");
   //dump_points(means, num_means, dim);

   for (i = 0; i < num_points; i++) 
      free(points[i]);
   free(points);
   
   for (i = 0; i < num_means; i++) 
   {
      free(means[i]);
   }
   free(means);
   free(clusters);

   return 0;
}
Пример #16
0
result_t JsonRpcHandler::invoke(object_base *v, obj_ptr<Handler_base> &retVal,
                                AsyncEvent *ac)
{
    if (ac)
        return CHECK_ERROR(CALL_E_NOASYNC);

    obj_ptr<Message_base> msg = Message_base::getInstance(v);
    if (msg == NULL)
        return CHECK_ERROR(CALL_E_BADVARTYPE);

    Isolate* isolate = Isolate::now();
    obj_ptr<HttpRequest_base> htreq = HttpRequest_base::getInstance(v);
    obj_ptr<SeekableStream_base> body;
    obj_ptr<Buffer_base> buf;
    v8::Local<v8::Value> jsval;
    v8::Local<v8::Object> o;
    Variant result;
    std::string str;
    int64_t len;
    int32_t sz, i;
    result_t hr;
    bool bFormReq = false;
    obj_ptr<List_base> params;

    if (htreq != NULL)
    {
        if (htreq->firstHeader("Content-Type", result) == CALL_RETURN_NULL)
            return CHECK_ERROR(Runtime::setError("jsonrpc: Content-Type is missing."));

        str = result.string();
        if (!qstricmp(str.c_str(), "application/x-www-form-urlencoded", 33))
        {
            obj_ptr<HttpCollection_base> form;
            htreq->get_form(form);
            if (form->first("jsonrpc", result) == CALL_RETURN_NULL)
                return CHECK_ERROR(Runtime::setError("jsonrpc: Invalid form data."));
            str = result.string();
            bFormReq = true;
        }
        else if (qstricmp(str.c_str(), "application/json", 16))
            return CHECK_ERROR(Runtime::setError("jsonrpc: Invalid Content-Type."));
    }

    if (!bFormReq)
    {
        msg->get_body(body);

        body->size(len);
        sz = (int32_t) len;

        body->rewind();
        hr = body->ac_read(sz, buf);
        if (hr < 0)
            return hr;
        if (hr == CALL_RETURN_NULL)
            return CHECK_ERROR(Runtime::setError("jsonrpc: request body is empty."));
        body.Release();

        buf->toString(str);
        buf.Release();
    }

    hr = encoding_base::jsonDecode(str.c_str(), jsval);
    if (hr < 0)
        return hr;

    if (!jsval->IsObject())
        return CHECK_ERROR(Runtime::setError("jsonrpc: Invalid rpc request."));

    o = v8::Local<v8::Object>::Cast(jsval);

    jsval = o->Get(v8::String::NewFromUtf8(isolate->m_isolate, "method",
                                           v8::String::kNormalString, 6));
    if (IsEmpty(jsval))
        return CHECK_ERROR(Runtime::setError("jsonrpc: method is missing."));

    msg->get_value(str);
    str += '/';
    str.append(*v8::String::Utf8Value(jsval));
    msg->set_value(str.c_str());

    jsval = o->Get(v8::String::NewFromUtf8(isolate->m_isolate, "params",
                                           v8::String::kNormalString, 6));
    if (!jsval.IsEmpty() && jsval->IsArray())
    {
        v8::Local<v8::Array> jsparams = v8::Local<v8::Array>::Cast(jsval);

        sz = jsparams->Length();
        msg->get_params(params);
        params->resize(sz);

        for (i = 0; i < sz; i++)
            params->_indexed_setter(i, jsparams->Get(i));
    }

    obj_ptr<Handler_base> hdlr1;
    hr = JSHandler::js_invoke(m_handler, v, hdlr1, NULL);
    if (hr >= 0 && hr != CALL_RETURN_NULL)
        hr = mq_base::ac_invoke(hdlr1, v);

    v8::Local<v8::String> strId = v8::String::NewFromUtf8(isolate->m_isolate, "id",
                                  v8::String::kNormalString, 2);
    jsval = o->Get(strId);

    o = v8::Object::New(isolate->m_isolate);
    o->Set(strId, jsval);

    if (hr < 0)
    {
        asyncLog(console_base::_ERROR, "JsonRpcHandler: " + getResultMessage(hr));

        result_t hr1 = encoding_base::jsonEncode(o, str);
        if (hr1 < 0)
            return hr1;

        if (str.length() <= 2)
            str.assign("{", 1);
        else
        {
            str.resize(str.length() - 1);
            str += ',';
        }

        if (hr == CALL_E_INVALID_CALL)
            str.append(
                "\"error\": {\"code\": -32601, \"message\": \"Method not found.\"}}");
        else
            str.append(
                "\"error\": {\"code\": -32603, \"message\": \"Internal error.\"}}");
    }
    else
    {
        msg->get_result(result);
        o->Set(v8::String::NewFromUtf8(isolate->m_isolate, "result",
                                       v8::String::kNormalString, 6), result);

        hr = encoding_base::jsonEncode(o, str);

        if (hr < 0)
            return hr;
    }

    body = new MemoryStream();

    if (bFormReq)
    {
        std::string strTemp;

        strTemp.assign(
            "<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><script>window.name=\"",
            94);

        encoding_base::jsstr(str.c_str(), false, str);
        strTemp.append(str);

        strTemp.append("\";</script></html>", 18);

        str = strTemp;
    }

    buf = new Buffer(str);
    hr = body->ac_write(buf);
    if (hr < 0)
        return hr;


    obj_ptr<Message_base> rep;
    hr = msg->get_response(rep);
    if (hr < 0)
        return hr;

    rep->set_body(body);

    if (htreq)
        ((HttpMessage_base *)(Message_base *)rep)->setHeader("Content-Type",
                bFormReq ? "text/html" : "application/json");

    return CALL_RETURN_NULL;
}
Пример #17
0
result_t X509Req::sign(const char *issuer, PKey_base *key,
                       v8::Local<v8::Object> opts, obj_ptr<X509Cert_base> &retVal,
                       exlib::AsyncEvent *ac)
{
    result_t hr;
    bool priv;

    hr = key->isPrivate(priv);
    if (hr < 0)
        return hr;

    if (!priv)
        return CHECK_ERROR(CALL_E_INVALIDARG);

    int ret;
    std::string subject;
    pk_context *pk;
    int32_t hash;
    std::string buf;
    obj_ptr<X509Cert> cert;

    if (!ac)
    {
        mpi serial;
        v8::Local<v8::Value> v;

        x509write_crt_init(&m_crt);

        hr = GetConfigValue(opts, "hash", hash);
        if (hr == CALL_E_PARAMNOTOPTIONAL)
            hash = m_csr.sig_md;
        else if (hr < 0)
            goto exit;

        if (hash < POLARSSL_MD_MD2 || hash > POLARSSL_MD_RIPEMD160)
        {
            hr = CALL_E_INVALIDARG;
            goto exit;
        }

        x509write_crt_set_md_alg(&m_crt, POLARSSL_MD_SHA1);

        v = opts->Get(v8::String::NewFromUtf8(isolate, "serial",
                                              v8::String::kNormalString, 6));
        if (!IsEmpty(v))
        {
            v8::String::Utf8Value str(v);

            if (!*str)
            {
                hr = CHECK_ERROR(_ssl::setError(POLARSSL_ERR_MPI_BAD_INPUT_DATA));
                goto exit;
            }

            mpi_init(&serial);
            ret = mpi_read_string(&serial, 10, *str);
            if (ret != 0)
            {
                mpi_free(&serial);
                hr = CHECK_ERROR(_ssl::setError(ret));
                goto exit;
            }
        }
        else
        {
            mpi_init(&serial);
            mpi_lset(&serial, 1);
        }

        ret = x509write_crt_set_serial(&m_crt, &serial);
        if (ret != 0)
        {
            mpi_free(&serial);
            hr = CHECK_ERROR(_ssl::setError(ret));
            goto exit;
        }

        mpi_free(&serial);

        date_t d1, d2;
        std::string s1, s2;

        hr = GetConfigValue(opts, "notBefore", d1);
        if (hr == CALL_E_PARAMNOTOPTIONAL)
            d1.now();
        else if (hr < 0)
            goto exit;
        d1.toX509String(s1);


        hr = GetConfigValue(opts, "notAfter", d2);
        if (hr == CALL_E_PARAMNOTOPTIONAL)
        {
            d2 = d1;
            d2.add(1, date_t::_YEAR);
        }
        else if (hr < 0)
            goto exit;
        d2.toX509String(s2);

        ret = x509write_crt_set_validity(&m_crt, s1.c_str(), s2.c_str());
        if (ret != 0)
        {
            hr = CHECK_ERROR(_ssl::setError(ret));
            goto exit;
        }

        bool is_ca = false;
        hr = GetConfigValue(opts, "ca", is_ca);
        if (hr < 0 && hr != CALL_E_PARAMNOTOPTIONAL)
            goto exit;

        int32_t pathlen = -1;
        hr = GetConfigValue(opts, "pathlen", pathlen);
        if (hr < 0 && hr != CALL_E_PARAMNOTOPTIONAL)
            goto exit;

        if (pathlen < -1 || pathlen > 127)
        {
            hr = CALL_E_INVALIDARG;
            goto exit;
        }

        ret = x509write_crt_set_basic_constraints(&m_crt, is_ca ? 1 : 0, pathlen);
        if (ret != 0)
        {
            hr = CHECK_ERROR(_ssl::setError(ret));
            goto exit;
        }

        int key_usage = parseString(opts->Get(v8::String::NewFromUtf8(isolate, "usage",
                                              v8::String::kNormalString, 5)), X509Cert::g_usages);
        if (key_usage < 0)
        {
            hr = key_usage;
            goto exit;
        }
        else if (key_usage)
        {
            ret = x509write_crt_set_key_usage(&m_crt, key_usage);
            if (ret != 0)
            {
                hr = CHECK_ERROR(_ssl::setError(ret));
                goto exit;
            }
        }

        int cert_type = parseString(opts->Get(v8::String::NewFromUtf8(isolate, "type",
                                              v8::String::kNormalString, 4)), X509Cert::g_types);
        if (cert_type < 0)
        {
            hr = cert_type;
            goto exit;
        }
        else if (cert_type)
        {
            ret = x509write_crt_set_ns_cert_type(&m_crt, cert_type);
            if (ret != 0)
            {
                hr = CHECK_ERROR(_ssl::setError(ret));
                goto exit;
            }
        }

        return CHECK_ERROR(CALL_E_NOSYNC);
    }

    pk = &((PKey *)key)->m_key;

    x509write_crt_set_subject_key(&m_crt, &m_csr.pk);
    x509write_crt_set_issuer_key(&m_crt, pk);

    hr = X509Req::get_subject(subject);
    if (hr < 0)
        goto exit;

    ret = x509write_crt_set_subject_name(&m_crt, subject.c_str());
    if (ret != 0)
    {
        hr = CHECK_ERROR(_ssl::setError(ret));
        goto exit;
    }

    ret = x509write_crt_set_issuer_name(&m_crt, issuer);
    if (ret != 0)
    {
        hr = CHECK_ERROR(_ssl::setError(ret));
        goto exit;
    }

    ret = x509write_crt_set_subject_key_identifier(&m_crt);
    if (ret != 0)
    {
        hr = CHECK_ERROR(_ssl::setError(ret));
        goto exit;
    }

    ret = x509write_crt_set_authority_key_identifier(&m_crt);
    if (ret != 0)
    {
        hr = CHECK_ERROR(_ssl::setError(ret));
        goto exit;
    }

    buf.resize(pk_get_size(pk) * 8 + 128);

    ret = x509write_crt_pem(&m_crt, (unsigned char *)&buf[0], buf.length(),
                            ctr_drbg_random, &g_ssl.ctr_drbg);
    if (ret < 0)
    {
        hr = CHECK_ERROR(_ssl::setError(ret));
        goto exit;
    }

    cert = new X509Cert();
    hr = cert->load(buf.c_str());
    if (hr < 0)
        goto exit;

    retVal = cert;

exit:
    x509write_crt_free(&m_crt);

    return hr;
}
Пример #18
0
int main(int argc, char *argv[]) 
{
   
   int fd_A, fd_B, fd_out;
   char * fdata_A, *fdata_B, *fdata_out;
   int matrix_len, file_size;
   struct stat finfo_A, finfo_B;
   char * fname_A, *fname_B,*fname_out;

   srand( (unsigned)time( NULL ) );

   // Make sure a filename is specified
   if (argv[1] == NULL)
   {
      printf("USAGE: %s [side of matrix]\n", argv[0]);
      exit(1);
   }

   fname_A = "matrix_file_A.txt";
   fname_B = "matrix_file_B.txt";
   fname_out = "matrix_file_out_serial.txt";
   CHECK_ERROR ( (matrix_len = atoi(argv[1])) < 0);
   file_size = ((matrix_len*matrix_len))*sizeof(int);

   printf("MatrixMult: Side of the matrix is %d \n", matrix_len);
   printf("MatrixMult: Running...\n");

   
   int value = 0, i, j;

   // Read in the file
   CHECK_ERROR((fd_A = open(fname_A,O_RDONLY)) < 0);
   // Get the file info (for file length)
   CHECK_ERROR(fstat(fd_A, &finfo_A) < 0);
   // Memory map the file
   CHECK_ERROR((fdata_A= mmap(0, file_size + 1,
      PROT_READ | PROT_WRITE, MAP_PRIVATE, fd_A, 0)) == NULL);

   // Read in the file
   CHECK_ERROR((fd_B = open(fname_B,O_RDONLY)) < 0);
   // Get the file info (for file length)
   CHECK_ERROR(fstat(fd_B, &finfo_B) < 0);
   // Memory map the file
   CHECK_ERROR((fdata_B= mmap(0, file_size + 1,
      PROT_READ | PROT_WRITE, MAP_PRIVATE, fd_B, 0)) == NULL);
   
   // Create File
   CHECK_ERROR((fd_out = open(fname_out,O_CREAT | O_RDWR,S_IRWXU)) < 0);
   // Resize
   CHECK_ERROR(ftruncate(fd_out, file_size) < 0);
   // Memory Map
   CHECK_ERROR((fdata_out= mmap(0, file_size + 1,
      PROT_READ | PROT_WRITE, MAP_PRIVATE, fd_out, 0)) == NULL);

   // Setup splitter args
   mm_data_t mm_data;
   mm_data.matrix_len = matrix_len;
   mm_data.matrix_A  = ((int *)fdata_A);
   mm_data.matrix_B  = ((int *)fdata_B);
   mm_data.matrix_out  = ((int *)fdata_out);
   

   printf("MatrixMult: Calling Serial Matrix Multiplication\n");

   //gettimeofday(&starttime,0);
   
   
   memset(mm_data.matrix_out, 0, file_size);
   matrix_mult(&mm_data);


   //printf("MatrixMult: Multiply Completed time = %ld\n", (endtime.tv_sec - starttime.tv_sec));

   CHECK_ERROR(munmap(fdata_A, file_size + 1) < 0);
   CHECK_ERROR(close(fd_A) < 0);

   CHECK_ERROR(munmap(fdata_B, file_size + 1) < 0);
   CHECK_ERROR(close(fd_B) < 0);

   CHECK_ERROR(close(fd_out) < 0);

   return 0;
}
Пример #19
0
result_t X509Cert::load(exlib::string txtCert)
{
    if (m_root)
        return CHECK_ERROR(CALL_E_INVALID_CALL);

    int32_t ret;

    if (qstrstr(txtCert.c_str(), "BEGIN CERTIFICATE"))
    {
        ret = mbedtls_x509_crt_parse(&m_crt, (const unsigned char *)txtCert.c_str(),
                                     txtCert.length() + 1);
        if (ret != 0)
            return CHECK_ERROR(_ssl::setError(ret));

        return 0;
    }

    _parser p(txtCert);
    QuickArray<std::pair<exlib::string, exlib::string> > values;
    std::map<exlib::string, bool> verifies;
    std::map<exlib::string, bool> certs;

    while (!p.end())
    {
        exlib::string cka_label;
        exlib::string cka_value;
        exlib::string cka_serial;
        exlib::string _value;
        bool in_multiline = false, in_obj = false;
        bool is_cert = false;
        bool is_trust = false;
        bool is_value = false;
        bool is_serial = false;
        bool is_ca = false;
        bool is_verify = false;

        while (!p.end())
        {
            exlib::string line;
            exlib::string cmd, type, value;

            p.getLine(line);
            _parser p1(line);

            p1.skipSpace();
            if (p1.get() == '#')
                continue;

            if (in_multiline)
            {
                if (p1.get() == '\\')
                {
                    while (p1.get() == '\\')
                    {
                        char ch1, ch2, ch3;

                        p1.skip();

                        ch1 = p1.getChar();
                        if (ch1 < '0' || ch1 > '7')
                            break;

                        ch2 = p1.getChar();
                        if (ch2 < '0' || ch2 > '7')
                            break;

                        ch3 = p1.getChar();
                        if (ch3 < '0' || ch3 > '7')
                            break;

                        ch1 = (ch1 - '0') * 64 + (ch2 - '0') * 8 + (ch3 - '0');
                        _value.append(&ch1, 1);
                    }
                    continue;
                }

                p1.getWord(cmd);
                if ((cmd == "END"))
                {
                    if (is_value)
                        cka_value = _value;
                    else if (is_serial)
                        cka_serial = _value;

                    in_multiline = false;
                }

                continue;
            }

            p1.getWord(cmd);

            p1.skipSpace();
            p1.getWord(type);
            if ((type == "MULTILINE_OCTAL"))
            {
                in_multiline = true;
                _value.resize(0);

                is_value = is_cert && (cmd == "CKA_VALUE");
                is_serial = (cmd == "CKA_SERIAL_NUMBER");
                continue;
            }

            p1.skipSpace();
            p1.getLeft(value);

            if (!in_obj)
            {
                if ((cmd == "CKA_CLASS"))
                {
                    in_obj = true;
                    is_cert = (value == "CKO_CERTIFICATE");
                    is_trust = (value == "CKO_NSS_TRUST");
                }
                continue;
            }

            if ((cmd == "CKA_LABEL"))
                cka_label = value;
            else if (is_trust && (cmd == "CKA_TRUST_SERVER_AUTH"))
            {
                is_ca = (value == "CKT_NSS_TRUSTED_DELEGATOR");
                is_verify = (value == "CKT_NSS_MUST_VERIFY_TRUST");
            }

            if (cmd.empty())
                break;
        }

        if (!cka_label.empty())
        {
            if (is_trust)
            {
                if (is_ca)
                    certs.insert(std::pair<exlib::string, bool>(cka_label + cka_serial, true));
                if (is_verify)
                    verifies.insert(std::pair<exlib::string, bool>(cka_label + cka_serial, true));
            }
            else if (is_cert && !cka_value.empty())
                values.append(std::pair<exlib::string, exlib::string>(cka_label + cka_serial, cka_value));
        }
    }

    bool is_loaded = false;
    int32_t i;

    for (i = 0; i < (int32_t)values.size(); i++)
    {
        std::pair<exlib::string, exlib::string> &c = values[i];
        std::map<exlib::string, bool>::iterator it_trust;

        it_trust = verifies.find(c.first);
        if (it_trust != verifies.end())
        {
            ret = mbedtls_x509_crt_parse_der(&m_crt,
                                             (const unsigned char *)c.second.c_str(),
                                             c.second.length());
            if (ret != 0)
                return CHECK_ERROR(_ssl::setError(ret));

            is_loaded = true;
        }
    }

    for (i = 0; i < (int32_t)values.size(); i++)
    {
        std::pair<exlib::string, exlib::string> &c = values[i];
        std::map<exlib::string, bool>::iterator it_trust;

        it_trust = certs.find(c.first);
        if (it_trust != certs.end())
        {
            ret = mbedtls_x509_crt_parse_der(&m_crt,
                                             (const unsigned char *)c.second.c_str(),
                                             c.second.length() );
            if (ret != 0)
                return CHECK_ERROR(_ssl::setError(ret));

            is_loaded = true;
        }
    }

    if (!is_loaded)
        return CHECK_ERROR(_ssl::setError(MBEDTLS_ERR_X509_INVALID_FORMAT));

    return 0;
}
Пример #20
0
/*!
 * This function is used to un subscribe on rtc event IT.
 *
 * @param        event  	type of event.
 * @param        callback  	event callback function.
 *
 * @return       This function returns 0 if successful.
 */
int mc13783_rtc_event_unsub(t_rtc_int event, void *callback)
{
	CHECK_ERROR(mc13783_rtc_event(event, callback, false));
	return ERROR_NONE;

}
Пример #21
0
/* IO monitor to watch the stdin, stdout and stderr file descriptors */
static void *
io_monitor (void *arg)
{
  subprocess_t *p = arg;

  int nfds;
  fd_set rfds, wfds;

  int stdout_fd = fileno (p->stdout);
  int stderr_fd = fileno (p->stderr);
  int stdin_fd = fileno (p->stdin);

  size_t stdout_size = 0;
  size_t stdout_current = 0;
  size_t stderr_size = 0;
  size_t stderr_current = 0;

  while (true)
    {
      FD_ZERO (&rfds);
      FD_SET (stdout_fd, &rfds);
      FD_SET (stderr_fd, &rfds);

      FD_ZERO (&wfds);
      FD_SET (stdin_fd, &wfds);

      nfds = (stdout_fd > stderr_fd) ? stdout_fd : stderr_fd;
      nfds = (stdin_fd > nfds) ? stdin_fd : nfds;

      CHECK_ERROR ((select (nfds + 1, &rfds, &wfds, NULL, NULL) == -1),
		   "select() failed");

      size_t count;
      char buffer_stdout[256], buffer_stderr[256];

      if (FD_ISSET (stdout_fd, &rfds))
	{
	  CHECK_ERROR (((int) (count = read (stdout_fd,
					     buffer_stdout,
					     sizeof (buffer_stdout))) == -1),
		       "read(stdout) failed");

	  /* Expand memory if not enough space left */
	  if ((stdout_current + count + 1) > stdout_size)
	    {
	      stdout_size = (stdout_current + count + 1) * 2;

	      p->stdout_buffer = realloc (p->stdout_buffer, stdout_size);
	      CHECK_ERROR ((p->stdout_buffer == NULL), "stdout read failed");
	    }

	  memcpy(&(p->stdout_buffer[stdout_current]), buffer_stdout, count);
	  stdout_current += count;
	  p->stdout_buffer[stdout_current] = '\0';
	}

      if (FD_ISSET (stderr_fd, &rfds))
	{
	  CHECK_ERROR (((int) (count = read (stderr_fd,
					     buffer_stderr,
					     sizeof (buffer_stderr))) == -1),
		       "read(stderr) failed");

	  if ((stderr_current + count + 1) > stderr_size)
	    {
	      stderr_size +=
		((stderr_current + count + 1 - stderr_size) / 1024 + 1) * 1024;

	      p->stderr_buffer = realloc (p->stderr_buffer, stderr_size);
	      CHECK_ERROR ((p->stderr_buffer == NULL), "stderr read failed");
	    }

	  memcpy(&(p->stderr_buffer[stderr_current]), buffer_stderr, count);
	  stderr_current += count;
	  p->stderr_buffer[stderr_current] = '\0';
	}

      if ((FD_ISSET (stdin_fd, &wfds)) && (p->stdin_buffer != NULL))
	{
	  size_t size = strlen (p->stdin_buffer);

	  count = write (stdin_fd, p->stdin_buffer, size);

	  if (((int) count == -1) && (count != size))
	    {
	      rlimit_error ("write(stdin) failed");
	      goto fail;
	    }

	  free (p->stdin_buffer);
	  p->stdin_buffer = NULL;
	}
    }

fail:
  return NULL;
}
Пример #22
0
/*!
 * This function implements IOCTL controls on a mc13783 rtc device.
 *
 * @param        inode       pointer on the node
 * @param        file        pointer on the file
 * @param        cmd         the command
 * @param        arg         the parameter
 * @return       This function returns 0 if successful.
 */
static int mc13783_rtc_ioctl(struct inode *inode, struct file *file,
			     unsigned int cmd, unsigned long arg)
{
	struct timeval *mc13783_time = NULL;

	if (_IOC_TYPE(cmd) != 'R')
		return -ENOTTY;

	if (arg) {
		if ((mc13783_time = kmalloc(sizeof(struct timeval), GFP_KERNEL))
		    == NULL) {
			return -ENOMEM;
		}
		if (copy_from_user(mc13783_time, (struct timeval *)arg,
				   sizeof(struct timeval))) {
			return -EFAULT;
		}
	}

	switch (cmd) {
	case MC13783_RTC_SET_TIME:
		TRACEMSG_RTC(_K_D("SET RTC"));
		CHECK_ERROR(mc13783_rtc_set_time(mc13783_time));
		break;
	case MC13783_RTC_GET_TIME:
		TRACEMSG_RTC(_K_D("GET RTC"));
		CHECK_ERROR(mc13783_rtc_get_time(mc13783_time));
		break;
	case MC13783_RTC_SET_ALARM:
		TRACEMSG_RTC(_K_D("SET RTC ALARM"));
		CHECK_ERROR(mc13783_rtc_set_time_alarm(mc13783_time));
		break;
	case MC13783_RTC_GET_ALARM:
		TRACEMSG_RTC(_K_D("GET RTC ALARM"));
		CHECK_ERROR(mc13783_rtc_get_time_alarm(mc13783_time));
		break;
	case MC13783_RTC_WAIT_ALARM:
		TRACEMSG_RTC(_K_I("WAIT ALARM..."));
		CHECK_ERROR(mc13783_rtc_event_sub(RTC_IT_ALARM,
						  callback_test_sub));
		CHECK_ERROR(mc13783_rtc_wait_alarm());
		TRACEMSG_RTC(_K_I("ALARM DONE"));
		CHECK_ERROR(mc13783_rtc_event_unsub(RTC_IT_ALARM,
						    callback_test_sub));
		break;
	case MC13783_RTC_ALARM_REGISTER:
		TRACEMSG_RTC(_K_I("MC13783 RTC ALARM REGISTER"));
		mc13783_event_init(&alarm_event);
		alarm_event.event = EVENT_TODAI;
		alarm_event.callback = callback_alarm_asynchronous;
		CHECK_ERROR(mc13783_event_subscribe(alarm_event));
		break;
	case MC13783_RTC_ALARM_UNREGISTER:
		TRACEMSG_RTC(_K_I("MC13783 RTC ALARM UNREGISTER"));
		mc13783_event_init(&alarm_event);
		alarm_event.event = EVENT_TODAI;
		alarm_event.callback = callback_alarm_asynchronous;
		CHECK_ERROR(mc13783_event_unsubscribe(alarm_event));
		mc13783_rtc_done = false;
		break;
	default:
		TRACEMSG_RTC(_K_D("%d unsupported ioctl command"), (int)cmd);
		return -EINVAL;
	}

	if (arg) {
		if (copy_to_user((struct timeval *)arg, mc13783_time,
				 sizeof(struct timeval))) {
			return -EFAULT;
		}
		kfree(mc13783_time);
	}

	return ERROR_NONE;
}
Пример #23
0
/* Monitoring the subprocess end and get the return value */
static void *
monitor (void *arg)
{
  subprocess_t *p = arg;
  struct timespec start_time;

  /* Initializing the pipes () */
  int stdin_pipe[2];		/* '0' = child_read,  '1' = parent_write */
  int stdout_pipe[2];		/* '0' = parent_read, '1' = child_write */
  int stderr_pipe[2];		/* '0' = parent_read, '1' = child_write */

  CHECK_ERROR (((pipe (stdin_pipe) == -1) ||
		(pipe (stdout_pipe) == -1) ||
		(pipe (stderr_pipe) == -1)), "pipe initialization failed");

  /* We create a child process running the subprocess and we wait for
   * it to finish. If a timeout elapsed the child is killed. Waiting
   * is done using sigtimedwait(). Race condition is avoided by
   * blocking the SIGCHLD signal before fork() and storing it into the
   * buffer while starting the timer in a separate pthread. */

  /* Blocking SIGCHLD before forking */
  sigset_t mask;

  CHECK_ERROR ((sigemptyset (&mask) == -1), "sigemptyset failed");
  CHECK_ERROR ((sigaddset (&mask, SIGCHLD) == -1), "sigaddset failed");

  CHECK_ERROR ((sigprocmask (SIG_BLOCK, &mask, NULL) == -1),
	       "sigprocmask failed");

  /* Getting start time of the subprocess (profiling information) */
  CHECK_ERROR ((clock_gettime (CLOCK_MONOTONIC, &start_time) == -1),
	       "getting start time failed");

  /* Forking the process */
  CHECK_ERROR (((p->pid = fork ()) == -1), "fork failed");

  if (p->pid == 0)	/***** Child process *****/
    {
      /* TODO: What if the child_monitor fails miserably ? It should
       * be signaled in the parent stderr and not in the child
       * stderr. */
      CHECK_ERROR ((child_monitor (p,
				   stdin_pipe,
				   stdout_pipe,
				   stderr_pipe) == RETURN_FAILURE),
		   "child monitor failed");
    }
  else			    /***** Parent process *****/
    {
      int status;
      pthread_t watchdog_pthread, io_pthread;
      struct rusage usage;

      CHECK_ERROR ((close (stdin_pipe[0]) == -1), "close(stdin[0]) failed");
      CHECK_ERROR (((p->stdin = fdopen (stdin_pipe[1], "w")) == NULL),
		   "fdopen(stdin[1]) failed");

      CHECK_ERROR ((close (stdout_pipe[1]) == -1), "close(stdout[1]) failed");
      CHECK_ERROR (((p->stdout = fdopen (stdout_pipe[0], "r")) == NULL),
		   "fdopen(stdout[0]) failed");

      CHECK_ERROR ((close (stderr_pipe[1]) == -1), "close(stderr[1]) failed");
      CHECK_ERROR (((p->stderr = fdopen (stderr_pipe[0], "r")) == NULL),
		   "fdopen(stderr[0]) failed");

      /* Running a watchdog to timeout the subprocess */
      if ((p->limits) && (p->limits->timeout > 0))
	CHECK_ERROR ((pthread_create (&watchdog_pthread, NULL, watchdog, p) !=
		      0), "watchdog creation failed");

      /* Running the io monitor to watch stdout and stderr */
      CHECK_ERROR ((pthread_create (&io_pthread, NULL, io_monitor, p) != 0),
		   "io_monitor creation failed");

      p->status = RUNNING;

      /* Waiting for synchronization with monitored process */
      CHECK_ERROR (wait4 (p->pid, &status, 0, &usage) == -1, "wait failed");

      /* Filtering syscalls with ptrace */
      if ((p->limits != NULL) && (p->limits->syscalls[0] > 0))
	{
	  if (syscall_filter (p, &status, &usage) == RETURN_FAILURE)
	    goto fail;
	}

      /***** The subprocess is finished now *****/

      /* Getting end time of the subprocess (profiling information) */
      struct timespec tmp_time, end_time;

      CHECK_ERROR ((clock_gettime (CLOCK_MONOTONIC, &end_time) == -1),
		   "getting end time failed");
      tmp_time = timespec_diff (start_time, end_time);

      p->real_time_usec =
	(time_t) (tmp_time.tv_sec * 1000000 + tmp_time.tv_nsec / 1000);

      /* Finding out what the status and retval are really */
      if (WIFEXITED (status))
	{			/* Exited normally */
	  p->status = TERMINATED;
	  p->retval = WEXITSTATUS (status);	/* Return value */
	}
      else if (WIFSIGNALED (status))
	{
	  p->retval = WTERMSIG (status);	/* Kill signal */

	  if (p->status < TERMINATED)
	    {
	      /* Trying to guess why by looking at errno value */
	      switch (WTERMSIG (status))
		{
		case SIGSEGV:
		  p->status = MEMORYOUT;
		  break;

		default:
		  p->status = KILLED;
		}
	    }
	  /* FIXME: It may be interesting to store the termination signal
	   * into another variable and to 'p->retval = errno' */
	}
      else if (WIFSTOPPED (status))
	{
	  p->status = STOPPED;
	  p->retval = WSTOPSIG (status);	/* Stop signal */
	}
      else if (WIFCONTINUED (status))
	{
	  p->status = RUNNING;
	  p->retval = 0;	/* Process is still running */
	}

    fail:
      /* Cleaning the io_monitor */
      pthread_cancel (io_pthread);

      /* Cleaning the watchdog if not already exited */
      if ((p->limits) && (p->limits->timeout > 0))
	pthread_cancel (watchdog_pthread);

      /* Cleaning and setting the profile information */
      /* User time in us */
      p->user_time_usec =
	usage.ru_utime.tv_sec * 1000 + usage.ru_utime.tv_usec;

      /* System time in us */
      p->sys_time_usec =
	usage.ru_stime.tv_sec * 1000 + usage.ru_stime.tv_usec;

      /* Memory usage */
      p->memory_kbytes = usage.ru_maxrss;
    }

  return NULL;
}
Пример #24
0
Файл: uac.c Проект: grpascal/GEO
/* Initialize the audio path */
int mxuvc_audio_init(const char *backend, const char *options)
{
	RECORD("\"%s\", \"%s\"", backend, options);
	struct libusb_device *dev = NULL;
	int ret=0, i, config;
	uint16_t vendor_id=0xdead, product_id=0xbeef;
	char *str=NULL, *opt, *value;
	int audio_sampling_rate;

	TRACE("Initializing the audio\n");

	/* Check that the correct video backend was requested*/
	if(strncmp(backend, "libusb-uac", 10)) {
		ERROR(-1, "The audio backend requested (%s) does not match "
			"the implemented one (libusb-uac)", backend);
	}

	/* Set init parameters to their default values */
	packets_per_transfer = PACKETS_PER_TRANSFER_DEFAULT;
	num_transfers        = NUM_TRANSFERS_DEFAULT;
	audio_duration_ms    = AUDIO_DURATION_MS_DEFAULT;
	audio_sampling_rate  = AUDIO_SAMPLING_RATE_DEFAULT;

	/* Copy the options string to a new buffer since next_opt() needs
	 * non const strings and options could be a const string */
	if(options != NULL) {
		str = (char*)malloc(strlen(options)+1);
		strncpy(str, options, strlen(options));
		*(str + strlen(options)) = '\0';
	}

	/* Get backend option from the option string */
	ret = next_opt(str, &opt, &value);
	while(ret == 0) {
		if(strncmp(opt, "vid", 3) == 0) {
			vendor_id = (uint16_t) strtoul(value, NULL, 16);
		} else if(strncmp(opt, "pid", 3) == 0) {
			product_id = (uint16_t) strtoul(value, NULL, 16);
		} else if(strncmp(opt, "packets_per_transfer", 19) == 0) {
			packets_per_transfer = (unsigned int) strtoul(value, NULL, 10);
		} else if(strncmp(opt, "num_transfers", 12) == 0) {
			num_transfers = (unsigned int) strtoul(value, NULL, 10);
		} else if(strncmp(opt, "audio_duration_ms", 17) == 0) {
			audio_duration_ms = (unsigned int) strtoul(value, NULL, 10);
		}
		else if (strncmp (opt, "audio_sampling_rate", 19) == 0) {
			audio_sampling_rate =
				(unsigned int) strtoul (value, NULL, 10);
		} else {
			WARNING("Unrecognized option: '%s'", opt);
		}
		ret = next_opt(NULL, &opt, &value);
	}

	/* Display the values we are going to use */
	TRACE("Using vid = 0x%x\n",                vendor_id);
	TRACE("Using pid = 0x%x\n",                product_id);
	TRACE("Using packets_per_transfer = %i\n", packets_per_transfer);
	TRACE("Using num_transfers = %i\n",        num_transfers);
	TRACE("Using audio_duration_ms = %i\n",    audio_duration_ms);
	TRACE("Using audio_sampling_rate = %i\n",  audio_sampling_rate);

	/* Free the memory allocated to parse 'options' */
	if(str)
		free(str);

	/* Initialize the backend */
	aud_started = 0;
	audio_disconnected = 0;
	ret = init_libusb(&audio_ctx);
	if(ret < 0)
		return -1;

	audio_hdl = libusb_open_device_with_vid_pid(audio_ctx, vendor_id,
							product_id);
	CHECK_ERROR(audio_hdl == NULL, -1, "Could not open USB device "
			"%x:%x", vendor_id, product_id);

	dev = libusb_get_device(audio_hdl);
	if(dev == NULL) {
		printf("Unexpected error: libusb_get_device returned a NULL "
				"pointer.");
		mxuvc_audio_deinit();
		return -1;
	}

	/* Get active USB configuration */
	libusb_get_configuration(audio_hdl, &config);

	/* Parse USB decriptors from active USB configuration
	 * to get all the UVC/UAC info needed */
	ret = aparse_usb_config(dev, config);
	if(ret < 0){
		mxuvc_audio_deinit();
		return -1;
	}

	/* Initialize audio */

	/* Claim audio control interface */
	/* Check if a kernel driver is active on the audio control interface */
	ret = libusb_kernel_driver_active(audio_hdl, aud_cfg.ctrlif);
	if(ret < 0)
		printf("Error: libusb_kernel_driver_active failed %d\n", ret);

	if(ret == 1) {
		TRACE("Detach the kernel driver...\n");
		/* If kernel driver is active, detach it so that we can claim
		 * the interface */
		ret = libusb_detach_kernel_driver(audio_hdl, aud_cfg.ctrlif);
		if(ret < 0)
			printf("Error: libusb_detach_kernel_driver failed "
					"%d\n", ret);
	}

	/* Claim audio control interface */
	ret = libusb_claim_interface(audio_hdl, aud_cfg.ctrlif);
	if(ret < 0) {
		printf("Error: libusb_claim_interface failed %d\n", ret);
	}

	/* Claim audio streaming interface */
	/* Check if a kernel driver is active on the audio interface */
	ret = libusb_kernel_driver_active(audio_hdl, aud_cfg.interface);
	if(ret < 0)
		printf("Error: libusb_kernel_driver_active failed %d\n", ret);

	if(ret == 1) {
		TRACE("Detach the kernel driver...\n");
		/* If kernel driver is active, detach it so that we can claim
		 * the interface */
		ret = libusb_detach_kernel_driver(audio_hdl, aud_cfg.interface);
		if(ret < 0)
			printf("Error: libusb_detach_kernel_driver failed "
					"%d\n",ret);
	}

	/* Claim audio streaming interface */
	ret = libusb_claim_interface(audio_hdl, aud_cfg.interface);
	if(ret < 0) {
		printf("Error: libusb_claim_interface failed %d\n",ret);
	}

	/* Select sampling rate */
	for(i=0;i<MAX_AUD_FMTS;i++) {
		if(aud_cfg.format[i].samFr == audio_sampling_rate){
			aud_cfg.fmt_idx = i;
			break;
		}
		CHECK_ERROR(i == MAX_AUD_FMTS-1, -1,
			"Unable to set the sampling rate to %i",
			audio_sampling_rate);
	}

	/* Map default UAC format to Audio format */
	cur_aud_format = AUD_FORMAT_PCM_RAW;

	/* Get min, max and real unit id for ctrl */
	AUDIO_CTRL *ctrl = uac_controls;
	int16_t min = 0, max = 0;
	uint16_t res = 0;
	while(ctrl->id != CTRL_NONE) {
		switch(ctrl->unit) {
			TRACE(">>>>>id:%d  unit:%d\n", ctrl->id,ctrl->unit);
			case FEATURE:
				ctrl->unit = aud_cfg.ctrl_feature;
				break;
			default:
				ERROR(-1, "Unsupported control unit (%i) for "
						"audio control %i",
						ctrl->unit, ctrl->id);
		}

		if (ctrl->id == CTRL_MUTE) {
			ctrl++;
			continue;
		}

		ret = get_ctrl(ctrl->id, GET_MIN, (void*) &min);
		CHECK_ERROR(ret < 0, -1,
				"Unable to get min (GET_MIN) for audio "
				"control: id=%i, cs=%i, cn=%i.",
				ctrl->id, ctrl->cs, ctrl->cn);
		ctrl->min = min;
		ret = get_ctrl(ctrl->id, GET_MAX, (void*) &max);
		CHECK_ERROR(ret < 0, -1,
				"Unable to get max (GET_MAX) for audio "
				"control: id=%i, cs=%i, cn=%i.",
				ctrl->id, ctrl->cs, ctrl->cn);
		ctrl->max = max;
		ret = get_ctrl(ctrl->id, GET_RES, (void*) &res);
		CHECK_ERROR(ret < 0, -1,
				"Unable to get res (GET_RES) for audio "
				"control: id=%i, cs=%i, cn=%i.",
				ctrl->id, ctrl->cs, ctrl->cn);
		ctrl->res = res;

		ctrl++;
	}

	/* Register removal USB event*/
	register_libusb_removal_cb((libusb_pollfd_removed_cb) audio_removed,
			audio_hdl);

	/* Start event thread/loop */
	ret = start_libusb_events();
	if(ret < 0)
		return -1;

	audio_initialized = 1;

	return 0;
}
Пример #25
0
/** insert_sorted()
 *  Look at the current links and insert into the lists in a sorted manner
 */
void insert_sorted(char * link, char *filename) {
   
   dprintf("Inserting %s.... ", link);
   
   int pos = dobsearch(link);
   
   if (pos >= use_len)
   {
      // at end
      dprintf("Inserting at end\n");
      links[use_len].link = link;
	   link_elem_t *new_elem;
      CHECK_ERROR((new_elem = (link_elem_t *)malloc(sizeof(link_elem_t))) == NULL);
      new_elem->next = NULL;
      new_elem->filename = filename; 
      links[use_len].elem = new_elem;

  	   use_len++;

	}
   else if (pos < 0)
   {
      // at front
      dprintf("Inserting at front\n");
      memmove(&links[1], links, use_len*sizeof(link_head_t));
      links[0].link = link;
      
      link_elem_t *new_elem;
      CHECK_ERROR((new_elem = (link_elem_t *)malloc(sizeof(link_elem_t))) == NULL);
      new_elem->next = NULL;
      new_elem->filename = filename; 
      links[0].elem = new_elem;
      
	   use_len++;
   }
   else if (strcmp(link, links[pos].link) == 0)
   {
      // match
      dprintf("link exists\n");
      assert(links[pos].elem);
      link_elem_t *new_elem;
      CHECK_ERROR((new_elem = (link_elem_t *)malloc(sizeof(link_elem_t))) == NULL);
      new_elem->filename = filename;
      new_elem->next = links[pos].elem;
      links[pos].elem = new_elem;
	}
   else
   {
      // insert at pos
      dprintf("Inserting in middle\n");
      memmove(&links[pos+1], &links[pos], (use_len-pos)*sizeof(link_head_t));
      links[pos].link = link;
	   
	   link_elem_t *new_elem;
      CHECK_ERROR((new_elem = (link_elem_t *)malloc(sizeof(link_elem_t))) == NULL);
      new_elem->next = NULL;
      new_elem->filename = filename; 
      links[pos].elem = new_elem;
      
	   use_len++;
   }

	if(use_len == length)
	{
		length *= 2;
	   links = (link_head_t*)realloc(links,length*sizeof(link_head_t));
	}
   
   
   dprintf("Inserted\n");  
}
Пример #26
0
GstDroidCamSrcQuirk *
gst_droidcamsrc_quirk_new (GKeyFile * file, const gchar * group)
{
  GstDroidCamSrcQuirk *quirk = g_slice_new0 (GstDroidCamSrcQuirk);
  GError *err = NULL;
  gchar *type = NULL;

  /* common properties first */
  quirk->id = g_strdup (group);

  quirk->direction = g_key_file_get_integer (file, group, "direction", &err);
  CHECK_ERROR (err, group, "direction");

  {
    gboolean has_image = g_key_file_has_key (file, group, "image", NULL);
    gboolean has_video = g_key_file_has_key (file, group, "video", NULL);

    if (!has_image && !has_video) {
      /* backwards compatibility */
      quirk->image = TRUE;
      quirk->video = FALSE;
    } else {
      quirk->image = has_image;
      quirk->video = has_video;
    }
  }

  type = g_key_file_get_value (file, group, "type", &err);
  if (err) {
    /* CHECK_ERROR() will issue a warning if the key "type" is not defined
     * but this is valid as the key is not mandatory */
    g_error_free (err);
    err = NULL;
  }

  quirk->type = GST_DROID_CAM_SRC_QUIRK_PROPERTY;

  if (!g_strcmp0 (type, "command")) {
    quirk->type = GST_DROID_CAM_SRC_QUIRK_COMMAND;
  }

  if (type) {
    g_free (type);
    type = NULL;
  }

  if (quirk->type == GST_DROID_CAM_SRC_QUIRK_PROPERTY) {
    quirk->prop = g_key_file_get_value (file, group, "prop", &err);
    CHECK_ERROR (err, group, "prop");

    quirk->on = g_key_file_get_value (file, group, "on", &err);
    CHECK_ERROR (err, group, "on");

    quirk->off = g_key_file_get_value (file, group, "off", &err);
    CHECK_ERROR (err, group, "off");

    if (!quirk->prop || !quirk->on || !quirk->off) {
      GST_WARNING ("incomplete quirk definition for %s", group);
      gst_droidcamsrc_quirk_free (quirk);
      quirk = NULL;
    }
  } else {

    quirk->command_enable =
        g_key_file_get_integer (file, group, "command_enable", &err);
    CHECK_ERROR (err, group, "command_enable");

    quirk->command_disable =
        g_key_file_get_integer (file, group, "command_disable", &err);
    CHECK_ERROR (err, group, "command_disable");
    quirk->arg1_enable =
        g_key_file_get_integer (file, group, "arg1_enable", &err);
    CHECK_ERROR (err, group, "arg1_enable");
    quirk->arg2_enable =
        g_key_file_get_integer (file, group, "arg2_enable", &err);
    CHECK_ERROR (err, group, "arg2_enable");
    quirk->arg1_disable =
        g_key_file_get_integer (file, group, "arg1_disable", &err);
    CHECK_ERROR (err, group, "arg1_disable");
    quirk->arg2_disable =
        g_key_file_get_integer (file, group, "arg2_disable", &err);
    CHECK_ERROR (err, group, "arg2_disable");
  }

  return quirk;
}
Пример #27
0
int main(int argc, char *argv[]) {
    int fd_keys;
    char *fdata_keys;
    struct stat finfo_keys;
    char *fname_keys;

	 /* Option to provide the encrypted words in a file as opposed to source code */
    //fname_encrypt = "encrypt.txt";
    
    if (argv[1] == NULL)
    {
        printf("USAGE: %s <keys filename>\n", argv[0]);
        exit(1);
    }
    fname_keys = argv[1];

    struct timeval starttime,endtime;
    srand( (unsigned)time( NULL ) );

    /*// Read in the file
    CHECK_ERROR((fd_encrypt = open(fname_encrypt,O_RDONLY)) < 0);
    // Get the file info (for file length)
    CHECK_ERROR(fstat(fd_encrypt, &finfo_encrypt) < 0);
    // Memory map the file
    CHECK_ERROR((fdata_encrypt= mmap(0, finfo_encrypt.st_size + 1,
        PROT_READ | PROT_WRITE, MAP_PRIVATE, fd_encrypt, 0)) == NULL);*/

    // Read in the file
    CHECK_ERROR((fd_keys = open(fname_keys,O_RDONLY)) < 0);
    // Get the file info (for file length)
    CHECK_ERROR(fstat(fd_keys, &finfo_keys) < 0);
    // Memory map the file
    CHECK_ERROR((fdata_keys= (char*)mmap(0, finfo_keys.st_size + 1,
        PROT_READ | PROT_WRITE, MAP_PRIVATE, fd_keys, 0)) == NULL);

    // Setup splitter args

	//dprintf("Encrypted Size is %ld\n",finfo_encrypt.st_size);
	dprintf("Keys Size is %ld\n",finfo_keys.st_size);

    str_data_t str_data;

    str_data.keys_file_len = finfo_keys.st_size;
    str_data.encrypted_file_len = 0;
    str_data.bytes_comp = 0;
    str_data.keys_file  = ((char *)fdata_keys);
    str_data.encrypt_file  = NULL;
    //str_data.encrypted_file_len = finfo_encrypt.st_size;
    //str_data.encrypt_file  = ((char *)fdata_encrypt);     

    printf("String Match: Calling Serial String Match\n");

    gettimeofday(&starttime,0);
    string_match_splitter(&str_data);
    gettimeofday(&endtime,0);

    printf("String Match: Completed %ld\n",(endtime.tv_sec - starttime.tv_sec));

    /*CHECK_ERROR(munmap(fdata_encrypt, finfo_encrypt.st_size + 1) < 0);
    CHECK_ERROR(close(fd_encrypt) < 0);*/

    CHECK_ERROR(munmap(fdata_keys, finfo_keys.st_size + 1) < 0);
    CHECK_ERROR(close(fd_keys) < 0);

    return 0;
}
Пример #28
0
int main(int argc, char *argv[]) {
   
   final_data_t hist_vals;
   int i;
   int fd;
   char *fdata;
   struct stat finfo;
   char * fname;

   // Make sure a filename is specified
   if (argv[1] == NULL)
   {
      printf("USAGE: %s <bitmap filename>\n", argv[0]);
      exit(1);
   }
   
   fname = argv[1];

   printf("Histogram: Running...\n");
   
   // Read in the file
   CHECK_ERROR((fd = open(fname, O_RDONLY)) < 0);
   // Get the file info (for file length)
   CHECK_ERROR(fstat(fd, &finfo) < 0);
   // Memory map the file
   CHECK_ERROR((fdata = mmap(0, finfo.st_size + 1, 
      PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)) == NULL);
   
   if ((fdata[0] != 'B') || (fdata[1] != 'M')) {
      printf("File is not a valid bitmap file. Exiting\n");
      exit(1);
   }
   
   test_endianess();    // will set the variable "swap"
   
   unsigned short *bitsperpixel = (unsigned short *)(&(fdata[BITS_PER_PIXEL_POS]));
   if (swap) {
      swap_bytes((char *)(bitsperpixel), sizeof(*bitsperpixel));
   }
   if (*bitsperpixel != 24) {    // ensure its 3 bytes per pixel
      printf("Error: Invalid bitmap format - ");
      printf("This application only accepts 24-bit pictures. Exiting\n");
      exit(1);
   }
   
   unsigned short *data_pos = (unsigned short *)(&(fdata[IMG_DATA_OFFSET_POS]));
   if (swap) {
      swap_bytes((char *)(data_pos), sizeof(*data_pos));
   }
   
   int imgdata_bytes = (int)finfo.st_size - (int)(*(data_pos));
   printf("This file has %d bytes of image data, %d pixels\n", imgdata_bytes,
                                                            imgdata_bytes / 3);
   
   // We use this global variable arrays to store the "key" for each histogram
   // bucket. This is to prevent memory leaks in the mapreduce scheduler                                                            
   for (i = 0; i < 256; i++) {
      blue_keys[i] = i;
      green_keys[i] = 1000 + i;
      red_keys[i] = 2000 + i;
   }

   // Setup scheduler args
   scheduler_args_t sched_args;
   memset(&sched_args, 0, sizeof(scheduler_args_t));
   sched_args.task_data = &(fdata[*data_pos]);   //&hist_data;
   sched_args.map = hist_map;
   sched_args.reduce = hist_reduce;
   sched_args.splitter = NULL; //hist_splitter;
   sched_args.key_cmp = myshortcmp;
   
   sched_args.unit_size = 3;  // 3 bytes per pixel
   sched_args.partition = NULL; // use default
   sched_args.result = &hist_vals;
   
   sched_args.data_size = imgdata_bytes;

   sched_args.L1_cache_size = atoi(GETENV("MR_L1CACHESIZE")); //1024 * 64;
   sched_args.num_map_threads = atoi(GETENV("MR_NUMTHREADS"));//8;
   sched_args.num_reduce_threads = atoi(GETENV("MR_NUMTHREADS"));//16;
   sched_args.num_merge_threads = atoi(GETENV("MR_NUMTHREADS")) / 2;//8;
   sched_args.num_procs = atoi(GETENV("MR_NUMPROCS"));//16;
   sched_args.key_match_factor = (float)atof(GETENV("MR_KEYMATCHFACTOR"));//2;

   fprintf(stderr, "Histogram: Calling MapReduce Scheduler\n");

   CHECK_ERROR(map_reduce_scheduler(&sched_args) < 0);

   short pix_val;
   int freq;
   short prev = 0;
   
   dprintf("\n\nBlue\n");
   dprintf("----------\n\n");
   for (i = 0; i < hist_vals.length; i++)
   {
      keyval_t * curr = &((keyval_t *)hist_vals.data)[i];
      pix_val = *((short *)curr->key);
      freq = (int)curr->val;
      
      if (pix_val - prev > 700) {
         if (pix_val >= 2000) {
            dprintf("\n\nRed\n");
            dprintf("----------\n\n");
         }
         else if (pix_val >= 1000) {
            dprintf("\n\nGreen\n");
            dprintf("----------\n\n");
         }
      }
      
      dprintf("%hd - %d\n", pix_val % 1000, freq);
      
      prev = pix_val;
   }

   free(hist_vals.data);

   CHECK_ERROR(munmap(fdata, finfo.st_size + 1) < 0);
   CHECK_ERROR(close(fd) < 0);

   return 0;
}
Пример #29
0
result_t fs_base::openFile(exlib::string fname, exlib::string flags,
    obj_ptr<SeekableStream_base>& retVal, AsyncEvent* ac)
{
    if (ac->isSync())
        return CHECK_ERROR(CALL_E_NOSYNC);

    exlib::string safe_name;
    path_base::normalize(fname, safe_name);

    size_t pos = safe_name.find('$');
    if (pos != exlib::string::npos && safe_name[pos + 1] == PATH_SLASH) {
        exlib::string zip_file = safe_name.substr(0, pos);
        exlib::string member = safe_name.substr(pos + 2);
        obj_ptr<ZipFile_base> zfile;
        obj_ptr<Buffer_base> data;
        exlib::string strData;
        result_t hr;

#ifdef _WIN32
        bool bChanged = false;
        exlib::string member1 = member;
        {
            int32_t sz = (int32_t)member1.length();
            const char* buf = member1.c_str();
            for (int32_t i = 0; i < sz; i++)
                if (buf[i] == PATH_SLASH) {
                    member[i] = '/';
                    bChanged = true;
                }
        }
#endif

        obj_ptr<cache_node> _node;
        obj_ptr<SeekableStream_base> zip_stream;
        obj_ptr<Stat_base> stat;
        std::list<obj_ptr<cache_node>>::iterator it;

        date_t _now;
        _now.now();

        s_cachelock.lock();
        for (it = s_cache.begin(); it != s_cache.end(); ++it)
            if ((*it)->m_name == zip_file) {
                _node = *it;
                break;
            }
        s_cachelock.unlock();

        if (_node && (_now.diff(_node->m_date) > 3000)) {
            hr = openFile(zip_file, "r", zip_stream, ac);
            if (hr < 0)
                return hr;

            hr = zip_stream->cc_stat(stat);
            if (hr < 0)
                return hr;

            date_t _mtime;
            stat->get_mtime(_mtime);

            if (_mtime.diff(_node->m_mtime) != 0)
                _node.Release();
            else
                _node->m_date = _now;
        }

        if (_node == NULL) {
            if (zip_stream == NULL) {
                hr = openFile(zip_file, "r", zip_stream, ac);
                if (hr < 0)
                    return hr;

                hr = zip_stream->cc_stat(stat);
                if (hr < 0)
                    return hr;
            }

            obj_ptr<Buffer_base> zip_data;
            hr = zip_stream->cc_readAll(zip_data);
            if (hr < 0)
                return hr;

            hr = zip_base::cc_open(zip_data, "r", zip_base::_ZIP_DEFLATED, zfile);
            if (hr < 0)
                return hr;

            obj_ptr<NArray> list;
            hr = zfile->cc_readAll("", list);
            if (hr < 0)
                return hr;

            _node = new cache_node();
            _node->m_name = zip_file;
            _node->m_list = list;
            _node->m_date.now();
            stat->get_mtime(_node->m_mtime);

            s_cachelock.lock();
            for (it = s_cache.begin(); it != s_cache.end(); ++it)
                if ((*it)->m_name == zip_file) {
                    *it = _node;
                    break;
                }
            if (it == s_cache.end())
                s_cache.push_back(_node);
            s_cachelock.unlock();
        }

        int32_t len, i;
        bool bFound = false;
        obj_ptr<ZipFile::Info> zi;

        _node->m_list->get_length(len);

        for (i = 0; i < len; i++) {
            Variant v;
            exlib::string s;

            _node->m_list->_indexed_getter(i, v);
            zi = (ZipFile::Info*)v.object();

            zi->get_filename(s);

            if (member == s) {
                bFound = true;
                break;
            }

#ifdef _WIN32
            if (bChanged && member1 == s) {
                member = member1;
                bFound = true;
                break;
            }
#endif
        }

        if (!bFound)
            return CALL_E_FILE_NOT_FOUND;

        date_t _d;

        zi->get_data(data);
        if (data)
            data->toString(strData);

        zi->get_date(_d);
        if (_d.empty())
            _d = _node->m_date;

        retVal = new MemoryStream::CloneStream(strData, _d);
    } else {
        obj_ptr<File> pFile = new File();
        result_t hr;

        Isolate* isolate = Runtime::check() ? Isolate::current() : ac->isolate();

        if (isolate && !isolate->m_bFileAccess)
            return CHECK_ERROR(CALL_E_INVALID_CALL);

        hr = pFile->open(safe_name, flags);
        if (hr < 0)
            return hr;

        retVal = pFile;
    }

    return 0;
}
Пример #30
0
result_t websocket_base::connect(const char* url, const char* origin,
                                 obj_ptr<Stream_base>& retVal, AsyncEvent* ac)
{
	class asyncConnect: public AsyncState
	{
	public:
		asyncConnect(const char* url, const char* origin,
		             obj_ptr<Stream_base>& retVal, AsyncEvent *ac) :
			AsyncState(ac), m_url(url), m_origin(origin), m_retVal(retVal)
		{
			set(handshake);
		}

		static int32_t handshake(AsyncState *pState, int32_t n)
		{
			asyncConnect *pThis = (asyncConnect *) pState;

			if (!qstrcmp(pThis->m_url.c_str(), "wss://", 6))
				pThis->m_url = "https://" + pThis->m_url.substr(6);
			else if (!qstrcmp(pThis->m_url.c_str(), "ws://", 5))
				pThis->m_url = "http://" + pThis->m_url.substr(5);
			else
				return CHECK_ERROR(Runtime::setError("websocket: unknown protocol"));

			pThis->m_headers = new Map();

			pThis->m_headers->put("Upgrade", "websocket");
			pThis->m_headers->put("Connection", "Upgrade");
			pThis->m_headers->put("Sec-WebSocket-Version", "13");

			if (!pThis->m_origin.empty())
				pThis->m_headers->put("Origin", pThis->m_origin.c_str());

			char keys[16];
			int32_t i;

			for (i = 0; i < sizeof(keys); i ++)
				keys[i] = (char)rand();

			std::string key;
			baseEncode(
			    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
			    6, (const char*)&keys, sizeof(keys), key);

			pThis->m_headers->put("Sec-WebSocket-Key", key);

			key.append("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");

			unsigned char output[20];
			mbedtls_sha1((const unsigned char*)key.data(), key.size(), output);

			baseEncode(
			    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
			    6, (const char*)output, 20, pThis->m_accept);

			pThis->set(response);
			return http_base::request("GET", pThis->m_url.c_str(),
			                          NULL, pThis->m_headers, pThis->m_httprep, pThis);
		}

		static int32_t response(AsyncState *pState, int32_t n)
		{
			asyncConnect *pThis = (asyncConnect *) pState;

			Variant v;
			result_t hr;
			int32_t status;

			pThis->m_httprep->get_status(status);
			if (status != 101)
				return CHECK_ERROR(Runtime::setError("websocket: server error."));

			hr = pThis->m_httprep->firstHeader("Upgrade", v);
			if (hr < 0)
				return hr;

			if (hr == CALL_RETURN_NULL)
				return CHECK_ERROR(Runtime::setError("websocket: missing Upgrade header."));

			if (qstricmp(v.string().c_str(), "websocket"))
				return CHECK_ERROR(Runtime::setError("websocket: invalid Upgrade header."));

			bool bUpgrade;
			pThis->m_httprep->get_upgrade(bUpgrade);
			if (!bUpgrade)
				return CHECK_ERROR(Runtime::setError("websocket: invalid connection header."));

			hr = pThis->m_httprep->firstHeader("Sec-WebSocket-Accept", v);
			if (hr < 0)
				return hr;

			if (hr == CALL_RETURN_NULL)
				return CHECK_ERROR(Runtime::setError("websocket: missing Sec-WebSocket-Accept header."));

			if (qstrcmp(v.string().c_str(), pThis->m_accept.c_str()))
				return CHECK_ERROR(Runtime::setError("websocket: invalid Sec-WebSocket-Accept header."));

			pThis->m_httprep->get_stream(pThis->m_retVal);

			return pThis->done(0);
		}

	private:
		std::string m_url;
		std::string m_origin;
		obj_ptr<Stream_base>& m_retVal;
		obj_ptr<HttpResponse_base> m_httprep;
		obj_ptr<Map> m_headers;
		std::string m_accept;
	};

	if (!ac)
		return CHECK_ERROR(CALL_E_NOSYNC);

	return (new asyncConnect(url, origin, retVal, ac))->post(0);
}