Example #1
0
/*
int main()
{
  return 0;
}
*/
int communicate(struct donnees* donnees)
{
  printf("communicate\n");
  struct client* client=donnees->client;
  ulong ip = client->sockaddr->sin_addr.s_addr;
  struct peer* peer = find_peer(donnees->peer_list, ip);
  struct file_list* file_list = donnees->file_list;
  struct peer_list* peer_list = donnees->peer_list;
  int refresh_time=get_refresh_time();
  printf("refresh time:%d\n",refresh_time);
  char* recv_buffer= malloc(sizeof(char)*RECV_BUF_SIZE);
  char* send_buffer= malloc(sizeof(char)*SEND_BUF_SIZE);  
  char* s1 = malloc(RECV_BUF_SIZE*sizeof(char));
  char* s2 = malloc(RECV_BUF_SIZE*sizeof(char));
  char* s3 = malloc(RECV_BUF_SIZE*sizeof(char));
  char* s4 = malloc(RECV_BUF_SIZE*sizeof(char));
  char* s5 = malloc(RECV_BUF_SIZE*sizeof(char));
  char* s6 = malloc(RECV_BUF_SIZE*sizeof(char));
  char* s0 = malloc(RECV_BUF_SIZE*sizeof(char));
  char* saux = malloc(RECV_BUF_SIZE*sizeof(char));
  char** tab = malloc(7*sizeof(char *));
  tab[0]=s0;
  tab[1]=s1;
  tab[2]=s2;
  tab[3]=s3;
  tab[4]=s4;
  tab[5]=s5;
  tab[6]=s6;
  int port;
  int read;
  int decalage;
  int length;
  int piece_size;
  struct timeval *t = malloc(sizeof(struct timeval));
  struct timeval *t2 = malloc(sizeof(struct timeval));
  struct timezone *tz = malloc(sizeof(struct timezone));
  struct timezone *tz2 = malloc(sizeof(struct timezone));
  gettimeofday(t,tz);
  while(1)
    { 
      recv_buffer[0]='\0';
      send_buffer[0]='\0';
      gettimeofday(t2,tz2);
      if(( (int)(t2->tv_sec - t->tv_sec))>3*refresh_time)
	{
	  if(peer!=NULL)
	    {
	      peer->time--;
	      if(!peer->time)
		{
		  peer_list_peer_delete(peer_list,file_list,peer->ip_address);
		}
	    }
	  //free  
	  free(s0);
	  free(s1);
	  free(s2);
	  free(s3);
	  free(s4);
	  free(s5);
	  free(s6);
	  free(saux);
	  free(recv_buffer);
	  free(send_buffer);
	  free(tab);
	  free(t);
	  free(t2);
	  free(tz);
	  free(tz2);
	  end(client,donnees->ct);
	  return 0;
	}
      read=read_client(client->sock, recv_buffer);
      if(read > 0)
	{
	  gettimeofday(t,tz);
	  if(peer!=NULL)
	    peer->time ++;
	  //print_data(file_list, peer_list);	  
	  printf("received:\n");
	  switch(recv_buffer[0])
	    {
	     pthread_mutex_lock(& mutex);
	    case'a':
	      decalage=0;
	      while(compte_crochet_fermant(recv_buffer)<2)
		{
		  decalage+=read;
		  read=read_client(client->sock, recv_buffer + decalage);
		}	  
	      recv_buffer[decalage+read]='\0';
	      printf("%s\n", recv_buffer);
	      parse(recv_buffer, tab);
	      port = atoi(s2);
	      if(strcmp(s0,"announce")==0 && strcmp(s1,"listen")==0 && strcmp(s3,"seed")==0 && strcmp(s5,"leech")==0)
		{
		  
		  if(peer == NULL)
		    {
		      peer = peer_init(ip, port);
		      peer_list_add(peer_list, peer);
		      peer->time=1;
		    }
		  int i=0;
		  while(strlen(s4+i) > 0)
		    {
		      if(compte_espace(s4+i)>3)
			{		 
			  
			  sscanf(s4+i, "%s %d %d %s", s1, &length, &piece_size, s2);
			  sprintf(saux, "%s %d %d %s", s1, length, piece_size, s2);
			  struct file* file = find_file(file_list, s1);
			  if(NULL == file)
			    {
			      file = remplit_file(s1, length, piece_size, s2);
			      file_list_add(file_list, file);
			    }
			  add_link(file, peer); 
			  i+=strlen(saux)+1;
			  
			}
		      else
			{
			  
			  sscanf(s4+i, "%s %d %d %s", s1, &length, &piece_size, s2); 
			  struct file* file = find_file(file_list, s1);
			  if(NULL == file)
			    {
			      file = remplit_file(s1, length, piece_size, s2);
			      file_list_add(file_list, file);
			    }
			  add_link(file, peer); 
			  s4[i]='\0';			
			}
		    }
		  struct file_list* f_add = keys_string_to_file_list(s6);
		  
		  update_add(file_list, peer, f_add);
		  file_list_delete(f_add);
		  write_client(client->sock, "ok");
		  printf("replied:ok\n");
		  
		}
	      break;
	      
	    case'u':
	      decalage=0;
	      while(compte_crochet_fermant(recv_buffer)<2)
		{
		  decalage+=read;
		  read=read_client(client->sock, recv_buffer + decalage);
		}	  
	      recv_buffer[decalage+read]='\0'; 
	      printf("%s\n", recv_buffer);	      
	      parse(recv_buffer, tab);
	      if(strcmp(s0,"update")==0 && strcmp(s1,"seed")==0 && strcmp(s3,"leech")==0)
		{
		  if(peer==NULL){
		    //free  
		    free(s0);
		    free(s1);
		    free(s2);
		    free(s3);
		    free(s4);
		    free(s5);
		    free(s6);
		    free(saux);
		    free(recv_buffer);
		    free(send_buffer);
		    free(tab);
		    free(t);
		    free(t2);
		    free(tz);
		    free(tz2);
		    end(client, donnees->ct);
		    
		    return 0;}//ferme la socket
		  else
		    { 
		    
		      char* res=fusion_keys_string(s2, s4);
		      struct file_list* f = keys_string_to_file_list(res);
		      update_diff(f, peer->file_list, file_list, peer);
		      file_list_delete(f);
		      free(res);
		      write_client(client->sock, "ok");
		      printf("replied:ok\n");
		  
		    }	    
		}
	      break;
	      
	    case'l':
	      decalage=0;
	      while(compte_crochet_fermant(recv_buffer)<1)
		{
		  decalage+=read;
		  read=read_client(client->sock, recv_buffer + decalage);
		}	  
	      recv_buffer[decalage+read]='\0'; 
	      printf("%s\n", recv_buffer);	      
	      parse(recv_buffer, tab);
	      if(strcmp(s0,"look")==0)
		{
		  char* filename="filename";
		  int egal=1;
		  int i;
		  s2[0]='\n';
		  for(i=0;i<8;i++)
		    {
		      if(s1[i]!=filename[i]) egal --;
		    }
		  if(egal==1)
		    {
		      for(i=10;i<((int) strlen(s1))-1;i++)
			{
			  s2[i-10]=s1[i];
			}
		      s2[strlen(s1)-11]='\0';
		      
		      printf("recherche:\nfilename=%s\n",s2);
		      struct file* file=find_file_name(file_list, s2);
		      if(file==NULL) write_client(client->sock, "list []");
		      else
			{
			  sprintf(send_buffer, "list [%s %d %d %s]", s2, file->length, file->p_size, file->key);
			  write_client(client->sock, send_buffer);
			  printf("replied:%s\n", send_buffer);
			}
		    }
		}
	      break;

	    case'g':
	      recv_buffer[read]='\0'; 
	      printf("%s\n", recv_buffer);	      
	      parse(recv_buffer, tab);
	      if(strcmp(s0,"getfile")==0)
		{
		  struct file* f=find_file(file_list, s1);
		  if(f==NULL||f->peer_list->first==NULL)
		    {
		      sprintf(send_buffer, "peers %s []", s1);
		      write_client(client->sock, send_buffer);
		    }
		  else
		    {
		      struct elt_peer* aux=f->peer_list->first;
		      struct in_addr* in_addr1=malloc(sizeof(struct in_addr));
		      in_addr1->s_addr=aux->peer->ip_address;
		      char* d= inet_ntoa(*in_addr1);
		      sprintf(send_buffer, "peers %s [%s:%d", s1, d, aux->peer->port);
		      aux=aux->next;
		      while(aux!=NULL)
			{
			  struct in_addr* in_addr=malloc(sizeof(struct in_addr));
			  in_addr->s_addr=aux->peer->ip_address;
			  char* c= inet_ntoa(*in_addr);
			  sprintf(send_buffer+strlen(send_buffer), " %s:%d", c, aux->peer->port);
			  aux=aux->next;
			}
		      sprintf(send_buffer+strlen(send_buffer), "]");
		      write_client(client->sock, send_buffer);
		      printf("replied:%s\n", send_buffer);
		    }
		}
	      break;

	    default:
	      printf("entree non valide");
	      //free  
	      free(s0);
	      free(s1);
	      free(s2);
	      free(s3);
	      free(s4);
	      free(s5);
	      free(s6);
	      free(saux);
	      free(recv_buffer);
	      free(send_buffer);
	      free(tab);
	      free(t);
	      free(t2);
	      free(tz);
	      free(tz2);
	      end(client,donnees->ct);
	      return 0;
	      
	     
	    }
	  pthread_mutex_unlock( &mutex);
	}
      
    }
  return EXIT_SUCCESS;
}
Example #2
0
void*
client_request_get (void *arg) {
    r = (struct client_request *) arg;
    struct daemon_list  *d_list;
    struct daemon_list  *list_item_to_delete;
    struct daemon       *next_d;
    int                 seeder_count;
    
    if (!r)
        return NULL;


    /* First we find the file in the cache */
    
    if (find_file () < 0)
        return NULL;
    /* file_to_dl should now be the good one */


    /* Find the daemons owning the file by checking its IP */
    if ((d_list = find_daemons ()) != NULL) {
        if (client_send (r->client,
            " < no seeder for the requested file. Former seeders must have been disconnected.\n") < 0)
            log_failure (log_file, "cr_get: client_send () failed");
        return NULL;
    }

    
    /* about handling multi-seeders and block-by-block download */
    
    // we know the number of seeders
    seeder_count = d_list->id;
    
    /* FIXME : calculate smartly the blocks to consider,
     * given :
     * - number of seeders
     * - size of file to dl
     * - a max_size for a block ? Not implemented
     */
     
    /* loop where we have to post a job for each seeder
     */
    next_d = d_list->daemon;
    while (next_d != NULL) {
        // FIXME : act !!!! do something !!!
        
        list_item_to_delete = d_list;
        d_list = d_list->next;
        free (list_item_to_delete);
    }



    /* Sending the "get key begin end" message */
    sprintf (answer,
             "get %s %d %ld\n",
             file_to_dl->key,
             0,
             file_to_dl->size);
    if (daemon_send (d, answer) < 0) {
        log_failure (log_file, "cr_get: could not send the get command");
        return NULL;
    }
    
    
/* FIXME */
#if 0
    sem_wait (&downloads_lock);
    char *full_path;
    struct dl_file *f;

    full_path = malloc (strlen (prefs->shared_folder)
                        + strlen (file_to_dl->filename) + 2);
    if (!full_path) {
        log_failure (log_file, "OMG NO MALLOC IS POSSIBLE");
        return NULL;
    }
    else {
        sprintf (full_path, "%s/%s",
                        prefs->shared_folder, file_to_dl->filename);
    }
    f = dl_file_new (full_path);
    if (!f) {
        log_failure (log_file, "SHARED FOLDER : %S", prefs->shared_folder);
        log_failure (log_file, "f was NULL %s", full_path);
    }
    downloads = dl_file_add (downloads, f);
    if (!downloads)
        log_failure (log_file, "downlaods was NULL");
    else
        log_failure (log_file, "downloads->path : %s", downloads->path);
    sem_post (&downloads_lock);
#endif

    return NULL;
}
Example #3
0
VALUE require_compiled(VALUE fname, VALUE* result, int bLoad)
{
    VALUE path;
    char* szName1 = 0;
    VALUE retval = Qtrue;
    
    if (TYPE(fname) != T_STRING)
        rb_raise(rb_eLoadError, "can not load non-string");

    szName1 = RSTRING_PTR(fname);

    if ( String_endsWith(szName1,".rb") ) 
    {
        rb_str_chop_bang(fname); rb_str_chop_bang(fname); rb_str_chop_bang(fname);
    }
    //rb_funcall(fname, rb_intern("sub!"), 2, rb_str_new2(".rb"), rb_str_new2("") );
    szName1 = RSTRING_PTR(fname);

    if ( strcmp("strscan",szName1)==0 || strcmp("enumerator",szName1)==0 ||
        strcmp("stringio",szName1)==0 || strcmp("socket",szName1)==0 )
        return Qtrue;

    RHO_LOCK(require_lock);

    if ( !bLoad && isAlreadyLoaded(fname) == Qtrue )
        goto RCompExit;

    path = find_file(fname);

    if ( path != 0 )
    {
        VALUE seq;

        RAWLOG_INFO1("require_compiled: %s", szName1);

        //optimize require
        //rb_ary_push(GET_VM()->loaded_features, path);
        rb_ary_push(GET_VM()->loaded_features, fname);

#ifdef RHODES_EMULATOR
        if ( strstr( RSTRING_PTR(path), ".rb") == 0 )
            rb_str_cat(path,".rb",3);

        GET_VM()->src_encoding_index = rb_utf8_encindex();
        rb_load(path, 0);

        if( rho_simconf_getBool("reload_app_changes") )
        {
            if ( strncmp( RSTRING_PTR(path), rho_native_rhopath(), strlen(rho_native_rhopath()) ) == 0 )
                rb_ary_delete(GET_VM()->loaded_features, fname);
        }
#else
        //rb_gc_disable();
        seq = loadISeqFromFile(path);
        

        //*result = rb_funcall(seq, rb_intern("eval"), 0 );
        *result = rb_iseq_eval(seq);
        
        //rb_gc_enable();
#endif
        goto RCompExit;
    }

    RAWLOG_ERROR1("require_compiled: error: can not find %s", RSTRING_PTR(fname));
    retval = Qnil;

RCompExit:
    RHO_UNLOCK(require_lock);
    return retval;
}
Example #4
0
void
pidgin_stock_load_stock_icon_theme(PidginStockIconTheme *theme)
{
	GtkIconFactory *icon_factory;
	gsize i;
	GtkWidget *win;

	if (theme != NULL) {
		purple_prefs_set_string(PIDGIN_PREFS_ROOT "/stock/icon-theme",
		                        purple_theme_get_name(PURPLE_THEME(theme)));
		purple_prefs_set_path(PIDGIN_PREFS_ROOT "/stock/icon-theme-dir",
		                      purple_theme_get_dir(PURPLE_THEME(theme)));
	}
	else {
		purple_prefs_set_string(PIDGIN_PREFS_ROOT "/stock/icon-theme", "");
		purple_prefs_set_path(PIDGIN_PREFS_ROOT "/stock/icon-theme-dir", "");
	}

	icon_factory = gtk_icon_factory_new();

	gtk_icon_factory_add_default(icon_factory);

	win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	gtk_widget_realize(win);

	/* All non-sized icons */
	for (i = 0; i < G_N_ELEMENTS(stock_icons); i++) {
		GtkIconSource *source;
		GtkIconSet *iconset;
		gchar *filename;

		if (stock_icons[i].dir == NULL) {
			/* GTK+ Stock icon */
			iconset = gtk_style_context_lookup_icon_set(gtk_widget_get_style_context(win),
			                                            stock_icons[i].filename);
		} else {
			filename = find_file(stock_icons[i].dir, stock_icons[i].filename);

			if (filename == NULL)
				continue;

			source = gtk_icon_source_new();
			gtk_icon_source_set_filename(source, filename);
			gtk_icon_source_set_direction_wildcarded(source, TRUE);
			gtk_icon_source_set_size_wildcarded(source, TRUE);
			gtk_icon_source_set_state_wildcarded(source, TRUE);

			iconset = gtk_icon_set_new();
			gtk_icon_set_add_source(iconset, source);

			gtk_icon_source_free(source);
			g_free(filename);
		}

		gtk_icon_factory_add(icon_factory, stock_icons[i].name, iconset);

		gtk_icon_set_unref(iconset);
	}

	/* All non-status sized icons */
	for (i = 0; i < G_N_ELEMENTS(sized_stock_icons); i++)
	{
		GtkIconSet *iconset = gtk_icon_set_new();

#define ADD_SIZED_ICON(name, size) \
		if (sized_stock_icons[i].name) \
			add_sized_icon(iconset, name, PIDGIN_ICON_THEME(theme), size, sized_stock_icons[i], FALSE);
		ADD_SIZED_ICON(microscopic, "11");
		ADD_SIZED_ICON(extra_small, "16");
		ADD_SIZED_ICON(small, "22");
		ADD_SIZED_ICON(medium, "32");
		ADD_SIZED_ICON(large, "48");
		ADD_SIZED_ICON(huge, "64");
#undef ADD_SIZED_ICON

		gtk_icon_factory_add(icon_factory, sized_stock_icons[i].name, iconset);
		gtk_icon_set_unref(iconset);
	}

	gtk_widget_destroy(win);
	g_object_unref(G_OBJECT(icon_factory));
	reload_settings();
}
Example #5
0
/**
 * This is the main message reading loop.  Messages are read, validated,
 * decrypted if necessary, then passed to the appropriate routine for handling.
 */
