コード例 #1
0
ファイル: bsnmpimport.c プロジェクト: hmatyschok/MeshBSD
static int32_t
snmp_import_table(struct snmp_toolinfo *snmptoolctx, struct snmp_oid2str *obj)
{
	int32_t i, tok;
	enum snmp_tc tc;
	struct snmp_index_entry *entry;

	if ((entry = calloc(1, sizeof(struct snmp_index_entry))) == NULL) {
		syslog(LOG_ERR, "malloc() failed: %s", strerror(errno));
		return (-1);
	}

	STAILQ_INIT(&(entry->index_list));

	for (i = 0, tok = gettoken(snmptoolctx); i < SNMP_INDEXES_MAX; i++) {
		int32_t syntax;
		struct enum_pairs *enums = NULL;

		if (tok != TOK_TYPE && tok != TOK_DEFTYPE && tok != TOK_ENUM &&
		    tok != TOK_BITS)
			break;

		if ((syntax = parse_type(snmptoolctx, &tok, &tc, &enums)) < 0) {
			enum_pairs_free(enums);
			snmp_index_listfree(&(entry->index_list));
			free(entry);
			return (-1);
		}

		if (snmp_syntax_insert(&(entry->index_list), enums, syntax,
		    tc) < 0) {
			snmp_index_listfree(&(entry->index_list));
			enum_pairs_free(enums);
			free(entry);
			return (-1);
		}
	}

	if (i == 0 || i > SNMP_INDEXES_MAX) {
		warnx("Bad number of indexes at line %d", input->lno);
		snmp_index_listfree(&(entry->index_list));
		free(entry);
		return (-1);
	}

	if (tok != TOK_STR) {
		warnx("String expected after indexes at line %d", input->lno);
		snmp_index_listfree(&(entry->index_list));
		free(entry);
		return (-1);
	}

	entry->string = obj->string;
	entry->strlen = obj->strlen;
	asn_append_oid(&(entry->var), &(obj->var));

	if ((i = snmp_table_insert(snmptoolctx, entry)) < 0) {
		snmp_index_listfree(&(entry->index_list));
		free(entry);
		return (-1);
	} else if (i == 0) {
		/* Same entry already present in lists. */
		free(entry->string);
		free(entry);
		return (0);
	}

	(void) snmp_import_update_table(ENTRY_INDEX, entry);

	return (1);
}
コード例 #2
0
ファイル: interface.c プロジェクト: outadoc/RicochetRobots
//
// Affiche une fenêtre de menu.
//
int displayMenu(char **choices, int nbChoices, char title[], bool logo) {
    if(choices == NULL || nbChoices < 1) return -1;
    
    //variables pour l'affichage du menu
    ITEM **menuItems = NULL;
    MENU *menu = NULL;
    WINDOW *menuWin = NULL;
    
    int i = 0, c;
    int winWidth = POPUP_WINDOW_WIDTH;
    //largeur du menu = longueur du plus grand des choix possibles
    int menuWidth = max_strlen(choices, nbChoices) + 2;
    
    //on alloue de la mémoire pour initialiser les éléments du menu
    menuItems = (ITEM **) calloc(nbChoices + 1, sizeof(ITEM *));
    
    //on créé de nouveaux éléments à partir des choix fournis
    for(i = 0; i < nbChoices; i++) {
        menuItems[i] = new_item(choices[i], NULL);
    }
    
    //on met un élément nul à la fin du tableau
    menuItems[nbChoices] = (ITEM *) NULL;
    
    while(true) {
        clear();
        
        menuWin = (logo) ? getMenuWindow(nbChoices, title) : getMenuWindowNoLogo(nbChoices, title, -1, -1);
        
        //on initialise le menu
        menu = new_menu((ITEM **) menuItems);
        
        //on lui précise bien que le menu fait N lignes et 1 colonne
        set_menu_format(menu, nbChoices, 1);
        
        menu_opts_off(menu, O_NONCYCLIC);
        set_menu_mark(menu, "> ");
        
        //on associe le menu à une fenêtre et une sous-fenêtre
        set_menu_win(menu, menuWin);
        //fenêtre hauteur largeur x y
        set_menu_sub(menu, derwin(menuWin, nbChoices, menuWidth, (logo) ? 15 : 4, (winWidth - menuWidth) / 2));
        
        //et hop, on affiche le menu et on rafraîchit.
        post_menu(menu);
        
        refresh();
        wrefresh(menuWin);
        
        curs_set(0);
        noecho();
        
        //boucle pour le menu
        while((c = getch())) {
            bool resized = false;
            
            switch(c) {
                case KEY_DOWN:
                    menu_driver(menu, REQ_DOWN_ITEM);
                    break;
                case KEY_UP:
                    menu_driver(menu, REQ_UP_ITEM);
                    break;
                case KEY_ESC_ALT:
                    return -1;
                case KEY_RESIZE:
                    //si on a redimensionné le terminal, on ré-exécute la boucle d'affichage
                    resized = true;
                    break;
                case KEY_MENU_ENTER: {
                    int choice = item_index(current_item(menu));
                    
                    //on libère la mémoire pour le menu, les choix, la fenêtre
                    unpost_menu(menu);
                    free_menu(menu);
                    
                    for(i = 0; i < nbChoices; ++i)
                        free_item(menuItems[i]);
                    
                    clear();
                    refresh();
                    
                    delwin(menuWin);
                    
                    //on réactive l'affichage des caractères tapés et du curseur
                    echo();
                    curs_set(1);
                    
                    return choice;
                }
            }
            
            if(resized) break;
            wrefresh(menuWin);
        }

    }
    
    return 0;
}
コード例 #3
0
ファイル: llips_general.c プロジェクト: mplu/RPi-kee
/********************************************//**
 * \brief Create an image with a view of histogram (RGBY).
 *
 * \param img_in t_img* - input image
 * \param img_out t_img* - output image
 * \return CPU_CHAR - status of operation
 *
 * Width and precision of histogram depend on image width
 ***********************************************/