void mainloop()
{
    struct uftp_h *header;
    struct uftp2_h *v2_header;
    unsigned char *buf, *decrypted, *message;
    unsigned int decryptlen, meslen, expectedlen;
    int packetlen, listidx, i;
    uint8_t version, *func;
    uint32_t v2func;
    struct sockaddr_in src;
    struct timeval *tv;
    const int bsize = 9000;  // Roughly size of ethernet jumbo frame

    log0(0, 0, "%s", VERSIONSTR);
    for (i = 0; i < key_count; i++) {
        log1(0, 0, "Loaded key with fingerprint %s",
                  print_key_fingerprint(privkey[i]));
    }

    buf = calloc(bsize, 1);
    decrypted = calloc(bsize, 1);
    if ((buf == NULL) || (decrypted == NULL)){
        syserror(0, 0, "calloc failed!");
        exit(1);
    }
    header = (struct uftp_h *)buf;
    v2_header = (struct uftp2_h *)buf;

    while (1) {
        tv = getrecenttimeout();
        if (read_packet(listener, &src, buf, &packetlen,
                        bsize, tv) <= 0) {
            continue;
        }

        if ((header->uftp_id == UFTP_VER_NUM) ||
                (header->uftp_id == UFTP_3_0_VER)) {
            version = header->uftp_id;
            expectedlen = sizeof(struct uftp_h) + ntohs(header->blsize);
            listidx = find_file(ntohl(header->group_id));
        } else if (ntohl(v2_header->uftp_id) == V2_UFTP_ID) {
            version = UFTP_V2_VER;
            expectedlen = V2_PACKETSIZE;
            listidx = find_file(ntohl(v2_header->tx_id));
            v2func = ntohl(v2_header->func);
        } else {
            log(0, 0, "Invalid message from %s: not uftp packet "
                      "or invalid version", inet_ntoa(src.sin_addr));
            continue;
        }
        if (packetlen != expectedlen) {
            log(0, 0, "Invalid packet size from %s: got %d, expected %d",
                      inet_ntoa(src.sin_addr), packetlen, expectedlen);
            continue;
        }

        if (((version == UFTP_VER_NUM) || (version == UFTP_3_0_VER)) &&
                (header->func == ENCRYPTED) && (listidx != -1) &&
                (group_list[listidx].keytype != KEY_NONE)) {
            if (group_list[listidx].phase == PHASE_REGISTERED) {
                log(ntohl(header->group_id), 0, "Got encrypted packet from %s "
                        "but keys not established", inet_ntoa(src.sin_addr));
            }

            if (!validate_and_decrypt(buf, &decrypted, &decryptlen,
                    group_list[listidx].mtu, group_list[listidx].keytype,
                    group_list[listidx].groupkey, group_list[listidx].groupsalt,
                    group_list[listidx].ivlen, group_list[listidx].hashtype,
                    group_list[listidx].grouphmackey,
                    group_list[listidx].hmaclen, group_list[listidx].sigtype,
                    group_list[listidx].serverkey,
                    group_list[listidx].server_keylen)) {
                log(ntohl(header->group_id), 0, "Rejecting message from %s: "
                        "decrypt/validate failed", inet_ntoa(src.sin_addr));
                continue;
            }
            func = (uint8_t *)decrypted;
            message = decrypted;
            meslen = decryptlen;
        } else if ((version == UFTP_VER_NUM) || (version == UFTP_3_0_VER)) {
            if ((listidx != -1) && (group_list[listidx].keytype != KEY_NONE) &&
                    ((header->func == FILEINFO) || (header->func == FILESEG) ||
                     (header->func == DONE) || (header->func == DONE_CONF) ||
                     ((header->func == ABORT) &&
                         (group_list[listidx].phase != PHASE_REGISTERED)))) {
                log(0, 0, "Rejecting %s message from %s: not encrypted",
                        func_name(header->func), inet_ntoa(src.sin_addr));
                continue;
            }
            func = (uint8_t *)&header->func;
            message = buf + sizeof(struct uftp_h);
            meslen = ntohs(header->blsize);
        } else {
            // Version 2
            message = buf;
            meslen = V2_PACKETSIZE;
        }

        if (((version == UFTP_VER_NUM) || (version == UFTP_3_0_VER)) &&
                (header->func == PROXY_KEY)) {
            handle_proxy_key(&src, buf);
            continue;
        }
        if (((version == UFTP_VER_NUM) || (version == UFTP_3_0_VER)) &&
                (header->func == HB_RESP)) {
            handle_hb_response(listener, &src, buf, hb_hosts, hbhost_count,
                               noname, privkey[0]);
            continue;
        }
        if ((((version == UFTP_VER_NUM) || (version == UFTP_3_0_VER)) &&
                 (header->func == ANNOUNCE)) ||
                ((version == UFTP_V2_VER) && (v2func == V2_ANNOUNCE))) {
            // Ignore any ANNOUNCE for a group we're already handling
            if (listidx == -1) {
                handle_announce(src, version, buf);
            } else if (group_list[listidx].phase == PHASE_MIDGROUP) {
                // Make sure we don't time out while waiting for other
                // clients to register with the server.
                set_timeout(listidx);
            }
        } else {
            if (listidx == -1) {
                // group / file ID not in list
                continue;
            }
            if (group_list[listidx].version != version) {
                log(group_list[listidx].group_id, group_list[listidx].file_id,
                        "Version mismatch");
                continue;
            }
            if ((((version == UFTP_VER_NUM) || (version == UFTP_3_0_VER)) &&
                     (*func == ABORT)) ||
                    ((version == UFTP_V2_VER) && (v2func == V2_ABORT))) {
                handle_abort(listidx, message, meslen);
                continue;
            }
            switch (group_list[listidx].phase) {
            case PHASE_REGISTERED:
                if (version == UFTP_V2_VER) {
                    // This is repeated in one of the cases below, but it's
                    // separated out anyway to keep the V2 stuff separate.
                    handle_regconf(listidx, message, meslen);
                } else if (group_list[listidx].keytype != KEY_NONE) {
                    if (*func == KEYINFO) {
                        handle_keyinfo(listidx, buf);
                    } else {
                        log(group_list[listidx].group_id,
                                group_list[listidx].file_id,
                                "Expected KEYINFO, got %s", func_name(*func));
                    }
                } else if (group_list[listidx].keytype == KEY_NONE) {
                    if (*func == REG_CONF) {
                        handle_regconf(listidx, message, meslen);
                    } else if (*func == FILEINFO) {
                        handle_fileinfo(listidx, message, meslen);
                    } else {
                        log(group_list[listidx].group_id,
                                group_list[listidx].file_id,
                                "Expected REG_CONF, got %s", func_name(*func));
                    }
                }
                break;
            case PHASE_MIDGROUP:
                if (((version == UFTP_VER_NUM) || (version == UFTP_3_0_VER)) &&
                        (*func == FILEINFO)) {
                    handle_fileinfo(listidx, message, meslen);
                } else if (((version == UFTP_VER_NUM) ||
                            (version == UFTP_3_0_VER)) && (*func == KEYINFO)) {
                    handle_keyinfo(listidx, buf);
                } else if (((version == UFTP_V2_VER) && (v2func == V2_DONE)) ||
                        (((version == UFTP_VER_NUM) ||
                          (version == UFTP_3_0_VER)) && (*func == DONE))) {
                    handle_done(listidx, message, meslen);
                } else {
                    // Other clients may be still getting earlier files or
                    // setting up, so silently ignore anything unexpected
                    // and reset the timeout.
                    set_timeout(listidx);
                }
                break;
            case PHASE_RECEIVING:
                if (((version == UFTP_VER_NUM) || (version == UFTP_3_0_VER)) &&
                        (*func == FILEINFO)) {
                    handle_fileinfo(listidx, message, meslen);
                } else if (((version == UFTP_V2_VER) &&
                            (v2func == V2_FILESEG)) ||
                        (((version == UFTP_VER_NUM) ||
                          (version == UFTP_3_0_VER)) && (*func == FILESEG))) {
                    handle_fileseg(listidx, message, meslen);
                } else if (((version == UFTP_V2_VER) && (v2func == V2_DONE)) ||
                        (((version == UFTP_VER_NUM) ||
                          (version == UFTP_3_0_VER)) && (*func == DONE))) {
                    handle_done(listidx, message, meslen);
                }
                break;
            case PHASE_COMPLETE:
                if (((version == UFTP_V2_VER) && (v2func == V2_DONE_CONF)) ||
                        (((version == UFTP_VER_NUM) || 
                          (version == UFTP_3_0_VER)) && (*func == DONE_CONF))) {
                    handle_done_conf(listidx, message, meslen);
                }
                break;
            }
        }
    }
}
Example #6
0
bool file_exists(const std::string& name)
{
	return do_file_exists(find_file(name));
}
Example #7
0
File: rom.c Project: GPDP2/mupen64
int fill_header(const char *argv)
{
   char arg[1024];
   strncpy(arg, argv, 1000);
   if (find_file(arg))
     {
	printf ("file not found or wrong path\n");
	return 0;
     }
/*------------------------------------------------------------------------*/   
   findsize();
   if (rom) free(rom);
   rom = malloc(0x40);
   
   tmp=0;
   
   if (!z)
     fread(rom, 1, 0x40, rom_file);
   else if (z == 1)
     gzread(z_rom_file, rom, 0x40);
   else
     {
	unzOpenCurrentFile(zip);
	unzReadCurrentFile(zip, rom, 0x40);
	unzCloseCurrentFile(zip);
     }
   if (!z) fclose(rom_file);
   else if (z==1) gzclose(z_rom_file);
   else unzClose(zip);
   
   if (rom[0]==0x37)
     {
	for (i=0; i<(0x40/2); i++)
	  {
	     tmp=rom[i*2];
	     rom[i*2]=rom[i*2+1];
	     rom[i*2+1]=tmp;
	  }
     }
   if (rom[0]==0x40)
     {
	for (i=0; i<(0x40/4); i++)
	  {
	     tmp=rom[i*4];
	     rom[i*4]=rom[i*4+3];
	     rom[i*4+3]=tmp;
	     tmp=rom[i*4+1];
	     rom[i*4+1]=rom[i*4+2];
	     rom[i*4+2]=tmp;
	  }
     }
   else if ((rom[0] != 0x80) || (rom[1] != 0x37) || (rom[2] != 0x12) || (rom[3] != 0x40))
     {
	free(rom);
	rom = NULL;
	return 0;
     }
   
   if (ROM_HEADER == NULL) ROM_HEADER= malloc(sizeof(rom_header));
   memcpy(ROM_HEADER, rom, 0x40);
   free(rom);
   rom = NULL;
   return taille_rom;
}
Example #8
0
int
main(int argc, char *argv[])
{
    char *prog_name = argv[0];
    int sock_fd;
    unsigned long result = 0;

    argc--; argv++;

    if (argc > 0 && strcmp(argv[0], "-w") == 0)
    {
	opt_nowait = 1;
	argc--; argv++;
    }

    if (argc > 0 && strcmp(argv[0], "-?") == 0)
    {
	usage(prog_name);
	argc--; argv++;
    }

    if(argc == 0)
	return 0;

    sock_fd = connect_to_jade();
    if(sock_fd == -1)
	return 1;

    while(result == 0 && argc > 0)
    {
	result = 5;
	if(**argv == '-')
	{
	    switch((*argv)[1])
	    {
		char buf[512];

	    case 'q':
		opt_quiet = 1;
		result = 0;
		break;

	    case 'f':			/* -f FUNCTION */
		if(argc < 2)
		    goto opt_error;
		buf[0] = '(';
		strcpy(buf + 1, argv[1]);
		strcat(buf, ")");
		result = eval_lisp_form(sock_fd, buf);
		argc--; argv++;
		break;

	    case 'e':			/* -e FORM */
		if(argc < 2)
		    goto opt_error;
		result = eval_lisp_form(sock_fd, argv[1]);
		argc--; argv++;
		break;

	    case 'x':
		if(argc < 2)
		    goto opt_error;
		sprintf(buf, "(make-window-on-display \"%s\")", argv[1]);
		result = eval_lisp_form(sock_fd, buf);
		argc--; argv++;
		break;

	    case 'X':
		{
		    char *dpy = getenv("DISPLAY");
		    if(dpy == 0)
			fprintf(stderr, "No DISPLAY environment variable\n");
		    else
		    {
			sprintf(buf, "(make-window-on-display \"%s\")", dpy);
			result = eval_lisp_form(sock_fd, buf);
		    }
		    break;
		}

	    case 0:
		do {
		    if(isatty(0))
			printf("jade%% "), fflush(stdout);
		    if(fgets(buf, sizeof(buf), stdin) == 0)
			result = 10;
		    else
			result = eval_lisp_form(sock_fd, buf);
		} while(result == 0);
		argc--; argv++;
		break;

	    case '-':
		{
		    int bufsiz = 1024, bufuse = 0;
		    char *input_buf = malloc(bufsiz);
		    if(input_buf == 0)
		    {
			perror("malloc");
			result = 10;
			break;
		    }
		    strcpy(input_buf, "(progn ");
		    bufuse = 7;

		    while(fgets(buf, sizeof(buf), stdin) != 0)
		    {
			int len = strlen(buf);
			if(bufuse + len + 1 >= bufsiz)
			{
			    bufsiz *= 2;
			    input_buf = realloc(buf, bufsiz);
			    if(input_buf == 0)
			    {
				perror("realloc");
				result = 10;
				break;
			    }
			}
			memcpy(input_buf + bufuse, buf, len);
			bufuse += len;
		    }
		    if(input_buf != 0)
		    {
			input_buf[bufuse] = ')';
			input_buf[bufuse+1] = 0;
			result = eval_lisp_form(sock_fd, input_buf);
			free(input_buf);
		    }
		}
		break;

	    case '?': case 'h':
		usage(prog_name);
		break;

	    default:
	    opt_error:
		fprintf(stderr, "unknown option `%s'; try `%s -h'\n",
			*argv, prog_name);
		result =  5;
	    }
	    argc--; argv++;
	}
	else if(argc > 0)
	{
	    unsigned long linenum = 0;
	    if(argc >= 1 && **argv == '+')	/* +LINE-NUMBER */
	    {
#ifdef HAVE_STRTOL
		linenum = strtol(*argv + 1, NULL, 0) - 1;
#else
		linenum = atol(*argv + 1) - 1;
#endif
		if(linenum <= 0)
		    linenum = 1;
		argc--; argv++;
	    }
	    result = find_file(sock_fd, *argv, linenum);
	    argc--; argv++;
	}
    }

    disconnect_from_jade(sock_fd);
    return result;
}
Example #9
0
static void dump_file(FILE *fp, Disk_Image_t *di, const char *filename) {

	uint8_t start_track, start_sector;
	uint8_t ss_track, ss_sector;
	uint8_t reclen;
	int flength;

	if (!find_file(fp, di, filename, &start_track, &start_sector, &ss_track, &ss_sector, &reclen, 
			&flength)) {
		log_error("Did not find file '%s' in image\n", filename);
		exit(2);
	}

	// now we have found a REL file
	// we compare the file as file chain with the information as stored in the side sectors
	
	// first read the whole file, taking note of the sector addresses
	uint8_t *data = NULL;
	uint8_t *dtracks = NULL;
	uint8_t *dsectors = NULL;
	int dlength = 0, dblklen = 0;
	read_file(fp, di, start_track, start_sector, &data, &dtracks, &dsectors, &dlength, &dblklen);
	log_debug("read file gives %d bytes of data in %d blocks\n", dlength, dblklen);

	// keep track of file blocks from side sectors
	// allocate as much memory as a single super side sector with its side sectors can address
	uint8_t *stracks = malloc(SSS_INDEX_SSB_MAX * SSG_SIDE_SECTORS_MAX * SSB_INDEX_SECTOR_MAX);
	uint8_t *ssectors = malloc(SSS_INDEX_SSB_MAX * SSG_SIDE_SECTORS_MAX * SSB_INDEX_SECTOR_MAX);
	// the list of side sector block addresses
	uint8_t *ssbtracks = malloc(SSS_INDEX_SSB_MAX * SSG_SIDE_SECTORS_MAX);
	uint8_t *ssbsectors = malloc(SSS_INDEX_SSB_MAX * SSG_SIDE_SECTORS_MAX);
	int sblklen = 0;
	// second, read the side sector structure
	uint8_t super[256];
	if (di->HasSSB) {
		read_sector(fp, di, ss_track, ss_sector, super);
	
		if (super[SSB_OFFSET_SUPER_254] != 254) {
			log_error("Super side sector at %d/%d does not have super side sector "
				"marker 254, has %d instead\n", 
				ss_track, ss_sector, super[SSB_OFFSET_SUPER_254]);
		}

		// the link address is the address of the first side sector group
		if (super[BLK_OFFSET_NEXT_TRACK] != super[SSS_OFFSET_SSB_POINTER]
			|| super[BLK_OFFSET_NEXT_SECTOR] != super[SSS_OFFSET_SSB_POINTER+1]) {
			log_error("Super side sector link chain is broken: link is %d/%d,"
				" but first side sector group is %d/%d\n",
				super[BLK_OFFSET_NEXT_TRACK], super[BLK_OFFSET_NEXT_SECTOR],
				super[SSS_OFFSET_SSB_POINTER], super[SSS_OFFSET_SSB_POINTER+1]);
		}

		// note: this reads in the complete side sector block chain (i.e. all side sectors)
		append_ssg(fp, di, super[SSS_OFFSET_SSB_POINTER], super[SSS_OFFSET_SSB_POINTER+1], 
				&stracks, &ssectors, &sblklen, reclen, &ssbtracks, &ssbsectors,
				dblklen);

		// now compare the entry points in that file each six side sectors with the values
		// in the super side sector
		int numssg = 1 + sblklen / SSB_INDEX_SECTOR_MAX;
		int ssp = SSS_OFFSET_SSB_POINTER;
		for (int i = 0; i < numssg; i+=SSG_SIDE_SECTORS_MAX) {
			//log_debug("checking ssp %d\n", i);
			if (super[ssp] != ssbtracks[i] || super[ssp+1] != ssbsectors[i]) {
				log_error("Super side sector pointer #%d is wrong, "
					"should be %d/%d (@%d), but is %d/%d (@%d)\n",
					(ssp - SSS_OFFSET_SSB_POINTER) >> 1,
					255 & ssbtracks[i], 255 & ssbsectors[i], i,
					255 & super[ssp], 255 & super[ssp+1], ssp);
			}
			ssp += 2;
		}
Example #10
0
int preprocess(char *source, FILE *f_target, struct constant *constants) {
    /*
     * Writes the contents of source into the target file pointer, while
     * recursively resolving constants and includes using the includefolder
     * for finding included files.
     *
     * Returns 0 on success, a positive integer on failure.
     */

    extern int current_operation;
    extern char current_target[2048];
    extern char include_stack[MAXINCLUDES][1024];
    int line = 0;
    int i = 0;
    int j = 0;
    int level = 0;
    int level_true = 0;
    int level_comment = 0;
    int success;
    size_t buffsize;
    char *buffer;
    char *ptr;
    char *token;
    char in_string = 0;
    char valuebuffer[262144];
    char definition[256];
    char tmp[2048];
    char includepath[2048];
    char actualpath[2048];
    FILE *f_source;

    current_operation = OP_PREPROCESS;
    strcpy(current_target, source);

    for (i = 0; i < MAXINCLUDES && include_stack[i][0] != 0; i++) {
        if (strcmp(source, include_stack[i]) == 0) {
            errorf("Circular dependency detected, printing include stack:\n", source);
            fprintf(stderr, "    !!! %s\n", source);
            for (j = MAXINCLUDES - 1; j >= 0; j--) {
                if (include_stack[j][0] == 0)
                    continue;
                fprintf(stderr, "        %s\n", include_stack[j]);
            }
            return 1;
        }
    }

    if (i == MAXINCLUDES) {
        errorf("Too many nested includes.\n");
        return 1;
    }

    strcpy(include_stack[i], source);

    f_source = fopen(source, "rb");
    if (!f_source) {
        errorf("Failed to open %s.\n", source);
        return 1;
    }

    // Skip byte order mark if it exists
    if (fgetc(f_source) == 0xef)
        fseek(f_source, 3, SEEK_SET);
    else
        fseek(f_source, 0, SEEK_SET);

    // first constant is file name
    // @todo: what form?
    strcpy(constants[0].name, "__FILE__");
    if (constants[0].value == 0)
        constants[0].value = (char *)malloc(1024);
    snprintf(constants[0].value, 1024, "\"%s\"", source);

    strcpy(constants[1].name, "__LINE__");

    strcpy(constants[2].name, "__EXEC");
    if (constants[2].value == 0)
        constants[2].value = (char *)malloc(1);

    strcpy(constants[3].name, "__EVAL");
    if (constants[3].value == 0)
        constants[3].value = (char *)malloc(1);

    while (true) {
        // get line
        line++;
        buffsize = LINEBUFFSIZE;
        buffer = (char *)malloc(buffsize + 1);
        if (getline(&buffer, &buffsize, f_source) == -1) {
            free(buffer);
            break;
        }

        // fix Windows line endings
        if (strlen(buffer) >= 2 && buffer[strlen(buffer) - 2] == '\r') {
            buffer[strlen(buffer) - 2] = '\n';
            buffer[strlen(buffer) - 1] = 0;
        }

        // add next lines if line ends with a backslash
        while (strlen(buffer) >= 2 && buffer[strlen(buffer) - 2] == '\\') {
            if (strlen(buffer) >= buffsize) {
                errorf("Line %i exceeds maximum length.\n", line);
                return 1;
            }
            buffsize -= strlen(buffer);
            ptr = (char *)malloc(buffsize + 1);
            if (getline(&ptr, &buffsize, f_source) == -1)
                break;
            strncpy(strrchr(buffer, '\\'), ptr, buffsize);
            line++;
            free(ptr);

            // fix windows line endings again
            if (strlen(buffer) >= 2 && buffer[strlen(buffer) - 2] == '\r') {
                buffer[strlen(buffer) - 2] = '\n';
                buffer[strlen(buffer) - 1] = 0;
            }
        }

        // Check for block comment delimiters
        for (i = 0; i < strlen(buffer); i++) {
            if (in_string != 0) {
                if (buffer[i] == in_string && buffer[i-1] != '\\')
                    in_string = 0;
                else
                    continue;
            } else {
                if (level_comment == 0 &&
                        (buffer[i] == '"' || buffer[i] == '\'') &&
                        (i == 0 || buffer[i-1] != '\\'))
                    in_string = buffer[i];
            }

            if (buffer[i] == '/' && buffer[i+1] == '/') {
                buffer[i+1] = 0;
                buffer[i] = '\n';
            } else if (buffer[i] == '/' && buffer[i+1] == '*') {
                level_comment++;
                buffer[i] = ' ';
                buffer[i+1] = ' ';
            } else if (buffer[i] == '*' && buffer[i+1] == '/') {
                level_comment--;
                if (level_comment < 0)
                    level_comment = 0;
                buffer[i] = ' ';
                buffer[i+1] = ' ';
            }

            if (level_comment > 0) {
                buffer[i] = ' ';
                continue;
            }
        }

        // trim leading spaces
        trim_leading(buffer, LINEBUFFSIZE);

        // skip lines inside untrue ifs
        if (level > level_true) {
            if ((strlen(buffer) < 5 || strncmp(buffer, "#else", 5) != 0) &&
                    (strlen(buffer) < 6 || strncmp(buffer, "#endif", 6) != 0)) {
                free(buffer);
                continue;
            }
        }

        // second constant is line number
        if (constants[1].value == 0)
            constants[1].value = (char *)malloc(16);
        sprintf(constants[1].value, "%i", line - 1);

        // get the constant name
        if (strlen(buffer) >= 9 && (strncmp(buffer, "#define", 7) == 0 ||
                strncmp(buffer, "#undef", 6) == 0 ||
                strncmp(buffer, "#ifdef", 6) == 0 ||
                strncmp(buffer, "#ifndef", 7) == 0)) {
            definition[0] = 0;
            ptr = buffer + 7;
            while (*ptr == ' ')
                ptr++;
            strncpy(definition, ptr, 256);
            ptr = definition;
            while (*ptr != ' ' && *ptr != '(' && *ptr != '\n')
                ptr++;
            *ptr = 0;

            if (strlen(definition) == 0) {
                errorf("Missing definition in line %i of %s.\n", line, source);
                return 2;
            }
        }

        // check for preprocessor commands
        if (level_comment == 0 && strlen(buffer) >= 9 && strncmp(buffer, "#define", 7) == 0) {
            i = 0;
            while (strlen(constants[i].name) != 0 &&
                    strcmp(constants[i].name, definition) != 0 &&
                    i <= MAXCONSTS)
                i++;

            if (i == MAXCONSTS) {
                errorf("Maximum number of %i definitions exceeded in line %i of %s.\n", MAXCONSTS, line, source);
                return 3;
            }

            if (constants[i].name[0] != 0)
                nwarningf("redefinition-wo-undef", "Constant \"%s\" is being redefined without an #undef in line %i.\n", definition, line);

            ptr = buffer + strlen(definition) + 8;
            while (*ptr != ' ' && *ptr != '\t' && *ptr != '(' && *ptr != '\n')
                ptr++;

            // Get arguments and resolve macros in macro
            for (j = 0; j < MAXARGS; j++)
                constants[i].arguments[j][0] = 0;

            if (*ptr == '(' && strchr(ptr, ')') != NULL) {
                strncpy(tmp, ptr + 1, sizeof(tmp));

                if (strchr(tmp, ')') == NULL) {
                    errorf("Macro arguments too long in line %i of %s.\n", line, source);
                }
                *strchr(tmp, ')') = 0;

                token = strtok(tmp, ",");
                for (j = 0; j < MAXARGS && token; j++) {
                    strncpy(constants[i].arguments[j], token, sizeof(constants[i].arguments[j]));
                    trim(constants[i].arguments[j], sizeof(constants[i].arguments[j]));

                    token = strtok(NULL, ",");
                }

                ptr = strchr(ptr, ')') + 1;
            }

            while (*ptr == ' ' || *ptr == '\t')
                ptr++;

            if (*ptr != '\n') {
                strncpy(valuebuffer, ptr, sizeof(valuebuffer));
                valuebuffer[strlen(valuebuffer) - 1] = 0;

                success = resolve_macros(valuebuffer, sizeof(valuebuffer), constants);
                if (success) {
                    errorf("Failed to resolve macros in line %i of %s.\n", line, source);
                    return success;
                }

                if (strnlen(valuebuffer, sizeof(valuebuffer)) == sizeof(valuebuffer)) {
                    errorf("Macro value in line %i of %s exceeds maximum size (%i).\n", line, source, sizeof(valuebuffer));
                    return 3;
                }

                if (constants[i].value != 0)
                    free(constants[i].value);
                constants[i].value = (char *)malloc(strlen(valuebuffer) + 1);
                strcpy(constants[i].value, valuebuffer);
            } else {
                constants[i].value = (char *)malloc(1);
                constants[i].value[0] = 0;
            }

            strncpy(constants[i].name, definition, sizeof(constants[i].name));
        } else if (level_comment == 0 && strlen(buffer) >= 6 && strncmp(buffer, "#undef", 6) == 0) {
            i = 0;
            while (strlen(constants[i].name) != 0 &&
                    strcmp(constants[i].name, definition) != 0 &&
                    i <= MAXCONSTS)
                i++;

            if (i == MAXCONSTS) {
                errorf("Include %s not found in line %i of %s.\n", definition, line, source);
                return 3;
            }

            constants[i].name[0] = 0;
        } else if (level_comment == 0 && strlen(buffer) >= 8 &&
                (strncmp(buffer, "#ifdef", 6) == 0 || strncmp(buffer, "#ifndef", 7) == 0)) {
            level++;
            if (strncmp(buffer, "#ifndef", 7) == 0)
                level_true++;
            for (i = 0; i < MAXCONSTS; i++) {
                if (strcmp(definition, constants[i].name) == 0) {
                    if (strncmp(buffer, "#ifdef", 6) == 0)
                        level_true++;
                    if (strncmp(buffer, "#ifndef", 7) == 0)
                        level_true--;
                }
            }
        } else if (level_comment == 0 && strlen(buffer) >= 5 && strncmp(buffer, "#else", 5) == 0) {
            if (level == level_true)
                level_true--;
            else
                level_true = level;
        } else if (level_comment == 0 && strlen(buffer) >= 6 && strncmp(buffer, "#endif", 6) == 0) {
            if (level == 0) {
                errorf("Unexpected #endif in line %i of %s.\n", line, source);
                return 4;
            }
            if (level == level_true)
                level_true--;
            level--;
        } else if (level_comment == 0 && strlen(buffer) >= 11 && strncmp(buffer, "#include", 8) == 0) {
            for (i = 0; i < strlen(buffer) ; i++) {
                if (buffer[i] == '<' || buffer[i] == '>')
                    buffer[i] = '"';
            }
            if (strchr(buffer, '"') == NULL) {
                errorf("Failed to parse #include in line %i in %s.\n", line, source);
                return 5;
            }
            strncpy(includepath, strchr(buffer, '"') + 1, sizeof(includepath));
            if (strchr(includepath, '"') == NULL) {
                errorf("Failed to parse #include in line %i in %s.\n", line, source);
                return 6;
            }
            *strchr(includepath, '"') = 0;
            if (find_file(includepath, source, actualpath)) {
                errorf("Failed to find %s.\n", includepath);
                return 7;
            }
            free(buffer);
            success = preprocess(actualpath, f_target, constants);
            if (success)
                return success;

            current_operation = OP_PREPROCESS;
            strcpy(current_target, source);

            for (i = 0; i < MAXINCLUDES && include_stack[i][0] != 0; i++);
            include_stack[i - 1][0] = 0;

            continue;
        }

        if (buffer[0] != '#' && strlen(buffer) > 1) {
            success = resolve_macros(buffer, buffsize, constants);
            if (success) {
                errorf("Failed to resolve macros in line %i of %s.\n", line, source);
                return success;
            }
            fputs(buffer, f_target);
        }
        free(buffer);
    }

    fclose(f_source);

    return 0;
}
Example #11
0
PRIVATE DIR *HTVMSopendir(char *dirname)
{
static DIR dir;
char *closebracket;
long status;
struct dsc$descriptor_s entryname_desc;
struct dsc$descriptor_s dirname_desc;
static char *DirEntry;
char Actual[256];
char VMSentry[256];
char UnixEntry[256];
int index;
char *dot;

   /* check if directory exists */
   /* dirname can look like /disk$user/duns/www/test/multi    */
   /* or like               /disk$user/duns/www/test/multi/   */
   /* DirEntry should look like     disk$user:[duns.www.test]multi in both cases */
   /* dir.dirname should look like  disk$user:[duns.www.test.multi] */
   sprintf(UnixEntry, "%.*s", sizeof(UnixEntry) - 2, dirname);
   if (UnixEntry[strlen(UnixEntry)-1] != '/')
      strcat(UnixEntry,"/");

   StrAllocCopy(DirEntry, HTVMS_name("",UnixEntry));
   if (strlen(DirEntry) > sizeof(dir.dirname) - 1)
      return (NULL);
   strcpy(dir.dirname, DirEntry);
   index = strlen(DirEntry) - 1;

   if (DirEntry[index] == ']')
      DirEntry[index] = '\0';

   if ((dot = strrchr(DirEntry,'.')) == NULL)
   {  /* convert disk$user:[duns] into disk$user:[000000]duns.dir */
      char *openbr = strrchr(DirEntry,'[');
      if (!openbr)
      { /* convert disk$user: into disk$user:[000000]000000.dir */
         if (strlen(dir.dirname) > sizeof(dir.dirname) - 10)
            return (NULL);
         sprintf(dir.dirname, "%.*s[000000]", sizeof(dir.dirname) - 9, DirEntry);
	 StrAllocCat(DirEntry,"[000000]000000.dir");
      }
      else
      {
	 char End[256];
	 strcpy(End,openbr+1);
	 *(openbr+1) = '\0';
	 StrAllocCat(DirEntry,"000000]");
	 StrAllocCat(DirEntry,End);
	 StrAllocCat(DirEntry,".dir");
      }
   }
   else
   {
      *dot = ']';
      StrAllocCat(DirEntry,".dir");
   }
   /* lib$find_file needs a fixed-size buffer */
   LYstrncpy(Actual, DirEntry, sizeof(Actual)-1);

   dir.context = 0;
   dirname_desc.dsc$w_length = strlen(Actual);
   dirname_desc.dsc$b_dtype = DSC$K_DTYPE_T;
   dirname_desc.dsc$b_class = DSC$K_CLASS_S;
   dirname_desc.dsc$a_pointer = (char *)&(Actual);

   /* look for the directory */
   entryname_desc.dsc$w_length = 255;
   entryname_desc.dsc$b_dtype = DSC$K_DTYPE_T;
   entryname_desc.dsc$b_class = DSC$K_CLASS_S;
   entryname_desc.dsc$a_pointer = VMSentry;

   status = lib$find_file(&(dirname_desc),
			  &entryname_desc,
			  &(dir.context),
			  0,0,0,0);
   if (!(status & 0x01))
   { /* directory not found */
      return(NULL);
   }

   if (strlen(dir.dirname) > sizeof(dir.dirname) - 10)
       return (NULL);
   if (HTVMSFileVersions)
       strcat(dir.dirname,"*.*;*");
   else
       strcat(dir.dirname,"*.*");
   dir.context = 0;
   dir.dirname_desc.dsc$w_length = strlen(dir.dirname);
   dir.dirname_desc.dsc$b_dtype = DSC$K_DTYPE_T;
   dir.dirname_desc.dsc$b_class = DSC$K_CLASS_S;
   dir.dirname_desc.dsc$a_pointer = (char *)&(dir.dirname);
   return(&dir);
}
Example #12
0
/*
 * Description:   Create the child process to be helped
 *
 * Returns: 
 *
 * Notes/Dependencies:  
 */
long
process_begin(
	HANDLE proc,
	char **argv,
	char **envp,
	char *exec_path,
	char *as_user)
{
	sub_process *pproc = (sub_process *)proc;
	char *shell_name = 0;
	int file_not_found=0;
	HANDLE exec_handle;
	char buf[256];
	DWORD bytes_returned;
	DWORD flags;
	char *command_line;
	STARTUPINFO startInfo;
	PROCESS_INFORMATION procInfo;
	char *envblk=NULL;
	OFSTRUCT file_info;


	/*
	 *  Shell script detection...  if the exec_path starts with #! then
	 *  we want to exec shell-script-name exec-path, not just exec-path
	 *  NT doesn't recognize #!/bin/sh or #!/etc/Tivoli/bin/perl.  We do not
	 *  hard-code the path to the shell or perl or whatever:  Instead, we
	 *  assume it's in the path somewhere (generally, the NT tools
	 *  bin directory)
	 *  We use OpenFile here because it is capable of searching the Path.
	 */

	exec_handle = find_file(exec_path, &file_info);

	/*
	 * If we couldn't open the file, just assume that Win32 will be able
	 * to find and execute it.
	 */
	if (exec_handle == (HANDLE)HFILE_ERROR) {
		file_not_found++;
	}
	else {
		/* Attempt to read the first line of the file */
		if (ReadFile( exec_handle, 
				buf, sizeof(buf) - 1, /* leave room for trailing NULL */
				&bytes_returned, 0) == FALSE || bytes_returned < 2) {
	
			pproc->last_err = GetLastError();
			pproc->lerrno = E_IO;
			CloseHandle(exec_handle);
			return(-1);
		}
		if (buf[0] == '#' && buf[1] == '!') {
			/*
			 *  This is a shell script...  Change the command line from
			 *	exec_path args to shell_name exec_path args
			 */
			char *p;
	
			/*  Make sure buf is NULL terminated */
			buf[bytes_returned] = 0;
			/*
			 * Depending on the file system type, etc. the first line
			 * of the shell script may end with newline or newline-carriage-return
			 * Whatever it ends with, cut it off.
			 */
			p= strchr(buf, '\n');
			if (p)
				*p = 0;
			p = strchr(buf, '\r');
			if (p)
				*p = 0;
		
			/*
			 *  Find base name of shell
			 */
			shell_name = strrchr( buf, '/');
			if (shell_name) {
				shell_name++;
			} else {
				shell_name = &buf[2];/* skipping "#!" */
			}

		} 
		CloseHandle(exec_handle);
	}

	flags = 0;

	if (file_not_found)
		command_line = make_command_line( shell_name, exec_path, argv);
	else
		command_line = make_command_line( shell_name, file_info.szPathName,
				 argv);

	if ( command_line == NULL ) {
		pproc->last_err = 0;
		pproc->lerrno = E_NO_MEM;
		return(-1);
	}

	if (envp) {
		if (arr2envblk(envp, &envblk) ==FALSE) {
			pproc->last_err = 0;
			pproc->lerrno = E_NO_MEM;
			free( command_line );
			return(-1);
		}
	}

	if ((shell_name) || (file_not_found)) {
		exec_path = 0;	/* Search for the program in %Path% */
	} else {
		exec_path = file_info.szPathName;
	}

	/*
	 *  Set up inherited stdin, stdout, stderr for child
	 */
	GetStartupInfo(&startInfo);
	startInfo.dwFlags = STARTF_USESTDHANDLES;
	startInfo.lpReserved = 0;
	startInfo.cbReserved2 = 0;
	startInfo.lpReserved2 = 0;
	startInfo.lpTitle = shell_name ? shell_name : exec_path;
	startInfo.hStdInput = (HANDLE)pproc->sv_stdin[1];
	startInfo.hStdOutput = (HANDLE)pproc->sv_stdout[1];
	startInfo.hStdError = (HANDLE)pproc->sv_stderr[1];

	/*
	 * See if we need to setuid to a different user.
	 */
	if (as_user) {
		return -1;
	}

	if (as_user) {
		return -1;
	} else {
		if (CreateProcess(
			exec_path,
			command_line,
			NULL,
			0, /* default security attributes for thread */
			TRUE, /* inherit handles (e.g. helper pipes, oserv socket) */
			flags, 
			envblk,
			0, /* default starting directory */
			&startInfo,
			&procInfo) == FALSE) {
		
			pproc->last_err = GetLastError();
			pproc->lerrno = E_FORK;
			fprintf(stderr, "process_begin: CreateProcess(%s, %s, ...) failed.\n", exec_path, command_line);
			free( command_line );
			return(-1);
		}
	}
	
	pproc->pid = (int)procInfo.hProcess;
	/* Close the thread handle -- we'll just watch the process */
	CloseHandle(procInfo.hThread);
	
	/* Close the halves of the pipes we don't need */
	if (pproc->sv_stdin) {
		CloseHandle((HANDLE)pproc->sv_stdin[1]);
		(HANDLE)pproc->sv_stdin[1] = 0;
	}
	if (pproc->sv_stdout) {
		CloseHandle((HANDLE)pproc->sv_stdout[1]);
		(HANDLE)pproc->sv_stdout[1] = 0;
	}
	if (pproc->sv_stderr) {
		CloseHandle((HANDLE)pproc->sv_stderr[1]);
		(HANDLE)pproc->sv_stderr[1] = 0;
	}

	free( command_line );
	pproc->lerrno=0;
	return 0;
}
Example #13
0
bool display_deps(environment const & env, std::ostream & out, std::ostream & err, char const * fname) {
    name import("import");
    name prelude("prelude");
    name period(".");
    std::ifstream in(fname);
    if (in.bad() || in.fail()) {
        err << "failed to open file '" << fname << "'" << std::endl;
        return false;
    }
    scanner s(in, fname);
    optional<unsigned> k;
    std::string base = dirname(fname);
    bool import_prefix = false;
    bool import_args   = false;
    bool ok            = true;
    bool is_prelude    = false;
    auto display_dep = [&](optional<unsigned> const & k, name const & f) {
        import_args = true;
        try {
            std::string m_name = find_file(base, k, name_to_file(f), {".lean", ".hlean", ".olean", ".lua"});
            int last_idx = m_name.find_last_of(".");
            std::string rawname = m_name.substr(0, last_idx);
            std::string ext = m_name.substr(last_idx);
            if (ext == ".lean" || ext == ".hlean")
                m_name = rawname + ".olean";
            display_path(out, m_name);
            import_prefix = true;
            out << "\n";
        } catch (exception & new_ex) {
            err << "error: file '" << name_to_file(s.get_name_val()) << "' not found in the LEAN_PATH" << std::endl;
            ok  = false;
        }
    };

    while (true) {
        scanner::token_kind t = scanner::token_kind::Identifier;
        try {
            t = s.scan(env);
        } catch (exception &) {
            continue;
        }
        if (t == scanner::token_kind::Eof) {
            if (!is_prelude)
                display_dep(optional<unsigned>(), name("init"));
            return ok;
        } else if (t == scanner::token_kind::CommandKeyword && s.get_token_info().value() == prelude) {
            is_prelude = true;
        } else if (t == scanner::token_kind::CommandKeyword && s.get_token_info().value() == import) {
            k = optional<unsigned>();
            import_prefix = true;
        } else if (import_prefix && t == scanner::token_kind::Keyword && s.get_token_info().value() == period) {
            if (!k)
                k = 0;
            else
                k = *k + 1;
        } else if ((import_prefix || import_args) && t == scanner::token_kind::Identifier) {
            display_dep(k, s.get_name_val());
            k = optional<unsigned>();
        } else {
            import_args   = false;
            import_prefix = false;
        }
    }
}
mp_obj_t mp_builtin___import__(uint n_args, mp_obj_t *args) {
    /*
    printf("import:\n");
    for (int i = 0; i < n_args; i++) {
        printf("  ");
        mp_obj_print(args[i], PRINT_REPR);
        printf("\n");
    }
    */

    mp_obj_t fromtuple = mp_const_none;
    int level = 0;
    if (n_args >= 4) {
        fromtuple = args[3];
        if (n_args >= 5) {
            level = MP_OBJ_SMALL_INT_VALUE(args[4]);
        }
    }

    if (level != 0) {
        nlr_jump(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
            "Relative import is not implemented"));
    }

    uint mod_len;
    const char *mod_str = (const char*)mp_obj_str_get_data(args[0], &mod_len);

    // check if module already exists
    mp_obj_t module_obj = mp_module_get(mp_obj_str_get_qstr(args[0]));
    if (module_obj != MP_OBJ_NULL) {
        // If it's not a package, return module right away
        char *p = strchr(mod_str, '.');
        if (p == NULL) {
            return module_obj;
        }
        // If fromlist is not empty, return leaf module
        if (fromtuple != mp_const_none) {
            return module_obj;
        }
        // Otherwise, we need to return top-level package
        qstr pkg_name = qstr_from_strn(mod_str, p - mod_str);
        return mp_module_get(pkg_name);
    }

    uint last = 0;
    VSTR_FIXED(path, MICROPY_PATH_MAX)
    module_obj = MP_OBJ_NULL;
    mp_obj_t top_module_obj = MP_OBJ_NULL;
    mp_obj_t outer_module_obj = MP_OBJ_NULL;
    uint i;
    for (i = 1; i <= mod_len; i++) {
        if (i == mod_len || mod_str[i] == '.') {
            // create a qstr for the module name up to this depth
            qstr mod_name = qstr_from_strn(mod_str, i);

            // find the file corresponding to the module name
            mp_import_stat_t stat;
            if (vstr_len(&path) == 0) {
                // first module in the dotted-name; search for a directory or file
                stat = find_file(mod_str, i, &path);
            } else {
                // latter module in the dotted-name; append to path
                vstr_add_char(&path, PATH_SEP_CHAR);
                vstr_add_strn(&path, mod_str + last, i - last);
                stat = stat_dir_or_file(&path);
            }

            // fail if we couldn't find the file
            if (stat == MP_IMPORT_STAT_NO_EXIST) {
                nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_ImportError, "ImportError: No module named '%s'", qstr_str(mod_name)));
            }

            module_obj = mp_module_get(mod_name);
            if (module_obj == MP_OBJ_NULL) {
                // module not already loaded, so load it!

                module_obj = mp_obj_new_module(mod_name);

                if (stat == MP_IMPORT_STAT_DIR) {
                    vstr_add_char(&path, PATH_SEP_CHAR);
                    vstr_add_str(&path, "__init__.py");
                    if (mp_import_stat(vstr_str(&path)) != MP_IMPORT_STAT_FILE) {
                        vstr_cut_tail_bytes(&path, sizeof("/__init__.py") - 1); // cut off /__init__.py
                        nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_ImportError,
                            "Per PEP-420 a dir without __init__.py (%s) is a namespace package; "
                            "namespace packages are not supported", vstr_str(&path)));
                    }
                    do_load(module_obj, &path);
                    vstr_cut_tail_bytes(&path, sizeof("/__init__.py") - 1); // cut off /__init__.py
                } else { // MP_IMPORT_STAT_FILE
                    do_load(module_obj, &path);
                    // TODO: We cannot just break here, at the very least, we must execute
                    // trailer code below. But otherwise if there're remaining components,
                    // that would be (??) object path within module, not modules path within FS.
                    // break;
                }
            }
            if (outer_module_obj != MP_OBJ_NULL) {
                qstr s = qstr_from_strn(mod_str + last, i - last);
                mp_store_attr(outer_module_obj, s, module_obj);
            }
            outer_module_obj = module_obj;
            if (top_module_obj == MP_OBJ_NULL) {
                top_module_obj = module_obj;
            }
            last = i + 1;
        }
    }

    if (i < mod_len) {
        // we loaded a package, now need to load objects from within that package
        // TODO
        assert(0);
    }

    // If fromlist is not empty, return leaf module
    if (fromtuple != mp_const_none) {
        return module_obj;
    }
    // Otherwise, we need to return top-level package
    return top_module_obj;
}
Example #15
0
/*
 * Description:   Create the child process to be helped
 *
 * Returns: success <=> 0
 *
 * Notes/Dependencies:
 */
long
process_begin(
	HANDLE proc,
	char **argv,
	char **envp,
	char *exec_path,
	char *as_user)
{
	sub_process *pproc = (sub_process *)proc;
	char *shell_name = 0;
	int file_not_found=0;
	HANDLE exec_handle;
	char exec_fname[MAX_PATH];
	const char *path_var = NULL;
	char **ep;
	char buf[256];
	DWORD bytes_returned;
	DWORD flags;
	char *command_line;
	STARTUPINFO startInfo;
	PROCESS_INFORMATION procInfo;
	char *envblk=NULL;

	/*
	 *  Shell script detection...  if the exec_path starts with #! then
	 *  we want to exec shell-script-name exec-path, not just exec-path
	 *  NT doesn't recognize #!/bin/sh or #!/etc/Tivoli/bin/perl.  We do not
	 *  hard-code the path to the shell or perl or whatever:  Instead, we
	 *  assume it's in the path somewhere (generally, the NT tools
	 *  bin directory)
	 */

	/* Use the Makefile's value of PATH to look for the program to
	   execute, because it could be different from Make's PATH
	   (e.g., if the target sets its own value.  */
	if (envp)
		for (ep = envp; *ep; ep++) {
			if (strncmp (*ep, "PATH=", 5) == 0
			    || strncmp (*ep, "Path=", 5) == 0) {
				path_var = *ep + 5;
				break;
			}
		}
	exec_handle = find_file(exec_path, path_var,
				exec_fname, sizeof(exec_fname));

	/*
	 * If we couldn't open the file, just assume that Windows will be
	 * somehow able to find and execute it.
	 */
	if (exec_handle == INVALID_HANDLE_VALUE) {
		file_not_found++;
	}
	else {
		/* Attempt to read the first line of the file */
		if (ReadFile( exec_handle,
				buf, sizeof(buf) - 1, /* leave room for trailing NULL */
				&bytes_returned, 0) == FALSE || bytes_returned < 2) {

			pproc->last_err = GetLastError();
			pproc->lerrno = E_IO;
			CloseHandle(exec_handle);
			return(-1);
		}
		if (buf[0] == '#' && buf[1] == '!') {
			/*
			 *  This is a shell script...  Change the command line from
			 *	exec_path args to shell_name exec_path args
			 */
			char *p;

			/*  Make sure buf is NULL terminated */
			buf[bytes_returned] = 0;
			/*
			 * Depending on the file system type, etc. the first line
			 * of the shell script may end with newline or newline-carriage-return
			 * Whatever it ends with, cut it off.
			 */
			p= strchr(buf, '\n');
			if (p)
				*p = 0;
			p = strchr(buf, '\r');
			if (p)
				*p = 0;

			/*
			 *  Find base name of shell
			 */
			shell_name = strrchr( buf, '/');
			if (shell_name) {
				shell_name++;
			} else {
				shell_name = &buf[2];/* skipping "#!" */
			}

		}
		CloseHandle(exec_handle);
	}

	flags = 0;

	if (file_not_found)
		command_line = make_command_line( shell_name, exec_path, argv);
	else
		command_line = make_command_line( shell_name, exec_fname, argv);

	if ( command_line == NULL ) {
		pproc->last_err = 0;
		pproc->lerrno = E_NO_MEM;
		return(-1);
	}

	if (envp) {
		if (arr2envblk(envp, &envblk) ==FALSE) {
			pproc->last_err = 0;
			pproc->lerrno = E_NO_MEM;
			free( command_line );
			return(-1);
		}
	}

	if ((shell_name) || (file_not_found)) {
		exec_path = 0;	/* Search for the program in %Path% */
	} else {
		exec_path = exec_fname;
	}

	/*
	 *  Set up inherited stdin, stdout, stderr for child
	 */
	GetStartupInfo(&startInfo);
	startInfo.dwFlags = STARTF_USESTDHANDLES;
	startInfo.lpReserved = 0;
	startInfo.cbReserved2 = 0;
	startInfo.lpReserved2 = 0;
	startInfo.lpTitle = shell_name ? shell_name : exec_path;
	startInfo.hStdInput = (HANDLE)pproc->sv_stdin[1];
	startInfo.hStdOutput = (HANDLE)pproc->sv_stdout[1];
	startInfo.hStdError = (HANDLE)pproc->sv_stderr[1];

	if (as_user) {
		if (envblk) free(envblk);
		return -1;
	} else {
		DB (DB_JOBS, ("CreateProcess(%s,%s,...)\n",
			exec_path ? exec_path : "NULL",
			command_line ? command_line : "NULL"));
		if (CreateProcess(
			exec_path,
			command_line,
			NULL,
			0, /* default security attributes for thread */
			TRUE, /* inherit handles (e.g. helper pipes, oserv socket) */
			flags,
			envblk,
			0, /* default starting directory */
			&startInfo,
			&procInfo) == FALSE) {

			pproc->last_err = GetLastError();
			pproc->lerrno = E_FORK;
			fprintf(stderr, "process_begin: CreateProcess(%s, %s, ...) failed.\n",
                                exec_path ? exec_path : "NULL", command_line);
			if (envblk) free(envblk);
			free( command_line );
			return(-1);
		}
	}

	pproc->pid = (pid_t)procInfo.hProcess;
	/* Close the thread handle -- we'll just watch the process */
	CloseHandle(procInfo.hThread);

	/* Close the halves of the pipes we don't need */
        CloseHandle((HANDLE)pproc->sv_stdin[1]);
        CloseHandle((HANDLE)pproc->sv_stdout[1]);
        CloseHandle((HANDLE)pproc->sv_stderr[1]);
        pproc->sv_stdin[1] = 0;
        pproc->sv_stdout[1] = 0;
        pproc->sv_stderr[1] = 0;

	free( command_line );
	if (envblk) free(envblk);
	pproc->lerrno=0;
	return 0;
}
/*
 * Due to lack of time this is just fwparam_ppc_boot_info which
 * adds the target used for boot to the list. It does not add
 * all possible targets (IBM please add).
 */