CPU_CHAR histogram(t_img * img_in,t_img * img_out)
{
    CPU_CHAR ret = ERR_NONE;
    CPU_INT16U i,j;

    CPU_INT32U histowidth ;
    CPU_INT32U histoheigh ;
    CPU_INT32U histo_x = 1 ;
    CPU_INT32U histo_y_red = 1,histo_y_green,histo_y_blue,histo_y_lum ;

    CPU_INT32U * redpixel = calloc((PIXEL_8bit_RANGE+1),sizeof(CPU_INT32U));
    CPU_INT32U * greenpixel = calloc((PIXEL_8bit_RANGE+1),sizeof(CPU_INT32U));
    CPU_INT32U * bluepixel = calloc((PIXEL_8bit_RANGE+1),sizeof(CPU_INT32U));
    CPU_INT32U * luminancepixel = calloc((PIXEL_8bit_RANGE+1),sizeof(CPU_INT32U));
    CPU_CHAR Luminance = 0;

    CPU_INT32U index,histomaxred=0,histomaxgreen=0,histomaxblue=0,histomaxlum =0;

    // configure historgam
    histowidth = (img_in->wi)/4.5;

    if(histowidth>PIXEL_8bit_RANGE)
    {
         histowidth = PIXEL_8bit_RANGE;
    }
    histoheigh = histowidth / 2 ;

    histo_y_green = histo_y_red + histowidth + 2;
    histo_y_blue = histo_y_green + histowidth + 2;
    histo_y_lum = histo_y_blue + histowidth + 2;

    //Write Header
    for(i=0;i<img_in->FileHeader_size;i++)
    {
        img_out->FileHeader[i] = img_in->FileHeader[i];
    }
    img_out->signature = img_in->signature;
    img_out->depth = img_in->depth;
    img_out->wi = img_in->wi;
    img_out->he = img_in->he;
    img_out->FileHeader_size = img_in->FileHeader_size;

    //count distribution of red pixel
    for(i=0;i< (img_in->he ) ;i++)
    {
        for(j=0 ; (j< img_in->wi );j++)
        {
            //getting red pixel
            index = img_in->Red[i][j] / (PIXEL_8bit_RANGE/(histowidth-1));
            redpixel[index]++;
            histomaxred = maxi(histomaxred,redpixel[index]);

            //getting green pixel
            index = img_in->Green[i][j] / (PIXEL_8bit_RANGE/(histowidth-1));
            greenpixel[index]++;
            histomaxgreen = maxi(histomaxgreen,greenpixel[index]);
            //getting red pixel
            index = img_in->Blue[i][j] / (PIXEL_8bit_RANGE/(histowidth-1));
            bluepixel[index]++;
            histomaxblue = maxi(histomaxblue,bluepixel[index]);

            //calcultate luminance Y = 0,299 R + 0,587 G + 0,114 B
            Luminance = (CPU_CHAR)(  (CPU_FP32)img_in->Red[i][j]   * 0.299
                                        + (CPU_FP32)img_in->Green[i][j] * 0.587
                                        + (CPU_FP32)img_in->Blue[i][j]  * 0.114 );

            //getting lumi pixel
            index = Luminance / (PIXEL_8bit_RANGE/(histowidth-1));
            luminancepixel[index]++;
            histomaxlum = maxi(histomaxlum,luminancepixel[index]);
        }
    }

    // normalize histogramm according to highest pixel distribution
    // and height of histogram, and to histogram width
    for(i=0;i<histowidth;i++)
    {
        redpixel[i] = redpixel[i] * histoheigh / histomaxred ;
        greenpixel[i] = greenpixel[i] * histoheigh / histomaxgreen ;
        bluepixel[i] = bluepixel[i] * histoheigh / histomaxblue ;

        luminancepixel[i] = luminancepixel[i] * histoheigh / histomaxblue ;

    }

    //copy input img to output including histogram
    for(i=0;i< (img_in->he ) ;i++)
    {
        for(j=0 ; (j< img_in->wi );j++)
        {
            // Looking for red drawing area
            if(    ((j>=histo_y_red) && (j<=(histo_y_red+histowidth)))
                && ((i>=histo_x) && (i<(histo_x+histoheigh)))
              )
            {
                if(redpixel[j-histo_y_red] >= (i-histo_x))
                {
                    img_out->Red[i][j]   = 255;
                    img_out->Green[i][j] = 0;
                    img_out->Blue[i][j]  = 0;
                }else
                {
                    img_out->Red[i][j]   = (img_in->Red[i][j])/2;
                    img_out->Green[i][j] = (img_in->Green[i][j])/2;
                    img_out->Blue[i][j]  = (img_in->Blue[i][j])/2;
                }
            }// Looking for green drawing area
            else if(   ((j>=histo_y_green) && (j<=(histo_y_green+histowidth)))
                    && ((i>=histo_x) && (i<(histo_x+histoheigh)))
                   )
            {
                if(greenpixel[j-histo_y_green] >= (i-histo_x))
                {
                    img_out->Red[i][j]   = 0;
                    img_out->Green[i][j] = 255;
                    img_out->Blue[i][j]  = 0;
                }else
                {
                    img_out->Red[i][j]   = (img_in->Red[i][j])/2;
                    img_out->Green[i][j] = (img_in->Green[i][j])/2;
                    img_out->Blue[i][j]  = (img_in->Blue[i][j])/2;
                }
            }// Looking for blue drawing area
            else if(   ((j>=histo_y_blue) && (j<=(histo_y_blue+histowidth)))
                    && ((i>=histo_x) && (i<(histo_x+histoheigh)))
                   )
            {
                if(bluepixel[j-histo_y_blue] >= (i-histo_x))
                {
                    img_out->Red[i][j]   = 0;
                    img_out->Green[i][j] = 0;
                    img_out->Blue[i][j]  = 255;
                }else
                {
                    img_out->Red[i][j]   = (img_in->Red[i][j])/2;
                    img_out->Green[i][j] = (img_in->Green[i][j])/2;
                    img_out->Blue[i][j]  = (img_in->Blue[i][j])/2;
                }
            }// looking for lum drawing area
            else if(   ((j>=histo_y_lum) && (j<=(histo_y_lum+histowidth)))
                    && ((i>=histo_x) && (i<(histo_x+histoheigh)))
                   )
            {
                if(luminancepixel[j-histo_y_lum] >= (i-histo_x))
                {
                    img_out->Red[i][j]   = 180;
                    img_out->Green[i][j] = 180;
                    img_out->Blue[i][j]  = 180;
                }else
                {
                    img_out->Red[i][j]   = (img_in->Red[i][j])/2;
                    img_out->Green[i][j] = (img_in->Green[i][j])/2;
                    img_out->Blue[i][j]  = (img_in->Blue[i][j])/2;
                }
            }
            else
            {
                img_out->Red[i][j]   = img_in->Red[i][j];
                img_out->Green[i][j] = img_in->Green[i][j];
                img_out->Blue[i][j]  = img_in->Blue[i][j];
            }
        }
    }




    return ret;
}
コード例 #4
0
ファイル: geoipupdate.c プロジェクト: Jimdo/geoipupdate
void *xcalloc(size_t nmemb, size_t size)
{
    void *ptr = calloc(nmemb, size);
    exit_if(!ptr, "Out of memory\n");
    return ptr;
}
コード例 #5
0
ファイル: DynStat.c プロジェクト: BlackyFox/5A
int main(int argc, char *argv[])
{
	/* Creation of the variables and initialization */
	int size = 16;
	int length = 0;
	char* buf1 = NULL;
	char* buf2 = NULL;
	char* testdubuffer = NULL;
	int ret = 0;

	/* Checking if we have only two arguments given */
	if (argc == 3)
	{
		/* Memory allocation for the two args given */
		/* Allocation for the size of the argument (max = size = 16) */
		buf1 = (char*)calloc(strnlen(argv[1], size)+1, sizeof(char));
		buf2 = (char*)calloc(strnlen(argv[2], size)+1, sizeof(char));

		/* Memory allocation for the "testdubuffer" variable */
		testdubuffer = (char*)calloc(strnlen("testdubuffer", 12)+1, sizeof(char));

		/* Writing argv[1] in buf1, argv[2] in buf2 and "testdubuffer" in testdubuffer */
		snprintf(buf1, strnlen(argv[1], size)+1, "%s", argv[1]);
		snprintf(buf2, strnlen(argv[2], size)+1, "%s", argv[2]);
		snprintf(testdubuffer, strnlen("testdubuffer", 12)+1, "%s", "testdubuffer");

		/* Outputing buf1, then buf2 */
		printf("%s\n", buf1);
		printf("buffer : %s\n", buf2);
		
		/* Memory liberation of buf2. Then reallocation for the right size */		
		free(buf2);
		buf2 = NULL;
		buf2 = (char*)calloc(strnlen(testdubuffer, 12)+1, sizeof(char));

		/* Wrinting testdubuffer in buf2 */
		snprintf(buf2, strnlen(testdubuffer, 12)+1, "%s", testdubuffer);

		/* Getting size of buf2 */
		length = strnlen(buf2, 12)+1;

		/* If writing worked (size>0), outputing buf2 and free memory */
		if(length > 0){
			printf("buffer : %s\n", buf2);
		/* If writing failed, free memory and exit with error code 3 */
		}else{
			perror("Copy of testdubuffer to buf2 failed");
			ret = 3;
		}
		free(buf2);
		free(buf1);
		free(testdubuffer);
		buf2 = NULL;
		buf1 = NULL;
		testdubuffer = NULL;
		size = 0;
		length = 0;
		return ret;
	}else{
		if (argc < 3)
		{
			/* If there are less than two arguments given, exiting with error code 1 */
			perror("Too few arguments");
			return 1;
		}else{
			/* If there are more than two arguments given, exiting with error code 2 */
			perror("Too many arguments");
			return 2;
		}
	}
}
コード例 #6
0
ファイル: main.c プロジェクト: k0ekk0ek/valiant
int
main (int argc, char *argv[])
{
  cfg_t *cfg;
  char *prog;
  char *config_file = "/etc/valiant/valiant.conf";
  vt_context_t *ctx;
  vt_dict_type_t *types[7];
  vt_error_t err;
  vt_thread_pool_t *pool;
  vt_stats_t *stats, *new_stats;

  if ((prog = strrchr (argv[0], '/')))
    prog++;
  else
    prog = argv[0];

  /* parse command line options */
  int c;
  char *short_opts = "c:hV";
  struct option long_opts[] = {
    {"help", no_argument, NULL, 'h'},
    {"version", no_argument, NULL, 'V'},
    {"config-file", required_argument, NULL, 'c'}
  };

  for (; (c = getopt_long (argc, argv, short_opts, long_opts, NULL)) != EOF; ) {
    switch (c) {
      case 'c':
        config_file = optarg;
        break;
      case 'h':
        help (prog);
        break; /* never reached */
      case 'V':
        version (prog);
        break; /* never reached */
      default:
        usage (prog);
        break; /* never reached */
    }
  }

  /* it's important that wathchdog is initialized before any threads are
     created because it sets the calling threads signal mask to ignore all
     signals */
  vt_watchdog_init ();







  /* parse configuration file */
  if (! (cfg = vt_cfg_parse (config_file)))
    return 1;

  types[0] = vt_dict_dnsbl_type ();
  types[1] = vt_dict_hash_type ();
  types[2] = vt_dict_pcre_type ();
  types[3] = vt_dict_rhsbl_type ();
  types[4] = vt_dict_spf_type ();
  types[5] = vt_dict_str_type ();
  types[6] = NULL;

  if (! (ctx = vt_context_create (types, cfg, &err)))
    vt_fatal ("cannot create context: %d", err);

  cfg_free (cfg);


  // drop priveleges
  // fprintf (stderr, "%s (%d)\n", __func__, __LINE__);
  // create workers

  // create stats printer
  stats = vt_stats_create (ctx->dicts, ctx->ndicts, &err);
  vt_stats_thread (stats);

  vt_worker_arg_t warg;
  warg.context = ctx;
  warg.stats = stats;

  if (! (pool = vt_thread_pool_create ((void *)&warg, ctx->max_threads, &vt_worker, &err)))
    return EXIT_FAILURE;
  vt_thread_pool_set_max_idle_threads (pool, ctx->max_idle_threads);
  vt_thread_pool_set_max_queued (pool, ctx->max_tasks);
  vt_debug ("created thread pool");
  /* open socket that we will listen on */
  struct sockaddr_storage their_addr;
  socklen_t addr_size;
  struct addrinfo hints, *res;
  int sock, conn;
  //vt_worker_arg_t *arg;
  int *task;

  memset (&hints, 0, sizeof (hints));
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_PASSIVE;

  getaddrinfo (NULL, ctx->port, &hints, &res);

  sock = socket (res->ai_family, res->ai_socktype, res->ai_protocol);
  bind(sock, res->ai_addr, res->ai_addrlen);
  listen(sock, 10);

  fd_set fds;
  struct timeval tv;
  int dead, ret;
  cfg_t *new_cfg;
  vt_context_t *new_ctx;
  vt_thread_pool_t *new_pool;
  tv.tv_sec = VT_SELECT_TIMEOUT_SECONDS;
  tv.tv_usec = VT_SELECT_TIMEOUT_MICROSECONDS;

  for (dead = 0; ! dead; ) {
    FD_ZERO (&fds);
    FD_SET (sock, &fds);

    ret = select (sock+1, &fds, NULL, NULL, &tv);

    /* always check if we received a signal or not */
    switch (vt_watchdog_signal ()) {
      case SIGTERM: /* terminate */
        dead = 1;
        break;
      case SIGHUP: /* reload */
        new_cfg = NULL;
        new_ctx = NULL;
        new_pool = NULL;
vt_debug ("%s:%d", __func__, __LINE__);
        if (! (new_cfg = vt_cfg_parse (config_file))) {
          vt_error ("%s: could not parse %s: reload aborted",
            __func__, config_file);
          goto failure_reload;
        }
vt_debug ("%s:%d", __func__, __LINE__);
        if (! (new_ctx = vt_context_create (types, new_cfg, &err))) {
          vt_error ("%s: could not create context: reload aborted", __func__);
          goto failure_reload;
        }
vt_debug ("%s:%d", __func__, __LINE__);
        cfg_free (new_cfg);
        new_cfg = NULL;

        new_stats = vt_stats_create (new_ctx->dicts, new_ctx->ndicts, &err);
        vt_stats_thread (stats);

        warg.context = new_ctx;
        warg.stats = new_stats;

        new_pool = vt_thread_pool_create ((void *)&warg,
          new_ctx->max_threads, &vt_worker, &err);
vt_debug ("%s:%d", __func__, __LINE__);
        if (! new_pool) {
          vt_error ("%s: could not create workers: reload aborted", __func__);
          goto failure_reload;
        }
        vt_thread_pool_set_max_idle_threads (new_pool, new_ctx->max_idle_threads);
        vt_thread_pool_set_max_queued (new_pool, new_ctx->max_tasks);
vt_debug ("%s:%d", __func__, __LINE__);
        vt_stats_destroy (stats, NULL);
        vt_cleanup (pool, ctx, 1);
        ctx = new_ctx;
        pool = new_pool;
        stats = new_stats;
        break;
failure_reload:
vt_error ("%s:%d", __func__, __LINE__);
        if (new_cfg)
          cfg_free (new_cfg);
        if (new_ctx)
          (void)vt_context_destroy (new_ctx, NULL);
        if (new_pool)
          (void)vt_thread_pool_destroy (new_pool, NULL);
        break;
    }

    if (ret < 0) {
      if (errno != EINTR)
        vt_fatal ("%s: select: %s", __func__, strerror (errno));
      /* ignore */
    } else if (ret > 0) {
      if ((conn = accept (sock, (struct sockaddr *)&their_addr, &addr_size)) < 0)
        vt_fatal ("%s: accept: %s", __func__, strerror (errno));
      if (! (task = calloc (1, sizeof (int))))
        vt_fatal ("%s: calloc: %s", __func__, strerror (errno));
      *task = conn;
      vt_thread_pool_push (pool, (void *)task, &err);
      // FIXME: handle more errors etc!
    }
  }

  // terminate
  (void)close (sock); // probably needs to be done differently!
  //
  vt_cleanup (pool, ctx, 0);
  // 0. close socket
  //    if there is one... etc!
  // 1. kill work force
  // 2. kill context
  // 3. exit
  /* cleanup workers and context */
  //vt_thread_pool_destroy (workers, &err);

  /* remove pid file */
  // IMPLEMENT

  return EXIT_SUCCESS;
}
コード例 #7
0
ファイル: egl-x11-clear.c プロジェクト: Astinj/grate
static struct window *window_create(struct display *display, const char *name,
				    unsigned int x, unsigned int y,
				    unsigned int width, unsigned int height)
{
	static const EGLint attribs[] = {
		EGL_RED_SIZE, 1,
		EGL_GREEN_SIZE, 1,
		EGL_BLUE_SIZE, 1,
		EGL_DEPTH_SIZE, 1,
		EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
		EGL_NONE
	};
	static const EGLint attrs[] = {
		EGL_CONTEXT_CLIENT_VERSION, 2,
		EGL_NONE
	};
	XSetWindowAttributes attr;
	struct window *window;
	unsigned long mask;
	XVisualInfo visual;
	EGLint num_configs;
	XVisualInfo *info;
	XSizeHints hints;
	EGLConfig config;
	int num_visuals;
	EGLint version;
	Window root;
	int screen;
	EGLint vid;

	window = calloc(1, sizeof(*window));
	if (!window)
		return NULL;

	window->display = display;

	screen = DefaultScreen(display->x11);
	root = RootWindow(display->x11, screen);

	if (!eglChooseConfig(display->egl, attribs, &config, 1, &num_configs)) {
		free(window);
		return NULL;
	}

	if (!eglGetConfigAttrib(display->egl, config, EGL_NATIVE_VISUAL_ID, &vid)) {
		free(window);
		return NULL;
	}

	visual.visualid = vid;

	info = XGetVisualInfo(display->x11, VisualIDMask, &visual, &num_visuals);
	if (!info) {
		free(window);
		return NULL;
	}

	memset(&attr, 0, sizeof(attr));
	attr.background_pixel = 0;
	attr.border_pixel = 0;
	attr.colormap = XCreateColormap(display->x11, root, info->visual, AllocNone);
	attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
	mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

	window->x11 = XCreateWindow(display->x11, root, 0, 0, width, height,
				    0, info->depth, InputOutput, info->visual,
				    mask, &attr);
	if (!window->x11) {
		free(window);
		return NULL;
	}

	memset(&hints, 0, sizeof(hints));
	hints.x = x;
	hints.y = y;
	hints.width = width;
	hints.height = height;
	hints.flags = USSize | USPosition;

	XSetNormalHints(display->x11, window->x11, &hints);
	XSetStandardProperties(display->x11, window->x11, name, name, None,
			       NULL, 0, &hints);

	eglBindAPI(EGL_OPENGL_ES_API);

	window->context = eglCreateContext(display->egl, config,
					   EGL_NO_CONTEXT, attrs);
	if (window->context == EGL_NO_CONTEXT) {
		free(window);
		return NULL;
	}

	eglQueryContext(display->egl, window->context, EGL_CONTEXT_CLIENT_VERSION, &version);
	printf("OpenGL ES: %d\n", version);

	window->surface = eglCreateWindowSurface(display->egl, config,
						 window->x11, NULL);
	if (window->surface == EGL_NO_SURFACE) {
		free(window);
		return NULL;
	}

	XFree(info);

	window->width = width;
	window->height = height;

	return window;
}
コード例 #8
0
ファイル: mteObjectsTable.c プロジェクト: OPSF/uClinux
int
write_mteObjectsEntryStatus(int action,
                            u_char * var_val,
                            u_char var_val_type,
                            size_t var_val_len,
                            u_char * statP, oid * name, size_t name_len)
{
    struct mteObjectsTable_data *StorageTmp = NULL;
    static struct mteObjectsTable_data *StorageNew, *StorageDel;
    size_t          newlen =
        name_len - (sizeof(mteObjectsTable_variables_oid) / sizeof(oid) +
                    3 - 1);
    static int      old_value;
    int             set_value;
    static netsnmp_variable_list *vars, *vp;
    struct header_complex_index *hciptr;


    StorageTmp =
        header_complex(mteObjectsTableStorage, NULL,
                       &name[sizeof(mteObjectsTable_variables_oid) /
                             sizeof(oid) + 3 - 1], &newlen, 1, NULL, NULL);

    if (var_val_type != ASN_INTEGER || var_val == NULL) {
        snmp_log(LOG_ERR,
                 "write to mteObjectsEntryStatus not ASN_INTEGER\n");
        return SNMP_ERR_WRONGTYPE;
    }

    if (StorageTmp && StorageTmp->storagetype == ST_READONLY) {
        return SNMP_ERR_NOTWRITABLE;
    }

    set_value = *((long *) var_val);


    /*
     * check legal range, and notReady is reserved for us, not a user 
     */
    if (set_value < 1 || set_value > 6 || set_value == RS_NOTREADY)
        return SNMP_ERR_INCONSISTENTVALUE;


    switch (action) {
    case RESERVE1:
        /*
         * stage one: test validity 
         */
        if (StorageTmp == NULL) {
            /*
             * create the row now? 
             */


            /*
             * ditch illegal values now 
             */
            if (set_value == RS_ACTIVE || set_value == RS_NOTINSERVICE)
                return SNMP_ERR_INCONSISTENTVALUE;


            /*
             * destroying a non-existent row is actually legal 
             */
            if (set_value == RS_DESTROY) {
                return SNMP_ERR_NOERROR;
            }


            /*
             * illegal creation values 
             */
            if (set_value == RS_ACTIVE || set_value == RS_NOTINSERVICE) {
                return SNMP_ERR_INCONSISTENTVALUE;
            }
        } else {
            /*
             * row exists.  Check for a valid state change 
             */
            if (set_value == RS_CREATEANDGO
                || set_value == RS_CREATEANDWAIT) {
                /*
                 * can't create a row that exists 
                 */
                return SNMP_ERR_INCONSISTENTVALUE;
            }
            /*
             * XXX: interaction with row storage type needed 
             */
        }
        break;




    case RESERVE2:
        /*
         * memory reseveration, final preparation... 
         */
        if (StorageTmp == NULL) {
            /*
             * creation 
             */
            vars = NULL;


            snmp_varlist_add_variable(&vars, NULL, 0, ASN_OCTET_STR, NULL, 0);  /* mteOwner */
            snmp_varlist_add_variable(&vars, NULL, 0, ASN_OCTET_STR, NULL, 0);  /* mteObjectsName */
            snmp_varlist_add_variable(&vars, NULL, 0, ASN_UNSIGNED, NULL, 0);   /* mteObjectsIndex */

            if (header_complex_parse_oid
                (&
                 (name
                  [sizeof(mteObjectsTable_variables_oid) / sizeof(oid) +
                   2]), newlen, vars) != SNMPERR_SUCCESS) {
                /*
                 * XXX: free, zero vars 
                 */
                return SNMP_ERR_INCONSISTENTNAME;
            }
            vp = vars;


            StorageNew = SNMP_MALLOC_STRUCT(mteObjectsTable_data);
            if (StorageNew == NULL)
                return SNMP_ERR_GENERR;
            StorageNew->mteOwner = netsnmp_strdup_and_null(vp->val.string,
                                                           vp->val_len);
            StorageNew->mteOwnerLen = vp->val_len;
            vp = vp->next_variable;
            StorageNew->mteObjectsName  =
                netsnmp_strdup_and_null(vp->val.string,
                                        vp->val_len);
            StorageNew->mteObjectsNameLen = vp->val_len;
            vp = vp->next_variable;
            StorageNew->mteObjectsIndex = *(vp->val.integer);

            /*
             * XXX: fill in default row values here into StorageNew 
             */
            StorageNew->mteObjectsID = calloc(1, sizeof(oid) * sizeof(2));      /* 0.0 */
            StorageNew->mteObjectsIDLen = 2;
            StorageNew->mteObjectsIDWildcard = MTEOBJECTSIDWILDCARD_FALSE;

            StorageNew->mteObjectsEntryStatus = set_value;
            /*
             * XXX: free, zero vars, no longer needed? 
             */
        }


        break;




    case FREE:
        /*
         * XXX: free, zero vars 
         */
        /*
         * Release any resources that have been allocated 
         */
        break;




    case ACTION:
        /*
         * The variable has been stored in set_value for you to
         * use, and you have just been asked to do something with
         * it.  Note that anything done here must be reversable in
         * the UNDO case 
         */


        if (StorageTmp == NULL) {
            /*
             * row creation, so add it 
             */
            if (StorageNew != NULL)
                mteObjectsTable_add(StorageNew);
            /*
             * XXX: ack, and if it is NULL? 
             */
        } else if (set_value != RS_DESTROY) {
            /*
             * set the flag? 
             */
            old_value = StorageTmp->mteObjectsEntryStatus;
            StorageTmp->mteObjectsEntryStatus = *((long *) var_val);
        } else {
            /*
             * destroy...  extract it for now 
             */
            hciptr =
                header_complex_find_entry(mteObjectsTableStorage,
                                          StorageTmp);
            StorageDel =
                header_complex_extract_entry(&mteObjectsTableStorage,
                                             hciptr);
        }
        break;




    case UNDO:
        /*
         * Back out any changes made in the ACTION case 
         */
        if (StorageTmp == NULL) {
            /*
             * row creation, so remove it again 
             */
            hciptr =
                header_complex_find_entry(mteObjectsTableStorage,
                                          StorageTmp);
            StorageDel =
                header_complex_extract_entry(&mteObjectsTableStorage,
                                             hciptr);
            /*
             * XXX: free it 
             */
        } else if (StorageDel != NULL) {
            /*
             * row deletion, so add it again 
             */
            mteObjectsTable_add(StorageDel);
        } else {
            StorageTmp->mteObjectsEntryStatus = old_value;
        }
        break;




    case COMMIT:
        /*
         * Things are working well, so it's now safe to make the change
         * permanently.  Make sure that anything done here can't fail! 
         */
        if (StorageDel != NULL) {
            StorageDel = 0;
            /*
             * XXX: free it, its dead 
             */
        } else {
            if (StorageTmp
                && StorageTmp->mteObjectsEntryStatus == RS_CREATEANDGO) {
                StorageTmp->mteObjectsEntryStatus = RS_ACTIVE;
            } else if (StorageTmp &&
                       StorageTmp->mteObjectsEntryStatus ==
                       RS_CREATEANDWAIT) {
                StorageTmp->mteObjectsEntryStatus = RS_NOTINSERVICE;
            }
        }
        break;
    }
    return SNMP_ERR_NOERROR;
}
コード例 #9
0
ファイル: testwt_clb.c プロジェクト: hpcdev/xdm
int main (int argc, char **argv)
{
  int exoid, num_dim, num_nodes, num_elem, num_elem_blk;
  int num_elem_in_block[10], num_nodes_per_elem[10];
  int num_node_sets, num_side_sets, error;
  int i, j, k, kk, m, *elem_map, *connect;
  int node_list[100],elem_list[100],side_list[100];
  int ebids[10], ssids[10], nsids[10], nattr[10];
  int num_nodes_per_set[10], num_elem_per_set[10];
  int num_df_per_set[10];
  int  num_qa_rec, num_info;
  int num_glo_vars, num_nod_vars, num_ele_vars, num_nset_vars, num_sset_vars;
  int *truth_tab, *nset_tab, *sset_tab;
  int whole_time_step, num_time_steps;
  int CPU_word_size,IO_word_size;
  int prop_array[2];

  float *glob_var_vals, *nodal_var_vals, *elem_var_vals, *nset_var_vals, *sset_var_vals;
  float time_value;
  float x[100], y[100], z[100];
  float attrib[1], dist_fact[100];
  char *coord_names[3], *qa_record[2][4], *info[3], *var_names[7];
  char *prop_names[2];
  char *eb_type[10];
   
  ex_opts (EX_VERBOSE || EX_ABORT);

  /* Specify compute and i/o word size */

  CPU_word_size = 0;                   /* sizeof(float) */
  IO_word_size = 4;                    /* (4 bytes) */

  /* create EXODUS II file */

  exoid = ex_create ("test.exo",       /* filename path */
		     EX_CLOBBER,      /* create mode */
		     &CPU_word_size,  /* CPU float word size in bytes */
		     &IO_word_size);  /* I/O float word size in bytes */
  printf ("after ex_create for test.exo, exoid = %d\n", exoid);
  printf (" cpu word size: %d io word size: %d\n",CPU_word_size,IO_word_size);

  /* ncopts = NC_VERBOSE; */

  /* initialize file with parameters */

  num_dim = 3;
  num_nodes = 33;
  num_elem = 7;
  num_elem_blk = 7;
  num_node_sets = 2;
  num_side_sets = 5;

  error = ex_put_init (exoid, "This is a test", num_dim, num_nodes, num_elem,
		       num_elem_blk, num_node_sets, num_side_sets);

  printf ("after ex_put_init, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  /* write nodal coordinates values and names to database */

  /* Quad #1 */
  x[0] = 0.0; y[0] = 0.0; z[0] = 0.0;
  x[1] = 1.0; y[1] = 0.0; z[1] = 0.0;
  x[2] = 1.0; y[2] = 1.0; z[2] = 0.0;
  x[3] = 0.0; y[3] = 1.0; z[3] = 0.0;

  /* Quad #2 */
  x[4]  =  1.0; y[4]  =  0.0; z[4]  =  0.0;
  x[5]  =  2.0; y[5]  =  0.0; z[5]  =  0.0;
  x[6]  =  2.0; y[6]  =  1.0; z[6]  =  0.0;
  x[7]  =  1.0; y[7]  =  1.0; z[7]  =  0.0;

  /* Hex #1 */
  x[8]  =  0.0; y[8]  =  0.0; z[8]  =  0.0;
  x[9]  = 10.0; y[9]  =  0.0; z[9]  =  0.0;
  x[10] = 10.0; y[10] =  0.0; z[10] =-10.0;
  x[11] =  1.0; y[11] =  0.0; z[11] =-10.0;
  x[12] =  1.0; y[12] = 10.0; z[12] =  0.0;
  x[13] = 10.0; y[13] = 10.0; z[13] =  0.0;
  x[14] = 10.0; y[14] = 10.0; z[14] =-10.0;
  x[15] =  1.0; y[15] = 10.0; z[15] =-10.0;

  /* Tetra #1 */
  x[16] =  0.0; y[16] =  0.0; z[16] =  0.0;
  x[17] =  1.0; y[17] =  0.0; z[17] =  5.0;
  x[18] = 10.0; y[18] =  0.0; z[18] =  2.0;
  x[19] =  7.0; y[19] =  5.0; z[19] =  3.0;

  /* Wedge #1 */
  x[20] =  3.0; y[20] =  0.0; z[20] =  6.0;
  x[21] =  6.0; y[21] =  0.0; z[21] =  0.0;
  x[22] =  0.0; y[22] =  0.0; z[22] =  0.0;
  x[23] =  3.0; y[23] =  2.0; z[23] =  6.0;
  x[24] =  6.0; y[24] =  2.0; z[24] =  2.0;
  x[25] =  0.0; y[25] =  2.0; z[25] =  0.0;

  /* Tetra #2 */
  x[26] =  2.7; y[26] =  1.7; z[26] =  2.7;
  x[27] =  6.0; y[27] =  1.7; z[27] =  3.3;
  x[28] =  5.7; y[28] =  1.7; z[28] =  1.7;
  x[29] =  3.7; y[29] =  0.0; z[29] =  2.3;

  /* 3d Tri */
  x[30] =  0.0; y[30] =  0.0; z[30] =  0.0;
  x[31] = 10.0; y[31] =  0.0; z[31] =  0.0;
  x[32] = 10.0; y[32] = 10.0; z[32] = 10.0;

  error = ex_put_coord (exoid, x, y, z);
  printf ("after ex_put_coord, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  coord_names[0] = "xcoor";
  coord_names[1] = "ycoor";
  coord_names[2] = "zcoor";

  error = ex_put_coord_names (exoid, coord_names);
  printf ("after ex_put_coord_names, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  /* write element order map */

  elem_map = (int *) calloc(num_elem, sizeof(int));

  for (i=1; i<=num_elem; i++)
    {
      elem_map[i-1] = i;
    }

  error = ex_put_map (exoid, elem_map);
  printf ("after ex_put_map, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  free (elem_map);


  /* write element block parameters */

  num_elem_in_block[0] = 1;
  num_elem_in_block[1] = 1;
  num_elem_in_block[2] = 1;
  num_elem_in_block[3] = 1;
  num_elem_in_block[4] = 1;
  num_elem_in_block[5] = 1;
  num_elem_in_block[6] = 1;

  num_nodes_per_elem[0] = 4; /* elements in block #1 are 4-node quads  */
  num_nodes_per_elem[1] = 4; /* elements in block #2 are 4-node quads  */
  num_nodes_per_elem[2] = 8; /* elements in block #3 are 8-node hexes  */
  num_nodes_per_elem[3] = 4; /* elements in block #4 are 4-node tetras */
  num_nodes_per_elem[4] = 6; /* elements in block #5 are 6-node wedges */
  num_nodes_per_elem[5] = 8; /* elements in block #6 are 8-node tetras */
  num_nodes_per_elem[6] = 3; /* elements in block #7 are 3-node tris   */

  ebids[0] = 10;
  ebids[1] = 11;
  ebids[2] = 12;
  ebids[3] = 13;
  ebids[4] = 14;
  ebids[5] = 15;
  ebids[6] = 16;

  nattr[0] = nattr[1] = nattr[2] = nattr[3] = 1;
  nattr[4] = nattr[5] = nattr[6] = 1;
   
  eb_type[0] = "quad";
  eb_type[1] = "quad";
  eb_type[2] = "hex";
  eb_type[3] = "tetra";
  eb_type[4] = "wedge";
  eb_type[5] = "tetra";
  eb_type[6] = "tri";
     
  error = ex_put_concat_elem_block (exoid, ebids, eb_type,
				    num_elem_in_block, num_nodes_per_elem,
				    nattr, 0);
  printf ("after ex_put_concat_elem_block, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  /* write element block properties */

  prop_names[0] = "MATL";
  prop_names[1] = "DENSITY";
  error = ex_put_prop_names(exoid,EX_ELEM_BLOCK,2,prop_names);
  printf ("after ex_put_prop_names, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_ELEM_BLOCK, ebids[0], "MATL", 10);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_ELEM_BLOCK, ebids[1], "MATL", 20);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_ELEM_BLOCK, ebids[2], "MATL", 30);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_ELEM_BLOCK, ebids[3], "MATL", 40);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_ELEM_BLOCK, ebids[4], "MATL", 50);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_ELEM_BLOCK, ebids[5], "MATL", 60);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_ELEM_BLOCK, ebids[6], "MATL", 70);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* write element connectivity */

  connect = (int *) calloc(8, sizeof(int));
  connect[0] = 1; connect[1] = 2; connect[2] = 3; connect[3] = 4;

  error = ex_put_elem_conn (exoid, ebids[0], connect);
  printf ("after ex_put_elem_conn, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  connect[0] = 5; connect[1] = 6; connect[2] = 7; connect[3] = 8;

  error = ex_put_elem_conn (exoid, ebids[1], connect);
  printf ("after ex_put_elem_conn, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  connect[0] = 9; connect[1] = 10; connect[2] = 11; connect[3] = 12;
  connect[4] = 13; connect[5] = 14; connect[6] = 15; connect[7] = 16;

  error = ex_put_elem_conn (exoid, ebids[2], connect);
  printf ("after ex_put_elem_conn, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  connect[0] = 17; connect[1] = 18; connect[2] = 19; connect[3] = 20;

  error = ex_put_elem_conn (exoid, ebids[3], connect);
  printf ("after ex_put_elem_conn, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  connect[0] = 21; connect[1] = 22; connect[2] = 23;
  connect[3] = 24; connect[4] = 25; connect[5] = 26;

  error = ex_put_elem_conn (exoid, ebids[4], connect);
  printf ("after ex_put_elem_conn, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  connect[0] = 17; connect[1] = 18; connect[2] = 19; connect[3] = 20;
  connect[4] = 27; connect[5] = 28; connect[6] = 30; connect[7] = 29;

  error = ex_put_elem_conn (exoid, ebids[5], connect);
  printf ("after ex_put_elem_conn, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  connect[0] = 31; connect[1] = 32; connect[2] = 33;

  error = ex_put_elem_conn (exoid, ebids[6], connect);
  printf ("after ex_put_elem_conn, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  free (connect);


  /* write element block attributes */

  attrib[0] = 3.14159;
  error = ex_put_elem_attr (exoid, ebids[0], attrib);
  printf ("after ex_put_elem_attr, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  attrib[0] = 6.14159;
  error = ex_put_elem_attr (exoid, ebids[1], attrib);
  printf ("after ex_put_elem_attr, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_elem_attr (exoid, ebids[2], attrib);
  printf ("after ex_put_elem_attr, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_elem_attr (exoid, ebids[3], attrib);
  printf ("after ex_put_elem_attr, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_elem_attr (exoid, ebids[4], attrib);
  printf ("after ex_put_elem_attr, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_elem_attr (exoid, ebids[5], attrib);
  printf ("after ex_put_elem_attr, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_elem_attr (exoid, ebids[6], attrib);
  printf ("after ex_put_elem_attr, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  /* write individual node sets */


  nsids[0] = 20; nsids[1] = 21;
  num_nodes_per_set[0] = 5; num_nodes_per_set[1] = 3;
  num_df_per_set[0] = 5; num_df_per_set[1] = 3;

  error = ex_put_concat_node_sets (exoid, nsids, num_nodes_per_set,
				   num_df_per_set, 0, 0, 0, 0);

  printf ("after ex_put_concat_node_sets, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  node_list[0] = 100; node_list[1] = 101; node_list[2] = 102; 
  node_list[3] = 103; node_list[4] = 104; 

  dist_fact[0] = 1.0; dist_fact[1] = 2.0; dist_fact[2] = 3.0;
  dist_fact[3] = 4.0; dist_fact[4] = 5.0;

  error = ex_put_node_set (exoid, 20, node_list);
  printf ("after ex_put_node_set, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_node_set_dist_fact (exoid, 20, dist_fact);
  printf ("after ex_put_node_set_dist_fact, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  node_list[0] = 200; node_list[1] = 201; node_list[2] = 202; 

  dist_fact[0] = 1.1; dist_fact[1] = 2.1; dist_fact[2] = 3.1;

  error = ex_put_node_set (exoid, 21, node_list);
  printf ("after ex_put_node_set, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_node_set_dist_fact (exoid, 21, dist_fact);
  printf ("after ex_put_node_set_dist_fact, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  error = ex_put_prop(exoid, EX_NODE_SET, 20, "FACE", 4);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_NODE_SET, 21, "FACE", 5);
  printf ("after ex_put_prop, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  prop_array[0] = 1000;
  prop_array[1] = 2000;

  error = ex_put_prop_array(exoid, EX_NODE_SET, "VELOCITY", prop_array);
  printf ("after ex_put_prop_array, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  /* Define the sideset params at one time, then write individually */
  ssids[0] = 30;
  ssids[1] = 31;
  ssids[2] = 32;
  ssids[3] = 33;
  ssids[4] = 34;

  num_elem_per_set[0] = 2;
  num_elem_per_set[1] = 2;
  num_elem_per_set[2] = 7;
  num_elem_per_set[3] = 8;
  num_elem_per_set[4] = 10;

  num_df_per_set[0] = 4;
  num_df_per_set[1] = 4;
  num_df_per_set[2] = 0;
  num_df_per_set[3] = 0;
  num_df_per_set[4] = 0;

  error = ex_put_concat_side_sets (exoid, ssids, num_elem_per_set,
				   num_df_per_set, 0, 0, 0, 0, 0);
  printf ("after ex_put_concat_side_sets, error = %d\n", error);

  /* write individual side sets */

  /* side set #1  - quad */

  elem_list[0] = 2; elem_list[1] = 2;

  side_list[0] = 4; side_list[1] = 2;

  dist_fact[0] = 30.0; dist_fact[1] = 30.1; dist_fact[2] = 30.2;
  dist_fact[3] = 30.3;

  error = ex_put_side_set (exoid, 30, elem_list, side_list);
  printf ("after ex_put_side_set, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_side_set_dist_fact (exoid, 30, dist_fact);
  printf ("after ex_put_side_set_dist_fact, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* side set #2  - quad, spanning 2 elements  */

  elem_list[0] = 1; elem_list[1] = 2;

  side_list[0] = 2; side_list[1] = 3;

  dist_fact[0] = 31.0; dist_fact[1] = 31.1; dist_fact[2] = 31.2;
  dist_fact[3] = 31.3;

  error = ex_put_side_set (exoid, 31, elem_list, side_list);
  printf ("after ex_put_side_set, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_side_set_dist_fact (exoid, 31, dist_fact);
  printf ("after ex_put_side_set_dist_fact, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* side set #3  - hex */

  elem_list[0] = 3; elem_list[1] = 3;
  elem_list[2] = 3; elem_list[3] = 3;
  elem_list[4] = 3; elem_list[5] = 3;
  elem_list[6] = 3;

  side_list[0] = 5; side_list[1] = 3;
  side_list[2] = 3; side_list[3] = 2;
  side_list[4] = 4; side_list[5] = 1;
  side_list[6] = 6;

  error = ex_put_side_set (exoid, 32, elem_list, side_list);
  printf ("after ex_put_side_set, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* side set #4  - tetras */

  elem_list[0] = 4; elem_list[1] = 4;
  elem_list[2] = 4; elem_list[3] = 4;
  elem_list[4] = 6; elem_list[5] = 6;
  elem_list[6] = 6; elem_list[7] = 6;

  side_list[0] = 1; side_list[1] = 2;
  side_list[2] = 3; side_list[3] = 4;
  side_list[4] = 1; side_list[5] = 2;
  side_list[6] = 3; side_list[7] = 4;

  error = ex_put_side_set (exoid, 33, elem_list, side_list);
  printf ("after ex_put_side_set, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* side set #5  - wedges and tris */

  elem_list[0] = 5; elem_list[1] = 5;
  elem_list[2] = 5; elem_list[3] = 5;
  elem_list[4] = 5; elem_list[5] = 7;
  elem_list[6] = 7; elem_list[7] = 7;
  elem_list[8] = 7; elem_list[9] = 7;

  side_list[0] = 1; side_list[1] = 2;
  side_list[2] = 3; side_list[3] = 4;
  side_list[4] = 5; side_list[5] = 1;
  side_list[6] = 2; side_list[7] = 3;
  side_list[8] = 4; side_list[9] = 5;

  error = ex_put_side_set (exoid, 34, elem_list, side_list);
  printf ("after ex_put_side_set, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_SIDE_SET, 30, "COLOR", 100);
  printf ("after ex_put_prop, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_SIDE_SET, 31, "COLOR", 101);
  printf ("after ex_put_prop, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* write QA records; test empty and just blank-filled records */

  num_qa_rec = 2;


  qa_record[0][0] = "TESTWT";
  qa_record[0][1] = "testwt";
  qa_record[0][2] = "07/07/93";
  qa_record[0][3] = "15:41:33";
  qa_record[1][0] = "";
  qa_record[1][1] = "                            ";
  qa_record[1][2] = "";
  qa_record[1][3] = "                        ";

  error = ex_put_qa (exoid, num_qa_rec, qa_record);
  printf ("after ex_put_qa, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* write information records; test empty and just blank-filled records */

  num_info = 3;


  info[0] = "This is the first information record.";
  info[1] = "";
  info[2] = "                                     ";

  error = ex_put_info (exoid, num_info, info);
  printf ("after ex_put_info, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }



  /* write results variables parameters and names */
  num_glo_vars  = 1;
  num_nod_vars  = 2;
  num_ele_vars  = 3;
  num_nset_vars = 4;
  num_sset_vars = 7;

  truth_tab = (int *) calloc ((num_elem_blk  * num_ele_vars),  sizeof(int));
  nset_tab  = (int *) calloc ((num_node_sets * num_nset_vars), sizeof(int));
  sset_tab  = (int *) calloc ((num_side_sets * num_sset_vars), sizeof(int));

  k = 0;
  for (i=0; i<num_elem_blk; i++) {
    for (j=0; j<num_ele_vars; j++) {
      truth_tab[k++] = 1;
    }
  }
   
  k = 0;
  for (i=0; i<num_node_sets; i++) {
    for (j=0; j<num_nset_vars; j++) {
      if (k%2 == 0)
	nset_tab[k++] = 1;
      else
	nset_tab[k++] = 0;
    }
  }
   
  k = 0;
  for (i=0; i<num_side_sets; i++) {
    for (j=0; j<num_sset_vars; j++) {
      if (k%2 == 0)
	sset_tab[k++] = 0;
      else
	sset_tab[k++] = 1;
    }
  }
   
  ex_put_all_var_param(exoid, num_glo_vars, num_nod_vars, num_ele_vars, truth_tab,
		       num_nset_vars, nset_tab, num_sset_vars, sset_tab);
  printf ("after ex_put_all_var_param, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  free (truth_tab);
  free (nset_tab);
  free (sset_tab);
   
  var_names[0] = "glo_vars";
  error = ex_put_var_names (exoid, "g", num_glo_vars, var_names);
  printf ("after ex_put_var_names, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  /*              12345678901234567890123456789012 */
  var_names[0] = "node_variable_a_very_long_name_0";
  var_names[1] = "nod_var1";
  error = ex_put_var_names (exoid, "n", num_nod_vars, var_names);
  printf ("after ex_put_var_names, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }



  var_names[0] = "ele_var0";
  var_names[1] = "ele_var1";
  var_names[2] = "ele_var2";
  error = ex_put_var_names (exoid, "e", num_ele_vars, var_names);
  printf ("after ex_put_var_names, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  var_names[0] = "nset_var0";
  var_names[1] = "nset_var1";
  var_names[2] = "nset_var2";
  var_names[3] = "nset_var3";
  error = ex_put_var_names (exoid, "m", num_nset_vars, var_names);
  printf ("after ex_put_var_names, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  var_names[0] = "sset_var0";
  var_names[1] = "sset_var1";
  var_names[2] = "sset_var2";
  var_names[3] = "sset_var3";
  var_names[4] = "sset_var4";
  var_names[5] = "sset_var5";
  var_names[6] = "sset_var6";
  error = ex_put_var_names (exoid, "s", num_sset_vars, var_names);
  printf ("after ex_put_var_names, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* for each time step, write the analysis results;
   * the code below fills the arrays glob_var_vals, 
   * nodal_var_vals, and elem_var_vals with values for debugging purposes;
   * obviously the analysis code will populate these arrays
   */

  whole_time_step = 1;
  num_time_steps = 10;

  glob_var_vals =  (float *) calloc (num_glo_vars, CPU_word_size);
  nodal_var_vals = (float *) calloc (num_nodes, CPU_word_size);
  elem_var_vals =  (float *) calloc (4, CPU_word_size);
  nset_var_vals =  (float *) calloc (5, CPU_word_size);
  sset_var_vals =  (float *) calloc (10, CPU_word_size);

  for (i=0; i<num_time_steps; i++)
    {
      time_value = (float)(i+1)/100.;

      /* write time value */

      error = ex_put_time (exoid, whole_time_step, &time_value);
      printf ("after ex_put_time, error = %d\n", error);

      if (error) {
	ex_close (exoid);
	exit(-1);
      }

      /* write global variables */

      for (j=0; j<num_glo_vars; j++) {
	glob_var_vals[j] = (float)(j+2) * time_value;
      }

      error = ex_put_glob_vars (exoid, whole_time_step, num_glo_vars, 
				glob_var_vals);
      printf ("after ex_put_glob_vars, error = %d\n", error);

      if (error) {
	ex_close (exoid);
	exit(-1);
      }

      /* write nodal variables */

      for (k=1; k<=num_nod_vars; k++) {
	for (j=0; j<num_nodes; j++) {
	  nodal_var_vals[j] = (float)k + ((float)(j+1) * time_value);
	}

	error = ex_put_nodal_var (exoid, whole_time_step, k, num_nodes,
				  nodal_var_vals);
	printf ("after ex_put_nodal_var, error = %d\n", error);
	if (error) {
	  ex_close (exoid);
	  exit(-1);
	}

      }

      /* write element variables */

      for (k=1; k<=num_ele_vars; k++) {
	for (j=0; j<num_elem_blk; j++) {
	  for (m=0; m<num_elem_in_block[j]; m++) {
	    elem_var_vals[m] = (float)(k+1) + (float)(j+2) + 
	      ((float)(m+1)*time_value);
	  }
	  error = ex_put_elem_var (exoid, whole_time_step, k, ebids[j],
				   num_elem_in_block[j], elem_var_vals);
	  printf ("after ex_put_elem_var, error = %d\n", error);
	  if (error) {
	    ex_close (exoid);
	    exit(-1);
	  }
	}
      }

      /* write nodeset variables */

      kk = 0;
      for (j=0; j<num_node_sets; j++) {
	for (k=0; k<num_nset_vars; k++) {
	  if (kk++ % 2 == 0) {
	    for (m=0; m<num_nodes_per_set[j]; m++) {
	      nset_var_vals[m] = (float)(k+1) + (float)(j+2) + 
		((float)(m+1)*time_value);
	    }
	    error = ex_put_nset_var (exoid, whole_time_step, k+1, nsids[j],
				     num_nodes_per_set[j], nset_var_vals);
	    printf ("after ex_put_nset_var, error = %d\n", error);
	    if (error) {
	      ex_close (exoid);
	      exit(-1);
	    }
	  }
	}
      }

      /* write sideset variables */

      kk = 0;
      for (j=0; j<num_side_sets; j++) {
	for (k=0; k<num_sset_vars; k++) {
	  if (kk++ % 2 != 0) {
	    for (m=0; m<num_elem_per_set[j]; m++) {
	      sset_var_vals[m] = (float)(k+1) + (float)(j+2) + 
		((float)(m+1)*time_value);
	    }
	    error = ex_put_sset_var (exoid, whole_time_step, k+1, ssids[j],
				     num_elem_per_set[j], sset_var_vals);
	    printf ("after ex_put_sset_var, error = %d\n", error);
	    if (error) {
	      ex_close (exoid);
	      exit(-1);
	    }
	  }
	}
      }

      whole_time_step++;

      /* update the data file; this should be done at the end of every time step
       * to ensure that no data is lost if the analysis dies
       */
      error = ex_update (exoid);
      printf ("after ex_update, error = %d\n", error);
      if (error) {
	ex_close (exoid);
	exit(-1);
      }
    }
  free(glob_var_vals);
  free(nodal_var_vals);
  free(elem_var_vals);
  free(nset_var_vals);
  free(sset_var_vals);

  /* close the EXODUS files
   */
  error = ex_close (exoid);
  printf ("after ex_close, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }
  return 0;
}
コード例 #10
0
ファイル: level.c プロジェクト: Drooids/Corange
level* level_load_file(char* filename) {
  
  for(int i = 0; i < num_tile_types; i++) {
    tile_counts[i] = 0;
  }
  
  level* l = malloc(sizeof(level));
  l->num_tile_sets = num_tile_types;
  l->tile_sets = malloc(sizeof(tile_set) * num_tile_types);
  l->tile_map = calloc(sizeof(int), MAX_WIDTH * MAX_HEIGHT);
  
  SDL_RWops* file = SDL_RWFromFile(filename, "r");
  char line[MAX_WIDTH];
  
  int y = 0;
  int x = 0;
  while(SDL_RWreadline(file, line, 1024)) {
    
    for(x = 0; x < strlen(line); x++) {
      char c = line[x];
      int type = tile_for_char(c);
      
      l->tile_map[x + y * MAX_WIDTH] = type;
      tile_counts[type]++;
    }
    
    y++;
  }
  
  SDL_RWclose(file);
  
  /* Start from 1, type 0 is none! */
  for(int i = 1; i < num_tile_types; i++) {
    
    int num_tiles = tile_counts[i];
    
    float* position_data = malloc(sizeof(float) * 3 * 4 * num_tiles);
    float* uv_data = malloc(sizeof(float) * 2 * 4 * num_tiles);
    
    int pos_i  = 0;
    int uv_i = 0;
    
    for(x = 0; x < MAX_WIDTH; x++)
    for(y = 0; y < MAX_HEIGHT; y++) {
      int type = l->tile_map[x + y * MAX_WIDTH];
      if( type == i ) {
        
        position_data[pos_i] = x * TILE_SIZE; pos_i++;
        position_data[pos_i] = y * TILE_SIZE; pos_i++;
        position_data[pos_i] = 0; pos_i++;
        
        position_data[pos_i] = (x+1) * TILE_SIZE; pos_i++;
        position_data[pos_i] = y * TILE_SIZE; pos_i++;
        position_data[pos_i] = 0; pos_i++;
        
        position_data[pos_i] = (x+1) * TILE_SIZE; pos_i++;
        position_data[pos_i] = (y+1) * TILE_SIZE; pos_i++;
        position_data[pos_i] = 0; pos_i++;
        
        position_data[pos_i] = x * TILE_SIZE; pos_i++;
        position_data[pos_i] = (y+1) * TILE_SIZE; pos_i++;
        position_data[pos_i] = 0; pos_i++;
        
        uv_data[uv_i] = 0; uv_i++;
        uv_data[uv_i] = 0; uv_i++;
        
        uv_data[uv_i] = 1; uv_i++;
        uv_data[uv_i] = 0; uv_i++;
        
        uv_data[uv_i] = 1; uv_i++;
        uv_data[uv_i] = 1; uv_i++;
        
        uv_data[uv_i] = 0; uv_i++;
        uv_data[uv_i] = 1; uv_i++;
        
      }
    }
    
    l->tile_sets[i].num_tiles = num_tiles;
    
    glGenBuffers(1, &l->tile_sets[i].positions_buffer);
    glGenBuffers(1, &l->tile_sets[i].texcoords_buffer);
    
    glBindBuffer(GL_ARRAY_BUFFER, l->tile_sets[i].positions_buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3 * 4 * num_tiles, position_data, GL_STATIC_DRAW);
    
    glBindBuffer(GL_ARRAY_BUFFER, l->tile_sets[i].texcoords_buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 2 * 4 * num_tiles, uv_data, GL_STATIC_DRAW);
    
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    
    free(position_data);
    free(uv_data);
  
  }
    
  return l;
}
コード例 #11
0
void hi_ncurses_fpager_redraw(hi_ncurses_fpager *pager)
{
  int x, y;
  unsigned char val;
  off_t offset;
  char buffer[256];
  hi_diff_hunk *hunk;
  werase(pager->window);
  gboolean diff;
  void *highlighter_data = NULL;
  hi_ncurses_highlight *highlighter;
  enum hi_ncurses_colour colour;
  char format_str[256];
  int bytes;
  enum hi_ncurses_colour *highlight_colours = NULL;
  
  highlighter = pager->highlighter;
  
  if ((highlighter != NULL) && (highlighter->begin_func != NULL))
  {
    highlighter_data = highlighter->begin_func(pager->file);
  }
  
  /* Make the pager we're selected highlighted */
  if (pager == pager->curses->focused_pager)
    wattron(pager->window, A_REVERSE);
  
  box(pager->window, ACS_VLINE, ACS_HLINE);

  if (pager == pager->curses->focused_pager)
    wattroff(pager->window, A_REVERSE);
  
  mvwprintw(pager->window, pager->height-1, 2," %s ", pager->file->filename);  
  
  snprintf(format_str,256,pager->location_mode->constructor_string, pager->bytes_in_location);

  bytes = (pager->set_bytes_per_row == 0 ? pager->bytes_per_row : pager->set_bytes_per_row);
  if (bytes > pager->bytes_per_row)
  {
    bytes = pager->bytes_per_row;
  }
  
  highlight_colours = calloc((pager->height-2)*bytes, sizeof(enum hi_ncurses_colour));
  if ((highlighter != NULL) && (highlighter->block_func != NULL))
  {
	  highlighter->block_func(pager->file, pager->offset, (pager->height-2)*bytes, highlight_colours);
  }


  for (y=0; y< pager->height-2; y++)
  {
    for (x=0; x<bytes; x++)
    {
      offset = pager->offset+x+(pager->set_bytes_per_row == 0 ? pager->bytes_per_row*y : pager->set_bytes_per_row*y);

      if (offset < pager->file->size)
      {
          if (x == 0)
          {

            
            snprintf(buffer, 256, format_str, (unsigned int) offset);
            wmove(pager->window, y+1,2);
            waddstr(pager->window, buffer);
            

          }
          val = pager->file->memory[offset];
        
          diff = FALSE;
          if (pager->diff)
          {
            hunk = hi_diff_get_hunk(pager->diff, pager->file, offset);
            if (hunk != NULL && hunk->type == HI_DIFF_TYPE_DIFF)
            {
              diff = TRUE;
            }
            
          }
        
          if (TRUE == diff)
            wattron(pager->window, A_REVERSE);
          
          colour = highlight_colours[offset-pager->offset];
          if ((highlighter != NULL) && (highlighter->highlight_func != NULL))
          {
            colour = highlighter->highlight_func(pager->file, offset, val, highlighter_data);
            
          }

        
          if (colour != hi_ncurses_colour_normal)
          {
            wcolor_set(pager->window, colour, NULL);
          }
        
          /* Display byte */
          pager->display_mode->display_byte_func(pager, y+1, 3+pager->bytes_in_location, x, offset, val);
 
          if (colour != hi_ncurses_colour_normal)
          {
            wcolor_set(pager->window, hi_ncurses_colour_normal,NULL);
          }
          if (TRUE == diff)
            wattroff(pager->window, A_REVERSE);
            
      }
    }
  
  }
  if ((highlighter != NULL) && (highlighter->end_func != NULL))
  {
       highlighter->end_func(highlighter_data);
  }

  free(highlight_colours);
      
  wrefresh(pager->window);
}
コード例 #12
0
void *VSICalloc( size_t nCount, size_t nSize )

{
    return( calloc( nCount, nSize ) );
}
コード例 #13
0
ファイル: crm_correlate.c プロジェクト: GerHobbelt/crm114
//      How to do a correlate-style CLASSIFY on some text.
//
int crm_expr_correlate_classify(CSL_CELL *csl, ARGPARSE_BLOCK *apb,
        VHT_CELL **vht,
        CSL_CELL *tdw,
        char *txtptr, int txtstart, int txtlen)
{
    //      classify the sparse spectrum of this input window
    //      as belonging to a particular type.
    //
    //       This code should look very familiar- it's cribbed from
    //       the code for LEARN
    //
    int i, j, k;
    char ptext[MAX_PATTERN]; //  the regex pattern
    int plen;
    //  the hash file names
    char htext[MAX_PATTERN + MAX_CLASSIFIERS * MAX_FILE_NAME_LEN];
    int htext_maxlen = MAX_PATTERN + MAX_CLASSIFIERS * MAX_FILE_NAME_LEN;
    int hlen;
    //  the match statistics variable
    char stext[MAX_PATTERN + MAX_CLASSIFIERS * (MAX_FILE_NAME_LEN + 100)];
    int stext_maxlen = MAX_PATTERN + MAX_CLASSIFIERS * (MAX_FILE_NAME_LEN + 100);
    int slen;
    char svrbl[MAX_PATTERN]; //  the match statistics text buffer
    int svlen;
    int fnameoffset;
    char fname[MAX_FILE_NAME_LEN];
    int eflags;
    int cflags;

    struct stat statbuf;    //  for statting the hash file
    //regex_t regcb;

    unsigned int fcounts[MAX_CLASSIFIERS]; // total counts for feature normalize

    double cpcorr[MAX_CLASSIFIERS];         // corpus correction factors
    int64_t linear_hits[MAX_CLASSIFIERS];   // actual hits per classifier
    int64_t square_hits[MAX_CLASSIFIERS];   // square of runlenths of match
    int64_t cube_hits[MAX_CLASSIFIERS];     // cube of runlength matches
    int64_t quad_hits[MAX_CLASSIFIERS];     // quad of runlength matches
    int incr_hits[MAX_CLASSIFIERS];         // 1+2+3... hits per classifier

    int64_t total_linear_hits; // actual total linear hits for all classifiers
    int64_t total_square_hits; // actual total square hits for all classifiers
    int64_t total_cube_hits;   // actual total cube hits for all classifiers
    int64_t total_quad_hits;   // actual total cube hits for all classifiers
    int64_t total_features;    // total number of characters in the system

    hitcount_t totalhits[MAX_CLASSIFIERS];
    double tprob;       //  total probability in the "success" domain.

    int textlen;  //  text length  - rougly corresponds to
    //  information content of the text to classify

    double ptc[MAX_CLASSIFIERS]; // current running probability of this class
    double renorm = 0.0;

    char *hashes[MAX_CLASSIFIERS];
    int hashlens[MAX_CLASSIFIERS];
    char *hashname[MAX_CLASSIFIERS];
    int succhash;
    int vbar_seen;     // did we see '|' in classify's args?
    int maxhash;
    int fnstart, fnlen;
    int fn_start_here;
    int textoffset;
    int bestseen;
    int thistotal;

    if (internal_trace)
        fprintf(stderr, "executing a CLASSIFY\n");

    //          we use the main line txtptr, txtstart, and txtlen now,
    //          so we don't need to extract anything from the b1start stuff.

    //           extract the hash file names
    hlen = crm_get_pgm_arg(htext, htext_maxlen, apb->p1start, apb->p1len);
    hlen = crm_nexpandvar(htext, hlen, htext_maxlen, vht, tdw);

    //           extract the "this is a word" regex
    //
    plen = crm_get_pgm_arg(ptext, MAX_PATTERN, apb->s1start, apb->s1len);
    plen = crm_nexpandvar(ptext, plen, MAX_PATTERN, vht, tdw);

    //            extract the optional "match statistics" variable
    //
    svlen = crm_get_pgm_arg(svrbl, MAX_PATTERN, apb->p2start, apb->p2len);
    svlen = crm_nexpandvar(svrbl, svlen, MAX_PATTERN, vht, tdw);
    {
        int vstart, vlen;
        if (crm_nextword(svrbl, svlen, 0, &vstart, &vlen))
        {
            crm_memmove(svrbl, &svrbl[vstart], vlen);
            svlen = vlen;
            svrbl[vlen] = 0;
        }
        else
        {
            svlen = 0;
            svrbl[0] = 0;
        }
    }

    //     status variable's text (used for output stats)
    //
    stext[0] = 0;
    slen = 0;

    //            set our flags, if needed.  The defaults are
    //            "case"
    cflags = REG_EXTENDED;
    eflags = 0;

    if (apb->sflags & CRM_NOCASE)
    {
        if (user_trace)
            fprintf(stderr, " setting NOCASE for tokenization\n");
        cflags += REG_ICASE;
        eflags = 1;
    }


    //       Now, the loop to open the files.
    bestseen = 0;
    thistotal = 0;

    //      initialize our arrays for N .css files
    for (i = 0; i < MAX_CLASSIFIERS; i++)
    {
        fcounts[i] = 0;       // check later to prevent a divide-by-zero
                              // error on empty .css file
        cpcorr[i] = 0.0;      // corpus correction factors
        linear_hits[i] = 0;   // linear hits
        square_hits[i] = 0;   // square of the runlength
        cube_hits[i] = 0;     // cube of the runlength
        quad_hits[i] = 0;     // quad of the runlength
        incr_hits[i] = 0;     // 1+2+3... hits hits
        totalhits[i] = 0;     // absolute hit counts
        ptc[i] = 0.5;         // priori probability
    }

    //

    vbar_seen = 0;
    maxhash = 0;
    succhash = 0;
    fnameoffset = 0;

    //    now, get the file names and mmap each file
    //     get the file name (grody and non-8-bit-safe, but doesn't matter
    //     because the result is used for open() and nothing else.
    //   GROT GROT GROT  this isn't NULL-clean on filenames.  But then
    //    again, stdio.h itself isn't NULL-clean on filenames.
    if (user_trace)
        fprintf(stderr, "Classify list: -%.*s-\n", hlen, htext);
    fn_start_here = 0;
    fnlen = 1;
    while (fnlen > 0 && ((maxhash < MAX_CLASSIFIERS - 1)))
    {
        if (crm_nextword(htext,
                         hlen, fn_start_here,
                         &fnstart, &fnlen)
           && fnlen > 0)
        {
            strncpy(fname, &htext[fnstart], fnlen);
            fname[fnlen] = 0;
            //      fprintf(stderr, "fname is '%s' len %d\n", fname, fnlen);
            fn_start_here = fnstart + fnlen + 1;
            if (user_trace)
            {
                fprintf(stderr, "Classifying with file -%s- succhash=%d, maxhash=%d\n",
                        fname, succhash, maxhash);
            }
            if (fname[0] == '|' && fname[1] == 0)
            {
                if (vbar_seen)
                {
                    nonfatalerror("Only one '|' allowed in a CLASSIFY.\n",
                                  "We'll ignore it for now.");
                }
                else
                {
                    succhash = maxhash;
                }
                vbar_seen++;
            }
            else
            {
                //  be sure the file exists
                //             stat the file to get it's length
                k = stat(fname, &statbuf);
                //             quick check- does the file even exist?
                if (k != 0)
                {
                    nonfatalerror("Nonexistent Classify table named: ",
                                  fname);
                }
                else
                {
                    // [i_a] check hashes[] range BEFORE adding another one!
                    if (maxhash >= MAX_CLASSIFIERS)
                    {
                        nonfatalerror("Too many classifier files.",
                                      "Some may have been disregarded");
                    }
                    else
                    {
                        //  file exists - do the mmap
                        //
                        hashlens[maxhash] = statbuf.st_size;
                        // [i_a] hashlens[maxhash] must be fixed for the header size!
                        hashes[maxhash] = crm_mmap_file(fname,
                                                        0,
                                                        hashlens[maxhash],
                                                        PROT_READ,
                                                        MAP_SHARED,
                                                        CRM_MADV_RANDOM,
                                                        &hashlens[maxhash]);
                        if (hashes[maxhash] == MAP_FAILED)
                        {
                            nonfatalerror("Couldn't memory-map the table file",
                                          fname);
                        }
                        else
                        {
                            //
                            //     Check to see if this file is the right version
                            //
                            //     FIXME : for now, there's no version number
                            //     associated with a .correllation file
                            // int fev;
                            // if (0)
                            //(hashes[maxhash][0].hash != 1 ||
                            //  hashes[maxhash][0].key  != 0)
                            //{
                            //  fev = fatalerror ("The .css file is the wrong version!  Filename is: ",
                            //                   fname);
                            //  return (fev);
                            //}

                            //
                            //     save the name for later...
                            //
                            hashname[maxhash] = (char *)calloc((fnlen + 10), sizeof(hashname[maxhash][0]));
                            if (!hashname[maxhash])
                            {
                                untrappableerror(
                                    "Couldn't alloc hashname[maxhash]\n", "We need that part later, so we're stuck.  Sorry.");
                            }
                            else
                            {
                                strncpy(hashname[maxhash], fname, fnlen);
                                hashname[maxhash][fnlen] = 0;
                            }
                            maxhash++;
                        }
                    }
                }
            }
        }
    }

    //
    //    If there is no '|', then all files are "success" files.
    if (succhash == 0)
        succhash = maxhash;

    //    a CLASSIFY with no arguments is always a "success".
    if (maxhash == 0)
        return 0;

    if (user_trace)
    {
        fprintf(stderr, "Running with %d files for success out of %d files\n",
                succhash, maxhash);
    }

    // sanity checks...  Uncomment for super-strict CLASSIFY.
    //
    //    do we have at least 1 valid .css files?
    if (maxhash == 0)
    {
        return nonfatalerror("Couldn't open at least 1 .css file for classify().", "");
    }

#if 0
    //    do we have at least 1 valid .css file at both sides of '|'?
    if (!vbar_seen || succhash <= 0 || (maxhash <= succhash))
    {
        return nonfatalerror("Couldn't open at least 1 .css file per SUCC | FAIL category "
                             "for classify().\n", "Hope you know what are you doing.");
    }
#endif

    //
    //   now all of the files are mmapped into memory,
    //   and we can do the correlations and add up matches.
    i = 0;
    j = 0;
    k = 0;
    thistotal = 0;

    //     put in the ptr/start/len values we got from the outside caller
    textoffset = txtstart;
    textlen = txtlen;

    //
    //    We keep track of the hits in these categories
    //  linear_hits[MAX_CLASSIFIERS];  // actual hits per classifier
    //  square_hits[MAX_CLASSIFIERS];  // square of runlenths of match
    //  incr_hits[MAX_CLASSIFIERS];  // 1+2+3... hits per classifier
    //

    //   Now we do the actual correllation.
    //   for each file...
    //    slide the incoming text (mdw->filetext[textofset])
    //     across the corpus text (hashes[] from 0 to hashlens[])
    //      and count the bytes that are the same, the runlengths,
    //       etc.

    for (k = 0; k < maxhash; k++)
    {
        int it;  // it is the start index into the tested text
        int ik;  // ik is the start index into the known corpus text
        int ilm; // ilm is the "local" matches (N in a row)

        //    for each possible displacement of the known  (ik) text...
        for (ik = 0;
             ik < hashlens[k];
             ik++)
        {
            int itmax;

            ilm = 0;
            itmax = textlen;
            if (ik + itmax > hashlens[k])
                itmax = hashlens[k] - ik;
            // for each position in the test (it) text...
            for (it = 0;
                 it < itmax;
                 it++)
            {
                //   do the characters in this position match?
                if (hashes[k][ik + it] == txtptr[textoffset + it])
                {
                    // yes they matched
                    linear_hits[k]++;
                    ilm++;
                    square_hits[k] = square_hits[k] + (ilm * ilm);
                    cube_hits[k] = cube_hits[k] + (ilm * ilm * ilm);
                    quad_hits[k] = quad_hits[k] + (ilm * ilm * ilm * ilm);
                }
                else
                {
                    //   nope, they didn't match.
                    //   So, we do the end-of-runlength stuff:
                    ilm = 0;
                }
                if (0)
                    fprintf(stderr, "ik: %d  it: %d  chars %c %c lin: %lld  sqr: %lld cube: %lld quad: %lld\n",
                            ik, it,
                            hashes[k][ik + it],
                            txtptr[textoffset + it],
                            (long long int)linear_hits[k],
                            (long long int)square_hits[k],
                            (long long int)cube_hits[k],
                            (long long int)quad_hits[k]);
            }
        }
    }


    //   Now we have the total hits for each text corpus.  We can then
    //  turn that into a vague probability measure, and then renormalize
    //  that to get probabilities.
    //
    //   But first, let's reflect on what we've got here.  We our test
    //   text, and we have a corpus which is "nominally correllated",
    //   and another corpus that is nominally uncorrellated.
    //
    //   The uncorrellated text will have an average match rate of 1/256'th
    //   in the linear domain (well, for random bytes; english text will match
    //   a lot more often, due to the fact that ASCII only uses the low 7
    //   bits, most text is written in lower case, Zipf's law, etc.
    //
    //   We can calculate a predicted total on a per-character basis for all
    //   of the corpi, then use that as an average expectation.

    //    Calculate total hits
    total_linear_hits = 0;
    total_square_hits = 0;
    total_cube_hits = 0;
    total_quad_hits = 0;
    total_features = 0;
    for (k = 0; k < maxhash; k++)
    {
        total_linear_hits += linear_hits[k];
        total_square_hits += square_hits[k];
        total_cube_hits += cube_hits[k];
        total_quad_hits += quad_hits[k];
        total_features += hashlens[k];
    }


    for (k = 0; k < maxhash; k++)
    {
        if (hashlens[k] > 0
           && total_features > 0)
        {
            //     Note that we don't normalize the probabilities yet- we do
            //     that down below.
            //
            //     .00397 is not a magic number - it's the random coincidence
            //     rate for 1 chance in 256, with run-length-squared boost.
            //     .00806 is the random coincidence rate for 7-bit characters.
            //
            //ptc[k] = ((0.0+square_hits[k] - (.00397 * hashlens[k] )));
            //      ptc[k] = ((0.0+square_hits[k] - (.00806 * hashlens[k] )))
            //        / hashlens[k];

            //      ptc[k] = (0.0+square_hits[k] ) / hashlens[k];
            //      ptc[k] = (0.0+ quad_hits[k] ) / hashlens[k];
            ptc[k] = (0.0 + quad_hits[k]) / linear_hits[k];

            if (ptc[k] < 0)
                ptc[k] = 10 * DBL_MIN;
        }
        else
        {
            ptc[k] = 0.5;
        }
    }


    //    ptc[k] = (sqrt (0.0 + square_hits[k])-linear_hits[k] ) / hashlens[k] ;
    //    ptc[k] =  (0.0 + square_hits[k] - linear_hits[k] ) ;
    //    ptc[k] =  ((0.0 + square_hits[k]) / hashlens[k]) ;
    //    ptc[k] = sqrt ((0.0 + square_hits[k]) / hashlens[k]) ;
    //    ptc[k] = ((0.0 + linear_hits[k]) / hashlens[k]) ;


    //   calculate renormalizer (the Bayesian formula's denomenator)
    renorm = 0.0;

    //   now calculate the per-ptc numerators
    for (k = 0; k < maxhash; k++)
        renorm = renorm + (ptc[k]);

    //   check for a zero normalizer
    if (renorm == 0)
        renorm = 1.0;

    //  and renormalize
    for (k = 0; k < maxhash; k++)
        ptc[k] = ptc[k] / renorm;

    //   if we have underflow (any probability == 0.0 ) then
    //   bump the probability back up to 10^-308, or
    //   whatever a small multiple of the minimum double
    //   precision value is on the current platform.
    //
    for (k = 0; k < maxhash; k++)
    {
        if (ptc[k] < 10 * DBL_MIN)
            ptc[k] = 10 * DBL_MIN;
    }

    if (internal_trace)
    {
        for (k = 0; k < maxhash; k++)
        {
            fprintf(stderr,
                    " file: %d  linear: %lld  square: %lld  RMS: %6.4e  ptc[%d] = %6.4e\n",
                    k, (long long int)linear_hits[k], (long long int)square_hits[k],
                    sqrt(0.0 + square_hits[k]), k, ptc[k]);
        }
    }

    //  end of repeat-the-regex loop


    //  cleanup time!
    //  remember to let go of the fd's and mmaps
    for (k = 0; k < maxhash; k++)
    {
        crm_munmap_file(hashes[k]);
    }

    if (user_trace)
    {
        for (k = 0; k < maxhash; k++)
            fprintf(stderr, "Probability of match for file %d: %f\n", k, ptc[k]);
    }
    //
    tprob = 0.0;
    for (k = 0; k < succhash; k++)
        tprob = tprob + ptc[k];
    //
    //      Do the calculations and format some output, which we may or may
    //      not use... but we need the calculated result anyway.
    //
    if (1 /* svlen > 0 */)
    {
        char buf[1024];
        double accumulator;
        double remainder;
        double overall_pR;
        int m;
        buf[0] = 0;
        accumulator = 10 * DBL_MIN;
        for (m = 0; m < succhash; m++)
        {
            accumulator += ptc[m];
        }
        remainder = 10 * DBL_MIN;
        for (m = succhash; m < maxhash; m++)
        {
            remainder += ptc[m];
        }
        overall_pR = log10(accumulator) - log10(remainder);

        //   note also that strcat _accumulates_ in stext.
        //  There would be a possible buffer overflow except that _we_ control
        //   what gets written here.  So it's no biggie.

        if (tprob > 0.5)
        {
            sprintf(buf, "CLASSIFY succeeds; (correlate) success probability: %6.4f  pR: %6.4f\n", tprob, overall_pR);
        }
        else
        {
            sprintf(buf, "CLASSIFY fails; (correlate) success probability: %6.4f  pR: %6.4f\n", tprob, overall_pR);
        }
        if (strlen(stext) + strlen(buf) <= stext_maxlen)
            strcat(stext, buf);

        //   find best single matching file
        //
        bestseen = 0;
        for (k = 0; k < maxhash; k++)
        {
            if (ptc[k] > ptc[bestseen])
            {
                bestseen = k;
            }
        }
        remainder = 10 * DBL_MIN;
        for (m = 0; m < maxhash; m++)
        {
            if (bestseen != m)
            {
                remainder += ptc[m];
            }
        }

        //   ... and format some output of best single matching file
        //
        snprintf(buf, WIDTHOF(buf), "Best match to file #%d (%s) "
                                    "prob: %6.4f  pR: %6.4f\n",
                 bestseen,
                 hashname[bestseen],
                 ptc[bestseen],
                 (log10(ptc[bestseen]) - log10(remainder)));
        buf[WIDTHOF(buf) - 1] = 0;
        if (strlen(stext) + strlen(buf) <= stext_maxlen)
            strcat(stext, buf);
        sprintf(buf, "Total features in input file: %d\n", hashlens[bestseen]);
        if (strlen(stext) + strlen(buf) <= stext_maxlen)
            strcat(stext, buf);

        //     Now do the per-file breakdowns:
        //
        for (k = 0; k < maxhash; k++)
        {
            int m;
            remainder = 10 * DBL_MIN;
            for (m = 0; m < maxhash; m++)
            {
                if (k != m)
                {
                    remainder += ptc[m];
                }
            }
            snprintf(buf, WIDTHOF(buf),
                     "#%d (%s):"
                     " features: %d, L1: %lld L2: %lld L3: %lld, L4: %lld prob: %3.2e, pR: %6.2f\n",
                     k,
                     hashname[k],
                     hashlens[k],
                     (long long int)linear_hits[k],
                     (long long int)square_hits[k],
                     (long long int)cube_hits[k],
                     (long long int)quad_hits[k],
                     ptc[k],
                     (log10(ptc[k]) - log10(remainder)));
            buf[WIDTHOF(buf) - 1] = 0;
            // strcat (stext, buf);
            if (strlen(stext) + strlen(buf) <= stext_maxlen)
                strcat(stext, buf);
        }
        // check here if we got enough room in stext to stuff everything
        // perhaps we'd better rise a nonfatalerror, instead of just
        // whining on stderr
        if (strcmp(&(stext[strlen(stext) - strlen(buf)]), buf) != 0)
        {
            nonfatalerror("WARNING: not enough room in the buffer to create "
                          "the statistics text.  Perhaps you could try bigger "
                          "values for MAX_CLASSIFIERS or MAX_FILE_NAME_LEN?",
                          " ");
        }
        if (svlen > 0)
        {
            crm_destructive_alter_nvariable(svrbl, svlen,                    stext, (int)strlen(stext), csl->calldepth);
        }
    }

    //
    //  Free the hashnames, to avoid a memory leak.
    //
    for (i = 0; i < maxhash; i++)
        free(hashname[i]);
    if (tprob <= 0.5)
    {
        if (user_trace)
            fprintf(stderr, "CLASSIFY was a FAIL, skipping forward.\n");
        //    and do what we do for a FAIL here
        CRM_ASSERT(csl->cstmt >= 0);
        CRM_ASSERT(csl->cstmt <= csl->nstmts);
#if defined(TOLERATE_FAIL_AND_OTHER_CASCADES)
        csl->next_stmt_due_to_fail = csl->mct[csl->cstmt]->fail_index;
#else
        csl->cstmt = csl->mct[csl->cstmt]->fail_index - 1;
#endif
        if (internal_trace)
        {
            fprintf(stderr, "CLASSIFY.CORRELATE is jumping to statement line: %d/%d\n", csl->mct[csl->cstmt]->fail_index, csl->nstmts);
        }
        CRM_ASSERT(csl->cstmt >= 0);
        CRM_ASSERT(csl->cstmt <= csl->nstmts);
        csl->aliusstk[csl->mct[csl->cstmt]->nest_level] = -1;
        return 0;
    }


    //
    //   all done... if we got here, we should just continue execution
    if (user_trace)
        fprintf(stderr, "CLASSIFY was a SUCCESS, continuing execution.\n");
// regcomp_failed:
    return 0;
}
コード例 #14
0
int getAllInterfacesAndAddresses (JNIEnv *env, netif **netifPP)
{
    DWORD ret;
    IP_ADAPTER_ADDRESSES *ptr, *adapters=0;
    ULONG len=ipinflen, count=0;
    netif *nif=0, *dup_nif, *last=0, *loopif=0, *curr;
    int tun=0, net=0;

    *netifPP = 0;

   /*
    * Get the IPv4 interfaces. This information is the same
    * as what previous JDK versions would return.
    */

    ret = enumInterfaces(env, netifPP);
    if (ret == -1) {
        return -1;
    } else {
        count = ret;
    }

    /* locate the loopback (and the last) interface */
    for (nif=*netifPP, last=nif; nif!=0; nif=nif->next) {
        if (nif->ifType == MIB_IF_TYPE_LOOPBACK) {
            loopif = nif;
        }
        last = nif;
    }

    // Retrieve IPv4 addresses with the IP Helper API
    curr = *netifPP;
    while (curr != NULL) {
        netaddr *netaddrP;
        ret = enumAddresses_win(env, curr, &netaddrP);
        if (ret == -1) {
            return -1;
        }
        curr->addrs = netaddrP;
        curr->naddrs += ret;
        curr = curr->next;
    }

    ret = getAdapters (env, &adapters);
    if (ret != ERROR_SUCCESS) {
        goto err;
    }

    /* Now get the IPv6 information. This includes:
     *  (a)  IPv6 information associated with interfaces already found
     *  (b)  IPv6 information for IPv6 only interfaces (probably tunnels)
     *
     * For compatibility with previous releases we use the naming
     * information gotten from enumInterfaces() for (a) entries
     * However, the index numbers are taken from the new API.
     *
     * The procedure is to go through the list of adapters returned
     * by the new API looking for entries that correspond to IPv4 interfaces
     * already found.
     */

    ptr = adapters;
    while (ptr != NULL) {
        int c;
        netif *nif0;
        if (ptr->IfType == IF_TYPE_SOFTWARE_LOOPBACK && (loopif != NULL)) {
            c = getAddrsFromAdapter(ptr, &loopif->addrs);
            if (c == -1) {
                goto err;
            }
            loopif->naddrs += c;
        } else {
            int index = ptr->IfIndex;
            if (index != 0) {
                /* This entry is associated with an IPv4 interface */
                for (nif=*netifPP; nif!=0; nif=nif->next) {
                    if (nif->index == index) {
                        /* found the interface entry
                         * set the index to the IPv6 index and add the
                         * IPv6 addresses
                         */
                        nif->ipv6Index = ptr->Ipv6IfIndex;
                        c = getAddrsFromAdapter(ptr, &nif->addrs);
                        nif->naddrs += c;
                        break;
                    }
                }
            } else {
                /* This entry is IPv6 only */
                char newname [128];
                int c;

                /* Windows allocates duplicate adapter entries
                 * for tunnel interfaces when there are multiple
                 * physical adapters. Need to check
                 * if this is a duplicate (ipv6Index is the same)
                 */
                dup_nif = 0;
                for (nif0=*netifPP; nif0!=0; nif0=nif0->next) {
                    if (nif0->hasIpv6Address &&
                                ptr->Ipv6IfIndex == nif0->ipv6Index) {
                        dup_nif = nif0;
                        break;
                    }
                }
                if (dup_nif == 0) {
                    /* new interface */
                    nif = (netif *) calloc (1, sizeof(netif));
                    if (nif == 0) {
                        goto err;
                    }
                    if (ptr->IfType == IF_TYPE_TUNNEL) {
                        sprintf (newname, "tun%d", tun);
                        tun ++;
                    } else {
                        sprintf (newname, "net%d", net);
                        net ++;
                    }
                    nif->name = malloc (strlen(newname)+1);
                    nif->displayName = malloc (wcslen(ptr->FriendlyName)*2+2);
                    if (nif->name == 0 || nif->displayName == 0) {
                        goto err;
                    }
                    strcpy (nif->name, newname);
                    wcscpy ((PWCHAR)nif->displayName, ptr->FriendlyName);
                    nif->dNameIsUnicode = TRUE;

                    // the java.net.NetworkInterface abstraction only has index
                    // so the Ipv6IfIndex needs to map onto index
                    nif->index = ptr->Ipv6IfIndex;
                    nif->ipv6Index = ptr->Ipv6IfIndex;
                    nif->hasIpv6Address = TRUE;

                    last->next = nif;
                    last = nif;
                    count++;
                    c = getAddrsFromAdapter(ptr, &nif->addrs);
                    if (c == -1) {
                        goto err;
                    }
                    nif->naddrs += c;
                } else {
                    /* add the addresses from this adapter to the
                     * original (dup_nif)
                     */
                    c = getAddrsFromAdapter(ptr, &dup_nif->addrs);
                    if (c == -1) {
                        goto err;
                    }
                    dup_nif->naddrs += c;
                }
            }
        }
        ptr=ptr->Next;
    }

    free (adapters);
    return count;

err:
    if (*netifPP) {
        free_netif (*netifPP);
    }
    if (adapters) {
        free (adapters);
    }
    return -1;
}
コード例 #15
0
ファイル: vectors.c プロジェクト: foolswood/Physyn
inline vector Vmk(void) {
	return calloc(dimensions, sizeof(float));
}
コード例 #16
0
static int getAddrsFromAdapter(IP_ADAPTER_ADDRESSES *ptr, netaddr **netaddrPP) {
    LPSOCKADDR                   sock;
    int                          count = 0;
    netaddr                     *curr, *start=0, *prev=0;
    PIP_ADAPTER_UNICAST_ADDRESS uni_addr;
    PIP_ADAPTER_ANYCAST_ADDRESS any_addr;
    PIP_ADAPTER_PREFIX prefix;

    /* If chain passed in, find end */
    if (*netaddrPP != NULL) {
        for (start=*netaddrPP; start->next!=NULL; start=start->next) {
        }
        prev=start;
    }

    prefix = ptr->FirstPrefix;
    /* Unicast */
    uni_addr = ptr->FirstUnicastAddress;
    while (uni_addr != NULL) {
        /* address is only usable if dad state is preferred or deprecated */
        if (uni_addr->DadState == IpDadStateDeprecated ||
                uni_addr->DadState == IpDadStatePreferred) {
            sock = uni_addr->Address.lpSockaddr;

            // IPv4 addresses already retrieved with enumAddresses_win
            if (sock->sa_family == AF_INET) {
                uni_addr = uni_addr->Next;
                continue;
            }

            curr = (netaddr *)calloc (1, sizeof (netaddr));
            if (curr == 0) {
                return -1;
            }
            if (start == NULL) {
                start = curr;
            }
            if (prev != NULL) {
                prev->next = curr;
            }
            prev = curr;
            SOCKETADDRESS_COPY (&curr->addr, sock);
            if (prefix != NULL) {
              curr->mask = (short)prefix->PrefixLength;
              prefix = prefix->Next;
            }
            count ++;
        }
        uni_addr = uni_addr->Next;
    }
    /* Anycast */
    any_addr = ptr->FirstAnycastAddress;
    while (any_addr != NULL) {
        curr = (netaddr *)calloc (1, sizeof (netaddr));
        if (curr == 0) {
            return -1;
        }
        if (start == NULL) {
            start = curr;
        }
        if (prev != NULL) {
            prev->next = curr;
        }
        prev = curr;
        sock = any_addr->Address.lpSockaddr;
        SOCKETADDRESS_COPY (&curr->addr, sock);
        count ++;
        any_addr = any_addr->Next;
    }
    if (*netaddrPP == NULL) {
        *netaddrPP = start;
    }
    return count;
}
コード例 #17
0
ファイル: tokenizerV4.c プロジェクト: DLambros91/C-Playground
char *TKGetNextToken( TokenizerT * tk )
{	// Begin TKGetNextToken

	/**
	 * Check that the string is not empty.
	 */

	if(tk->str == '\0')
	{	// Begin if-statement
		return '\0';
	}	// End if-statement

	/*
	 * calloc(tk->strSize-tk->curChar, sizeof(char));
	 * This will assign for the first token the amount of space
	 * required to contain the entire string in the case that the first token
	 * the whole input is one token. The next time the function is used it will
	 * allocate the size of the string minus the amount of characters already
	 * surpassed.
	 */
	char *arr = calloc(tk->strSize-tk->curChar, sizeof(char));

	int i = 0; // Current index in arr[i]

	while ((char)tk->str[tk->curChar] != '\0')
	{	// Begin while-loop

		/**
		 * This if-statement will check if tk->str[tk->curChar] is
		 * a whitespace character. If a whitespace character is found
		 * the current character which contains the whitespace
		 * will be incremented over (e.g. tk->curChar++) so that the
		 * next time the method is called it will start after the
		 * whitespace character.
		 */
		if((char)tk->str[tk->curChar] == ' ')
		{	// Begin if-statement
			tk->curChar++;
			if((char)tk->str[tk->curChar] == '\0')
			{
				arr[i] = ' ';
				break;
			}
		}	// End if-statement
		else if(isalpha(tk->str[tk->curChar]))
		{	// Begin if-statement
			arr[i] = tk->str[tk->curChar];	// Store current str[index] in arr[i]
			i++;
			tk->curChar++;

			/**
			 * Continue tokenizing word while next character is an alphanumeric
			 * character.
			 */
			while(isalnum(tk->str[tk->curChar]) && (char)tk->str[tk->curChar] != '\0')
			{	// Begin while loop
				arr[i] = tk->str[tk->curChar];
				i++;
				tk->curChar++;
			}	//
			tk->tokenDesc[tk->manyTokens] = "word";
			break;
		}
		else if(isdigit(tk->str[tk->curChar]))
		{
			arr[i] = tk->str[tk->curChar];
			i++;
			tk->curChar++;
			while(isdigit(tk->str[tk->curChar]) && (char)tk->str[tk->curChar] != '\0')
			{
				arr[i] = tk->str[tk->curChar];
				i++;
				tk->curChar++;
			}
			if((char)tk->str[tk->curChar] == 'L')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "long decimal number";
				tk->curChar++;
				break;
			}
			else if((char)tk->str[tk->curChar] == '.')
			{
				tk->tokenDesc[tk->manyTokens] = "float";
				arr[i] = tk->str[tk->curChar];
				i++;
				tk->curChar++;
				while(isdigit(tk->str[tk->curChar]))
				{
					arr[i] = tk->str[tk->curChar];
					i++;
					tk->curChar++;
					if((char)tk->str[tk->curChar] == 'e')
					{
						arr[i] = tk->str[tk->curChar];
						i++;
						tk->curChar++;
						if((char)tk->str[tk->curChar] == '-' || (char)tk->str[tk->curChar] == '+')
						{
							arr[i] = tk->str[tk->curChar];
							i++;
							tk->curChar++;
							if(!isdigit(tk->str[tk->curChar]))
							{
								tk->tokenDesc[tk->manyTokens] = "improper float";
								break;
							}
							while(isdigit(tk->str[tk->curChar]))
							{
								arr[i] = tk->str[tk->curChar];
								i++;
								tk->curChar++;
							}
							tk->tokenDesc[tk->manyTokens] = "scientific float";
							break;
						}
						else
						{
							tk->tokenDesc[tk->manyTokens] = "improper float";
							break;
						}
					}
				}
				break;
			}
			tk->tokenDesc[tk->manyTokens] = "decimal number";
			tk->curChar++;
			break;
		}
		else if((char)tk->str[tk->curChar] == '[')
		{
			arr[i] = tk->str[tk->curChar];
			tk->tokenDesc[tk->manyTokens] = "left brace";
			tk->curChar++;
			break;
		}
		else if((char)tk->str[tk->curChar] == ']')
		{
			arr[i] = tk->str[tk->curChar];
			tk->tokenDesc[tk->manyTokens] = "right brace";
			tk->curChar++;
			break;
		}
		else if((char)tk->str[tk->curChar] == '(')
		{
			arr[i] = tk->str[tk->curChar];
			tk->tokenDesc[tk->manyTokens] = "left parentheses";
			tk->curChar++;
			break;
		}
		else if((char)tk->str[tk->curChar] == ')')
		{
			arr[i] = tk->str[tk->curChar];
			tk->tokenDesc[tk->manyTokens] = "right parentheses";
			tk->curChar++;
			break;
		}
		else if((char)tk->str[tk->curChar] == '+')
		{
			arr[i] = tk->str[tk->curChar];
			i++;
			tk->tokenDesc[tk->manyTokens] = "plus";
			tk->curChar++;
			if((char)tk->str[tk->curChar] == '=')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "plusequals";
				tk->curChar++;
			}
			else if((char)tk->str[tk->curChar] == '+')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "increment";
				tk->curChar++;
			}
			break;
		}
		else if((char)tk->str[tk->curChar] == '-')
		{
			arr[i] = tk->str[tk->curChar];
			i++;
			tk->tokenDesc[tk->manyTokens] = "minus";
			tk->curChar++;
			if((char)tk->str[tk->curChar] == '=')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "minusequals";
				tk->curChar++;
			}
			else if((char)tk->str[tk->curChar] == '-')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "decrement";
				tk->curChar++;
			}
			break;
		}
		else if((char)tk->str[tk->curChar] == '\%')
		{
			arr[i] = tk->str[tk->curChar];
			i++;
			tk->curChar++;

			if((char)tk->str[tk->curChar] == 'd')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "signed decimal integer conversion character";
			}
			else if((char)tk->str[tk->curChar] == 'u')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "unsigned decimal integer conversion character (used in printf only)";
			}
			else if((char)tk->str[tk->curChar] == 'x')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "unsigned hexidecimal integer conversion character";
			}
			else if((char)tk->str[tk->curChar] == 'h')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "unsigned short integer conversion character (used in scanf only)";
			}
			else if((char)tk->str[tk->curChar] == 'o')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "unsigned octal integer conversion character";
			}
			else if((char)tk->str[tk->curChar] == 'c')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "single character conversion character";
			}
			else if((char)tk->str[tk->curChar] == 's')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "null terminated string conversion character";
			}
			else if((char)tk->str[tk->curChar] == 'f')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "fixed point notation for float or double conversion character";
			}
			else if((char)tk->str[tk->curChar] == 'e')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "scientific notation for float or double conversion character (printf only)";
			}
			else if((char)tk->str[tk->curChar] == 'g')
			{
				arr[i] = tk->str[tk->curChar];
				tk->tokenDesc[tk->manyTokens] = "use %e or %f, whichever is shorter conversion character (printf only)";
			}
			tk->curChar++;
			break;
		}
	}	// End while-loop
	return arr;
}	// End TKGetNextToken
コード例 #18
0
ファイル: tagutils-misc.c プロジェクト: gonzopancho/asuswrt
static unsigned char*
_get_utf8_text(const id3_ucs4_t* native_text)
{
	unsigned char *utf8_text = NULL;
	char *in, *in8, *iconv_buf;
	iconv_result rc;
	int i, n;

	in = (char*)id3_ucs4_latin1duplicate(native_text);
	if(!in)
	{
		goto out;
	}

	in8 = (char*)id3_ucs4_utf8duplicate(native_text);
	if(!in8)
	{
		free(in);
		goto out;
	}

	iconv_buf = (char*)calloc(MAX_ICONV_BUF, sizeof(char));
	if(!iconv_buf)
	{
		free(in); free(in8);
		goto out;
	}

	i = lang_index;
	// (1) try utf8 -> default
	rc = do_iconv(iconv_map[i].cpnames[0], "UTF-8", in8, strlen(in8), iconv_buf, MAX_ICONV_BUF);
	if(rc == ICONV_OK)
	{
		utf8_text = (unsigned char*)in8;
		free(iconv_buf);
	}
	else if(rc == ICONV_TRYNEXT)
	{
		// (2) try default -> utf8
		rc = do_iconv("UTF-8", iconv_map[i].cpnames[0], in, strlen(in), iconv_buf, MAX_ICONV_BUF);
		if(rc == ICONV_OK)
		{
			utf8_text = (unsigned char*)iconv_buf;
		}
		else if(rc == ICONV_TRYNEXT)
		{
			// (3) try other encodes
			for(n = 1; n < N_LANG_ALT && iconv_map[i].cpnames[n]; n++)
			{
				rc = do_iconv("UTF-8", iconv_map[i].cpnames[n], in, strlen(in), iconv_buf, MAX_ICONV_BUF);
				if(rc == ICONV_OK)
				{
					utf8_text = (unsigned char*)iconv_buf;
					break;
				}
			}
			if(!utf8_text)
			{
				// cannot iconv
				utf8_text = (unsigned char*)id3_ucs4_utf8duplicate(native_text);
				free(iconv_buf);
			}
		}
		free(in8);
	}
	free(in);

 out:
	if(!utf8_text)
	{
		utf8_text = (unsigned char*)strdup("UNKNOWN");
	}

	return utf8_text;
}
CWE762_Mismatched_Memory_Management_Routines__delete_array_class_calloc_84_goodB2G::CWE762_Mismatched_Memory_Management_Routines__delete_array_class_calloc_84_goodB2G(TwoIntsClass * dataCopy)
{
    data = dataCopy;
    /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
    data = (TwoIntsClass *)calloc(100, sizeof(TwoIntsClass));
}
コード例 #20
0
ファイル: utilities.c プロジェクト: Strigimar/AnalyzeRandom
int
generatorOptions(char** streamFile)
{
	char	file[200];
	int		option = NUMOFGENERATORS+1;
	FILE	*fp;
	
	while ( (option < 0) || (option > NUMOFGENERATORS) ) {
		option = displayGeneratorOptions();
		switch( option ) {
			case 0:
				printf("\t\tUser Prescribed Input File: ");
				scanf("%s", file);
				*streamFile = (char*)calloc(200, sizeof(char));
				sprintf(*streamFile, "%s", file);
				printf("\n");
				if ( (fp = fopen(*streamFile, "r")) == NULL ) {
					printf("File Error:  file %s could not be opened.\n",  *streamFile);
					exit(-1);
				}
				else
					fclose(fp);
				break;
			case 1:
				*streamFile = "Linear-Congruential";
				break;
			case 2:
				*streamFile = "Quadratic-Congruential-1";
				break;
			case 3:
				*streamFile = "Quadratic-Congruential-2";
				break;
			case 4:
				*streamFile = "Cubic-Congruential";
				break;
			case 5:
				*streamFile = "XOR";
				break;
			case 6:
				*streamFile = "Modular-Exponentiation";
				break;
			case 7:
				*streamFile = "Blum-Blum-Shub";
				break;
			case 8:
				*streamFile = "Micali-Schnorr";
				break;
			case 9:
				*streamFile = "G using SHA-1";
				break;
				
			/* INTRODUCE NEW PRNG NAMES HERE */
			/*
			case 10:  *streamFile = "myNewPRNG";
				break;
			*/
			default:
				printf("Error:  Out of range - Try again!\n");
				break;
		}
	}
	return option;
}
コード例 #21
0
static void frontend_xdk_get_environment_settings(int *argc, char *argv[],
      void *args, void *params_data)
{
   HRESULT ret;
#ifdef _XBOX360
   unsigned long license_mask;
   DWORD volume_device_type;
#endif
#ifndef IS_SALAMANDER
   static char path[PATH_MAX_LENGTH] = {0};
#if defined(_XBOX1)
   LAUNCH_DATA ptr;
   DWORD launch_type;
#elif defined(_XBOX360)
   DWORD dwLaunchDataSize;
#endif
#endif
#ifndef IS_SALAMANDER
   bool original_verbose       = verbosity_is_enabled();
#endif

   (void)ret;

#ifndef IS_SALAMANDER
#if defined(HAVE_LOGGER)
   logger_init();
#elif defined(HAVE_FILE_LOGGER)
   retro_main_log_file_init("/retroarch-log.txt");
#endif
#endif

#ifdef _XBOX360
   /* Detect install environment. */
   if (XContentGetLicenseMask(&license_mask, NULL) == ERROR_SUCCESS)
   {
      XContentQueryVolumeDeviceType("GAME",&volume_device_type, NULL);

      switch(volume_device_type)
      {
         case XCONTENTDEVICETYPE_HDD: /* Launched from content package on HDD */
         case XCONTENTDEVICETYPE_MU:  /* Launched from content package on USB/Memory Unit. */
         case XCONTENTDEVICETYPE_ODD: /* Launched from content package on Optial Disc Drive. */
         default:                     /* Launched from content package on unknown device. */
            break;
      }
   }
#endif

#if defined(_XBOX1)
   strlcpy(g_defaults.dirs[DEFAULT_DIR_CORE],
         "D:", sizeof(g_defaults.dirs[DEFAULT_DIR_CORE]));
   fill_pathname_join(g_defaults.path.config, g_defaults.dirs[DEFAULT_DIR_CORE],
         file_path_str(FILE_PATH_MAIN_CONFIG), sizeof(g_defaults.path.config));
   fill_pathname_join(g_defaults.dirs[DEFAULT_DIR_SAVESTATE],
         g_defaults.dirs[DEFAULT_DIR_CORE],
         "savestates",
         sizeof(g_defaults.dirs[DEFAULT_DIR_SAVESTATE]));
   fill_pathname_join(g_defaults.dirs[DEFAULT_DIR_SRAM],
         g_defaults.dirs[DEFAULT_DIR_CORE],
         "savefiles",
         sizeof(g_defaults.dirs[DEFAULT_DIR_SRAM]));
   fill_pathname_join(g_defaults.dirs[DEFAULT_DIR_SYSTEM],
         g_defaults.dirs[DEFAULT_DIR_CORE],
         "system",
         sizeof(g_defaults.dirs[DEFAULT_DIR_SYSTEM]));
   fill_pathname_join(g_defaults.dirs[DEFAULT_DIR_SCREENSHOT],
         g_defaults.dirs[DEFAULT_DIR_CORE],
         "screenshots",
         sizeof(g_defaults.dirs[DEFAULT_DIR_SCREENSHOT]));
   fill_pathname_join(g_defaults.dirs[DEFAULT_DIR_OVERLAY],
         g_defaults.dirs[DEFAULT_DIR_CORE],
         "overlays",
         sizeof(g_defaults.dirs[DEFAULT_DIR_OVERLAY]));
   fill_pathname_join(g_defaults.dirs[DEFAULT_DIR_ASSETS],
         g_defaults.dirs[DEFAULT_DIR_CORE],
         "media", sizeof(g_defaults.dirs[DEFAULT_DIR_ASSETS]));
   fill_pathname_join(g_defaults.dirs[DEFAULT_DIR_CORE_ASSETS],
         g_defaults.dirs[DEFAULT_DIR_CORE],
         "downloads", sizeof(g_defaults.dirs[DEFAULT_DIR_CORE_ASSETS]));
   fill_pathname_join(g_defaults.dirs[DEFAULT_DIR_PLAYLIST],
         g_defaults.dirs[DEFAULT_DIR_CORE],
         "playlists", sizeof(g_defaults.dirs[DEFAULT_DIR_PLAYLIST]));
#elif defined(_XBOX360)
   strlcpy(g_defaults.dirs[DEFAULT_DIR_CORE],
         "game:",
         sizeof(g_defaults.dirs[DEFAULT_DIR_CORE]));
   strlcpy(g_defaults.path.config,
         "game:\\retroarch.cfg", sizeof(g_defaults.path.config));
   strlcpy(g_defaults.dirs[DEFAULT_DIR_SCREENSHOT],
         "game:",
         sizeof(g_defaults.dirs[DEFAULT_DIR_SCREENSHOT]));
   strlcpy(g_defaults.dirs[DEFAULT_DIR_SAVESTATE],
         "game:\\savestates",
         sizeof(g_defaults.dirs[DEFAULT_DIR_SAVESTATE]));
   strlcpy(g_defaults.dirs[DEFAULT_DIR_PLAYLIST],
         "game:\\playlists",
         sizeof(g_defaults.dirs[DEFAULT_DIR_PLAYLIST]));
   strlcpy(g_defaults.dirs[DEFAULT_DIR_SRAM],
         "game:\\savefiles",
         sizeof(g_defaults.dirs[DEFAULT_DIR_SRAM]));
   strlcpy(g_defaults.dirs[DEFAULT_DIR_SYSTEM],
         "game:\\system", sizeof(g_defaults.dirs[DEFAULT_DIR_SYSTEM]));
#endif
   fill_pathname_join(g_defaults.dirs[DEFAULT_DIR_CORE_INFO],
         g_defaults.dirs[DEFAULT_DIR_CORE],
         "info", sizeof(g_defaults.dirs[DEFAULT_DIR_CORE_INFO]));

#ifndef IS_SALAMANDER
#if defined(_XBOX1)
   if (XGetLaunchInfo(&launch_type, &ptr) == ERROR_SUCCESS)
   {
      char *extracted_path = NULL;
      if (launch_type == LDT_FROM_DEBUGGER_CMDLINE)
         goto exit;

      extracted_path = (char*)&ptr.Data;

      if (
            !string_is_empty(extracted_path)
            && (strstr(extracted_path, "Pool") == NULL)
            /* Hack. Unknown problem */)
      {
         /* Auto-start game */
         strlcpy(path, extracted_path, sizeof(path));
      }
   }
#elif defined(_XBOX360)
   if (XGetLaunchDataSize(&dwLaunchDataSize) == ERROR_SUCCESS)
   {
      char *extracted_path                 = (char*)calloc(dwLaunchDataSize, sizeof(char));
      BYTE* pLaunchData                    = (BYTE*)calloc(dwLaunchDataSize, sizeof(BYTE));

      XGetLaunchData(pLaunchData, dwLaunchDataSize);
      memset(extracted_path, 0, dwLaunchDataSize);

      strlcpy(extracted_path, pLaunchData, dwLaunchDataSize);

      /* Auto-start game */
      if (!string_is_empty(extracted_path))
         strlcpy(path, extracted_path, sizeof(path));

      if (pLaunchData)
         free(pLaunchData);
   }
#endif
   if (!string_is_empty(path))
   {
      struct rarch_main_wrap *args = (struct rarch_main_wrap*)params_data;

      if (args)
      {
         /* Auto-start game. */
         args->touched        = true;
         args->no_content     = false;
         args->verbose        = false;
         args->config_path    = NULL;
         args->sram_path      = NULL;
         args->state_path     = NULL;
         args->content_path   = path;
         args->libretro_path  = NULL;
      }
   }
#endif

#ifndef IS_SALAMANDER
#ifdef _XBOX1
exit:
   if (original_verbose)
      verbosity_enable();
   else
      verbosity_disable();
#endif
#endif
}
コード例 #22
0
EAPI Eeze_Udev_Watch *
eeze_udev_watch_add(Eeze_Udev_Type     type,
                    int                event,
                    Eeze_Udev_Watch_Cb cb,
                    void              *user_data)
{
   _udev_monitor *mon = NULL;
   int fd;
   Ecore_Fd_Handler *handler;
   Eeze_Udev_Watch *watch = NULL;
   struct _store_data *store = NULL;

   if (!(store = calloc(1, sizeof(struct _store_data))))
     return NULL;

   if (!(watch = malloc(sizeof(Eeze_Udev_Watch))))
     goto error;

   if (!(mon = udev_monitor_new_from_netlink(udev, "udev")))
     goto error;

#ifndef OLD_UDEV_RRRRRRRRRRRRRR

   switch (type)
     {
      case EEZE_UDEV_TYPE_KEYBOARD:
        udev_monitor_filter_add_match_subsystem_devtype(mon, "input", NULL);
        break;

      case EEZE_UDEV_TYPE_MOUSE:
        udev_monitor_filter_add_match_subsystem_devtype(mon, "input", NULL);
        break;

      case EEZE_UDEV_TYPE_TOUCHPAD:
        udev_monitor_filter_add_match_subsystem_devtype(mon, "input", NULL);
        break;

      case EEZE_UDEV_TYPE_DRIVE_MOUNTABLE:
      case EEZE_UDEV_TYPE_DRIVE_INTERNAL:
        udev_monitor_filter_add_match_subsystem_devtype(mon, "block", NULL);
        break;

      case EEZE_UDEV_TYPE_DRIVE_REMOVABLE:
      case EEZE_UDEV_TYPE_DRIVE_CDROM:
        break;

      case EEZE_UDEV_TYPE_POWER_AC:
      case EEZE_UDEV_TYPE_POWER_BAT:
        udev_monitor_filter_add_match_subsystem_devtype(mon, "power_supply",
                                                        NULL);
        break;

      case EEZE_UDEV_TYPE_NET:
        udev_monitor_filter_add_match_subsystem_devtype(mon, "net", NULL);
        break;

      case EEZE_UDEV_TYPE_IS_IT_HOT_OR_IS_IT_COLD_SENSOR:
        udev_monitor_filter_add_match_subsystem_devtype(mon, "hwmon", NULL);
        break;

      /*
              case EEZE_UDEV_TYPE_ANDROID:
                udev_monitor_filter_add_match_subsystem_devtype(mon, "input", "usb_interface");
                break;
       */

      case EEZE_UDEV_TYPE_V4L:
        udev_monitor_filter_add_match_subsystem_devtype(mon, "video4linux",
                                                        NULL);
        break;

      case EEZE_UDEV_TYPE_BLUETOOTH:
        udev_monitor_filter_add_match_subsystem_devtype(mon, "bluetooth",
                                                        NULL);
        break;

      default:
        break;
     }

#endif

   if (udev_monitor_enable_receiving(mon))
     goto error;

   fd = udev_monitor_get_fd(mon);
   store->func = cb;
   store->data = user_data;
   store->mon = mon;
   store->type = type;
   store->watch = watch;
   store->event = event;

   if (!(handler = ecore_main_fd_handler_add(fd, ECORE_FD_READ,
                                             _get_syspath_from_watch, store, NULL, NULL)))
     goto error;

   watch->mon = mon;
   watch->handler = handler;
   return watch;
error:
   if (store)
     free(store);
   if (watch)
     free(watch);
   if (mon)
     udev_monitor_unref(mon);
   ERR("Could not create watch!");
   return NULL;
}
コード例 #23
0
ファイル: uparse.c プロジェクト: bradclawsie/uparse
// Parse the query string part of a url and turn it into q query_arg_list_t, which
// is a list of query_key_val_t structs and a count.
query_arg_list_t *get_query_arg_list(char *const query_str, unsigned int *err_out) {

    *err_out = UPARSE_ERROR; 
    
    if (NULL == query_str) {
        *err_out = NO_UPARSE_ERROR; 
        return NULL;
    }

    // stringify the delims for strsep
    char query_pair_delim_str[2];
    snprintf(query_pair_delim_str,2,"%c",QUERY_PAIR_DELIM);
    char query_key_value_delim_str[2];
    snprintf(query_key_value_delim_str,2,"%c",QUERY_KEY_VAL_DELIM);
    
    char *c = query_str;
    size_t const str_len = 256;
    
    char *key = (char *) calloc(str_len, sizeof(char));
    char *val = (char *) calloc(str_len, sizeof(char));
    if ((NULL == key) || (NULL == val)) {
        fprintf(stderr,"key or val is null\n");
        free(key);
        free(val);
        return NULL;
    }
    
    unsigned int const STATE_KEY_READ = 0;
    unsigned int const STATE_VAL_READ = 1;
    unsigned int state = STATE_KEY_READ;
    
    bool valid_key            = false;
    bool valid_val            = false;
    bool valid_query_key_vals = false;
    
    size_t j = 0;
    size_t k = 0;

    size_t key_val_count = 0;
    size_t const max_query_key_vals = 512;
    query_key_val_t **query_key_vals =
        (query_key_val_t **) malloc(max_query_key_vals * sizeof(query_key_val_t *));
    bzero((void *) query_key_vals,max_query_key_vals * sizeof(query_key_val_t *));
    
    while (*c) {
        if (STATE_KEY_READ == state) {
            if (QUERY_PAIR_DELIM == c[0]) {
                fprintf(stderr,"found query pair delim %c when parsing key\n",QUERY_PAIR_DELIM);
                free(key);
                free(val);
                free_query_key_val_t_list(query_key_vals,key_val_count);
                return NULL;
            }
            if (QUERY_KEY_VAL_DELIM == c[0]) {
                if (!valid_key) {
                    fprintf(stderr,"found query key/val delim %c but no valid key\n",QUERY_KEY_VAL_DELIM);
                    free(key);
                    free(val);
                    free_query_key_val_t_list(query_key_vals,key_val_count);
                    return NULL;
                } else {
                    state = STATE_VAL_READ;
                    key[j] = '\0';
                }
            } else {
                if (j == (str_len - 1)) {
                    fprintf(stderr,"key length exceeds %lu\n",str_len);
                    free(key);
                    free(val);
                    free_query_key_val_t_list(query_key_vals,key_val_count);
                    *err_out = OVERFLOW_ERROR; 
                    return NULL;
                } else {                    
                    key[j++] = c[0];
                    valid_key = true;
                }
            } 
        } else if (STATE_VAL_READ == state) {
            if (!valid_key) {
                fprintf(stderr,"valid_key = false while parsing val\n");
                free(key);
                free(val);
                free_query_key_val_t_list(query_key_vals,key_val_count);
                return NULL;                
            }
            if (QUERY_KEY_VAL_DELIM == c[0]) {
                fprintf(stderr,"parsing val and saw key/val delim %c \n",QUERY_KEY_VAL_DELIM);
                free(key);
                free(val);
                free_query_key_val_t_list(query_key_vals,key_val_count);
                return NULL;                
            }
            if (QUERY_PAIR_DELIM == c[0]) {
                if (!valid_val) {
                    fprintf(stderr,"found query pair delim %c but no valid val\n",QUERY_PAIR_DELIM);
                    free(key);
                    free(val);
                    free_query_key_val_t_list(query_key_vals,key_val_count);
                    return NULL;
                } else {
                    val[k] = '\0';
                    query_key_vals[key_val_count] = (query_key_val_t *) malloc(sizeof(query_key_val_t));
                    if (NULL == query_key_vals[key_val_count]) {
                        fprintf(stderr,"cannot allocate query_key_vals[%lu]\n",key_val_count);
                        free(key);
                        free(val);
                        free_query_key_val_t_list(query_key_vals,key_val_count);
                        return NULL;                        
                    }
                    query_key_vals[key_val_count]->key = strdup(key);
                    if (NULL == query_key_vals[key_val_count]->key) {
                        fprintf(stderr,"cannot allocate query_key_vals[%lu]->key\n",key_val_count);
                        free(key);
                        free(val);
                        free_query_key_val_t_list(query_key_vals,key_val_count);
                        return NULL;                        
                    }
                    query_key_vals[key_val_count]->val = strdup(val);
                    if (NULL == query_key_vals[key_val_count]->val) {
                        fprintf(stderr,"cannot allocate query_key_vals[%lu]->val\n",key_val_count);
                        free(key);
                        free(val);
                        free_query_key_val_t_list(query_key_vals,key_val_count);
                        return NULL;                        
                    }
                    key_val_count++;
                    if (key_val_count == (max_query_key_vals - 1)) {
                        fprintf(stderr,"query query_key_vals length exceeds %lu\n",max_query_key_vals);
                        *err_out = OVERFLOW_ERROR;
                        free(key);
                        free(val);
                        free_query_key_val_t_list(query_key_vals,key_val_count);
                        return NULL;
                    }   
                    valid_query_key_vals = true;
                    valid_key = false;
                    valid_val = false;
                    j = 0;
                    k = 0;
                    free(key);
                    free(val);
                    key = (char *) calloc(str_len, sizeof(char));
                    val = (char *) calloc(str_len, sizeof(char));                 
                    if ((NULL == key) || (NULL == val)) {
                        fprintf(stderr,"key or val is null\n");
                        free(key);
                        free(val);
                        free_query_key_val_t_list(query_key_vals,key_val_count);
                        return NULL;
                    }
                    state = STATE_KEY_READ;
                }
            } else {
                if (k == (str_len - 1)) {
                    fprintf(stderr,"val length exceeds %lu\n",str_len);
                    *err_out = OVERFLOW_ERROR;
                    free(key);
                    free(val);
                    free_query_key_val_t_list(query_key_vals,key_val_count);
                    return NULL;
                } else {
                    val[k++] = c[0];
                    valid_val = true;
                }
            }
        } else {
            fprintf(stderr,"unknown parse state\n");
            free(key);
            free(val);
            free_query_key_val_t_list(query_key_vals,key_val_count);
            return NULL;
        }
        c++;
    }

    if (valid_key && valid_val) {
        query_key_vals[key_val_count] = (query_key_val_t *) malloc(sizeof(query_key_val_t));
        if (NULL == query_key_vals[key_val_count]) {
            fprintf(stderr,"cannot allocate query_key_vals[%lu]\n",key_val_count);
            free(key);
            free(val);
            free_query_key_val_t_list(query_key_vals,key_val_count);
            return NULL;                        
        }
        query_key_vals[key_val_count]->key = strdup(key);
        if (NULL == query_key_vals[key_val_count]->key) {
            fprintf(stderr,"cannot allocate query_key_vals[%lu]->key\n",key_val_count);
            free(key);
            free(val);
            free_query_key_val_t_list(query_key_vals,key_val_count);
            return NULL;                        
        }
        query_key_vals[key_val_count]->val = strdup(val);
        if (NULL == query_key_vals[key_val_count]->val) {
            fprintf(stderr,"cannot allocate query_key_vals[%lu]->val\n",key_val_count);
            free(key);
            free(val);
            free_query_key_val_t_list(query_key_vals,key_val_count);
            return NULL;                        
        }
        valid_query_key_vals = true;
        key_val_count++;
    }

    free(key);
    free(val);
    
    if (!valid_query_key_vals) {
        fprintf(stderr,"no valid key/val query_key_vals found\n");
        free_query_key_val_t_list(query_key_vals,key_val_count);
        return NULL;
    }

    query_key_vals = (query_key_val_t **) realloc(query_key_vals,key_val_count * sizeof(query_key_val_t *));
    
    query_arg_list_t *query_arg_list =
        (query_arg_list_t *) malloc(sizeof(query_arg_list_t));
    if (NULL == query_arg_list) {
        fprintf(stderr,"cannot allocate query_arg_list\n");
        free_query_key_val_t_list(query_key_vals,key_val_count);
        return NULL;
    }
    bzero((void *) query_arg_list,sizeof(query_arg_list_t));
    query_arg_list->query_key_vals = query_key_vals;
    query_arg_list->count = key_val_count;
    *err_out = NO_UPARSE_ERROR; 
    return query_arg_list;
}
コード例 #24
0
ファイル: match.x.c プロジェクト: KoalaTea/Redteam
char * xsh(int argc, char ** argv)
{
	char * scrpt;
	int ret, i, j;
	char ** varg;
	char * me = argv[0];

	stte_0();
	 key(pswd, pswd_z);
	arc4(msg1, msg1_z);
	arc4(date, date_z);
	if (date[0] && (atoll(date)<time(NULL)))
		return msg1;
	arc4(shll, shll_z);
	arc4(inlo, inlo_z);
	arc4(xecc, xecc_z);
	arc4(lsto, lsto_z);
	arc4(tst1, tst1_z);
	 key(tst1, tst1_z);
	arc4(chk1, chk1_z);
	if ((chk1_z != tst1_z) || memcmp(tst1, chk1, tst1_z))
		return tst1;
	ret = chkenv(argc);
	arc4(msg2, msg2_z);
	if (ret < 0)
		return msg2;
	varg = (char **)calloc(argc + 10, sizeof(char *));
	if (!varg)
		return 0;
	if (ret) {
		arc4(rlax, rlax_z);
		if (!rlax[0] && key_with_file(shll))
			return shll;
		arc4(opts, opts_z);
		arc4(text, text_z);
		arc4(tst2, tst2_z);
		 key(tst2, tst2_z);
		arc4(chk2, chk2_z);
		if ((chk2_z != tst2_z) || memcmp(tst2, chk2, tst2_z))
			return tst2;
		/* Prepend hide_z spaces to script text to hide it. */
		scrpt = malloc(hide_z + text_z);
		if (!scrpt)
			return 0;
		memset(scrpt, (int) ' ', hide_z);
		memcpy(&scrpt[hide_z], text, text_z);
	} else {			/* Reexecute */
		if (*xecc) {
			scrpt = malloc(512);
			if (!scrpt)
				return 0;
			sprintf(scrpt, xecc, me);
		} else {
			scrpt = me;
		}
	}
	j = 0;
	varg[j++] = argv[0];		/* My own name at execution */
	if (ret && *opts)
		varg[j++] = opts;	/* Options on 1st line of code */
	if (*inlo)
		varg[j++] = inlo;	/* Option introducing inline code */
	varg[j++] = scrpt;		/* The script itself */
	if (*lsto)
		varg[j++] = lsto;	/* Option meaning last option */
	i = (ret > 1) ? ret : 0;	/* Args numbering correction */
	while (i < argc)
		varg[j++] = argv[i++];	/* Main run-time arguments */
	varg[j] = 0;			/* NULL terminated array */
#if DEBUGEXEC
	debugexec(shll, j, varg);
#endif
	execvp(shll, varg);
	return shll;
}
コード例 #25
0
ファイル: yp_ping.c プロジェクト: AhmadTux/DragonFlyBSD
int
__yp_ping(struct in_addr *restricted_addrs, int cnt, char *dom, short *port)
{
	struct timeval		tv = { 5, 0 };
	struct ping_req		**reqs;
	unsigned long		i;
	int			async;
	struct sockaddr_in	sin, *any = NULL;
	struct netbuf		addr;
	int			winner = -1;
	u_int32_t		xid_seed, xid_lookup;
	int			sock, dontblock = 1;
	CLIENT			*clnt;
	char			*foo = dom;
	int			validsrvs = 0;

	/* Set up handles. */
	reqs = calloc(1, sizeof(struct ping_req *) * cnt);
	xid_seed = time(NULL) ^ getpid();

	for (i = 0; i < cnt; i++) {
		bzero((char *)&sin, sizeof(sin));
		sin.sin_family = AF_INET;
		bcopy((char *)&restricted_addrs[i],
			(char *)&sin.sin_addr, sizeof(struct in_addr));
		sin.sin_port = htons(__pmap_getport(&sin, YPPROG,
					YPVERS, IPPROTO_UDP));
		if (sin.sin_port == 0)
			continue;
		reqs[i] = calloc(1, sizeof(struct ping_req));
		bcopy((char *)&sin, (char *)&reqs[i]->sin, sizeof(sin));
		any = &reqs[i]->sin;
		reqs[i]->xid = xid_seed;
		xid_seed++;
		validsrvs++;
	}

	/* Make sure at least one server was assigned */
	if (!validsrvs) {
		free(reqs);
		return(-1);
	}

	/* Create RPC handle */
	sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	clnt = clntudp_create(any, YPPROG, YPVERS, tv, &sock);
	if (clnt == NULL) {
		close(sock);
		for (i = 0; i < cnt; i++)
			if (reqs[i] != NULL)
				free(reqs[i]);
		free(reqs);
		return(-1);
	}
	clnt->cl_auth = authunix_create_default();
	tv.tv_sec = 0;

	clnt_control(clnt, CLSET_TIMEOUT, (char *)&tv);
	async = TRUE;
	clnt_control(clnt, CLSET_ASYNC, (char *)&async);
	ioctl(sock, FIONBIO, &dontblock);

	/* Transmit */
	for (i = 0; i < cnt; i++) {
		if (reqs[i] != NULL) {
			clnt_control(clnt, CLSET_XID, (char *)&reqs[i]->xid);
			addr.len = sizeof(reqs[i]->sin);
			addr.buf = (char *) &reqs[i]->sin;
			clnt_control(clnt, CLSET_SVC_ADDR, &addr);
			ypproc_domain_nonack_2_send(&foo, clnt);
		}
	}

	/* Receive reply */
	ypproc_domain_nonack_2_recv(&foo, clnt);

	/* Got a winner -- look him up. */
	clnt_control(clnt, CLGET_XID, (char *)&xid_lookup);
	for (i = 0; i < cnt; i++) {
		if (reqs[i] != NULL && reqs[i]->xid == xid_lookup) {
			winner = i;
			*port = reqs[i]->sin.sin_port;
		}
	}

	/* Shut everything down */
	auth_destroy(clnt->cl_auth);
	clnt_destroy(clnt);
	close(sock);

	for (i = 0; i < cnt; i++)
		if (reqs[i] != NULL)
			free(reqs[i]);
	free(reqs);

	return(winner);
}
コード例 #26
0
ファイル: 3600sh.c プロジェクト: k-langer/Simple-Shell-3600
void readCommand() {
	/* allocate files used for redirection of stderr, stdin, stdout */
	char  **file = calloc(3, sizeof(char*));
  	if (!file) {
  		memoryError();
  	}

	for (int i = 0; i < 3; i++)
	{
	    file[i] = calloc(MAX_INPUT_LENGTH + 1, sizeof(char));
	    if (!file[i]) {
	      	memoryError();
	    }
	}

	/* initialize status to designate different modes as identified in #defines */
	status parseStatus = 0;
	
	char** args = readArgs(&parseStatus, file); 	
	
	/* determine whether shell should exit after executing command */
	bool terminate = EOF_FOUND & parseStatus;
	//Bit masking is used to use a single value for status.
	switch(parseStatus & (INVALID_SYNTAX | INVALID_ESCAPE)){
		case INVALID_SYNTAX:
			printf("Error: Invalid syntax.\n");
			if (terminate)
				do_exit();			
			return;
		case INVALID_ESCAPE:
			printf("Error: Unrecognized escape sequence.\n");
			if (terminate)
				do_exit();			
			return;
	}

	/* if "exit" is inputted, quit the shell */
	if (args[0]) {
		if (args[1] == NULL && strncmp(args[0], EXIT_COMMAND, strlen(EXIT_COMMAND)) == 0) {
			do_exit();
		}
	}
	
 	int restore_stdout = 0;
	int restore_stdin = 0; 
	int restore_stderr = 0; 
 	int f = -1;
	
	/* check if any redirection was requested and set up proper files */
	if (parseStatus & REDIR_STDOUT)
	{ 
		/*open afile with read and write permissions for the user. */
		/*Create it if needed, and truncate it if opened*/
		f = open(file[STDOUT],O_RDWR|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR); 
		if (f == -1) //-1 indicates that there was a problem with the file
		{
			printf("Error: Invalid syntax.\n");
			if (terminate) {//if it is EOF, terminate
				do_exit();
			}
			return; //otherwise, print another prompt
		}
		/*Open a file with the path "file" and the intention to read and write from it. */
		/*If it does not exist create it and give read and write permissions to the user*/
        	restore_stdout = dup(STDOUT); //keep a copy of STDOUT
        	close(STDOUT); //Close STDOUT
		dup(f); //Copy the same file descriptor but set it to the newly closed STDOUT
		close(f); //Close original file
	}
	if (parseStatus & REDIR_STDERR)
	{
		f = open(file[STDERR],O_RDWR|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR); 
		if (f == -1)
		{
			printf("Error: Invalid syntax.\n");
			if (terminate) {
				do_exit();
			}
			return;
		}
        	restore_stderr = dup(STDERR); //keep a copy of STDOUT
        	close(STDERR); //Close STDOUT
		dup(f); //Copy the same file descriptor but set it to the newly closed STDOUT
		close(f); //Close original file
	}
	if (parseStatus & REDIR_STDIN)//type==(2<<STDIN))
	{ 
		/*Do not create a file, as it would be empty and useless to STDIN*/
		/*Open as read only because it is an input source*/
		f = open(file[STDIN],O_RDONLY); 
		if (f == -1)
		{
			printf("Error: Unable to open redirection file.\n");
			if (terminate) {
				do_exit();
			}
			return;
		}
        	restore_stdin = dup(STDIN); 
        	close(STDIN); 
		dup(f); 
		close(f); 
	}

  /* workaround to allow 'cd' command */
  if(args[0] && strncmp(args[0], "cd", 2) == 0)
  {
     int error = 0; 
     if(args[1])
     	  error = chdir(args[1]);
     else
	error = chdir("/home");
     if(error)
	printf("cd: %s: No such file or directory\n",args[1]);
	
	return;
  }
  
  pid_t parent = fork();
  
  if (parent < 0) {
    printf("Error: process creation failed");  
    do_exit();
  }

  /* if we are in the child process, execute the command */
  else if (!parent) {
    if (execvp(args[0], args)) {
    	if((*args)[0]) {
          printf("Error: ");
          switch(errno) { //based on values in `man errno`
            case 1: printf("Permission denied.\n"); break;
            case 2: printf("Command not found.\n"); break;
	    case 13: printf("Permission denied.\n"); break;
            default: printf("Unkown error.\n"); break;
    	    }
      }
    }
    exit(0);
  } else {
	/* in parent, wait for child if not a background process */
	if (!(parseStatus & BACKGROUND)) {  
    		waitpid(parent, NULL, 0);
	}
    	if (terminate) {
      		do_exit();
   	}
  }

  /* restore any file redirections as necessary */
  if(restore_stdin)
  {
  	close(STDIN);
  	dup(restore_stdin);
  	close(restore_stdin);
  }
  if(restore_stdout)
  {
  	close(STDOUT);
  	dup(restore_stdout);
  	close(restore_stdout);
  }
  if(restore_stderr)
  {
  	close(STDERR);
  	dup(restore_stderr);
  	close(restore_stderr);
  }

  /* free all allocated memory */
  for (int i = 0; i < 3; i++) {
    free(file[i]);
  }
  free(file);
  deleteArgs(args);
  free(args);
}
コード例 #27
0
ファイル: mediacodec.c プロジェクト: 02002love/vlc
/*****************************************************************************
 * OpenDecoder: Create the decoder instance
 *****************************************************************************/
static int OpenDecoder(vlc_object_t *p_this, pf_MediaCodecApi_init pf_init)
{
    decoder_t *p_dec = (decoder_t *)p_this;
    decoder_sys_t *p_sys;
    mc_api *api;
    const char *mime = NULL;

    /* Video or Audio if "mediacodec-audio" bool is true */
    if (p_dec->fmt_in.i_cat != VIDEO_ES && (p_dec->fmt_in.i_cat != AUDIO_ES
     || !var_InheritBool(p_dec, CFG_PREFIX "audio")))
        return VLC_EGENERIC;

    if (p_dec->fmt_in.i_cat == VIDEO_ES)
    {
        if (!p_dec->fmt_in.video.i_width || !p_dec->fmt_in.video.i_height)
        {
            /* We can handle h264 without a valid video size */
            if (p_dec->fmt_in.i_codec != VLC_CODEC_H264)
            {
                msg_Dbg(p_dec, "resolution (%dx%d) not supported",
                        p_dec->fmt_in.video.i_width, p_dec->fmt_in.video.i_height);
                return VLC_EGENERIC;
            }
        }

        switch (p_dec->fmt_in.i_codec) {
        case VLC_CODEC_HEVC: mime = "video/hevc"; break;
        case VLC_CODEC_H264: mime = "video/avc"; break;
        case VLC_CODEC_H263: mime = "video/3gpp"; break;
        case VLC_CODEC_MP4V: mime = "video/mp4v-es"; break;
        case VLC_CODEC_WMV3: mime = "video/x-ms-wmv"; break;
        case VLC_CODEC_VC1:  mime = "video/wvc1"; break;
        case VLC_CODEC_VP8:  mime = "video/x-vnd.on2.vp8"; break;
        case VLC_CODEC_VP9:  mime = "video/x-vnd.on2.vp9"; break;
        /* case VLC_CODEC_MPGV: mime = "video/mpeg2"; break; */
        }
    }
    else
    {
        switch (p_dec->fmt_in.i_codec) {
        case VLC_CODEC_AMR_NB: mime = "audio/3gpp"; break;
        case VLC_CODEC_AMR_WB: mime = "audio/amr-wb"; break;
        case VLC_CODEC_MPGA:
        case VLC_CODEC_MP3:    mime = "audio/mpeg"; break;
        case VLC_CODEC_MP2:    mime = "audio/mpeg-L2"; break;
        case VLC_CODEC_MP4A:   mime = "audio/mp4a-latm"; break;
        case VLC_CODEC_QCELP:  mime = "audio/qcelp"; break;
        case VLC_CODEC_VORBIS: mime = "audio/vorbis"; break;
        case VLC_CODEC_OPUS:   mime = "audio/opus"; break;
        case VLC_CODEC_ALAW:   mime = "audio/g711-alaw"; break;
        case VLC_CODEC_MULAW:  mime = "audio/g711-mlaw"; break;
        case VLC_CODEC_FLAC:   mime = "audio/flac"; break;
        case VLC_CODEC_GSM:    mime = "audio/gsm"; break;
        case VLC_CODEC_A52:    mime = "audio/ac3"; break;
        case VLC_CODEC_EAC3:   mime = "audio/eac3"; break;
        case VLC_CODEC_ALAC:   mime = "audio/alac"; break;
        case VLC_CODEC_DTS:    mime = "audio/vnd.dts"; break;
        /* case VLC_CODEC_: mime = "audio/mpeg-L1"; break; */
        /* case VLC_CODEC_: mime = "audio/aac-adts"; break; */
        }
    }
    if (!mime)
    {
        msg_Dbg(p_dec, "codec %4.4s not supported",
                (char *)&p_dec->fmt_in.i_codec);
        return VLC_EGENERIC;
    }

    api = calloc(1, sizeof(mc_api));
    if (!api)
        return VLC_ENOMEM;
    api->p_obj = p_this;
    api->b_video = p_dec->fmt_in.i_cat == VIDEO_ES;
    if (pf_init(api) != VLC_SUCCESS)
    {
        free(api);
        return VLC_EGENERIC;
    }

    /* Allocate the memory needed to store the decoder's structure */
    if ((p_sys = calloc(1, sizeof(*p_sys))) == NULL)
    {
        api->clean(api);
        free(api);
        return VLC_ENOMEM;
    }
    p_sys->api = api;
    p_dec->p_sys = p_sys;

    p_dec->pf_decode_video = DecodeVideo;
    p_dec->pf_decode_audio = DecodeAudio;

    p_dec->fmt_out.i_cat = p_dec->fmt_in.i_cat;
    p_dec->fmt_out.video = p_dec->fmt_in.video;
    p_dec->fmt_out.audio = p_dec->fmt_in.audio;
    p_dec->b_need_packetized = true;
    p_sys->mime = mime;
    p_sys->b_new_block = true;

    if (p_dec->fmt_in.i_cat == VIDEO_ES)
    {
        p_sys->u.video.i_width = p_dec->fmt_in.video.i_width;
        p_sys->u.video.i_height = p_dec->fmt_in.video.i_height;

        p_sys->u.video.timestamp_fifo = timestamp_FifoNew(32);
        if (!p_sys->u.video.timestamp_fifo)
        {
            CloseDecoder(p_this);
            return VLC_ENOMEM;
        }

        if (p_dec->fmt_in.i_codec == VLC_CODEC_H264)
            h264_get_profile_level(&p_dec->fmt_in,
                                   &p_sys->u.video.i_h264_profile, NULL, NULL);

        p_sys->psz_name = MediaCodec_GetName(VLC_OBJECT(p_dec), p_sys->mime,
                                              p_sys->u.video.i_h264_profile);
        if (!p_sys->psz_name)
        {
            CloseDecoder(p_this);
            return VLC_EGENERIC;
        }

        /* Check if we need late opening */
        switch (p_dec->fmt_in.i_codec)
        {
        case VLC_CODEC_H264:
            if (!p_sys->u.video.i_width || !p_sys->u.video.i_height)
            {
                msg_Warn(p_dec, "waiting for sps/pps for codec %4.4s",
                         (const char *)&p_dec->fmt_in.i_codec);
                return VLC_SUCCESS;
            }
        case VLC_CODEC_VC1:
            if (!p_dec->fmt_in.i_extra)
            {
                msg_Warn(p_dec, "waiting for extra data for codec %4.4s",
                         (const char *)&p_dec->fmt_in.i_codec);
                return VLC_SUCCESS;
            }
            break;
        }
    }
    else
    {
        p_sys->u.audio.i_channels = p_dec->fmt_in.audio.i_channels;

        p_sys->psz_name = MediaCodec_GetName(VLC_OBJECT(p_dec), p_sys->mime, 0);
        if (!p_sys->psz_name)
        {
            CloseDecoder(p_this);
            return VLC_EGENERIC;
        }

        /* Marvel ACodec assert if channel count is 0 */
        if (!strncmp(p_sys->psz_name, "OMX.Marvell",
                     __MIN(strlen(p_sys->psz_name), strlen("OMX.Marvell"))))
            p_sys->u.audio.b_need_channels = true;

        /* Check if we need late opening */
        switch (p_dec->fmt_in.i_codec)
        {
        case VLC_CODEC_VORBIS:
        case VLC_CODEC_MP4A:
            if (!p_dec->fmt_in.i_extra)
            {
                msg_Warn(p_dec, "waiting for extra data for codec %4.4s",
                         (const char *)&p_dec->fmt_in.i_codec);
                return VLC_SUCCESS;
            }
            break;
        }
        if (!p_sys->u.audio.i_channels && p_sys->u.audio.b_need_channels)
        {
            msg_Warn(p_dec, "waiting for valid channel count");
            return VLC_SUCCESS;
        }
    }

    return StartMediaCodec(p_dec);
}
コード例 #28
0
ファイル: bsnmpimport.c プロジェクト: hmatyschok/MeshBSD
static int32_t
snmp_import_object(struct snmp_toolinfo *snmptoolctx)
{
	char *string;
	int i;
	int32_t tok;
	struct snmp_oid2str *oid2str;

	if (snmp_import_head(snmptoolctx) < 0)
		return (-1);

	if ((oid2str = calloc(1, sizeof(struct snmp_oid2str))) == NULL) {
		syslog(LOG_ERR, "calloc() failed: %s", strerror(errno));
		return (-1);
	}

	if ((string = strdup(nexttok)) == NULL) {
		syslog(LOG_ERR, "strdup() failed: %s", strerror(errno));
		free(oid2str);
		return (-1);
	}

	oid2str->string = string;
	oid2str->strlen = strlen(nexttok);

	asn_append_oid(&(oid2str->var), &(current_oid));
	if (snmp_suboid_append(&(oid2str->var), (asn_subid_t) val) < 0)
		goto error;

	/*
	 * Prepared the entry - now figure out where to insert it.
	 * After the object we have following options:
	 * 1) new line, blank, ) - then it is an enum oid -> snmp_enumlist;
	 * 2) new line , ( - nonleaf oid -> snmp_nodelist;
	 * 2) ':' - table entry - a variable length SYNTAX_TYPE (one or more)
	 *     may follow and second string must end line -> snmp_tablelist;
	 * 3) OID , string  ) - this is a trap entry or a leaf -> snmp_oidlist;
	 * 4) SYNTAX_TYPE, string (not always), get/set modifier - always last
	 *     and )- this is definitely a leaf.
	 */

	switch (tok = gettoken(snmptoolctx)) {
	    case  ')':
		if ((i = snmp_enum_insert(snmptoolctx, oid2str)) < 0)
			goto error;
		if (i == 0) {
			free(oid2str->string);
			free(oid2str);
		}
		return (1);

	    case '(':
		if (snmp_suboid_append(&current_oid, (asn_subid_t) val) < 0)
			goto error;

		/* 
		 * Ignore the error for nodes since the .def files currently
		 * contain different strings for 1.3.6.1.2.1 - mibII. Only make
		 * sure the memory is freed and don't complain.
		 */
		if ((i = snmp_node_insert(snmptoolctx, oid2str)) <= 0) {
			free(string);
			free(oid2str);
		}
		return (snmp_import_object(snmptoolctx));

	    case ':':
		if (snmp_suboid_append(&current_oid, (asn_subid_t) val) < 0)
			goto error;
		if (snmp_import_table(snmptoolctx, oid2str) < 0)
			goto error;
		/*
		 * A different table entry type was malloced and the data is
		 * contained there.
		 */
		free(oid2str);
		return (1);

	    case TOK_TYPE:
		/* FALLTHROUGH */
	    case TOK_DEFTYPE:
		/* FALLTHROUGH */
	    case TOK_ENUM:
	    	/* FALLTHROUGH */
	    case TOK_BITS:
		if (snmp_import_leaf(snmptoolctx, &tok, oid2str) < 0)
				goto error;
		return (1);

	    default:
		warnx("Unexpected token at line %d - %s", input->lno,
		    input->fname);
		break;
	}

error:
	snmp_mapping_entryfree(oid2str);

	return (-1);
}
コード例 #29
0
ファイル: interface.c プロジェクト: outadoc/RicochetRobots
//
// Demande à l'utilisateur s'il souhaite rejouer.
//
bool wantsToReplay(WINDOW *win, int top) {
    if(win == NULL || top < 0) return false;
    
    //variables pour l'affichage du menu
    ITEM **menuItems = NULL;
    MENU *menu = NULL;
    
    int i = 0, c;
    int nbChoices = 2;
    
    char *choices[] = {
        "Menu Principal",
        "Quitter"
    };
    
    int winWidth = POPUP_WINDOW_WIDTH;
    //largeur du menu = longueur du plus grand des choix possibles
    int menuWidth = 22;
    
    //on alloue de la mémoire pour initialiser les éléments du menu
    menuItems = (ITEM **) calloc(nbChoices + 1, sizeof(ITEM *));
    
    //on créé de nouveaux éléments à partir des choix fournis
    for(i = 0; i < nbChoices; i++) {
        menuItems[i] = new_item(choices[i], NULL);
    }
    
    //on met un élément nul à la fin du tableau
    menuItems[nbChoices] = (ITEM *) NULL;
    
    //on initialise le menu
    menu = new_menu((ITEM **) menuItems);
    
    //on lui précise bien que le menu fait 1 ligne et 2 colonnes
    set_menu_format(menu, 1, 2);
    
    //on associe le menu à une fenêtre et une sous-fenêtre
    set_menu_win(menu, win);
    //fenêtre hauteur largeur x y
    set_menu_sub(menu, derwin(win, nbChoices, menuWidth, top, (winWidth - menuWidth) / 2));
    
    menu_opts_off(menu, O_NONCYCLIC);
    set_menu_mark(menu, "");
    
    //et hop, on affiche le menu et on rafraîchit.
	post_menu(menu);
	
    refresh();
    wrefresh(win);
    
    curs_set(0);
    noecho();
    
    //boucle pour le menu
    while((c = getch())) {
        switch(c) {
            case KEY_LEFT:
            case KEY_UP:
                menu_driver(menu, REQ_LEFT_ITEM);
                break;
            case KEY_RIGHT:
            case KEY_DOWN:
                menu_driver(menu, REQ_RIGHT_ITEM);
                break;
            case KEY_MENU_ENTER: {
                int choice = item_index(current_item(menu));
                
                unpost_menu(menu);
                free_menu(menu);
                
                for(i = 0; i < nbChoices; ++i)
                    free_item(menuItems[i]);
                
                //si l'indice est 1 on renvoie 0 et vice-versa
                return !choice;
            }
        }
        
        wrefresh(win);
    }
    
    return false;
}