int fwparam_ppc_get_targets(struct list_head *list)
{
	char filename[FILENAMESZ];
	struct boot_context *context;
	int error;
	char *devtree;

	/*
	 * For powerpc, our operations are fundamentally to locate
	 * either the one boot target (the singleton disk), or to find
	 * the nics that support iscsi boot.  The only nics in IBM
	 * systems that can support iscsi are the ones that provide
	 * the appropriate FCODE with a load method.
	 */
	memset(filename, 0, FILENAMESZ);
	snprintf(filename, FILENAMESZ, "%s%s", DT_TOP, BOOTPATH);

	if (debug)
		fprintf(stderr, "%s: file:%s; debug:%d\n", __func__, filename,
			debug);

	devtree = find_devtree(filename);
	if (!devtree)
		return EINVAL;

	/*
	 * Always search the device-tree to find the capable nic devices.
	 */
	error = loop_devs(devtree);
	if (error)
		goto free_devtree;

	if (find_file(filename) < 1)
		error = ENODEV;
	else {
		if (debug)
			printf("%s:\n%s\n\n", filename, bootpath_val);
		/*
		 * We find *almost* everything we need in the
		 * bootpath, save the mac-address.
		 */

		if (!strstr(bootpath_val, "iscsi")) {
			error = EINVAL;
			goto free_devtree;
		}
		ofwdevs[0] = calloc(1, sizeof(struct ofw_dev));
		if (!ofwdevs[0]) {
			error = ENOMEM;
			goto free_devtree;
		}

		error = parse_params(bootpath_val, ofwdevs[0]);
		if (!error)
			error = locate_mac(devtree, ofwdevs[0]);
		if (!error) {
			context = calloc(1, sizeof(*context));
			if (!context)
				error = ENOMEM;
			else {
				fill_context(context, ofwdevs[0]);
				list_add_tail(&context->list, list);
			}
		}
		free(ofwdevs[0]);
	}

free_devtree:
	free(devtree);
	return error;
}
Example #17
0
/*
 * Return non-zero value if (path/file_name) exists, 0 if it does not.
 * Need to pass in the inode base as well (pointer to inode 1(first)).
 */
int file_exists(char *path, char *inode_base, char *file_name){
	char *string = combine_path_and_file(path, file_name);
	struct basic_fileinfo fileinfo = find_file(string, inode_base);
	free(string);
	return fileinfo.inode;
}
mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) {
#if DEBUG_PRINT
    DEBUG_printf("__import__:\n");
    for (size_t i = 0; i < n_args; i++) {
        DEBUG_printf("  ");
        mp_obj_print(args[i], PRINT_REPR);
        DEBUG_printf("\n");
    }
#endif

    mp_obj_t module_name = args[0];
    mp_obj_t fromtuple = mp_const_none;
    mp_int_t level = 0;
    if (n_args >= 4) {
        fromtuple = args[3];
        if (n_args >= 5) {
            level = MP_OBJ_SMALL_INT_VALUE(args[4]);
            if (level < 0) {
                mp_raise_ValueError(NULL);
            }
        }
    }

    size_t mod_len;
    const char *mod_str = mp_obj_str_get_data(module_name, &mod_len);

    if (level != 0) {
        // What we want to do here is to take name of current module,
        // chop <level> trailing components, and concatenate with passed-in
        // module name, thus resolving relative import name into absolute.
        // This even appears to be correct per
        // http://legacy.python.org/dev/peps/pep-0328/#relative-imports-and-name
        // "Relative imports use a module's __name__ attribute to determine that
        // module's position in the package hierarchy."
        level--;
        mp_obj_t this_name_q = mp_obj_dict_get(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(MP_QSTR___name__));
        assert(this_name_q != MP_OBJ_NULL);
        #if MICROPY_CPYTHON_COMPAT
        if (MP_OBJ_QSTR_VALUE(this_name_q) == MP_QSTR___main__) {
            // This is a module run by -m command-line switch, get its real name from backup attribute
            this_name_q = mp_obj_dict_get(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
        }
        #endif
        mp_map_t *globals_map = &mp_globals_get()->map;
        mp_map_elem_t *elem = mp_map_lookup(globals_map, MP_OBJ_NEW_QSTR(MP_QSTR___path__), MP_MAP_LOOKUP);
        bool is_pkg = (elem != NULL);

#if DEBUG_PRINT
        DEBUG_printf("Current module/package: ");
        mp_obj_print(this_name_q, PRINT_REPR);
        DEBUG_printf(", is_package: %d", is_pkg);
        DEBUG_printf("\n");
#endif

        size_t this_name_l;
        const char *this_name = mp_obj_str_get_data(this_name_q, &this_name_l);

        const char *p = this_name + this_name_l;
        if (!is_pkg) {
            // We have module, but relative imports are anchored at package, so
            // go there.
            chop_component(this_name, &p);
        }

        while (level--) {
            chop_component(this_name, &p);
        }

        // We must have some component left over to import from
        if (p == this_name) {
            mp_raise_ValueError("cannot perform relative import");
        }

        uint new_mod_l = (mod_len == 0 ? (size_t)(p - this_name) : (size_t)(p - this_name) + 1 + mod_len);
        char *new_mod = mp_local_alloc(new_mod_l);
        memcpy(new_mod, this_name, p - this_name);
        if (mod_len != 0) {
            new_mod[p - this_name] = '.';
            memcpy(new_mod + (p - this_name) + 1, mod_str, mod_len);
        }

        qstr new_mod_q = qstr_from_strn(new_mod, new_mod_l);
        mp_local_free(new_mod);
        DEBUG_printf("Resolved base name for relative import: '%s'\n", qstr_str(new_mod_q));
        module_name = MP_OBJ_NEW_QSTR(new_mod_q);
        mod_str = qstr_str(new_mod_q);
        mod_len = new_mod_l;
    }

    // check if module already exists
    qstr module_name_qstr = mp_obj_str_get_qstr(module_name);
    mp_obj_t module_obj = mp_module_get(module_name_qstr);
    if (module_obj != MP_OBJ_NULL) {
        DEBUG_printf("Module already loaded\n");
        // If it's not a package, return module right away
        char *p = strchr(mod_str, '.');
        if (p == NULL) {
            return module_obj;
        }
        // If fromlist is not empty, return leaf module
        if (fromtuple != mp_const_none) {
            return module_obj;
        }
        // Otherwise, we need to return top-level package
        qstr pkg_name = qstr_from_strn(mod_str, p - mod_str);
        return mp_module_get(pkg_name);
    }
    DEBUG_printf("Module not yet loaded\n");

    uint last = 0;
    VSTR_FIXED(path, MICROPY_ALLOC_PATH_MAX)
    module_obj = MP_OBJ_NULL;
    mp_obj_t top_module_obj = MP_OBJ_NULL;
    mp_obj_t outer_module_obj = MP_OBJ_NULL;
    uint i;
    for (i = 1; i <= mod_len; i++) {
        if (i == mod_len || mod_str[i] == '.') {
            // create a qstr for the module name up to this depth
            qstr mod_name = qstr_from_strn(mod_str, i);
            DEBUG_printf("Processing module: %s\n", qstr_str(mod_name));
            DEBUG_printf("Previous path: =%.*s=\n", vstr_len(&path), vstr_str(&path));

            // find the file corresponding to the module name
            mp_import_stat_t stat;
            if (vstr_len(&path) == 0) {
                // first module in the dotted-name; search for a directory or file
                stat = find_file(mod_str, i, &path);
            } else {
                // latter module in the dotted-name; append to path
                vstr_add_char(&path, PATH_SEP_CHAR);
                vstr_add_strn(&path, mod_str + last, i - last);
                stat = stat_dir_or_file(&path);
            }
            DEBUG_printf("Current path: %.*s\n", vstr_len(&path), vstr_str(&path));

            if (stat == MP_IMPORT_STAT_NO_EXIST) {
                #if MICROPY_MODULE_WEAK_LINKS
                // check if there is a weak link to this module
                if (i == mod_len) {
                    mp_map_elem_t *el = mp_map_lookup((mp_map_t*)&mp_builtin_module_weak_links_map, MP_OBJ_NEW_QSTR(mod_name), MP_MAP_LOOKUP);
                    if (el == NULL) {
                        goto no_exist;
                    }
                    // found weak linked module
                    module_obj = el->value;
                    mp_module_call_init(mod_name, module_obj);
                } else {
                    no_exist:
                #else
                {
                #endif
                    // couldn't find the file, so fail
                    if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
                        mp_raise_msg(&mp_type_ImportError, "module not found");
                    } else {
                        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError,
                            "no module named '%q'", mod_name));
                    }
                }
            } else {
                // found the file, so get the module
                module_obj = mp_module_get(mod_name);
            }

            if (module_obj == MP_OBJ_NULL) {
                // module not already loaded, so load it!

                module_obj = mp_obj_new_module(mod_name);

                // if args[3] (fromtuple) has magic value False, set up
                // this module for command-line "-m" option (set module's
                // name to __main__ instead of real name). Do this only
                // for *modules* however - packages never have their names
                // replaced, instead they're -m'ed using a special __main__
                // submodule in them. (This all apparently is done to not
                // touch package name itself, which is important for future
                // imports).
                if (i == mod_len && fromtuple == mp_const_false && stat != MP_IMPORT_STAT_DIR) {
                    mp_obj_module_t *o = MP_OBJ_TO_PTR(module_obj);
                    mp_obj_dict_store(MP_OBJ_FROM_PTR(o->globals), MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
                    #if MICROPY_CPYTHON_COMPAT
                    // Store module as "__main__" in the dictionary of loaded modules (returned by sys.modules).
                    mp_obj_dict_store(MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_loaded_modules_dict)), MP_OBJ_NEW_QSTR(MP_QSTR___main__), module_obj);
                    // Store real name in "__main__" attribute. Chosen semi-randonly, to reuse existing qstr's.
                    mp_obj_dict_store(MP_OBJ_FROM_PTR(o->globals), MP_OBJ_NEW_QSTR(MP_QSTR___main__), MP_OBJ_NEW_QSTR(mod_name));
                    #endif
                }

                if (stat == MP_IMPORT_STAT_DIR) {
                    DEBUG_printf("%.*s is dir\n", vstr_len(&path), vstr_str(&path));
                    // https://docs.python.org/3/reference/import.html
                    // "Specifically, any module that contains a __path__ attribute is considered a package."
                    mp_store_attr(module_obj, MP_QSTR___path__, mp_obj_new_str(vstr_str(&path), vstr_len(&path)));
                    size_t orig_path_len = path.len;
                    vstr_add_char(&path, PATH_SEP_CHAR);
                    vstr_add_str(&path, "__init__.py");
                    if (stat_file_py_or_mpy(&path) != MP_IMPORT_STAT_FILE) {
                        //mp_warning("%s is imported as namespace package", vstr_str(&path));
                    } else {
                        do_load(module_obj, &path);
                    }
                    path.len = orig_path_len;
                } else { // MP_IMPORT_STAT_FILE
                    do_load(module_obj, &path);
                    // This should be the last component in the import path.  If there are
                    // remaining components then it's an ImportError because the current path
                    // (the module that was just loaded) is not a package.  This will be caught
                    // on the next iteration because the file will not exist.
                }
            }
            if (outer_module_obj != MP_OBJ_NULL) {
                qstr s = qstr_from_strn(mod_str + last, i - last);
                mp_store_attr(outer_module_obj, s, module_obj);
            }
            outer_module_obj = module_obj;
            if (top_module_obj == MP_OBJ_NULL) {
                top_module_obj = module_obj;
            }
            last = i + 1;
        }
    }
Example #19
0
File: rom.c Project: GPDP2/mupen64
int rom_read(const char *argv)
{
   md5_state_t state;
   md5_byte_t digest[16];
   mupenEntry *entry;
   char buf[1024], arg[1024], *s;
   
   strncpy(arg, argv, 1000);
   if (find_file(arg))
     {
	strncpy(arg, "roms/", 1000);
	if (find_file(strncat(arg, argv, 1000)))
	  {
	     rom_file=fopen("path.cfg", "rb");
	     if(rom_file) fscanf(rom_file, "%1000s", buf);
	     else buf[0]=0;
	     if(rom_file) fclose(rom_file);
	     strncpy(arg, argv, 1000);
	     if (find_file(strcat(buf, arg)))
	       {
		  printf ("file not found or wrong path\n");
		  return 1;
	       }
	  }
     }
   printf ("file found\n");
/*------------------------------------------------------------------------*/   
   findsize();
   
   if (rom) free(rom);
   rom = malloc(taille_rom);

   tmp=0;
   if (!z)
     {
	for (i=0; i<taille_rom;i+=fread(rom+i, 1, 1000, rom_file))
	  {
	     if (tmp!=(int)((i/(float)taille_rom)*100))
	       {
		  tmp=(int)(i/(float)(taille_rom)*100);
		  display_loading_progress(tmp);
	       }
	  }
     }
   else if (z == 1)
     {
	for (i=0; i<taille_rom;i+=gzread(z_rom_file, rom+i, 1000))
	  {
	     if (tmp!=(int)((i/(float)taille_rom)*100))
	       {
		  tmp=(int)(i/(float)(taille_rom)*100);
		  display_loading_progress(tmp);
	       }
	  }
     }
   else
     {
	unzOpenCurrentFile(zip);
	for (i=0; i<taille_rom;i+=unzReadCurrentFile(zip, rom+i, 1000))
	  {
	     if (tmp!=(int)((i/(float)taille_rom)*100))
	       {
		  tmp=(int)(i/(float)(taille_rom)*100);
		  display_loading_progress(tmp);
	       }
	  }
	unzCloseCurrentFile(zip);
     }
   if (!z) fclose(rom_file);
   else if (z==1) gzclose(z_rom_file);
   else unzClose(zip);
   
   if (rom[0]==0x37)
     {
	printf ("byteswaping rom...\n");
	for (i=0; i<(taille_rom/2); i++)
	  {
	     tmp=rom[i*2];
	     rom[i*2]=rom[i*2+1];
	     rom[i*2+1]=tmp;
	  }
	printf ("rom byteswaped\n");
     }
   if (rom[0]==0x40)
     {
	for (i=0; i<(taille_rom/4); i++)
	  {
	     tmp=rom[i*4];
	     rom[i*4]=rom[i*4+3];
	     rom[i*4+3]=tmp;
	     tmp=rom[i*4+1];
	     rom[i*4+1]=rom[i*4+2];
	     rom[i*4+2]=tmp;
	  }
	printf("rom byteswaped\n");
     }
   else if ((rom[0] != 0x80) || (rom[1] != 0x37) || (rom[2] != 0x12) || (rom[3] != 0x40))
     {
	printf("wrong file format !\n");
	free(rom);
	rom = NULL;
	return 1;
     }
   printf("rom loaded succesfully\n");
  
   if (!ROM_HEADER) ROM_HEADER = malloc(sizeof(rom_header));
   memcpy(ROM_HEADER, rom, sizeof(rom_header));
   display_loading_progress(100);
   printf ("%x %x %x %x\n", ROM_HEADER->init_PI_BSB_DOM1_LAT_REG,
	   ROM_HEADER->init_PI_BSB_DOM1_PGS_REG,
	   ROM_HEADER->init_PI_BSB_DOM1_PWD_REG,
	   ROM_HEADER->init_PI_BSB_DOM1_PGS_REG2);
   printf("ClockRate=%x\n", sl((unsigned int)ROM_HEADER->ClockRate));
   printf("Version:%x\n", sl((unsigned int)ROM_HEADER->Release));
   printf("CRC: %x %x\n", sl((unsigned int)ROM_HEADER->CRC1), sl((unsigned int)ROM_HEADER->CRC2));
   printf ("name: %s\n", ROM_HEADER->nom);
   if (sl(ROM_HEADER->Manufacturer_ID) == 'N') printf ("Manufacturer: Nintendo\n");
   else printf ("Manufacturer: %x\n", (unsigned int)(ROM_HEADER->Manufacturer_ID));
   printf("Cartridge_ID: %x\n", ROM_HEADER->Cartridge_ID);
   switch(ROM_HEADER->Country_code)
     {
      case 0x0044:
	printf("Country : Germany\n");
	break;
      case 0x0045:
	printf("Country : United States\n");
	break;
      case 0x004A:
	printf("Country : Japan\n");
	break;
      case 0x0050:
	printf("European cartridge\n");
	break;
      case 0x0055:
	printf("Country : Australie\n");
      default:
	printf("Country Code : %x\n", ROM_HEADER->Country_code);
     }
   printf ("size: %d\n", (unsigned int)(sizeof(rom_header)));
   printf ("PC= %x\n", sl((unsigned int)ROM_HEADER->PC));
   
   // loading rom settings and checking if it's a good dump
   md5_init(&state);
   md5_append(&state, (const md5_byte_t *)rom, taille_rom);
   md5_finish(&state, digest);
   printf("md5 code:");
   for (i=0; i<16; i++) printf("%02X", digest[i]);
   printf("\n");
   
   ini_openFile();
   
   for (i=0; i<16; i++) sprintf(arg+i*2, "%02X", digest[i]);
   arg[32] = 0;
   strcpy(ROM_SETTINGS.MD5, arg);
   if ((entry = ini_search_by_md5(arg)) == NULL)
     {
	char mycrc[1024];
	printf("%x\n", (int)entry);
	sprintf(mycrc, "%08X-%08X-C%02X",
		(int)sl(ROM_HEADER->CRC1), (int)sl(ROM_HEADER->CRC2),
		ROM_HEADER->Country_code);
	if ((entry = ini_search_by_CRC(mycrc)) == NULL)
	  {
	     strcpy(ROM_SETTINGS.goodname, ROM_HEADER->nom);
	     strcat(ROM_SETTINGS.goodname, " (unknown rom)");
	     printf("%s\n", ROM_SETTINGS.goodname);
	     ROM_SETTINGS.eeprom_16kb = 0;
	     return 0;
	  }
	else
	  {
	     if (!ask_bad())
	       {
		  free(rom);
		  rom = NULL;
		  free(ROM_HEADER);
		  ROM_HEADER = NULL;
		  return 1;
	       }
	     strcpy(ROM_SETTINGS.goodname, entry->goodname);
	     strcat(ROM_SETTINGS.goodname, " (bad dump)");
	     if (strcmp(entry->refMD5, ""))
	       entry = ini_search_by_md5(entry->refMD5);
	     ROM_SETTINGS.eeprom_16kb = entry->eeprom16kb;
	     return 0;
	  }
     }
   s=entry->goodname;
   for (i=strlen(s); i > 0 && s[i-1] != '['; i--);
   if (i != 0)
     {
	if (s[i] == 'T' || s[i] == 't' || s[i] == 'h' || s[i] == 'f' || s[i] == 'o')
	  {
	     if (!ask_hack())
	       {
		  free(rom);
		  rom = NULL;
		  free(ROM_HEADER);
		  ROM_HEADER = NULL;
		  return 1;
	       }
	  }
	if (s[i] == 'b')
	  {
	     if (!ask_bad())
	       {
		  free(rom);
		  rom = NULL;
		  free(ROM_HEADER);
		  ROM_HEADER = NULL;
		  return 1;
	       }
	  }
     }
   strcpy(ROM_SETTINGS.goodname, entry->goodname);
   
   if (strcmp(entry->refMD5, ""))
     entry = ini_search_by_md5(entry->refMD5);
   ROM_SETTINGS.eeprom_16kb = entry->eeprom16kb;
   printf("eeprom type:%d\n", ROM_SETTINGS.eeprom_16kb);
   
   return 0;
}
MODULE *module_load(const char *file, /**< module filename, searches \p PATH */
							   int argc, /**< count of arguments in \p argv */
							   char *argv[]) /**< arguments passed from the command line */
{
	/* check for already loaded */
	MODULE *mod = module_find((char *)file);
	char buffer[FILENAME_MAX+1];
	char *fmod;
	bool isforeign = false;
	char pathname[1024];
	char *tpath = NULL;
#ifdef WIN32
	char from='/', to='\\';
#else
	char from='\\', to='/';
#endif
	char *p = NULL;
	void *hLib = NULL;
	LIBINIT init = NULL;
	int *pMajor = NULL, *pMinor = NULL;
	CLASS *previous = NULL;
	CLASS *c;

#ifdef NEVER /* this shouldn't ever be necessary but sometimes for debugging purposes it is helpful */
	/* if LD_LIBRARY_PATH is not set, default to current directory */
	if (getenv("LD_LIBRARY_PATH")==NULL)
	{
		putenv("LD_LIBRARY_PATH=.");
		output_verbose("Setting default LD_LIBRARY_DEFAULT to current directory");
	}
#endif

	if (mod!=NULL)
	{
		output_verbose("%s(%d): module '%s' already loaded", __FILE__, __LINE__, file);
		return mod;
	}
	else
	{
		output_verbose("%s(%d): module '%s' not yet loaded", __FILE__, __LINE__, file);
	}

	/* check for foreign modules */
	strcpy(buffer,file);
	fmod = strtok(buffer,"::");
	if (fmod!=NULL && strcmp(fmod, file) != 0)
	{
		char *modname = strtok(NULL,"::");
		MODULE *parent_mod = module_find(fmod);
		if(parent_mod == NULL)
			parent_mod = module_load(fmod, 0, NULL);
		previous = class_get_last_class();
		if(parent_mod != NULL && parent_mod->subload != NULL)
		{	/* if we've defined a subload routine and already loaded the parent module*/
			MODULE *child_mod;
			if(module_find(fmod) == NULL)
				module_load(fmod, 0, NULL);
			child_mod = parent_mod->subload(modname, &mod, (previous ? &(previous->next) : &previous), argc, argv);
			if(child_mod == NULL)
			{	/* failure */
				output_error("module_load(file='%s::%s'): subload failed", fmod, modname);
				return NULL;
			}
			if (mod != NULL)
			{	/* if we want to register another module */
				last_module->next = mod;
				last_module = mod;
				mod->oclass = previous ? previous->next : class_get_first_class();
			}
			return last_module;
		} else {
			struct {
				char *name;
				LOADER loader;
			} fmap[] = {
				{"matlab",NULL},
				{"java",load_java_module},
				{"python",load_python_module},
				{NULL,NULL} /* DO NOT DELETE THIS TERMINATOR ENTRY */
			}, *p;
			for (p=fmap; p->name!=NULL; p++)
			{
				if (strcmp(p->name, fmod)==0)
				{
					static char *args[1];
					isforeign = true;
					if (p->loader!=NULL)
						/* use external loader */
						return p->loader(modname,argc,argv);

					/* use a module with command args */
					argv = args;
					argc=1;
					argv[0] = modname;
					file=buffer;
					break;
				}
			}
			if (p==NULL)
			{
				output_error("module_load(file='%s',...): foreign module type %s not recognized or supported", fmod);
				return NULL;
			}
		}
	}

	/* create a new module entry */
	mod = (MODULE *)malloc(sizeof(MODULE));
	if (mod==NULL)
	{
		output_verbose("%s(%d): module '%s' memory allocation failed", __FILE__, __LINE__, file);
		errno=ENOMEM;
		return NULL;
	}
	else
		output_verbose("%s(%d): module '%s' memory allocated", __FILE__, __LINE__, file);

	/* locate the module */
	snprintf(pathname, 1024, "%s" DLEXT, file);
	tpath = find_file(pathname, NULL, X_OK|R_OK);
	if(tpath == NULL)
	{
		output_verbose("unable to locate %s in GLPATH, using library loader instead", pathname);
		tpath=pathname;
	}
	else
	{
#ifndef WIN32
		/* if the path is a relative path */
		struct stat buf;
		if (tpath[0]!='/' && stat(tpath,&buf)==0) 
		{
			char buffer[1024];

			/* add ./ to the beginning of the path */
			sprintf(buffer,"./%s", tpath);
			strcpy(tpath,buffer);
		}
#endif
		output_verbose("full path to library '%s' is '%s'", file, tpath);
	}

	/* convert path delims based on OS preference */
	for (p=strchr(tpath,from); p!=NULL; p=strchr(p,from))
		*p=to;

	/* ok, let's do it */
	hLib = DLLOAD(tpath);
	if (hLib==NULL)
	{
#if defined WIN32 && ! defined MINGW
		output_error("%s(%d): module '%s' load failed - %s (error code %d)", __FILE__, __LINE__, file, strerror(errno), GetLastError());
#else
		output_error("%s(%d): module '%s' load failed - %s", __FILE__, __LINE__, file, dlerror());
		output_debug("%s(%d): path to module is '%s'", __FILE__, __LINE__, tpath);
#endif
		dlload_error(pathname);
		errno = ENOENT;
		free(mod);
		return NULL;
	}
	else
		output_verbose("%s(%d): module '%s' loaded ok", __FILE__, __LINE__, file);

	/* get the initialization function */
	init = (LIBINIT)DLSYM(hLib,"init");
	if (init==NULL)
	{
		output_error("%s(%d): module '%s' does not export init()", __FILE__, __LINE__, file);
		dlload_error(pathname);
		errno = ENOEXEC;
		free(mod);
		return NULL;
	}
	else
		output_verbose("%s(%d): module '%s' exports init()", __FILE__, __LINE__, file);

	/* connect the module's exported data & functions */
	mod->hLib = (void*)hLib;
	pMajor = (int*)DLSYM(hLib, "major");
	pMinor = (int*)DLSYM(hLib, "minor");
	mod->major = pMajor?*pMajor:0;
	mod->minor = pMinor?*pMinor:0;
	mod->import_file = (int(*)(char*))DLSYM(hLib,"import_file");
	mod->export_file = (int(*)(char*))DLSYM(hLib,"export_file");
	mod->setvar = (int(*)(char*,char*))DLSYM(hLib,"setvar");
	mod->getvar = (void*(*)(char*,char*,unsigned int))DLSYM(hLib,"getvar");
	mod->check = (int(*)())DLSYM(hLib,"check");
#ifndef _NO_CPPUNIT
	mod->module_test = (int(*)(TEST_CALLBACKS*,int,char*[]))DLSYM(hLib,"module_test");
#endif
	mod->cmdargs = (int(*)(int,char**))DLSYM(hLib,"cmdargs");
	mod->kmldump = (int(*)(FILE*,OBJECT*))DLSYM(hLib,"kmldump");
	mod->subload = (MODULE *(*)(char *, MODULE **, CLASS **, int, char **))DLSYM(hLib, "subload");
	mod->test = (void(*)(int,char*[]))DLSYM(hLib,"test");
	mod->globals = NULL;
	strcpy(mod->name,file);
	mod->next = NULL;

	/* call the initialization function */
	mod->oclass = (*init)(&callbacks,(void*)mod,argc,argv);
	if (mod->oclass==NULL)
		return NULL;

	/* connect intrinsic functions */
	for (c=mod->oclass; c!=NULL; c=c->next) {
		char fname[1024];
		struct {
			FUNCTIONADDR *func;
			char *name;
			int optional;
		} map[] = {
			{&c->create,"create",FALSE},
			{&c->init,"init",TRUE},
			{&c->sync,"sync",TRUE},
			{&c->commit,"commit",TRUE},
			{&c->notify,"notify",TRUE},
			{&c->isa,"isa",TRUE},
			{&c->plc,"plc",TRUE},
			{&c->recalc,"recalc",TRUE},
		};
		int i;
		for (i=0; i<sizeof(map)/sizeof(map[0]); i++)
		{
			snprintf(fname, 1024,"%s_%s",map[i].name,isforeign?fmod:c->name);
			if ((*(map[i].func) = (FUNCTIONADDR)DLSYM(hLib,fname))==NULL && !map[i].optional)
			{
				output_fatal("intrinsic %s is not defined in class %s", fname,file);
				/*	TROUBLESHOOT
					A required intrinsic function was not found.  Please review and modify the class definition.
				 */
				errno=EINVAL;
				return NULL;
			}
			else
				if(!map[i].optional)
					output_verbose("%s(%d): module '%s' intrinsic %s found", __FILE__, __LINE__, file, fname);
		}
	}

	/* attach to list of known modules */
	if (first_module==NULL)
		first_module = mod;
	else
		last_module->next = mod;
	last_module = mod;
	return last_module;
}
Example #21
0
File: rom.c Project: GPDP2/mupen64
void calculateMD5(const char *argv, unsigned char digest[16])
{
   md5_state_t state;
   char arg[1024];
   
   strncpy(arg, argv, 1000);
   if (find_file(arg))
     {
	printf("file not found or wrong path\n");
	return;
     }
/*------------------------------------------------------------------------*/   
   findsize();
   if (rom) free(rom);
   rom = malloc(taille_rom);
   
   tmp=0;
   if (!z)
     {
	for (i=0; i<taille_rom;i+=fread(rom+i, 1, 1000, rom_file))
	  {
	     if (tmp!=(int)((i/(float)taille_rom)*100))
	       {
		  tmp=(int)(i/(float)(taille_rom)*100);
		  display_MD5calculating_progress(tmp);
	       }
	  }
     }
   else if (z == 1)
     {
	for (i=0; i<taille_rom;i+=gzread(z_rom_file, rom+i, 1000))
	  {
	     if (tmp!=(int)((i/(float)taille_rom)*100))
	       {
		  tmp=(int)(i/(float)(taille_rom)*100);
		  display_MD5calculating_progress(tmp);
	       }
	  }
     }
   else
     {
	unzOpenCurrentFile(zip);
	for (i=0; i<taille_rom;i+=unzReadCurrentFile(zip, rom+i, 1000))
	  {
	     if (tmp!=(int)((i/(float)taille_rom)*100))
	       {
		  tmp=(int)(i/(float)(taille_rom)*100);
		  display_MD5calculating_progress(tmp);
	       }
	  }
	unzCloseCurrentFile(zip);
     }
   if (!z) fclose(rom_file);
   else if (z==1) gzclose(z_rom_file);
   else unzClose(zip);
   
   display_MD5calculating_progress(100);
   
   if (rom[0]==0x37)
     {
	printf ("byteswaping rom...\n");
	for (i=0; i<(taille_rom/2); i++)
	  {
	     tmp=rom[i*2];
	     rom[i*2]=rom[i*2+1];
	     rom[i*2+1]=tmp;
	  }
	printf ("rom byteswaped\n");
     }
   if (rom[0]==0x40)
     {
	for (i=0; i<(taille_rom/4); i++)
	  {
	     tmp=rom[i*4];
	     rom[i*4]=rom[i*4+3];
	     rom[i*4+3]=tmp;
	     tmp=rom[i*4+1];
	     rom[i*4+1]=rom[i*4+2];
	     rom[i*4+2]=tmp;
	  }
	printf("rom byteswaped\n");
     }
   else if ((rom[0] != 0x80) || (rom[1] != 0x37) || (rom[2] != 0x12) || (rom[3] != 0x40))
     {
	printf("wrong file format !\n");
	free(rom);
	rom = NULL;
	return;
     }
   md5_init(&state);
   md5_append(&state, (const md5_byte_t *)rom, taille_rom);
   md5_finish(&state, digest);
   display_MD5calculating_progress(-1);
   free(rom);
   rom = NULL;
}
Example #22
0
const char *LP_find_file(LP_DIR_CTX **ctx, const char *directory)
{
    int status;
    char *p, *r;
    size_t l;
    unsigned long flags = 0;

/* Arrange 32-bit pointer to (copied) string storage, if needed. */
#if __INITIAL_POINTER_SIZE == 64
# pragma pointer_size save
# pragma pointer_size 32
    char *ctx_filespec_32p;
# pragma pointer_size restore
    char ctx_filespec_32[NAMX_MAXRSS + 1];
#endif                          /* __INITIAL_POINTER_SIZE == 64 */

#ifdef NAML$C_MAXRSS
    flags |= LIB$M_FIL_LONG_NAMES;
#endif

    if (ctx == NULL || directory == NULL) {
        errno = EINVAL;
        return 0;
    }

    errno = 0;
    if (*ctx == NULL) {
        size_t filespeclen = strlen(directory);
        char *filespec = NULL;

        if (filespeclen == 0) {
            errno = ENOENT;
            return 0;
        }

        /* MUST be a VMS directory specification!  Let's estimate if it is. */
        if (directory[filespeclen - 1] != ']'
            && directory[filespeclen - 1] != '>'
            && directory[filespeclen - 1] != ':') {
            errno = EINVAL;
            return 0;
        }

        filespeclen += 4;       /* "*.*;" */

        if (filespeclen > NAMX_MAXRSS) {
            errno = ENAMETOOLONG;
            return 0;
        }

        *ctx = malloc(sizeof(**ctx));
        if (*ctx == NULL) {
            errno = ENOMEM;
            return 0;
        }
        memset(*ctx, 0, sizeof(**ctx));

        strcpy((*ctx)->filespec, directory);
        strcat((*ctx)->filespec, "*.*;");

/* Arrange 32-bit pointer to (copied) string storage, if needed. */
#if __INITIAL_POINTER_SIZE == 64
# define CTX_FILESPEC ctx_filespec_32p
        /* Copy the file name to storage with a 32-bit pointer. */
        ctx_filespec_32p = ctx_filespec_32;
        strcpy(ctx_filespec_32p, (*ctx)->filespec);
#else                           /* __INITIAL_POINTER_SIZE == 64 */
# define CTX_FILESPEC (*ctx)->filespec
#endif                          /* __INITIAL_POINTER_SIZE == 64 [else] */

        (*ctx)->filespec_dsc.dsc$w_length = filespeclen;
        (*ctx)->filespec_dsc.dsc$b_dtype = DSC$K_DTYPE_T;
        (*ctx)->filespec_dsc.dsc$b_class = DSC$K_CLASS_S;
        (*ctx)->filespec_dsc.dsc$a_pointer = CTX_FILESPEC;
    }

    (*ctx)->result_dsc.dsc$w_length = 0;
    (*ctx)->result_dsc.dsc$b_dtype = DSC$K_DTYPE_T;
    (*ctx)->result_dsc.dsc$b_class = DSC$K_CLASS_D;
    (*ctx)->result_dsc.dsc$a_pointer = 0;

    status = lib$find_file(&(*ctx)->filespec_dsc, &(*ctx)->result_dsc,
                           &(*ctx)->VMS_context, 0, 0, 0, &flags);

    if (status == RMS$_NMF) {
        errno = 0;
        vaxc$errno = status;
        return NULL;
    }

    if (!$VMS_STATUS_SUCCESS(status)) {
        errno = EVMSERR;
        vaxc$errno = status;
        return NULL;
    }

    /*
     * Quick, cheap and dirty way to discard any device and directory, since
     * we only want file names
     */
    l = (*ctx)->result_dsc.dsc$w_length;
    p = (*ctx)->result_dsc.dsc$a_pointer;
    r = p;
    for (; *p; p++) {
        if (*p == '^' && p[1] != '\0') { /* Take care of ODS-5 escapes */
            p++;
        } else if (*p == ':' || *p == '>' || *p == ']') {
            l -= p + 1 - r;
            r = p + 1;
        } else if (*p == ';') {
            l = p - r;
            break;
        }
    }

    strncpy((*ctx)->result, r, l);
    (*ctx)->result[l] = '\0';
    str$free1_dx(&(*ctx)->result_dsc);

    return (*ctx)->result;
}
Example #23
0
mp_obj_t mp_builtin___import__(uint n_args, mp_obj_t *args) {
#if DEBUG_PRINT
    printf("__import__:\n");
    for (int i = 0; i < n_args; i++) {
        printf("  ");
        mp_obj_print(args[i], PRINT_REPR);
        printf("\n");
    }
#endif

    mp_obj_t module_name = args[0];
    mp_obj_t fromtuple = mp_const_none;
    int level = 0;
    if (n_args >= 4) {
        fromtuple = args[3];
        if (n_args >= 5) {
            level = MP_OBJ_SMALL_INT_VALUE(args[4]);
        }
    }

    uint mod_len;
    const char *mod_str = (const char*)mp_obj_str_get_data(module_name, &mod_len);

    if (level != 0) {
        // What we want to do here is to take name of current module,
        // chop <level> trailing components, and concatenate with passed-in
        // module name, thus resolving relative import name into absolue.
        // This even appears to be correct per
        // http://legacy.python.org/dev/peps/pep-0328/#relative-imports-and-name
        // "Relative imports use a module's __name__ attribute to determine that
        // module's position in the package hierarchy."
        mp_obj_t this_name_q = mp_obj_dict_get(mp_globals_get(), MP_OBJ_NEW_QSTR(MP_QSTR___name__));
        assert(this_name_q != MP_OBJ_NULL);
#if DEBUG_PRINT
        printf("Current module: ");
        mp_obj_print(this_name_q, PRINT_REPR);
        printf("\n");
#endif

        uint this_name_l;
        const char *this_name = (const char*)mp_obj_str_get_data(this_name_q, &this_name_l);

        uint dots_seen = 0;
        const char *p = this_name + this_name_l - 1;
        while (p > this_name) {
            if (*p == '.') {
                dots_seen++;
                if (--level == 0) {
                    break;
                }
            }
            p--;
        }

        if (dots_seen == 0 && level == 1) {
            // http://legacy.python.org/dev/peps/pep-0328/#relative-imports-and-name
            // "If the module's name does not contain any package information
            // (e.g. it is set to '__main__') then relative imports are
            // resolved as if the module were a top level module, regardless
            // of where the module is actually located on the file system."
            // Supposedly this if catches this condition and resolve it properly
            // TODO: But nobody knows for sure. This condition happens when
            // package's __init__.py does something like "import .submod". So,
            // maybe we should check for package here? But quote above doesn't
            // talk about packages, it talks about dot-less module names.
            p = this_name + this_name_l;
        } else if (level != 0) {
            nlr_raise(mp_obj_new_exception_msg(&mp_type_ImportError, "Invalid relative import"));
        }

        uint new_mod_l = (mod_len == 0 ? p - this_name : p - this_name + 1 + mod_len);
        char *new_mod = alloca(new_mod_l);
        memcpy(new_mod, this_name, p - this_name);
        if (mod_len != 0) {
            new_mod[p - this_name] = '.';
            memcpy(new_mod + (p - this_name) + 1, mod_str, mod_len);
        }

        qstr new_mod_q = qstr_from_strn(new_mod, new_mod_l);
        DEBUG_printf("Resolved relative name: %s\n", qstr_str(new_mod_q));
        module_name = MP_OBJ_NEW_QSTR(new_mod_q);
        mod_str = new_mod;
        mod_len = new_mod_l;
    }

    // check if module already exists
    mp_obj_t module_obj = mp_module_get(mp_obj_str_get_qstr(module_name));
    if (module_obj != MP_OBJ_NULL) {
        DEBUG_printf("Module already loaded\n");
        // If it's not a package, return module right away
        char *p = strchr(mod_str, '.');
        if (p == NULL) {
            return module_obj;
        }
        // If fromlist is not empty, return leaf module
        if (fromtuple != mp_const_none) {
            return module_obj;
        }
        // Otherwise, we need to return top-level package
        qstr pkg_name = qstr_from_strn(mod_str, p - mod_str);
        return mp_module_get(pkg_name);
    }
    DEBUG_printf("Module not yet loaded\n");

    uint last = 0;
    VSTR_FIXED(path, MICROPY_ALLOC_PATH_MAX)
    module_obj = MP_OBJ_NULL;
    mp_obj_t top_module_obj = MP_OBJ_NULL;
    mp_obj_t outer_module_obj = MP_OBJ_NULL;
    uint i;
    for (i = 1; i <= mod_len; i++) {
        if (i == mod_len || mod_str[i] == '.') {
            // create a qstr for the module name up to this depth
            qstr mod_name = qstr_from_strn(mod_str, i);
            DEBUG_printf("Processing module: %s\n", qstr_str(mod_name));
            DEBUG_printf("Previous path: %s\n", vstr_str(&path));

            // find the file corresponding to the module name
            mp_import_stat_t stat;
            if (vstr_len(&path) == 0) {
                // first module in the dotted-name; search for a directory or file
                stat = find_file(mod_str, i, &path);
            } else {
                // latter module in the dotted-name; append to path
                vstr_add_char(&path, PATH_SEP_CHAR);
                vstr_add_strn(&path, mod_str + last, i - last);
                stat = stat_dir_or_file(&path);
            }
            DEBUG_printf("Current path: %s\n", vstr_str(&path));

            // fail if we couldn't find the file
            if (stat == MP_IMPORT_STAT_NO_EXIST) {
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, "No module named '%s'", qstr_str(mod_name)));
            }

            module_obj = mp_module_get(mod_name);
            if (module_obj == MP_OBJ_NULL) {
                // module not already loaded, so load it!

                module_obj = mp_obj_new_module(mod_name);

                if (stat == MP_IMPORT_STAT_DIR) {
                    DEBUG_printf("%s is dir\n", vstr_str(&path));
                    // https://docs.python.org/3/reference/import.html
                    // "Specifically, any module that contains a __path__ attribute is considered a package."
                    mp_store_attr(module_obj, MP_QSTR___path__, mp_obj_new_str(vstr_str(&path), vstr_len(&path), false));
                    vstr_add_char(&path, PATH_SEP_CHAR);
                    vstr_add_str(&path, "__init__.py");
                    if (mp_import_stat(vstr_str(&path)) != MP_IMPORT_STAT_FILE) {
                        vstr_cut_tail_bytes(&path, sizeof("/__init__.py") - 1); // cut off /__init__.py
                        printf("Notice: %s is imported as namespace package\n", vstr_str(&path));
                    } else {
                        do_load(module_obj, &path);
                        vstr_cut_tail_bytes(&path, sizeof("/__init__.py") - 1); // cut off /__init__.py
                    }
                } else { // MP_IMPORT_STAT_FILE
                    do_load(module_obj, &path);
                    // TODO: We cannot just break here, at the very least, we must execute
                    // trailer code below. But otherwise if there're remaining components,
                    // that would be (??) object path within module, not modules path within FS.
                    // break;
                }
            }
            if (outer_module_obj != MP_OBJ_NULL) {
                qstr s = qstr_from_strn(mod_str + last, i - last);
                mp_store_attr(outer_module_obj, s, module_obj);
            }
            outer_module_obj = module_obj;
            if (top_module_obj == MP_OBJ_NULL) {
                top_module_obj = module_obj;
            }
            last = i + 1;
        }
    }

    if (i < mod_len) {
        // we loaded a package, now need to load objects from within that package
        // TODO
        assert(0);
    }

    // If fromlist is not empty, return leaf module
    if (fromtuple != mp_const_none) {
        return module_obj;
    }
    // Otherwise, we need to return top-level package
    return top_module_obj;
}
Example #24
0
int main (int argc, char *argv[])
{
  /* check that we were given at least one argument
   * (the transfer file name) */
  if (argc != 2) {
    printf("Usage: scr_transfer <transferfile>\n");
    return 1;
  }

  /* record the name of the transfer file */
  scr_transfer_file = strdup(argv[1]);
  if (scr_transfer_file == NULL) {
    scr_err("scr_transfer: Copying transfer file name @ %s:%d",
            __FILE__, __LINE__
    );
    return 1;
  }

  /* initialize our tracking variables */
  read_params();

  /* get file io mode */
  mode_t mode_file = scr_getmode(1, 1, 0);

  /* we cache the opened file descriptors to avoid extra opens,
   * seeks, and closes */
  int fd_src = -1;
  int fd_dst = -1;

  char* new_file_src = NULL;
  char* old_file_src = NULL;
  char* new_file_dst = NULL;
  char* old_file_dst = NULL;

  off_t new_position = 0;
  off_t old_position = 0;

  /* start in the stopped state */
  state = STOPPED;
  set_transfer_file_state(SCR_TRANSFER_KEY_STATE_STOP, 0);

  /* TODO: enable this value to be set from config file */
  /* TODO: page-align this buffer for faster performance */
  /* allocate our file copy buffer */
  size_t bufsize = scr_file_buf_size;
  char* buf = malloc(bufsize);
  if (buf == NULL) {
    scr_err("scr_transfer: Failed to allocate %llu bytes for file copy buffer @ %s:%d",
            (unsigned long long) bufsize, __FILE__, __LINE__
    );
    return 1;
  }

  int nread = 0;
  double secs_run   = 0.0;
  double secs_slept = 0.0;
  double secs_run_start  = scr_seconds();
  double secs_run_end    = secs_run_start;
  double secs_last_write = secs_run_start;
  scr_hash* hash = scr_hash_new();
  while (keep_running) {
    /* loop here sleeping and checking transfer file periodically
     * until state changes and / or some time elapses */
    /* reset our timer for our last write */
    double secs_remain = scr_transfer_secs;
    while (keep_running && (state == STOPPED || secs_remain > 0.0)) {
      /* remember our current state before reading transfer file */
      int old_state = state;

      /* read the transfer file, which fills in our hash and
       * also updates state and bytes_per_second */
      scr_hash_delete(&hash);
      hash = read_transfer_file();

      /* compute time we should sleep before writing more data based
       * on bandwidth and percent of runtime limits */
      if (state == RUNNING) {
        /* get the current time */
        double secs_now = scr_seconds();

        /* based on the amount we last wrote and our allocated bandwidth,
         * compute time we need to sleep before attempting our next write */
        double secs_remain_bw = 0.0;
        if (nread > 0 && bytes_per_second > 0.0) {
          double secs_to_wait_bw = (double) nread / bytes_per_second;
          double secs_waited_bw = secs_now - secs_last_write;
          secs_remain_bw = secs_to_wait_bw - secs_waited_bw;
        }

        /* based on the percentage of time we are allowed to be running,
         * compute time we need to sleep before attempting our next write */
        double secs_remain_runtime = 0.0;
        if (percent_runtime > 0.0) {
          /* stop the run clock, add to the run time,
           * and restart the run clock */
          secs_run_end = secs_now;
          secs_run += secs_run_end - secs_run_start;
          secs_run_start = secs_run_end;

          /* compute our total time, and the time we need to sleep */
          double secs_total = secs_run + secs_slept;
          secs_remain_runtime = secs_run / percent_runtime - secs_total;
        }

        /* take the maximum of these two values */
        secs_remain = secs_remain_bw;
        if (secs_remain_runtime > secs_remain) {
          secs_remain = secs_remain_runtime;
        }
      }

      /* check for a state transition */
      if (state != old_state) {
        if (state == RUNNING) {
          /* if we switched to RUNNING, kick out without sleeping and
           * reset the total run and sleep times */
          secs_remain = 0.0;
          secs_run    = 0.0;
          secs_slept  = 0.0;
        } else if (state == STOPPED) {
          /* if we switched to STOPPED, close our files if open */
          close_files(new_file_src, &fd_src, new_file_dst, &fd_dst);
          clear_parameters(&new_file_src, &new_file_dst, &new_position);
          clear_parameters(&old_file_src, &old_file_dst, &old_position);

          /* after closing our files, update our state in the transfer file */
          set_transfer_file_state(SCR_TRANSFER_KEY_STATE_STOP, 0);
        }
      }

      /* assume we can sleep for the full remainder of the time */
      double secs = secs_remain;

      /* if we're not running, always sleep for the full time */
      if (state != RUNNING) {
        secs = scr_transfer_secs;
      }

      /* set a maximum time to sleep before we read the hash file again
       * (ensures some responsiveness) */
      if (secs > scr_transfer_secs) {
        secs = scr_transfer_secs;
      }

      /* sleep if we need to */
      if (secs > 0.0) {
        /* stop the run clock and add to the total run time */
        secs_run_end = scr_seconds();
        secs_run += secs_run_end - secs_run_start;

        /* sleep */
        usleep((unsigned long) (secs * 1000000.0));
        secs_slept += secs;
        secs_remain -= secs;

        /* restart the run clock */
        secs_run_start = scr_seconds();
      }
    }

    /* write data out */
    if (state == RUNNING) {
      /* look for a new file to transfer */
      off_t filesize = 0;
      find_file(hash, &new_file_src, &new_file_dst, &new_position, &filesize);

      /* if we got a new file, close the old one (if open),
       * open the new file */
      if (bool_diff_files(new_file_src, old_file_src)) {
        /* close the old descriptor if it's open */
        if (fd_src >= 0) {
          scr_close(old_file_src, fd_src);
          fd_src = -1;
        }

        /* delete the old file name if we have one */
        if (old_file_src != NULL) {
          free(old_file_src);
          old_file_src = NULL;
        }

        /* reset our position counter */
        old_position = 0;

        /* open the file and remember the filename if we have one */
        if (new_file_src != NULL) {
          fd_src = scr_open(new_file_src, O_RDONLY);
          /* TODO: check for errors here */
          old_file_src = strdup(new_file_src);
          /* TODO: check for errors here */
        }
      }

      /* if we got a new file, close the old one (if open),
       * open the new file */
      if (bool_diff_files(new_file_dst, old_file_dst)) {
        /* close the old descriptor if it's open */
        if (fd_dst >= 0) {
          scr_close(old_file_dst, fd_dst);
          fd_dst = -1;
        }

        /* delete the old file name if we have one */
        if (old_file_dst != NULL) {
          free(old_file_dst);
          old_file_dst = NULL;
        }

        /* reset our position counter */
        old_position = 0;

        /* open the file and remember the filename if we have one */
        if (new_file_dst != NULL) {
          fd_dst = scr_open(new_file_dst, O_RDWR | O_CREAT, mode_file);
          /* TODO: check for errors here */
          old_file_dst = strdup(new_file_dst);
          /* TODO: check for errors here */
        }
      }

      /* we may have the same file, but perhaps the position changed
       * (may need to seek) */
      if (new_position != old_position) {
        if (fd_src >= 0) {
          lseek(fd_src, new_position, SEEK_SET);
          /* TODO: check for errors here */
        }

        if (fd_dst >= 0) {
          lseek(fd_dst, new_position, SEEK_SET);
          /* TODO: check for errors here */
        }

        /* remember the new position */
        old_position = new_position;
      }

      /* if we have two open files,
       * copy a chunk from source file to destination file */
      nread = 0;
      if (fd_src >= 0 && fd_dst >= 0) {
        /* compute number of bytes to read from file */
        size_t count = (size_t) (filesize - new_position);
        if (count > bufsize) {
          count = bufsize;
        }

        /* read a chunk */
        nread = scr_read(new_file_src, fd_src, buf, count);

        /* if we read data, write it out */
        if (nread > 0) {
          /* record the time of our write */
          secs_last_write = scr_seconds();

          /* write the chunk and force it out with an fsync */
          scr_write(new_file_dst, fd_dst, buf, nread);
          fsync(fd_dst);

          /* update our position */
          new_position += (off_t) nread;
          old_position = new_position;

          /* record the updated position in the transfer file */
          update_transfer_file(new_file_src, new_file_dst, new_position);
        }

        /* if we've written all of the bytes, close the files */
        if (new_position == filesize) {
          close_files(new_file_src, &fd_src, new_file_dst, &fd_dst);
          clear_parameters(&new_file_src, &new_file_dst, &new_position);
          clear_parameters(&old_file_src, &old_file_dst, &old_position);
        }
      } else {
        /* TODO: we may have an error
         * (failed to open the source or dest file) */
        /* if we found no file to transfer, move to a STOPPED state */
        if (new_file_src == NULL) {
          state = STOPPED;
          set_transfer_file_state(SCR_TRANSFER_KEY_STATE_STOP, 1);
        }
      }
    }
  }

  /* free our file copy buffer */
  if (buf != NULL) {
    free(buf);
    buf = NULL;
  }

  /* free the strdup'd tranfer file name */
  if (scr_transfer_file != NULL) {
    free(scr_transfer_file);
    scr_transfer_file = NULL;
  }

  return 0;
}
Example #25
0
void
find_cmd (void)
{
    find_file ();
}
bool LLImageRaw::createFromFile(const std::string &filename, bool j2c_lowest_mip_only)
{
	std::string name = filename;
	size_t dotidx = name.rfind('.');
	S8 codec = IMG_CODEC_INVALID;
	std::string exten;
	
	deleteData(); // delete any existing data

	if (dotidx != std::string::npos)
	{
		exten = name.substr(dotidx+1);
		LLStringUtil::toLower(exten);
		codec = getCodecFromExtension(exten);
	}
	else
	{
		exten = find_file(name, &codec);
		name = name + "." + exten;
	}
	if (codec == IMG_CODEC_INVALID)
	{
		return false; // format not recognized
	}

	llifstream ifs(name, llifstream::binary);
	if (!ifs.is_open())
	{
		// SJB: changed from llinfos to lldebugs to reduce spam
		lldebugs << "Unable to open image file: " << name << llendl;
		return false;
	}
	
	ifs.seekg (0, std::ios::end);
	int length = ifs.tellg();
	if (j2c_lowest_mip_only && length > 2048)
	{
		length = 2048;
	}
	ifs.seekg (0, std::ios::beg);

	if (!length)
	{
		llinfos << "Zero length file file: " << name << llendl;
		return false;
	}
	
	LLPointer<LLImageFormatted> image = LLImageFormatted::createFromType(codec);
	llassert(image.notNull());

	U8 *buffer = image->allocateData(length);
	ifs.read ((char*)buffer, length);	/* Flawfinder: ignore */
	ifs.close();
	
	BOOL success;

	success = image->updateData();
	if (success)
	{
		if (j2c_lowest_mip_only && codec == IMG_CODEC_J2C)
		{
			S32 width = image->getWidth();
			S32 height = image->getHeight();
			S32 discard_level = 0;
			while (width > 1 && height > 1 && discard_level < MAX_DISCARD_LEVEL)
			{
				width >>= 1;
				height >>= 1;
				discard_level++;
			}
			((LLImageJ2C *)((LLImageFormatted*)image))->setDiscardLevel(discard_level);
		}
		success = image->decode(this, 100000.0f);
	}
Example #27
0
multicart_open_error multicart_open(emu_options &options, const char *filename, const char *gamedrv, multicart_load_flags load_flags, multicart_t **cart)
{
	multicart_open_error err;
	zip_error ziperr;
	object_pool *pool;
	multicart_load_state state = {0, };
	const zip_file_header *header;
	const char *pcb_type;
	char *layout_text = NULL;

	/* allocate an object pool */
	pool = pool_alloc_lib(NULL);
	if (pool == NULL)
	{
		err = MCERR_OUT_OF_MEMORY;
		goto done;
	}

	/* allocate the multicart */
	state.multicart = (multicart_t*)pool_malloc_lib(pool, sizeof(*state.multicart));
	if (state.multicart == NULL)
	{
		err = MCERR_OUT_OF_MEMORY;
		goto done;
	}
	memset(state.multicart, 0, sizeof(*state.multicart));

	/* allocate the multicart's private data */
	state.multicart->data = (multicart_private*)pool_malloc_lib(pool, sizeof(*state.multicart->data));
	if (state.multicart->data == NULL)
	{
		err = MCERR_OUT_OF_MEMORY;
		goto done;
	}
	memset(state.multicart->data, 0, sizeof(*state.multicart->data));
	state.multicart->data->pool = pool;
	pool = NULL;

	/* open the ZIP file */
	ziperr = zip_file_open(filename, &state.zip);
	if (ziperr != ZIPERR_NONE)
	{
		err = MCERR_NOT_MULTICART;
		goto done;
	}

	/* find the layout.xml file */
	header = find_file(state.zip, "layout.xml");
	if (header == NULL)
	{
		err = MCERR_MISSING_LAYOUT;
		goto done;
	}

	/* reserve space for the layout text */
	layout_text = (char*)malloc(header->uncompressed_length + 1);
	if (layout_text == NULL)
	{
		err = MCERR_OUT_OF_MEMORY;
		goto done;
	}

	/* uncompress the layout text */
	ziperr = zip_file_decompress(state.zip, layout_text, header->uncompressed_length);
	if (ziperr != ZIPERR_NONE)
	{
		err = MCERR_ZIP_ERROR;
		goto done;
	}
	layout_text[header->uncompressed_length] = '\0';

	/* parse the layout text */
	state.layout_xml = xml_string_read(layout_text, NULL);
	if (state.layout_xml == NULL)
	{
		err = MCERR_XML_ERROR;
		goto done;
	}

	/* locate the PCB node */
	if (!find_pcb_and_resource_nodes(state.layout_xml, &state.pcb_node, &state.resources_node))
	{
		err = MCERR_NO_PCB_OR_RESOURCES;
		goto done;
	}

	/* get the PCB resource_type */
	pcb_type = xml_get_attribute_string(state.pcb_node, "type", "");
	state.multicart->pcb_type = pool_strdup_lib(state.multicart->data->pool, pcb_type);
	if (state.multicart->pcb_type == NULL)
	{
		err = MCERR_OUT_OF_MEMORY;
		goto done;
	}

	state.multicart->gamedrv_name = pool_strdup_lib(state.multicart->data->pool, gamedrv);
	if (state.multicart->gamedrv_name == NULL)
	{
		err = MCERR_OUT_OF_MEMORY;
		goto done;
	}

	/* do we have to load resources? */
	if (load_flags & MULTICART_FLAGS_LOAD_RESOURCES)
	{
		err = load_all_resources(options, &state);
		if (err != MCERR_NONE)
			goto done;

		err = load_all_sockets(&state);
		if (err != MCERR_NONE)
			goto done;
	}

	err = MCERR_NONE;

done:
	if (pool != NULL)
		pool_free_lib(pool);
	if (state.zip != NULL)
		zip_file_close(state.zip);
	if (layout_text != NULL)
		free(layout_text);
	if (state.layout_xml != NULL)
		xml_file_free(state.layout_xml);

	if ((err != MCERR_NONE) && (state.multicart != NULL))
	{
		multicart_close(options, state.multicart);
		state.multicart = NULL;
	}
	*cart = state.multicart;
	return err;
}
Example #28
0
File: lsc.c Project: wcheswick/ex
/*
 * Figure out where everything goes.  The major buttons vary depending on which
 * category is selected.  We place the minor buttons now which always appear
 * in a given place, though they are obscured when their type isn't selected.
 */
void
layout_screen(void) {
	utf8 *touch_screen;
	Pixel color;
	PixMap pm_up, pm_down;
	int i;

	Rectangle r;
	Rectangle left_col, right_col, subcat_right, subcat_left;
	button *last_top;
	Point top_secondary;
	int last_secondary_bottom;

	text_font = load_font(TEXT_FONT);
	button_font = load_font(BUTTON_FONT);
	big_button_font = load_font(BIG_BUTTON_FONT);

	touch_screen = lookup("touchscreen", 0, "no");
	set_font(button_font);

	if (!set_background(find_file("background.pnm", "lib/lsc"), SCREEN_WIDTH, SCREEN_HEIGHT)) {
		fprintf(stderr, "lsc: background file %s missing\n", "background.pnm");
//		exit(1);
	}

//set_background(find_file("lsc_background.pnm", "buttons"), SCREEN_WIDTH, SCREEN_HEIGHT);

	video_r.min.x = 81;
	video_r.max.x = video_r.min.x + VIDEO_WIDTH;
	video_r.min.y = 229;
	video_r.max.y = video_r.min.y + VIDEO_HEIGHT;

	fps_r.max.x = video_r.max.x;
	fps_r.min.x = fps_r.max.x - 130;
	fps_r.max.y = video_r.min.y - 3;
	fps_r.min.y = fps_r.max.y - (FONTHEIGHT(text_font) + 5);

	message_r.max.y = fps_r.max.y;
	message_r.min.y = fps_r.min.y;
	message_r.min.x = video_r.min.x;
	message_r.max.x = fps_r.min.x;

// "Changes made" @ 875,-877; -899; -920; -940
	timer_r = (Rectangle){{0, 1080-1070}, {SCREEN_WIDTH, 45}};
	bar_r = timer_r;
	bar_r.min.x += 40;

	hist_r = (Rectangle){{575, 0}, {800, 160}};
	explain_r = (Rectangle){{16, SCREEN_HEIGHT-62},
		{SCREEN_WIDTH-307, SCREEN_HEIGHT-39}};

	freeze_button    = lsc_button((Point){900+230,109}, "freeze", 0, 0);
	undo_button	 = lsc_button((Point){900+50,109}, "undo", 0, 0);
	startover_button = lsc_button((Point){900+50,29}, "startover", 0, 0);
	current_primary_button = (button *)0;

	default_button_state = Off;
	default_category = Cat_none;

#ifdef notdef
	default_category = Cat_none;

	top_secondary = (Point){SECONDARY_X,top_y};
#endif

#define PRIMARY_X	(SCREEN_WIDTH-244)
#define SECONDARY_X	(SCREEN_WIDTH-184)
#define BUTTON_TOP	(SCREEN_HEIGHT - 32)

#define	BELOW	((Point){SECONDARY_X, (last_button->r.min.y - 60)})

	button_field_r = (Rectangle){{PRIMARY_X, 0},
		{SCREEN_WIDTH, BUTTON_TOP}};
	default_button_state = Off;

	/*
	 * Define the primary buttons.  We fill in the positions of
	 * the buttons depending on the primary selected.  This is uglier
	 * than it should be.
	 */
	default_button_state = Off;
	default_category = Cat_change_color;
	primary_buttons[Cat_change_color].b = lsc_button((Point){0,0}, "color", 0, 0);

	default_category = Cat_change_look;
	primary_buttons[Cat_change_look].b = lsc_button((Point){0,0}, "look", 0, 0);

	default_category = Cat_change_shape;
	primary_buttons[Cat_change_shape].b = lsc_button((Point){0,0}, "shape", 0, 0);

	default_button_state = Hidden;

	/* color changers */

	primary_buttons[Cat_change_color].primary_bottom[Cat_change_color] =
	    primary_buttons[Cat_change_color].primary_bottom[Cat_change_look] =
	    primary_buttons[Cat_change_color].primary_bottom[Cat_change_shape] =
		BUTTON_TOP - DY(primary_buttons[Cat_change_color].b->pm[On].r);

	default_category = Cat_change_color;
	primary_buttons[default_category].b->r.min.y = 
	    primary_buttons[default_category].primary_bottom[default_category];
	last_button = primary_buttons[default_category].b;

	lsc_button(BELOW, "blkwht", do_point, init_lum);
	sample_secondary_button = last_button;
	lsc_button(BELOW, "brghtr", do_point, init_brighten);
	lsc_button(BELOW, "dimmer", do_point, init_truncatepix);
	lsc_button(BELOW, "contrast", do_point, init_high);
	lsc_button(BELOW, "negative", do_point, init_negative);
	lsc_button(BELOW, "solar", do_point, init_solarize);
	lsc_button(BELOW, "colorize", do_point, init_colorize);
	lsc_button(BELOW, "outline", do_sobel, 0);
	lsc_button(BELOW, "raisedgray", do_edge, 0);
	primary_buttons[Cat_change_color].secondary_bottom =
		last_button->r.min.y - BUTTON_SEP;
	primary_buttons[Cat_change_look].primary_bottom[Cat_change_color] = 
	    primary_buttons[Cat_change_color].secondary_bottom -
	    DY(primary_buttons[Cat_change_look].b->pm[On].r);
	primary_buttons[Cat_change_shape].primary_bottom[Cat_change_color] = 
	    primary_buttons[Cat_change_look].primary_bottom[Cat_change_color] -
	    DY(primary_buttons[Cat_change_shape].b->pm[On].r) - BUTTON_SEP;


	/* look changers */

	primary_buttons[Cat_change_look].primary_bottom[Cat_change_look] =
	    primary_buttons[Cat_change_look].primary_bottom[Cat_change_shape] = 
	    	primary_buttons[Cat_change_color].primary_bottom[Cat_change_color] -
	    	DY(primary_buttons[Cat_change_look].b->pm[On].r) - BUTTON_SEP;;

	default_category = Cat_change_look;
	primary_buttons[default_category].b->r.min.y = 
	    primary_buttons[default_category].primary_bottom[default_category];
	last_button = primary_buttons[default_category].b;

	lsc_button(BELOW, "bigpixels", do_remap, init_pixels4);
	lsc_button(BELOW, "blur", do_blur, 0);
	lsc_button(BELOW, "blurry", do_brownian, 0);
	lsc_button(BELOW, "focus", do_focus, 0);
	lsc_button(BELOW, "bleed", do_bleed, 0);
	lsc_button(BELOW, "oilpaint", do_new_oil, 0);
	lsc_button(BELOW, "crackle", do_shower, 0);
	lsc_button(BELOW, "zoom", do_remap, init_zoom);
	lsc_button(BELOW, "earthqke", do_shear, 0);
	lsc_button(BELOW, "speckle", do_cfs, 0);
	primary_buttons[Cat_change_look].secondary_bottom = last_button->r.min.y - BUTTON_SEP;
	primary_buttons[Cat_change_shape].primary_bottom[Cat_change_look] = 
	    primary_buttons[Cat_change_look].secondary_bottom - 
	    DY(primary_buttons[Cat_change_shape].b->pm[On].r);

	/* shape changers */

	primary_buttons[Cat_change_shape].primary_bottom[Cat_change_shape] =
	    	primary_buttons[Cat_change_look].primary_bottom[Cat_change_shape] -
	    	DY(primary_buttons[Cat_change_shape].b->pm[On].r) - BUTTON_SEP;;
	default_category = Cat_change_shape;
	primary_buttons[default_category].b->r.min.y = 
	    primary_buttons[default_category].primary_bottom[default_category];
	last_button = primary_buttons[default_category].b;

	lsc_button(BELOW, "fisheye", do_remap, init_fisheye);
	lsc_button(BELOW, "flip", do_remap, init_mirror);
	lsc_button(BELOW, "mirror", do_remap, init_copy_right);
	lsc_button(BELOW, "kite", do_remap, init_kite);
	lsc_button(BELOW, "pinch", do_remap, init_cone);
	lsc_button(BELOW, "cylinder", do_remap, init_cylinder);
	lsc_button(BELOW, "wave", do_smear, 0);
	lsc_button(BELOW, "twist", do_remap, init_twist);
	lsc_button(BELOW, "escher", do_remap, init_escher);
	lsc_button(BELOW, "shower", do_remap, init_shower2);
	primary_buttons[Cat_change_shape].secondary_bottom = last_button->r.min.y - BUTTON_SEP;
}
Example #29
0
File: open.c Project: delkon/gcc
gfc_unit *
new_unit (st_parameter_open *opp, gfc_unit *u, unit_flags * flags)
{
  gfc_unit *u2;
  stream *s;
  char tmpname[5 /* fort. */ + 10 /* digits of unit number */ + 1 /* 0 */];

  /* Change unspecifieds to defaults.  Leave (flags->action ==
     ACTION_UNSPECIFIED) alone so open_external() can set it based on
     what type of open actually works.  */

  if (flags->access == ACCESS_UNSPECIFIED)
    flags->access = ACCESS_SEQUENTIAL;

  if (flags->form == FORM_UNSPECIFIED)
    flags->form = (flags->access == ACCESS_SEQUENTIAL)
      ? FORM_FORMATTED : FORM_UNFORMATTED;

  if (flags->async == ASYNC_UNSPECIFIED)
    flags->async = ASYNC_NO;

  if (flags->status == STATUS_UNSPECIFIED)
    flags->status = STATUS_UNKNOWN;

  /* Checks.  */

  if (flags->delim == DELIM_UNSPECIFIED)
    flags->delim = DELIM_NONE;
  else
    {
      if (flags->form == FORM_UNFORMATTED)
	{
	  generate_error (&opp->common, LIBERROR_OPTION_CONFLICT,
			  "DELIM parameter conflicts with UNFORMATTED form in "
			  "OPEN statement");
	  goto fail;
	}
    }

  if (flags->blank == BLANK_UNSPECIFIED)
    flags->blank = BLANK_NULL;
  else
    {
      if (flags->form == FORM_UNFORMATTED)
	{
	  generate_error (&opp->common, LIBERROR_OPTION_CONFLICT,
			  "BLANK parameter conflicts with UNFORMATTED form in "
			  "OPEN statement");
	  goto fail;
	}
    }

  if (flags->pad == PAD_UNSPECIFIED)
    flags->pad = PAD_YES;
  else
    {
      if (flags->form == FORM_UNFORMATTED)
	{
	  generate_error (&opp->common, LIBERROR_OPTION_CONFLICT,
			  "PAD parameter conflicts with UNFORMATTED form in "
			  "OPEN statement");
	  goto fail;
	}
    }

  if (flags->decimal == DECIMAL_UNSPECIFIED)
    flags->decimal = DECIMAL_POINT;
  else
    {
      if (flags->form == FORM_UNFORMATTED)
	{
	  generate_error (&opp->common, LIBERROR_OPTION_CONFLICT,
			  "DECIMAL parameter conflicts with UNFORMATTED form "
			  "in OPEN statement");
	  goto fail;
	}
    }

  if (flags->encoding == ENCODING_UNSPECIFIED)
    flags->encoding = ENCODING_DEFAULT;
  else
    {
      if (flags->form == FORM_UNFORMATTED)
	{
	  generate_error (&opp->common, LIBERROR_OPTION_CONFLICT,
			  "ENCODING parameter conflicts with UNFORMATTED form in "
			  "OPEN statement");
	  goto fail;
	}
    }

  /* NB: the value for ROUND when it's not specified by the user does not
         have to be PROCESSOR_DEFINED; the standard says that it is
	 processor dependent, and requires that it is one of the
	 possible value (see F2003, 9.4.5.13).  */
  if (flags->round == ROUND_UNSPECIFIED)
    flags->round = ROUND_PROCDEFINED;
  else
    {
      if (flags->form == FORM_UNFORMATTED)
	{
	  generate_error (&opp->common, LIBERROR_OPTION_CONFLICT,
			  "ROUND parameter conflicts with UNFORMATTED form in "
			  "OPEN statement");
	  goto fail;
	}
    }

  if (flags->sign == SIGN_UNSPECIFIED)
    flags->sign = SIGN_PROCDEFINED;
  else
    {
      if (flags->form == FORM_UNFORMATTED)
	{
	  generate_error (&opp->common, LIBERROR_OPTION_CONFLICT,
			  "SIGN parameter conflicts with UNFORMATTED form in "
			  "OPEN statement");
	  goto fail;
	}
    }

  if (flags->position != POSITION_ASIS && flags->access == ACCESS_DIRECT)
   {
     generate_error (&opp->common, LIBERROR_OPTION_CONFLICT,
                     "ACCESS parameter conflicts with SEQUENTIAL access in "
                     "OPEN statement");
     goto fail;
   }
  else
   if (flags->position == POSITION_UNSPECIFIED)
     flags->position = POSITION_ASIS;

  if (flags->access == ACCESS_DIRECT
      && (opp->common.flags & IOPARM_OPEN_HAS_RECL_IN) == 0)
    {
      generate_error (&opp->common, LIBERROR_MISSING_OPTION,
		      "Missing RECL parameter in OPEN statement");
      goto fail;
    }

  if ((opp->common.flags & IOPARM_OPEN_HAS_RECL_IN) && opp->recl_in <= 0)
    {
      generate_error (&opp->common, LIBERROR_BAD_OPTION,
		      "RECL parameter is non-positive in OPEN statement");
      goto fail;
    }

  switch (flags->status)
    {
    case STATUS_SCRATCH:
      if ((opp->common.flags & IOPARM_OPEN_HAS_FILE) == 0)
	{
	  opp->file = NULL;
	  break;
	}

      generate_error (&opp->common, LIBERROR_BAD_OPTION,
		      "FILE parameter must not be present in OPEN statement");
      goto fail;

    case STATUS_OLD:
    case STATUS_NEW:
    case STATUS_REPLACE:
    case STATUS_UNKNOWN:
      if ((opp->common.flags & IOPARM_OPEN_HAS_FILE))
	break;

      opp->file = tmpname;
      opp->file_len = snprintf(opp->file, sizeof (tmpname), "fort.%d", 
			       (int) opp->common.unit);
      break;

    default:
      internal_error (&opp->common, "new_unit(): Bad status");
    }

  /* Make sure the file isn't already open someplace else.
     Do not error if opening file preconnected to stdin, stdout, stderr.  */

  u2 = NULL;
  if ((opp->common.flags & IOPARM_OPEN_HAS_FILE) != 0)
    u2 = find_file (opp->file, opp->file_len);
  if (u2 != NULL
      && (options.stdin_unit < 0 || u2->unit_number != options.stdin_unit)
      && (options.stdout_unit < 0 || u2->unit_number != options.stdout_unit)
      && (options.stderr_unit < 0 || u2->unit_number != options.stderr_unit))
    {
      unlock_unit (u2);
      generate_error (&opp->common, LIBERROR_ALREADY_OPEN, NULL);
      goto cleanup;
    }

  if (u2 != NULL)
    unlock_unit (u2);

  /* Open file.  */

  s = open_external (opp, flags);
  if (s == NULL)
    {
      char *path, *msg;
      size_t msglen;
      path = (char *) gfc_alloca (opp->file_len + 1);
      msglen = opp->file_len + 51;
      msg = (char *) gfc_alloca (msglen);
      unpack_filename (path, opp->file, opp->file_len);

      switch (errno)
	{
	case ENOENT: 
	  snprintf (msg, msglen, "File '%s' does not exist", path);
	  break;

	case EEXIST:
	  snprintf (msg, msglen, "File '%s' already exists", path);
	  break;

	case EACCES:
	  snprintf (msg, msglen, 
		    "Permission denied trying to open file '%s'", path);
	  break;

	case EISDIR:
	  snprintf (msg, msglen, "'%s' is a directory", path);
	  break;

	default:
	  msg = NULL;
	}

      generate_error (&opp->common, LIBERROR_OS, msg);
      goto cleanup;
    }

  if (flags->status == STATUS_NEW || flags->status == STATUS_REPLACE)
    flags->status = STATUS_OLD;

  /* Create the unit structure.  */

  u->file = xmalloc (opp->file_len);
  if (u->unit_number != opp->common.unit)
    internal_error (&opp->common, "Unit number changed");
  u->s = s;
  u->flags = *flags;
  u->read_bad = 0;
  u->endfile = NO_ENDFILE;
  u->last_record = 0;
  u->current_record = 0;
  u->mode = READING;
  u->maxrec = 0;
  u->bytes_left = 0;
  u->saved_pos = 0;

  if (flags->position == POSITION_APPEND)
    {
      if (sseek (u->s, 0, SEEK_END) < 0)
	generate_error (&opp->common, LIBERROR_OS, NULL);
      u->endfile = AT_ENDFILE;
    }

  /* Unspecified recl ends up with a processor dependent value.  */

  if ((opp->common.flags & IOPARM_OPEN_HAS_RECL_IN))
    {
      u->flags.has_recl = 1;
      u->recl = opp->recl_in;
      u->recl_subrecord = u->recl;
      u->bytes_left = u->recl;
    }
  else
    {
      u->flags.has_recl = 0;
      u->recl = max_offset;
      if (compile_options.max_subrecord_length)
	{
	  u->recl_subrecord = compile_options.max_subrecord_length;
	}
      else
	{
	  switch (compile_options.record_marker)
	    {
	    case 0:
	      /* Fall through */
	    case sizeof (GFC_INTEGER_4):
	      u->recl_subrecord = GFC_MAX_SUBRECORD_LENGTH;
	      break;

	    case sizeof (GFC_INTEGER_8):
	      u->recl_subrecord = max_offset - 16;
	      break;

	    default:
	      runtime_error ("Illegal value for record marker");
	      break;
	    }
	}
    }

  /* If the file is direct access, calculate the maximum record number
     via a division now instead of letting the multiplication overflow
     later.  */

  if (flags->access == ACCESS_DIRECT)
    u->maxrec = max_offset / u->recl;
  
  if (flags->access == ACCESS_STREAM)
    {
      u->maxrec = max_offset;
      u->recl = 1;
      u->bytes_left = 1;
      u->strm_pos = stell (u->s) + 1;
    }

  memmove (u->file, opp->file, opp->file_len);
  u->file_len = opp->file_len;

  /* Curiously, the standard requires that the
     position specifier be ignored for new files so a newly connected
     file starts out at the initial point.  We still need to figure
     out if the file is at the end or not.  */

  test_endfile (u);

  if (flags->status == STATUS_SCRATCH && opp->file != NULL)
    free (opp->file);
    
  if (flags->form == FORM_FORMATTED)
    {
      if ((opp->common.flags & IOPARM_OPEN_HAS_RECL_IN))
        fbuf_init (u, u->recl);
      else
        fbuf_init (u, 0);
    }
  else
    u->fbuf = NULL;

    
    
  return u;

 cleanup:

  /* Free memory associated with a temporary filename.  */

  if (flags->status == STATUS_SCRATCH && opp->file != NULL)
    free (opp->file);

 fail:

  close_unit (u);
  return NULL;
}
Example #30
0
static void
start_element(
    GMarkupParseContext *ctx,
    const gchar *tag,
    const gchar **attr_names,
    const gchar **attr_values,
    gpointer ud,
    GError **error)
{
    parse_data_t *pd = (parse_data_t*)ud;
    union
    {
        gint id;
        gpointer pid;
    } id;
    gint ii;

    // Check to see if the first element found has been closed
    // If so, ignore any junk following it.
    if (pd->closed_top)
        return;

    for (ii = 0; ii < TAG_MAP_SZ; ii++)
    {
        if (strcmp(tag, tag_map[ii].tag) == 0)
        {
            id.id = tag_map[ii].id;
            break;
        }
    }
    if (ii == TAG_MAP_SZ)
    {
        g_warning("Unrecognized start tag (%s)", tag);
        return;
    }
    g_queue_push_head(pd->tag_stack, id.pid);
    GType gtype = 0;
    GValue *gval = NULL;
    GValue *current = g_queue_peek_head(pd->stack);
    switch (id.id)
    {
        case R_SECTION:
        {
            const gchar *name;

            name = lookup_attr_value("name", attr_names, attr_values);
            if (name && strcmp(name, "icons") == 0)
            {
                gval = ghb_dict_value_new();
                if (pd->key) g_free(pd->key);
                pd->key = g_strdup(name);
                g_queue_push_head(pd->stack, gval);
            }
        } break;
        case R_ICON:
        {
            gchar *filename;
            const gchar *name;

            name = lookup_attr_value("file", attr_names, attr_values);
            filename = find_file(inc_list, name);
            name = lookup_attr_value("name", attr_names, attr_values);
            if (filename && name)
            {
                ghb_rawdata_t *rd;
                GdkPixbuf *pb;
                GError *err = NULL;

                pb = gdk_pixbuf_new_from_file(filename, &err);
                if (pb == NULL)
                {
                    g_warning("Failed to open icon file %s: %s", filename, err->message);
                    break;
                }
                gval = ghb_dict_value_new();
                int colorspace = gdk_pixbuf_get_colorspace(pb);
                gboolean alpha = gdk_pixbuf_get_has_alpha(pb);
                int width = gdk_pixbuf_get_width(pb);
                int height = gdk_pixbuf_get_height(pb);
                int bps = gdk_pixbuf_get_bits_per_sample(pb);
                int rowstride = gdk_pixbuf_get_rowstride(pb);

                ghb_dict_insert(gval, g_strdup("colorspace"),
                                ghb_int_value_new(colorspace));
                ghb_dict_insert(gval, g_strdup("alpha"),
                                ghb_boolean_value_new(alpha));
                ghb_dict_insert(gval, g_strdup("width"),
                                ghb_int_value_new(width));
                ghb_dict_insert(gval, g_strdup("height"),
                                ghb_int_value_new(height));
                ghb_dict_insert(gval, g_strdup("bps"),
                                ghb_int_value_new(bps));
                ghb_dict_insert(gval, g_strdup("rowstride"),
                                ghb_int_value_new(rowstride));

                rd = g_malloc(sizeof(ghb_rawdata_t));
                rd->data = gdk_pixbuf_get_pixels(pb);
                rd->size = height * rowstride * bps / 8;
                GValue *data = ghb_rawdata_value_new(rd);
                ghb_dict_insert(gval, g_strdup("data"), data);

                if (pd->key) g_free(pd->key);
                pd->key = g_strdup(name);
                g_free(filename);
            }
            else
            {
                g_warning("%s:missing a requried attribute", name);
                exit(EXIT_FAILURE);
            }
        } break;
        case R_PLIST:
        {
            gchar *filename;
            const gchar *name;

            name = lookup_attr_value("file", attr_names, attr_values);
            filename = find_file(inc_list, name);
            name = lookup_attr_value("name", attr_names, attr_values);
            if (filename && name)
            {
                gval = ghb_plist_parse_file(filename);
                if (pd->key) g_free(pd->key);
                pd->key = g_strdup(name);
                g_free(filename);
            }
            else
            {
                g_warning("%s:missing a requried attribute", name);
                exit(EXIT_FAILURE);
            }
        } break;
        case R_STRING:
        {
            gchar *filename;
            const gchar *name;

            name = lookup_attr_value("file", attr_names, attr_values);
            filename = find_file(inc_list, name);
            name = lookup_attr_value("name", attr_names, attr_values);
            if (filename && name)
            {
                gval = read_string_from_file(filename);
                if (pd->key) g_free(pd->key);
                pd->key = g_strdup(name);
                g_free(filename);
            }
            else
            {
                g_warning("%s:missing a requried attribute", name);
                exit(EXIT_FAILURE);
            }
        } break;
    }
    // Add the element to the current container
    if (gval)
    { // There's an element to add
        if (current == NULL)
        {
            pd->plist = gval;
            return;
        }
        gtype = G_VALUE_TYPE(current);
        if (gtype == ghb_array_get_type())
        {
            ghb_array_append(current, gval);
        }
        else if (gtype == ghb_dict_get_type())
        {
            if (pd->key == NULL)
            {
                g_warning("No key for dictionary item");
                ghb_value_free(gval);
            }
            else
            {
                ghb_dict_insert(current, g_strdup(pd->key), gval);
            }
        }
        else
        {
            g_error("Invalid container type. This shouldn't happen");
        }
    }
}