Exemplo n.º 1
0
/* Return 0 if failed */
static int search_hall_number(double origin_shift[3],
			      double conv_lattice[3][3],
			      const int candidates[],
			      const int num_candidates,
			      SPGCONST double primitive_lattice[3][3],
			      SPGCONST Symmetry * symmetry,
			      const double symprec)
{
  int i, hall_number;
  Centering centering;
  Pointgroup pointgroup;
  Symmetry * conv_symmetry;
  int int_transform_mat[3][3];
  double correction_mat[3][3], transform_mat[3][3];

  debug_print("search_hall_number:\n");

  hall_number = 0;
  conv_symmetry = NULL;

  pointgroup = ptg_get_transformation_matrix(int_transform_mat,
					     symmetry->rot,
					     symmetry->size);
  if (pointgroup.number == 0) {
    goto err;
  }

  mat_multiply_matrix_di3(conv_lattice, primitive_lattice, int_transform_mat);

  if (pointgroup.laue == LAUE1) {
    if (! change_basis_tricli(int_transform_mat,
			      conv_lattice,
			      primitive_lattice,
			      symprec)) {
      goto err;
    }
  }

  if (pointgroup.laue == LAUE2M) {
    if (! change_basis_monocli(int_transform_mat,
			       conv_lattice,
			       primitive_lattice,
			       symprec)) {
      goto err;
    }
  }

  if ((centering = get_centering(correction_mat,
				 int_transform_mat,
				 pointgroup.laue)) == CENTERING_ERROR) {
    goto err;
  }

  mat_multiply_matrix_id3(transform_mat, int_transform_mat, correction_mat);
  mat_multiply_matrix_d3(conv_lattice, primitive_lattice, transform_mat);

  if ((conv_symmetry = get_initial_conventional_symmetry(centering,
							 transform_mat,
							 symmetry)) == NULL) {
    goto err;
  }

  for (i = 0; i < num_candidates; i++) {
    if (match_hall_symbol_db(origin_shift,
			     conv_lattice, /* <-- modified only matched */
			     candidates[i],
			     pointgroup.number,
			     pointgroup.holohedry,
			     centering,
			     conv_symmetry,
			     symprec)) {
      hall_number = candidates[i];
      break;
    }
  }

  sym_free_symmetry(conv_symmetry);
  conv_symmetry = NULL;

  return hall_number;

 err:
  return 0;
}
Exemplo n.º 2
0
void * module_load_direct(void * blob, size_t length) {
	Elf32_Header * target = (Elf32_Header *)blob;

	if (target->e_ident[0] != ELFMAG0 ||
		target->e_ident[1] != ELFMAG1 ||
		target->e_ident[2] != ELFMAG2 ||
		target->e_ident[3] != ELFMAG3) {

		debug_print(ERROR, "Module is not a valid ELF object.");

		goto mod_load_error_unload;
	}

	char * shstrtab = NULL;
	char * symstrtab = NULL;
	Elf32_Shdr * sym_shdr = NULL;
	char * deps = NULL;
	size_t deps_length = 0;

	/* TODO: Actually load the ELF somewhere! This is moronic, you're not initializing a BSS! */
	/*       (and maybe keep the elf header somewhere) */

	{
		unsigned int i = 0;
		for (unsigned int x = 0; x < (unsigned int)target->e_shentsize * target->e_shnum; x += target->e_shentsize) {
			Elf32_Shdr * shdr = (Elf32_Shdr *)((uintptr_t)target + (target->e_shoff + x));
			if (i == target->e_shstrndx) {
				shstrtab = (char *)((uintptr_t)target + shdr->sh_offset);
			}
			i++;
		}
	}
	if (!shstrtab) {
		debug_print(ERROR, "Could not locate module section header string table.");
		goto mod_load_error_unload;
	}

	{
		for (unsigned int x = 0; x < (unsigned int)target->e_shentsize * target->e_shnum; x += target->e_shentsize) {
			Elf32_Shdr * shdr = (Elf32_Shdr *)((uintptr_t)target + (target->e_shoff + x));
			if (shdr->sh_type == SHT_STRTAB && (!strcmp((char *)((uintptr_t)shstrtab + shdr->sh_name), ".strtab"))) {
				symstrtab = (char *)((uintptr_t)target + shdr->sh_offset);
			}
		}
	}
	if (!shstrtab) {
		debug_print(ERROR, "Could not locate module symbol string table.");
		goto mod_load_error_unload;
	}

	{
		debug_print(INFO, "Checking dependencies.");
		for (unsigned int x = 0; x < (unsigned int)target->e_shentsize * target->e_shnum; x += target->e_shentsize) {
			Elf32_Shdr * shdr = (Elf32_Shdr *)((uintptr_t)target + (target->e_shoff + x));
			if ((!strcmp((char *)((uintptr_t)shstrtab + shdr->sh_name), "moddeps"))) {
				deps = (char*)((Elf32_Addr)target + shdr->sh_offset);
				deps_length = shdr->sh_size;

				unsigned int i = 0;
				while (i < deps_length) {
					if (strlen(&deps[i]) && !hashmap_get(modules, &deps[i])) {
						debug_print(ERROR, "   %s - not loaded", &deps[i]);
						goto mod_load_error_unload;
					}
					debug_print(INFO, "   %s", &deps[i]);
					i += strlen(&deps[i]) + 1;
				}
			}
		}
	}

	{
		for (unsigned int x = 0; x < (unsigned int)target->e_shentsize * target->e_shnum; x += target->e_shentsize) {
			Elf32_Shdr * shdr = (Elf32_Shdr *)((uintptr_t)target + (target->e_shoff + x));
			if (shdr->sh_type == SHT_SYMTAB) {
				sym_shdr = shdr;
			}
		}
	}
	if (!sym_shdr) {
		debug_print(ERROR, "Could not locate section for symbol table.");
		goto mod_load_error_unload;
	}

	{
		debug_print(INFO, "Loading sections.");
		for (unsigned int x = 0; x < (unsigned int)target->e_shentsize * target->e_shnum; x += target->e_shentsize) {
			Elf32_Shdr * shdr = (Elf32_Shdr *)((uintptr_t)target + (target->e_shoff + x));
			if (shdr->sh_type == SHT_NOBITS) {
				shdr->sh_addr = (Elf32_Addr)malloc(shdr->sh_size);
				memset((void *)shdr->sh_addr, 0x00, shdr->sh_size);
			} else {
				shdr->sh_addr = (Elf32_Addr)target + shdr->sh_offset;
			}
		}
	}

	int undefined = 0;

	hashmap_t * local_symbols = hashmap_create(10);
	{
		Elf32_Sym * table = (Elf32_Sym *)((uintptr_t)target + sym_shdr->sh_offset);
		while ((uintptr_t)table - ((uintptr_t)target + sym_shdr->sh_offset) < sym_shdr->sh_size) {
			if (table->st_name) {
				if (ELF32_ST_BIND(table->st_info) == STB_GLOBAL) {
					char * name = (char *)((uintptr_t)symstrtab + table->st_name);
					if (table->st_shndx == 0) {
						if (!hashmap_get(symboltable, name)) {
							debug_print(ERROR, "Unresolved symbol in module: %s", name);
							undefined = 1;
						}
					} else {
						Elf32_Shdr * s = NULL;
						{
							int i = 0;
							int set = 0;
							for (unsigned int x = 0; x < (unsigned int)target->e_shentsize * target->e_shnum; x += target->e_shentsize) {
								Elf32_Shdr * shdr = (Elf32_Shdr *)((uintptr_t)target + (target->e_shoff + x));
								if (i == table->st_shndx) {
									set = 1;
									s = shdr;
									break;
								}
								i++;
							}
							/*
							 * Common symbols
							 * If we were a proper linker, we'd look at a bunch of objects
							 * to find out if one of them defined this, but instead we have
							 * a strict hierarchy of symbol resolution, so we know that an
							 * undefined common symbol at this point should be immediately
							 * allocated and zeroed.
							 */
							if (!set && table->st_shndx == 65522) {
								if (!hashmap_get(symboltable, name)) {
									void * final = calloc(1, table->st_value);
									debug_print(NOTICE, "point %s to 0x%x", name, (uintptr_t)final);
									hashmap_set(symboltable, name, (void *)final);
									hashmap_set(local_symbols, name, (void *)final);
								}
							}
						}
						if (s) {
							uintptr_t final = s->sh_addr + table->st_value;
							hashmap_set(symboltable, name, (void *)final);
							hashmap_set(local_symbols, name, (void *)final);
						}
					}
				}
			}
			table++;
		}
Exemplo n.º 3
0
static gint sock_connect_with_timeout(gint sock,
				      const struct sockaddr *serv_addr,
				      gint addrlen,
				      guint timeout_secs)
{
	gint ret;

#ifdef G_OS_UNIX
	set_nonblocking_mode(sock, TRUE);
#endif

	ret = connect(sock, serv_addr, addrlen);

#ifdef G_OS_UNIX
	if (ret < 0) {
		if (EINPROGRESS == errno) {
			fd_set fds;
			struct timeval tv;

			tv.tv_sec = timeout_secs;
			tv.tv_usec = 0;
			FD_ZERO(&fds);
			FD_SET(sock, &fds);
			do {
				ret = select(sock + 1, NULL, &fds, NULL, &tv);
			} while (ret < 0 && EINTR == errno);
			if (ret < 0) {
				perror("sock_connect_with_timeout: select");
				return -1;
			} else if (ret == 0) {
				debug_print("sock_connect_with_timeout: timeout\n");
				errno = ETIMEDOUT;
				return -1;
			} else {
				gint val;
				guint len;

				if (FD_ISSET(sock, &fds)) {
					ret = 0;
				} else {
					debug_print("sock_connect_with_timeout: fd not set\n");
					return -1;
				}

				len = sizeof(val);
				if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &val, &len) < 0) {
					perror("sock_connect_with_timeout: getsockopt");
					return -1;
				}
				if (val != 0) {
					debug_print("sock_connect_with_timeout: getsockopt(SOL_SOCKET, SO_ERROR) returned error: %s\n", g_strerror(val));
					return -1;
				}
			}
		} else {
			perror("sock_connect_with_timeout: connect");
			return -1;
		}
	}

	set_nonblocking_mode(sock, FALSE);
#endif

	return ret;
}
Exemplo n.º 4
0
static void exec_autoforward_menu_cb(void)
{
  /* show modal dialog */
  GtkWidget *window;
  GtkWidget *vbox;
  GtkWidget *confirm_area;
  GtkWidget *ok_btn;
  GtkWidget *cancel_btn;
  GtkWidget *hbox;
  GtkWidget *label;
  GtkWidget *radio1;
  GtkWidget *radio2;
  GtkWidget *frame;
  GtkWidget *vbox_cond;
  GtkTreeIter iter;
  GtkTreeViewColumn *column;
  GtkWidget *view;
  GtkWidget *sw;
  GtkWidget *bbox;
  gchar *rcpath;
  gchar *to;
  gsize sz=0;
  GError *errval;
  gchar **folders;
  int nindex;
  
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_container_set_border_width(GTK_CONTAINER(window), 8);
  /*gtk_widget_set_size_request(window, 200, 100);*/
  gtk_window_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  gtk_window_set_modal(GTK_WINDOW(window), TRUE);
  gtk_window_set_policy(GTK_WINDOW(window), FALSE, TRUE, FALSE);
  gtk_widget_realize(window);

  vbox = gtk_vbox_new(FALSE, 6);
  gtk_widget_show(vbox);
  gtk_container_add(GTK_CONTAINER(window), vbox);

  confirm_area = gtk_hbutton_box_new();
  gtk_button_box_set_layout(GTK_BUTTON_BOX(confirm_area), GTK_BUTTONBOX_END);
  gtk_box_set_spacing(GTK_BOX(confirm_area), 6);


  ok_btn = gtk_button_new_from_stock(GTK_STOCK_OK);
  GTK_WIDGET_SET_FLAGS(ok_btn, GTK_CAN_DEFAULT);
  gtk_box_pack_start(GTK_BOX(confirm_area), ok_btn, FALSE, FALSE, 0);
  gtk_widget_show(ok_btn);

  cancel_btn = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
  GTK_WIDGET_SET_FLAGS(cancel_btn, GTK_CAN_DEFAULT);
  gtk_box_pack_start(GTK_BOX(confirm_area), cancel_btn, FALSE, FALSE, 0);
  gtk_widget_show(cancel_btn);

  gtk_widget_show(confirm_area);
	
  gtk_box_pack_end(GTK_BOX(vbox), confirm_area, FALSE, FALSE, 0);
  gtk_widget_grab_default(ok_btn);

  gtk_window_set_title(GTK_WINDOW(window), _("Autoforward Settings [autoforward]"));

  g_signal_connect(G_OBJECT(ok_btn), "clicked",
                   G_CALLBACK(prefs_ok_cb), window);
  g_signal_connect(G_OBJECT(cancel_btn), "clicked",
                   G_CALLBACK(prefs_cancel_cb), window);

  /* email settings */
  hbox = gtk_hbox_new(FALSE, 6);
  gtk_widget_show(hbox);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);

  label = gtk_label_new(_("Forward to(E-mail):"));
  gtk_widget_show(label);
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);

  g_address = gtk_entry_new();
  gtk_widget_show(g_address);
  gtk_box_pack_start(GTK_BOX(hbox), g_address, FALSE, TRUE, 0);

  /* email settings */
  g_startup = gtk_check_button_new_with_label(_("Enable plugin on startup"));
  gtk_widget_show(g_startup);
  gtk_box_pack_start(GTK_BOX(vbox), g_startup, FALSE, FALSE, 0);

#if 0
  g_unreadonly = gtk_check_button_new_with_label(_("Forward unread mail only"));
  gtk_widget_show(g_unreadonly);
  gtk_box_pack_start(GTK_BOX(vbox), g_unreadonly, FALSE, FALSE, 0);
#endif

  /* all */
  radio1 = gtk_radio_button_new_with_label(NULL, _("Forward all mail"));
  /* folder filtered */
  radio2 = gtk_radio_button_new_with_label_from_widget (GTK_RADIO_BUTTON (radio1),
                                                                   _("Forward mail in folder"));

  frame = gtk_frame_new(_("Forward condition:"));
  gtk_widget_show(frame);
  gtk_container_add(GTK_CONTAINER(vbox), frame);
    
  vbox_cond = gtk_vbox_new(FALSE, 6);
  gtk_widget_show(vbox_cond);
  gtk_container_add(GTK_CONTAINER(frame), vbox_cond);
    
  gtk_box_pack_start(GTK_BOX(vbox_cond), radio1, FALSE, FALSE, 6);
  gtk_box_pack_start(GTK_BOX(vbox_cond), radio2, FALSE, FALSE, 6);

  /* treeview */
  g_folders = gtk_list_store_new(1, G_TYPE_STRING);
  
  column = gtk_tree_view_column_new_with_attributes (_("Forward mail in following folder:"),
                                                     gtk_cell_renderer_text_new (),
                                                     "text", 0,
                                                     NULL);
  view=gtk_tree_view_new_with_model(GTK_TREE_MODEL(g_folders));
  gtk_tree_view_append_column (GTK_TREE_VIEW (view), column);
  sw = gtk_scrolled_window_new (NULL, NULL);
  gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
  gtk_container_add (GTK_CONTAINER (sw), view);
  gtk_box_pack_start (GTK_BOX(vbox_cond), sw, TRUE, TRUE, 2);


  /* add and delete */
  bbox = gtk_hbutton_box_new();
  gtk_button_box_set_layout(GTK_BUTTON_BOX(bbox), GTK_BUTTONBOX_END);
  gtk_box_set_spacing(GTK_BOX(bbox), 6);
  g_add_btn = gtk_button_new_from_stock(GTK_STOCK_ADD);
  g_delete_btn = gtk_button_new_from_stock(GTK_STOCK_DELETE);

  gtk_box_pack_start(GTK_BOX(bbox), g_add_btn, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(bbox), g_delete_btn, FALSE, FALSE, 0);
  gtk_widget_show_all(bbox);
    
  gtk_box_pack_end(GTK_BOX(vbox_cond), bbox, FALSE, FALSE, 6);
  gtk_widget_show_all(vbox_cond);
    

  g_signal_connect (g_add_btn, "clicked",
                    G_CALLBACK (add_mail_folder_cb), view);

  g_signal_connect (g_delete_btn, "clicked",
                    G_CALLBACK (delete_mail_folder_cb), view);

  g_signal_connect(GTK_BUTTON(radio1), "clicked",
                   G_CALLBACK(forward_mail_all_cb), view);

  g_signal_connect(GTK_BUTTON(radio2), "clicked",
                   G_CALLBACK(forward_mail_folder_cb), view);

  /* load settings */

  rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "autoforwardrc", NULL);
  g_keyfile = g_key_file_new();
  if (g_key_file_load_from_file(g_keyfile, rcpath, G_KEY_FILE_KEEP_COMMENTS, NULL)){
    g_startup_flg = g_key_file_get_boolean (g_keyfile, "forward", "startup", NULL);
    debug_print("startup:%s\n", g_startup_flg ? "true" : "false");
    if (g_startup_flg){
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g_startup), TRUE);
    }

#if 0
    g_unreadonly_flg = g_key_file_get_boolean (g_keyfile, "forward", "unreadonly", NULL);
    debug_print("unreadonly:%s\n", g_unreadonly_flg ? "true" : "false");
    if (g_unreadonly_flg){
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g_unreadonly), TRUE);
    }
#endif

    to=g_key_file_get_string (g_keyfile, "forward", "to", NULL);
    gtk_entry_set_text(GTK_ENTRY(g_address), to);

    g_forward_flg=g_key_file_get_boolean (g_keyfile, "forward", "all", NULL);
    if (g_forward_flg){
      gtk_widget_set_sensitive(GTK_WIDGET(view), FALSE);
      gtk_widget_set_sensitive(GTK_WIDGET(g_add_btn), FALSE);
      gtk_widget_set_sensitive(GTK_WIDGET(g_delete_btn), FALSE);
    }else{
      g_print("activate view and radio2\n");
      gtk_widget_set_sensitive(GTK_WIDGET(view), TRUE);
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(radio2), TRUE);
    }
    /**/
    
    folders = g_key_file_get_string_list(g_keyfile, "forward", "folder", &sz, &errval);
    if (folders!=NULL){
      nindex=0;
      for (nindex = 0; nindex < sz; nindex++){
        gtk_list_store_append(g_folders, &iter);
        gtk_list_store_set(g_folders, &iter, 0, folders[nindex], -1);
      }
    }
  }else{
    /* default settings */
    g_startup_flg = FALSE;
    g_forward_flg = TRUE;
    gtk_widget_set_sensitive(GTK_WIDGET(view), FALSE);
    gtk_widget_set_sensitive(GTK_WIDGET(g_add_btn), FALSE);
    gtk_widget_set_sensitive(GTK_WIDGET(g_delete_btn), FALSE);
  }
  g_free(rcpath);

  gtk_widget_show(window);
}
Exemplo n.º 5
0
void plugin_load(void)
{
  GtkWidget *mainwin;
  GtkWidget *statusbar;
  GtkWidget *plugin_box;
  GdkPixbuf *on_pixbuf;
  GdkPixbuf *off_pixbuf;
  gchar *rcpath;
  gboolean startup;

  syl_init_gettext("autoforward", "lib/locale");
  
  debug_print(gettext("Auto mail forward Plug-in"));
  debug_print(dgettext("autoforward", "Auto mail forward Plug-in"));

  syl_plugin_add_menuitem("/Tools", _("Autoforward Settings [autoforward]"), exec_autoforward_menu_cb, NULL);

  g_signal_connect(syl_app_get(), "add-msg", G_CALLBACK(exec_autoforward_cb), NULL);

  mainwin = syl_plugin_main_window_get();
  statusbar = syl_plugin_main_window_get_statusbar();
  plugin_box = gtk_hbox_new(FALSE, 0);

  on_pixbuf = gdk_pixbuf_new_from_xpm_data((const char**)online);
  g_plugin_on=gtk_image_new_from_pixbuf(on_pixbuf);
    
  off_pixbuf = gdk_pixbuf_new_from_xpm_data((const char**)offline);
  g_plugin_off=gtk_image_new_from_pixbuf(off_pixbuf);

  gtk_box_pack_start(GTK_BOX(plugin_box), g_plugin_on, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(plugin_box), g_plugin_off, FALSE, FALSE, 0);
    
  g_tooltip = gtk_tooltips_new();
    
  g_onoff_switch = gtk_button_new();
  gtk_button_set_relief(GTK_BUTTON(g_onoff_switch), GTK_RELIEF_NONE);
  GTK_WIDGET_UNSET_FLAGS(g_onoff_switch, GTK_CAN_FOCUS);
  gtk_widget_set_size_request(g_onoff_switch, 20, 20);

  gtk_container_add(GTK_CONTAINER(g_onoff_switch), plugin_box);
  g_signal_connect(G_OBJECT(g_onoff_switch), "clicked",
                   G_CALLBACK(exec_autoforward_onoff_cb), mainwin);
  gtk_box_pack_start(GTK_BOX(statusbar), g_onoff_switch, FALSE, FALSE, 0);

  gtk_widget_show_all(g_onoff_switch);
  gtk_widget_hide(g_plugin_on);
  info.name = g_strdup(_(PLUGIN_NAME));
  info.description = g_strdup(_(PLUGIN_DESC));

  rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "autoforwardrc", NULL);
  g_keyfile = g_key_file_new();
  if (g_key_file_load_from_file(g_keyfile, rcpath, G_KEY_FILE_KEEP_COMMENTS, NULL)){
    startup=g_key_file_get_boolean (g_keyfile, "forward", "startup", NULL);
    debug_print("startup:%s", startup ? "true" : "false");

    if (startup){
      g_enable=TRUE;
      gtk_widget_hide(g_plugin_off);
      gtk_widget_show(g_plugin_on);
      gtk_tooltips_set_tip(g_tooltip, g_onoff_switch,
                           _("Autoforward is enabled. Click the icon to disable plugin."),
                           NULL);
    }
      
    g_free(rcpath);
  }
}
Exemplo n.º 6
0
err_status_t
auth_type_self_test(const auth_type_t *at) {
  auth_test_case_t *test_case = at->test_data;
  auth_t *a;
  err_status_t status;
  uint8_t tag[SELF_TEST_TAG_BUF_OCTETS];
  int i, case_num = 0;

  debug_print(mod_auth, "running self-test for auth function %s", 
	      at->description);
  
  /*
   * check to make sure that we have at least one test case, and
   * return an error if we don't - we need to be paranoid here
   */
  if (test_case == NULL)
    return err_status_cant_check;

  /* loop over all test cases */  
  while (test_case != NULL) {

    /* check test case parameters */
    if (test_case->tag_length_octets > SELF_TEST_TAG_BUF_OCTETS)
      return err_status_bad_param;
    
    /* allocate auth */
    status = auth_type_alloc(at, &a, test_case->key_length_octets,
			     test_case->tag_length_octets);
    if (status)
      return status;
    
    /* initialize auth */
    status = auth_init(a, test_case->key);
    if (status) {
      auth_dealloc(a);
      return status;
    }

    /* zeroize tag then compute */
    octet_string_set_to_zero(tag, test_case->tag_length_octets);
    status = auth_compute(a, test_case->data,
			  test_case->data_length_octets, tag);

    if (status) {
      auth_dealloc(a);
      return status;
    }
    
    debug_print(mod_auth, "key: %s",
		octet_string_hex_string(test_case->key,
					test_case->key_length_octets));
    debug_print(mod_auth, "data: %s",
		octet_string_hex_string(test_case->data,
				   test_case->data_length_octets));
    debug_print(mod_auth, "tag computed: %s",
	   octet_string_hex_string(tag, test_case->tag_length_octets));
    debug_print(mod_auth, "tag expected: %s",
	   octet_string_hex_string(test_case->tag,
				   test_case->tag_length_octets));

    /* check the result */
    status = err_status_ok;
#ifdef CONFIG_RTK_VOIP_DRIVERS_PCM8186
    if ( test_case->tag_length_octets > 12)
    	test_case->tag_length_octets = 12;
#endif    
    for (i=0; i < test_case->tag_length_octets; i++)
      if (tag[i] != test_case->tag[i]) {
	status = err_status_algo_fail;
	debug_print(mod_auth, "test case %d failed", case_num);
	debug_print(mod_auth, "  (mismatch at octet %d)", i);
      }
    if (status) {
      auth_dealloc(a);
      return err_status_algo_fail;
    }
    
    /* deallocate the auth function */
    status = auth_dealloc(a);
    if (status)
      return status;
    
    /* 
     * the auth function passed the test case, so move on to the next test
     * case in the list; if NULL, we'll quit and return an OK
     */   
    test_case = test_case->next_test_case;
    ++case_num;
  }
  
  return err_status_ok;
}
Exemplo n.º 7
0
/*
 * This function allocates a new instance of this crypto engine.
 * The key_len parameter should be one of 30, 38, or 46 for
 * AES-128, AES-192, and AES-256 respectively.  Note, this key_len
 * value is inflated, as it also accounts for the 112 bit salt
 * value.  The tlen argument is for the AEAD tag length, which
 * isn't used in counter mode.
 */
static srtp_err_status_t srtp_aes_icm_openssl_alloc (srtp_cipher_t **c, int key_len, int tlen)
{
    srtp_aes_icm_ctx_t *icm;

    debug_print(srtp_mod_aes_icm, "allocating cipher with key length %d", key_len);

    /*
     * Verify the key_len is valid for one of: AES-128/192/256
     */
    if (key_len != SRTP_AES_128_KEYSIZE_WSALT &&
#ifndef SRTP_NO_AES192
        key_len != SRTP_AES_192_KEYSIZE_WSALT &&
#endif
        key_len != SRTP_AES_256_KEYSIZE_WSALT) {
        return srtp_err_status_bad_param;
    }

    /* allocate memory a cipher of type aes_icm */
    *c = (srtp_cipher_t *)srtp_crypto_alloc(sizeof(srtp_cipher_t));
    if (*c == NULL) {
        return srtp_err_status_alloc_fail;
    }
    memset(*c, 0x0, sizeof(srtp_cipher_t));

    icm = (srtp_aes_icm_ctx_t *)srtp_crypto_alloc(sizeof(srtp_aes_icm_ctx_t));
    if (icm == NULL) {
	srtp_crypto_free(*c);
	*c = NULL;
        return srtp_err_status_alloc_fail;
    }
    memset(icm, 0x0, sizeof(srtp_aes_icm_ctx_t));

    icm->ctx = EVP_CIPHER_CTX_new();
    if (icm->ctx == NULL) {
        srtp_crypto_free(icm);
        srtp_crypto_free(*c);
        *c = NULL;
        return srtp_err_status_alloc_fail;
    }

    /* set pointers */
    (*c)->state = icm;

    /* setup cipher parameters */
    switch (key_len) {
    case SRTP_AES_128_KEYSIZE_WSALT:
        (*c)->algorithm = SRTP_AES_128_ICM;
        (*c)->type = &srtp_aes_icm;
        icm->key_size = SRTP_AES_128_KEYSIZE;
        break;
#ifndef SRTP_NO_AES192
    case SRTP_AES_192_KEYSIZE_WSALT:
        (*c)->algorithm = SRTP_AES_192_ICM;
        (*c)->type = &srtp_aes_icm_192;
        icm->key_size = SRTP_AES_192_KEYSIZE;
        break;
#endif
    case SRTP_AES_256_KEYSIZE_WSALT:
        (*c)->algorithm = SRTP_AES_256_ICM;
        (*c)->type = &srtp_aes_icm_256;
        icm->key_size = SRTP_AES_256_KEYSIZE;
        break;
    }

    /* set key size        */
    (*c)->key_len = key_len;

    return srtp_err_status_ok;
}
Exemplo n.º 8
0
err_status_t
stat_test_rand_source(rand_source_func_t get_rand_bytes) {
#ifndef FIPS140_2
  return 0;
#else
  int i;
  double poker;
  octet_t *data, *data_end;
  uint16_t f[16] = {
    0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0
  };
  octet_t buffer[RAND_SRC_BUF_OCTETS];
  err_status_t status;
  int ones_count = 0;
  uint16_t runs[6] = { 0, 0, 0, 0, 0, 0 }; 
  uint16_t gaps[6] = { 0, 0, 0, 0, 0, 0 };
  uint16_t lo_value[6] = { 2315, 1114, 527, 240, 103, 103 };
  uint16_t hi_value[6] = { 2685, 1386, 723, 384, 209, 209 };
  int16_t  state = 0;
  uint16_t mask;
  
  /* counters for monobit, poker, and runs tests are initialized above */

  /* main loop: fill buffer, update counters for stat tests */
  for (i=0; i < 2500; i+=RAND_SRC_BUF_OCTETS) {
    
    /* fill data buffer */
    status = get_rand_bytes(buffer, RAND_SRC_BUF_OCTETS);
    if (status) {
	  debug_print(mod_stat, "couldn't get rand bytes: %d",status);
      return status;
	}

#if 0
    debug_print(mod_stat, "%s", 
		octet_string_hex_string(buffer, RAND_SRC_BUF_OCTETS));
#endif
  
    data = buffer;
    data_end = data + RAND_SRC_BUF_OCTETS;
    while (data < data_end) {

      /* update monobit test counter */
      ones_count += octet_get_weight(*data);

      /* update poker test counters */
      f[*data & 0x0f]++;    /* increment freq. count for low nibble  */
      f[(*data) >> 4]++;    /* increment freq. count for high nibble */

      /* update runs test counters */
      /* loop over the bits of this byte */
      for (mask = 1; mask < 256; mask <<= 1) {
	if (*data & mask) {
	  
	  /* next bit is a one  */
	  if (state > 0) {
	    
	    /* prefix is a run, so increment the run-count  */
	    state++;                          
	    
	    /* check for long runs */ 
	    if (state > 25) {
		  debug_print(mod_stat, ">25 runs (3): %d", state);
	      return err_status_algo_fail;
		}
	    
	  } else if (state < 0) {
	    
	    /* prefix is a gap  */
	    if (state < -25) {
		  debug_print(mod_stat, ">25 gaps (3): %d", state);
	      return err_status_algo_fail;    /* long-runs test failed   */
	    }
	    if (state < -6) {
	      state = -6;                     /* group together gaps > 5 */
	    }
	    gaps[-1-state]++;                 /* increment gap count      */
	    state = 1;                        /* set state at one set bit */
	  } else {
	    
	    /* state is zero; this happens only at initialization        */
	    state = 1;            
	  }
	} else {
	  
	  /* next bit is a zero  */
	  if (state > 0) {
	    
	    /* prefix is a run */
	    if (state > 25) {
		  debug_print(mod_stat, ">25 runs (4): %d", state);
	      return err_status_algo_fail;    /* long-runs test failed   */
	    }
	    if (state > 6) {
	      state = 6;                      /* group together runs > 5 */
	    }
	    runs[state-1]++;                  /* increment run count       */
	    state = -1;                       /* set state at one zero bit */
	  } else if (state < 0) {
	    
	    /* prefix is a gap, so increment gap-count (decrement state) */
	    state--;
	    
	    /* check for long gaps */ 
	    if (state < -25) {
		  debug_print(mod_stat, ">25 gaps (4): %d", state);
	      return err_status_algo_fail;
		}
	    
	  } else {
	    
	    /* state is zero; this happens only at initialization        */
	    state = -1;
	  }
	}
      }
      
      /* advance data pointer */
      data++;
    }
  }

  /* check to see if test data is within bounds */

  /* check monobit test data */

  debug_print(mod_stat, "stat: bit count: %d", ones_count);
  
  if ((ones_count < 9725) || (ones_count > 10275)) {
    debug_print(mod_stat, "stat: failed monobit test %d", ones_count);
    return err_status_algo_fail;
  }
  
  /* check poker test data */
  poker = 0.0;
  for (i=0; i < 16; i++) 
    poker += (double) f[i] * f[i];

  poker *= (16.0 / 5000.0);
  poker -= 5000.0;

  debug_print(mod_stat, "stat: poker test: %f", poker);
    
  if ((poker < 2.16) || (poker > 46.17)) {
      debug_print(mod_stat, "stat: failed poker test", NULL);
    return err_status_algo_fail;
  }

  /* check run and gap counts against the fixed limits */
  for (i=0; i < 6; i++) 
    if ((runs[i] < lo_value[i] ) || (runs[i] > hi_value[i])
	 || (gaps[i] < lo_value[i] ) || (gaps[i] > hi_value[i])) {
      debug_print(mod_stat, "stat: failed run/gap test", NULL);
      return err_status_algo_fail; 
    }

  debug_print(mod_stat, "passed random stat test", NULL);
  return err_status_ok;
#endif
}
Exemplo n.º 9
0
err_status_t
stat_test_runs(octet_t *data) {
  octet_t *data_end = data + STAT_TEST_DATA_LEN;
  uint16_t runs[6] = { 0, 0, 0, 0, 0, 0 }; 
  uint16_t gaps[6] = { 0, 0, 0, 0, 0, 0 };
  uint16_t lo_value[6] = { 2315, 1114, 527, 240, 103, 103 };
  uint16_t hi_value[6] = { 2685, 1386, 723, 384, 209, 209 };
  int16_t  state = 0;
  uint16_t mask;
  int i;
  
  /*
   * the state variable holds the number of bits in the
   * current run (or gap, if negative)
   */
  
  while (data < data_end) {

    /* loop over the bits of this byte */
    for (mask = 1; mask < 256; mask <<= 1) {
      if (*data & mask) {

 	/* next bit is a one  */
	if (state > 0) {

	  /* prefix is a run, so increment the run-count  */
	  state++;                          

	  /* check for long runs */ 
	  if (state > 25) {
		debug_print(mod_stat, ">25 runs: %d", state);
		return err_status_algo_fail;
	  }

	} else if (state < 0) {

	  /* prefix is a gap  */
	  if (state < -25) {
		debug_print(mod_stat, ">25 gaps: %d", state);
	    return err_status_algo_fail;    /* long-runs test failed   */
	  }
	  if (state < -6) {
	    state = -6;                     /* group together gaps > 5 */
	  }
	  gaps[-1-state]++;                 /* increment gap count      */
          state = 1;                        /* set state at one set bit */
	} else {

	  /* state is zero; this happens only at initialization        */
	  state = 1;            
	}
      } else {

	/* next bit is a zero  */
	if (state > 0) {

	  /* prefix is a run */
	  if (state > 25) {
		debug_print(mod_stat, ">25 runs (2): %d", state);
	    return err_status_algo_fail;    /* long-runs test failed   */
	  }
	  if (state > 6) {
	    state = 6;                      /* group together runs > 5 */
	  }
	  runs[state-1]++;                  /* increment run count       */
          state = -1;                       /* set state at one zero bit */
	} else if (state < 0) {

	  /* prefix is a gap, so increment gap-count (decrement state) */
	  state--;

	  /* check for long gaps */ 
	  if (state < -25) {
		debug_print(mod_stat, ">25 gaps (2): %d", state);
	    return err_status_algo_fail;
	  }

	} else {

	  /* state is zero; this happens only at initialization        */
	  state = -1;
	}
      }
    }

    /* move along to next octet */
    data++;
  }

  if (mod_stat.on) {
    debug_print(mod_stat, "runs test", NULL);
    for (i=0; i < 6; i++)
      debug_print(mod_stat, "  runs[]: %d", runs[i]);
    for (i=0; i < 6; i++)
      debug_print(mod_stat, "  gaps[]: %d", gaps[i]);
  }

  /* check run and gap counts against the fixed limits */
  for (i=0; i < 6; i++) 
    if (   (runs[i] < lo_value[i] ) || (runs[i] > hi_value[i])
	|| (gaps[i] < lo_value[i] ) || (gaps[i] > hi_value[i]))
      return err_status_algo_fail;

  
  return err_status_ok;
}
err_status_t cipher_type_self_test(const cipher_type_t *ct) {
    const cipher_test_case_t *test_case = ct->test_data;
    cipher_t *c;
    err_status_t status;
    uint8_t buffer[SELF_TEST_BUF_OCTETS];
    uint8_t buffer2[SELF_TEST_BUF_OCTETS];
    unsigned int len;
    int i, j, case_num = 0;

    debug_print(mod_cipher, "running self-test for cipher %s", ct->description);

    /*
     * check to make sure that we have at least one test case, and
     * return an error if we don't - we need to be paranoid here
     */
    if (test_case == NULL)
        return err_status_cant_check;

    /*
     * loop over all test cases, perform known-answer tests of both the
     * encryption and decryption functions
     */
    while (test_case != NULL) {

        /* allocate cipher */
        status = cipher_type_alloc(ct, &c, test_case->key_length_octets);
        if (status)
            return status;

        /*
         * test the encrypt function
         */
        debug_print(mod_cipher, "testing encryption", NULL);

        /* initialize cipher */
        status = cipher_init(c, test_case->key, direction_encrypt);
        if (status) {
            cipher_dealloc(c);
            return status;
        }

        /* copy plaintext into test buffer */
        if (test_case->ciphertext_length_octets > SELF_TEST_BUF_OCTETS) {
            cipher_dealloc(c);
            return err_status_bad_param;
        }
        for (i = 0; i < test_case->plaintext_length_octets; i++)
            buffer[i] = test_case->plaintext[i];

        debug_print(mod_cipher, "plaintext:    %s", octet_string_hex_string(
                buffer, test_case->plaintext_length_octets));

        /* set the initialization vector */
        status = cipher_set_iv(c, test_case->idx);
        if (status) {
            cipher_dealloc(c);
            return status;
        }

        /* encrypt */
        len = test_case->plaintext_length_octets;
        status = cipher_encrypt(c, buffer, &len);
        if (status) {
            cipher_dealloc(c);
            return status;
        }

        debug_print(mod_cipher, "ciphertext:   %s", octet_string_hex_string(
                buffer, test_case->ciphertext_length_octets));

        /* compare the resulting ciphertext with that in the test case */
        if (len != test_case->ciphertext_length_octets)
            return err_status_algo_fail;
        status = err_status_ok;
        for (i = 0; i < test_case->ciphertext_length_octets; i++)
            if (buffer[i] != test_case->ciphertext[i]) {
                status = err_status_algo_fail;
                debug_print(mod_cipher, "test case %d failed", case_num);
                debug_print(mod_cipher, "(failure at byte %d)", i);
                break;
            }
        if (status) {

            debug_print(mod_cipher, "c computed: %s", octet_string_hex_string(
                    buffer, 2 * test_case->plaintext_length_octets));
            debug_print(mod_cipher, "c expected: %s", octet_string_hex_string(
                    test_case->ciphertext, 2
                            * test_case->plaintext_length_octets));

            cipher_dealloc(c);
            return err_status_algo_fail;
        }

        /*
         * test the decrypt function
         */
        debug_print(mod_cipher, "testing decryption", NULL);

        /* re-initialize cipher for decryption */
        status = cipher_init(c, test_case->key, direction_decrypt);
        if (status) {
            cipher_dealloc(c);
            return status;
        }

        /* copy ciphertext into test buffer */
        if (test_case->ciphertext_length_octets > SELF_TEST_BUF_OCTETS) {
            cipher_dealloc(c);
            return err_status_bad_param;
        }
        for (i = 0; i < test_case->ciphertext_length_octets; i++)
            buffer[i] = test_case->ciphertext[i];

        debug_print(mod_cipher, "ciphertext:    %s", octet_string_hex_string(
                buffer, test_case->plaintext_length_octets));

        /* set the initialization vector */
        status = cipher_set_iv(c, test_case->idx);
        if (status) {
            cipher_dealloc(c);
            return status;
        }

        /* decrypt */
        len = test_case->ciphertext_length_octets;
        status = cipher_decrypt(c, buffer, &len);
        if (status) {
            cipher_dealloc(c);
            return status;
        }

        debug_print(mod_cipher, "plaintext:   %s", octet_string_hex_string(
                buffer, test_case->plaintext_length_octets));

        /* compare the resulting plaintext with that in the test case */
        if (len != test_case->plaintext_length_octets)
            return err_status_algo_fail;
        status = err_status_ok;
        for (i = 0; i < test_case->plaintext_length_octets; i++)
            if (buffer[i] != test_case->plaintext[i]) {
                status = err_status_algo_fail;
                debug_print(mod_cipher, "test case %d failed", case_num);
                debug_print(mod_cipher, "(failure at byte %d)", i);
            }
        if (status) {

            debug_print(mod_cipher, "p computed: %s", octet_string_hex_string(
                    buffer, 2 * test_case->plaintext_length_octets));
            debug_print(mod_cipher, "p expected: %s", octet_string_hex_string(
                    test_case->plaintext, 2
                            * test_case->plaintext_length_octets));

            cipher_dealloc(c);
            return err_status_algo_fail;
        }

        /* deallocate the cipher */
        status = cipher_dealloc(c);
        if (status)
            return status;

        /*
         * the cipher passed the test case, so move on to the next test
         * case in the list; if NULL, we'l proceed to the next test
         */
        test_case = test_case->next_test_case;
        ++case_num;
    }

    /* now run some random invertibility tests */

    /* allocate cipher, using paramaters from the first test case */
    test_case = ct->test_data;
    status = cipher_type_alloc(ct, &c, test_case->key_length_octets);
    if (status)
        return status;

    rand_source_init();

    for (j = 0; j < NUM_RAND_TESTS; j++) {
        unsigned length;
        int plaintext_len;
        uint8_t key[MAX_KEY_LEN];
        uint8_t iv[MAX_KEY_LEN];

        /* choose a length at random (leaving room for IV and padding) */
        length = rand() % (SELF_TEST_BUF_OCTETS - 64);
        debug_print(mod_cipher, "random plaintext length %d\n", length);
        status = rand_source_get_octet_string(buffer, length);
        if (status)
            return status;

        debug_print(mod_cipher, "plaintext:    %s", octet_string_hex_string(
                buffer, length));

        /* copy plaintext into second buffer */
        for (i = 0; (unsigned int) i < length; i++)
            buffer2[i] = buffer[i];

        /* choose a key at random */
        if (test_case->key_length_octets > MAX_KEY_LEN)
            return err_status_cant_check;
        status
                = rand_source_get_octet_string(key,
                        test_case->key_length_octets);
        if (status)
            return status;

        /* chose a random initialization vector */
        status = rand_source_get_octet_string(iv, MAX_KEY_LEN);
        if (status)
            return status;

        /* initialize cipher */
        status = cipher_init(c, key, direction_encrypt);
        if (status) {
            cipher_dealloc(c);
            return status;
        }

        /* set initialization vector */
        status = cipher_set_iv(c, test_case->idx);
        if (status) {
            cipher_dealloc(c);
            return status;
        }

        /* encrypt buffer with cipher */
        plaintext_len = length;
        status = cipher_encrypt(c, buffer, &length);
        if (status) {
            cipher_dealloc(c);
            return status;
        }
        debug_print(mod_cipher, "ciphertext:   %s", octet_string_hex_string(
                buffer, length));

        /*
         * re-initialize cipher for decryption, re-set the iv, then
         * decrypt the ciphertext
         */
        status = cipher_init(c, key, direction_decrypt);
        if (status) {
            cipher_dealloc(c);
            return status;
        }
        status = cipher_set_iv(c, test_case->idx);
        if (status) {
            cipher_dealloc(c);
            return status;
        }
        status = cipher_decrypt(c, buffer, &length);
        if (status) {
            cipher_dealloc(c);
            return status;
        }

        debug_print(mod_cipher, "plaintext[2]: %s", octet_string_hex_string(
                buffer, length));

        /* compare the resulting plaintext with the original one */
        if (length != plaintext_len)
            return err_status_algo_fail;
        status = err_status_ok;
        for (i = 0; i < plaintext_len; i++)
            if (buffer[i] != buffer2[i]) {
                status = err_status_algo_fail;
                debug_print(mod_cipher, "random test case %d failed", case_num);
                debug_print(mod_cipher, "(failure at byte %d)", i);
            }
        if (status) {
            cipher_dealloc(c);
            return err_status_algo_fail;
        }

    }

    return err_status_ok;
}
Exemplo n.º 11
0
/** 
 * Dispatch an object to its content and write out
 */
static inline void _Disassembler_dispatch(pVMObject o) {
    //dispatch
    // can't switch() objects, so:
    if(!o) return; // NULL isn't interesting.
    else if(o == nil_object)
        debug_print("{Nil}");
    else if(o == true_object)
        debug_print("{True}");
    else if(o == false_object)
        debug_print("{False}"); 
    else if((pVMClass)o == system_class)
        debug_print("{System Class object}");
    else if((pVMClass)o == block_class)
        debug_print("{Block Class object}");
    else if(o == Universe_get_global(Universe_symbol_for("system")))
        debug_print("{System}");
    else {
        pVMClass c = SEND(o, get_class);
        if(c == string_class) {
            debug_print("\"%s\"", SEND((pVMString)o, get_chars));
        } else if(c == double_class)
            debug_print("%g", SEND((pVMDouble)o, get_embedded_double));
        else if(c == integer_class)
            debug_print("%lld", SEND((pVMInteger)o, get_embedded_integer));
        else if(c == symbol_class) {
            debug_print("#%s", SEND((pVMSymbol)o, get_chars));
        } else
            debug_print("address: %p", (void*)o);
    }
}
Exemplo n.º 12
0
gint plugin_init(gchar **error)
{
  gchar *rcpath;

  /* Version check */
  /* No be able to test against new-contacts */
  if(!check_plugin_version(MAKE_NUMERIC_VERSION(3,8,1,46),
			   VERSION_NUMERIC, _("Notification"), error))
    return -1;

  /* Check if threading is enabled */
  if(!g_thread_supported()) {
    *error = g_strdup(_("The Notification plugin needs threading support."));
    return -1;
  }

  hook_f_item = hooks_register_hook(FOLDER_ITEM_UPDATE_HOOKLIST,
				    my_folder_item_update_hook, NULL);
  if(hook_f_item == (guint) -1) {
    *error = g_strdup(_("Failed to register folder item update hook in the "
			"Notification plugin"));
    return -1;
  }

  hook_f = hooks_register_hook(FOLDER_UPDATE_HOOKLIST,
			       my_folder_update_hook, NULL);
  if(hook_f == (guint) -1) {
    *error = g_strdup(_("Failed to register folder update hook in the "
			"Notification plugin"));
    hooks_unregister_hook(FOLDER_ITEM_UPDATE_HOOKLIST, hook_f_item);
    return -1;
  }


  hook_m_info = hooks_register_hook(MSGINFO_UPDATE_HOOKLIST,
				    my_msginfo_update_hook, NULL);
  if(hook_m_info == (guint) -1) {
    *error = g_strdup(_("Failed to register msginfo update hook in the "
			"Notification plugin"));
    hooks_unregister_hook(FOLDER_ITEM_UPDATE_HOOKLIST, hook_f_item);
    hooks_unregister_hook(FOLDER_UPDATE_HOOKLIST, hook_f);
    return -1;
  }

  hook_offline = hooks_register_hook(OFFLINE_SWITCH_HOOKLIST,
				     my_offline_switch_hook, NULL);
  if(hook_offline == (guint) -1) {
    *error = g_strdup(_("Failed to register offline switch hook in the "
			"Notification plugin"));
    hooks_unregister_hook(FOLDER_ITEM_UPDATE_HOOKLIST, hook_f_item);
    hooks_unregister_hook(FOLDER_UPDATE_HOOKLIST, hook_f);
    hooks_unregister_hook(MSGINFO_UPDATE_HOOKLIST, hook_m_info);
    return -1;
  }

  hook_mw_close = hooks_register_hook(MAIN_WINDOW_CLOSE,
				      my_main_window_close_hook, NULL);
  if(hook_mw_close == (guint) -1) {
    *error = g_strdup(_("Failed to register main window close hook in the "
			"Notification plugin"));
    hooks_unregister_hook(FOLDER_ITEM_UPDATE_HOOKLIST, hook_f_item);
    hooks_unregister_hook(FOLDER_UPDATE_HOOKLIST, hook_f);
    hooks_unregister_hook(MSGINFO_UPDATE_HOOKLIST, hook_m_info);
    hooks_unregister_hook(OFFLINE_SWITCH_HOOKLIST, hook_offline);
    return -1;
  }

  hook_got_iconified = hooks_register_hook(MAIN_WINDOW_GOT_ICONIFIED,
					   my_main_window_got_iconified_hook,
					   NULL);
  if(hook_got_iconified == (guint) -1) {
    *error = g_strdup(_("Failed to register got iconified hook in the "
			"Notification plugin"));
    hooks_unregister_hook(FOLDER_ITEM_UPDATE_HOOKLIST, hook_f_item);
    hooks_unregister_hook(FOLDER_UPDATE_HOOKLIST, hook_f);
    hooks_unregister_hook(MSGINFO_UPDATE_HOOKLIST, hook_m_info);
    hooks_unregister_hook(OFFLINE_SWITCH_HOOKLIST, hook_offline);
    hooks_unregister_hook(MAIN_WINDOW_CLOSE, hook_mw_close);
    return -1;
  }

  hook_account = hooks_register_hook(ACCOUNT_LIST_CHANGED_HOOKLIST,
				     my_account_list_changed_hook, NULL);
  if (hook_account == (guint) -1) {
    *error = g_strdup(_("Failed to register account list changed hook in the "
			"Notification plugin"));
    hooks_unregister_hook(FOLDER_ITEM_UPDATE_HOOKLIST, hook_f_item);
    hooks_unregister_hook(FOLDER_UPDATE_HOOKLIST, hook_f);
    hooks_unregister_hook(MSGINFO_UPDATE_HOOKLIST, hook_m_info);
    hooks_unregister_hook(OFFLINE_SWITCH_HOOKLIST, hook_offline);
    hooks_unregister_hook(MAIN_WINDOW_CLOSE, hook_mw_close);
    hooks_unregister_hook(MAIN_WINDOW_GOT_ICONIFIED, hook_got_iconified);
    return -1;
  }

  hook_theme_changed = hooks_register_hook(THEME_CHANGED_HOOKLIST, my_update_theme_hook, NULL);
  if(hook_theme_changed == (guint)-1) {
    *error = g_strdup(_("Failed to register theme change hook in the "
      "Notification plugin"));
    hooks_unregister_hook(FOLDER_ITEM_UPDATE_HOOKLIST, hook_f_item);
    hooks_unregister_hook(FOLDER_UPDATE_HOOKLIST, hook_f);
    hooks_unregister_hook(MSGINFO_UPDATE_HOOKLIST, hook_m_info);
    hooks_unregister_hook(OFFLINE_SWITCH_HOOKLIST, hook_offline);
    hooks_unregister_hook(MAIN_WINDOW_CLOSE, hook_mw_close);
    hooks_unregister_hook(MAIN_WINDOW_GOT_ICONIFIED, hook_got_iconified);
    hooks_unregister_hook(ACCOUNT_LIST_CHANGED_HOOKLIST, hook_account);
    return -1;
  }

  /* Configuration */
  prefs_set_default(notify_param);
  rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, COMMON_RC, NULL);
  prefs_read_config(notify_param, "NotificationPlugin", rcpath, NULL);
  g_free(rcpath);

  /* Folder specific stuff */
  notification_foldercheck_read_array();

  notification_notified_hash_startup_init();

  notify_gtk_init();

#ifdef NOTIFICATION_BANNER
  notification_update_banner();
#endif
#ifdef NOTIFICATION_LCDPROC
  notification_lcdproc_connect();
#endif
#ifdef NOTIFICATION_TRAYICON
  if(notify_config.trayicon_enabled &&
		 notify_config.trayicon_hide_at_startup && claws_is_starting()) {
    MainWindow *mainwin = mainwindow_get_mainwindow();

		g_idle_add(trayicon_startup_idle,NULL);
    if(mainwin && gtk_widget_get_visible(GTK_WIDGET(mainwin->window)))
      main_window_hide(mainwin);
    main_set_show_at_startup(FALSE);
  }
#endif
  my_account_list_changed_hook(NULL,NULL);

  if(notify_config.urgency_hint_new || notify_config.urgency_hint_unread)
	notification_update_msg_counts(NULL);

#ifdef NOTIFICATION_HOTKEYS
  notification_hotkeys_update_bindings();
#endif

  debug_print("Notification plugin loaded\n");

  return 0;
}
Exemplo n.º 13
0
int createTaskList(int devSelection){ //There exist only one l_taskList per Node and each task has a device.

int i,j;
//taskDevMap=malloc(clXplr.numDevices*sizeof(device_Task_Info));

int numDecls=getNumDecls(); //this first step enables to get the number of lines with matchmaking decls.
taskDevMap=malloc(numDecls*sizeof(device_Task_Info));

for (i = 0; i < numDecls; i++) {
			taskDevMap[i].min_tskIdx=-1; //By default each device has no assigned task.
}

readTaskBinding(taskDevMap); //function defined in taskScheduling.c to read taskSched.cfg file.

debug_print("1.- read taskDevMap succeed!!\n");


	switch (devSelection) {
	case ALL_DEVICES:
		//here we allocate space for the local l_taskList.
		l_taskList = (XCLtask*) malloc(sizeof(XCLtask) * l_numTasks);

		//Each task needs a handler (pointer) to its device
		for (i = 0; i < l_numTasks; i++) {
			l_taskList[i].device = (Device*) malloc(1*sizeof(Device)); //each task has only 1 device.
		}

		//int advance=0;
		//Here we fill the l_taskList and create the memory RackIDs.
		//for (i = 0; i <l_numTasks; i++) {
		for (i = 0; i <numDecls; i++) {
			//advance=taskDevMap[i].max_tskIdx-taskDevMap[i].min_tskIdx+1;
			if(taskDevMap[i].min_tskIdx!=(-1))//perform resource allocation iff has any assign.
			for (j = taskDevMap[i].min_tskIdx; j <= taskDevMap[i].max_tskIdx;j++) {
				debug_print("-----matching task %d , %d- %d ------\n",j,taskDevMap[i].min_tskIdx,taskDevMap[i].max_tskIdx);

				l_taskList[j].device = taskDevMap[i].mappedDevice;
				l_taskList[j].numTrays = 0;

				//here we query how many racks has this device.
				int rackIdx = l_taskList[j].device[0].numRackIDs;
				if (rackIdx == 0) {
					l_taskList[j].device[0].memHandler = malloc(1 * sizeof(cl_mem*));
					//l_taskList[j].device[0].memHandler[0] = malloc(1 * sizeof(cl_mem));
					l_taskList[j].RackID = rackIdx; //rack assignment
					l_taskList[j].device[0].numRackIDs++;
				} else {
					cl_mem** tmpRackID;
					tmpRackID = (cl_mem**) realloc(l_taskList[j].device[0].memHandler,(rackIdx + 1) * sizeof(cl_mem*));
					if (tmpRackID != NULL) {
						l_taskList[j].RackID = rackIdx;
						l_taskList[j].device[0].memHandler = tmpRackID;
						l_taskList[j].device[0].numRackIDs++;
					} else {
						printf("ERROR AT: Reallocating racks. %d , %d",	__FILE__, __LINE__);
					}
				}
			}

		}

		break;



	case CPU_DEVICES:
		//l_numTasks = 4;
		printf("CPU EXEC\n");
		l_taskList = (XCLtask*) malloc(sizeof(XCLtask) * l_numTasks);


		for (i = 0; i < l_numTasks; i++) {
			l_taskList[i].device = (Device*) malloc(sizeof(Device));
			l_taskList[i].device = cpu[0];//TODO: switch device number.
			l_taskList[i].numTrays = 0; //init the number of device memBuffers to zero

			int rackIdx = l_taskList[i].device[0].numRackIDs;
			if (rackIdx == 0) {
				l_taskList[i].device[0].memHandler = malloc(1 * sizeof(cl_mem*));
				l_taskList[i].RackID = rackIdx;
				l_taskList[i].device[0].numRackIDs++;
			} else {
				cl_mem** tmpRackID;
				tmpRackID = (cl_mem**) realloc(l_taskList[i].device[0].memHandler,
						(rackIdx + 1) * sizeof(cl_mem*));
				if (tmpRackID != NULL) {
					l_taskList[i].RackID = rackIdx;
					l_taskList[i].device[0].memHandler = tmpRackID;
					l_taskList[i].device[0].numRackIDs++;
				} else {
					printf("ERROR AT: Reallocating racks. %d , %d", __FILE__,
							__LINE__);
				}
			}

			//l_taskList[i].RackID=i;
			//l_taskList[i].device[0].numRackIDs++;
		}
		break;

	case GPU_DEVICES:
		//l_numTasks = 4;
		printf("GPU EXEC\n");
		l_taskList = (XCLtask*) malloc(sizeof(XCLtask) * l_numTasks);

		for (i = 0; i < l_numTasks; i++) {
			l_taskList[i].device = (Device*) malloc(sizeof(Device));
			l_taskList[i].device = gpu[0]; //TODO: switch device number.
			l_taskList[i].numTrays = 0; //init the number of device memBuffers to zero

			//here we query how many racks has this device.
			int rackIdx = l_taskList[i].device[0].numRackIDs;
			if (rackIdx == 0) {
				l_taskList[i].device[0].memHandler = malloc(1 * sizeof(cl_mem*));
				//l_taskList[i].device[0].memHandler[0]=malloc(1*sizeof(cl_mem));
				l_taskList[i].RackID = rackIdx;
				l_taskList[i].device[0].numRackIDs++;
			} else {
				cl_mem** tmpRackID;
				tmpRackID = (cl_mem**) realloc(l_taskList[i].device[0].memHandler,
						(rackIdx + 1) * sizeof(cl_mem*));
				if (tmpRackID != NULL) {
					l_taskList[i].RackID = rackIdx;
					l_taskList[i].device[0].memHandler = tmpRackID;
					l_taskList[i].device[0].numRackIDs++;
				} else {
					printf("ERROR AT: Reallocating racks. %d , %d", __FILE__,
							__LINE__);
				}
			}
		}

		break;

	case ACC_DEVICES:
		//l_numTasks = clXplr.numACCEL;
		l_taskList = (XCLtask*) malloc(sizeof(XCLtask) * l_numTasks);

		for (i = 0; i < l_numTasks; i++) {
			l_taskList[i].device = (Device*) malloc(sizeof(Device));
			l_taskList[i].device = accel[i];
			l_taskList[i].numTrays=0;//init the number of device memBuffers to zero
			//here we query how many racks has this device.
			int rackIdx = l_taskList[i].device[0].numRackIDs;
			if (rackIdx == 0) {
				l_taskList[i].device[0].memHandler = malloc(1 * sizeof(cl_mem*));
				//l_taskList[i].device[0].memHandler[0]=malloc(1*sizeof(cl_mem));
				l_taskList[i].RackID = rackIdx;
				l_taskList[i].device[0].numRackIDs++;
			} else {
				cl_mem** tmpRackID;
				tmpRackID = (cl_mem**) realloc(l_taskList[i].device[0].memHandler,
						(rackIdx + 1) * sizeof(cl_mem*));
				if (tmpRackID != NULL) {
					l_taskList[i].RackID = rackIdx;
					l_taskList[i].device[0].memHandler = tmpRackID;
					l_taskList[i].device[0].numRackIDs++;
				} else {
					printf("ERROR AT: Reallocating racks. %d , %d", __FILE__,
							__LINE__);
				}
			}

		}

		break;

	default:
		break;
	}
return 0;


}
// NB : matrix is passed in Column-Major storage. 
void
lod_cn_travelling_wave(double* const inout_matrix,
                       const int space_nb_x,
                       const int space_nb_y,
                       const double final_time,
                       const double tau,
                       const double eps)
{
  double h_x = 1./((double)space_nb_x-1.), h_y = 1./((double)space_nb_y-1.);
  Eigen::VectorXd x_border, y_border, x(space_nb_x), y(space_nb_y);
  Eigen::MatrixXd values, after_x, after_y, after_reaction;
  Eigen::SparseMatrix<double> operator_x, operator_y, laplace_x, unit_matrix_x, laplace_y, unit_matrix_y;

  // Boundaries.
  x_border.setLinSpaced(space_nb_x, 0., 1.);
  y_border.setLinSpaced(space_nb_y, 0., 1.);
  // Initial values.
  initial_values(values, x_border, y_border, eps);
  // Operators initialization;
  laplace_operator_1d(laplace_x, space_nb_x);
  identity_operator(unit_matrix_x, space_nb_x);
  laplace_operator_1d(laplace_y, space_nb_y);
  identity_operator(unit_matrix_y, space_nb_y);
  space_operator(operator_x, laplace_x, (tau*eps)/(h_x*h_x), unit_matrix_x);
  space_operator(operator_y, laplace_y, (tau*eps)/(h_y*h_y), unit_matrix_y);
#ifdef DEBUG_LOD_CN
debug_print("init values", values, 5, 5);
debug_print("laplace x", laplace_x, 5, 5);
debug_print("I x", unit_matrix_x, 5, 5);
debug_print("laplace y", laplace_y, 5, 5);
debug_print("I y", unit_matrix_y, 5, 5);
debug_print("Op x", operator_x, 5, 5);
debug_print("Op y", operator_y, 5, 5);
#endif

  double time = 0.;
  const double tcoeff = 1.;
  while (time < final_time)
  {
    // Step in x direction.
    // NB. Operators x and y are hermitian, so that we can commute them.
    // Apply an operator in x direction.
#ifdef DEBUG_LOD_CN
debug_print("values", values, 5, 5);
#endif
    after_x = values*operator_x;
    bc_x(y, y_border, time, 0., eps);
    after_x.col(0) = y*tcoeff;
    bc_x(y, y_border, time, 1., eps);
    after_x.col(space_nb_x-1) = y*tcoeff;
#ifdef DEBUG_LOD_CN
debug_print("after_x", after_x, 5, 5);
#endif
    // Apply an operator in y direction.
    after_y = operator_y*values;
    bc_y(x, x_border, time, 0., eps);
    after_y.row(0) = x.transpose()*tcoeff;
    bc_y(x, x_border, time, 1., eps);
    after_y.row(space_nb_y-1) = x.transpose()*tcoeff;
#ifdef DEBUG_LOD_CN
debug_print("after_y", after_y, 5, 5);
#endif
    // Apply the reaction operator.
    auto transform = ::boost::bind(reaction_operator, _1, tau/eps);
    after_reaction = after_y+after_y.unaryExpr(transform); 
#ifdef DEBUG_LOD_CN
debug_print("after_reaction", after_reaction, 5, 5);
#endif
    // Time advance.
    time += tau;
    // Second application of an operator in y direction.
    after_y = operator_y*after_reaction;
    bc_y(x, x_border, time, 0., eps);
    after_y.row(0) = x.transpose()*tcoeff;
    bc_y(x, x_border, time, 1., eps);
    after_y.row(space_nb_y-1) = x.transpose()*tcoeff;
#ifdef DEBUG_LOD_CN
debug_print("after_y", after_y, 5, 5);
#endif
    // Second application of an operator in x direction.
    values = after_y*operator_x;
    bc_x(y, y_border, time, 0., eps);
    values.col(0) = y*tcoeff;
    bc_x(y, y_border, time, 1., eps);
    values.col(space_nb_x-1) = y*tcoeff;
  }
  // Copy to the return value.
  memcpy(inout_matrix, values.data(), space_nb_x*space_nb_y*sizeof(double));
}
Exemplo n.º 15
0
err_status_t
aes_cbc_decrypt(aes_cbc_ctx_t *c,
		unsigned char *data, 
		unsigned int *bytes_in_data) {
  int i;
  v128_t state, previous;
  unsigned char *input  = data;   /* pointer to data being read    */
  unsigned char *output = data;   /* pointer to data being written */
  int bytes_to_encr = *bytes_in_data;
  uint8_t tmp;

  /*
   * verify that we're 16-octet aligned
   */
  if (*bytes_in_data & 0x0f)
    return err_status_bad_param;    

  /* set 'previous' block to iv*/
  for (i=0; i < 16; i++) {
    previous.v8[i] = c->previous.v8[i];
  }

  debug_print(mod_aes_cbc, "iv: %s", 
	      v128_hex_string(&previous));
  
  /*
   * loop over ciphertext blocks, decrypting then exoring with state
   * then writing plaintext to output
   */
  while (bytes_to_encr > 0) {
    
    /* set state to ciphertext input block */
    for (i=0; i < 16; i++) {
     state.v8[i] = *input++;
    }

    debug_print(mod_aes_cbc, "inblock:  %s", 
	      v128_hex_string(&state));
    
    /* decrypt state */
    aes_decrypt(&state, c->expanded_key);

    debug_print(mod_aes_cbc, "outblock: %s", 
	      v128_hex_string(&state));

    /* 
     * exor previous ciphertext block out of plaintext, and write new
     * plaintext block to output, while copying old ciphertext block
     * to the 'previous' block
     */
    for (i=0; i < 16; i++) {
      tmp = *output;
      *output++ = state.v8[i] ^ previous.v8[i];
      previous.v8[i] = tmp;
    }

    bytes_to_encr -= 16;
  }

  return err_status_ok;
}
Exemplo n.º 16
0
static SDL_assert_state
SDL_PromptAssertion(const SDL_assert_data *data, void *userdata)
{
    const char *envr;
    SDL_assert_state state = SDL_ASSERTION_ABORT;
    SDL_Window *window;

    (void) userdata;  /* unused in default handler. */

    debug_print("\n\n"
                "Assertion failure at %s (%s:%d), triggered %u time%s:\n"
                "  '%s'\n"
                "\n",
                data->function, data->filename, data->linenum,
                data->trigger_count, (data->trigger_count == 1) ? "" : "s",
                data->condition);

    /* let env. variable override, so unit tests won't block in a GUI. */
    envr = SDL_getenv("SDL_ASSERT");
    if (envr != NULL) {
        if (SDL_strcmp(envr, "abort") == 0) {
            return SDL_ASSERTION_ABORT;
        } else if (SDL_strcmp(envr, "break") == 0) {
            return SDL_ASSERTION_BREAK;
        } else if (SDL_strcmp(envr, "retry") == 0) {
            return SDL_ASSERTION_RETRY;
        } else if (SDL_strcmp(envr, "ignore") == 0) {
            return SDL_ASSERTION_IGNORE;
        } else if (SDL_strcmp(envr, "always_ignore") == 0) {
            return SDL_ASSERTION_ALWAYS_IGNORE;
        } else {
            return SDL_ASSERTION_ABORT;  /* oh well. */
        }
    }

    /* Leave fullscreen mode, if possible (scary!) */
    window = SDL_GetFocusWindow();
    if (window) {
        if (SDL_GetWindowFlags(window) & SDL_WINDOW_FULLSCREEN) {
            SDL_MinimizeWindow(window);
        } else {
            /* !!! FIXME: ungrab the input if we're not fullscreen? */
            /* No need to mess with the window */
            window = 0;
        }
    }

    /* platform-specific UI... */

#ifdef __WIN32__
    state = SDL_PromptAssertion_windows(data);

#elif __MACOSX__
    /* This has to be done in an Objective-C (*.m) file, so we call out. */
    extern SDL_assert_state SDL_PromptAssertion_cocoa(const SDL_assert_data *);
    state = SDL_PromptAssertion_cocoa(data);

#else
    /* this is a little hacky. */
    for ( ; ; ) {
        char buf[32];
        fprintf(stderr, "Abort/Break/Retry/Ignore/AlwaysIgnore? [abriA] : ");
        fflush(stderr);
        if (fgets(buf, sizeof (buf), stdin) == NULL) {
            break;
        }

        if (SDL_strcmp(buf, "a") == 0) {
            state = SDL_ASSERTION_ABORT;
            break;
        } else if (SDL_strcmp(envr, "b") == 0) {
            state = SDL_ASSERTION_BREAK;
            break;
        } else if (SDL_strcmp(envr, "r") == 0) {
            state = SDL_ASSERTION_RETRY;
            break;
        } else if (SDL_strcmp(envr, "i") == 0) {
            state = SDL_ASSERTION_IGNORE;
            break;
        } else if (SDL_strcmp(envr, "A") == 0) {
            state = SDL_ASSERTION_ALWAYS_IGNORE;
            break;
        }
    }
#endif

    /* Re-enter fullscreen mode */
    if (window) {
        SDL_RestoreWindow(window);
    }

    return state;
}
Exemplo n.º 17
0
void
solve_RelTroullier (int num_psp,
		    int *n_psp,
		    int *l_psp,
		    int *s_psp,
		    double *e_psp,
		    double *fill_psp,
		    double *rcut_psp,
		    double **r_psi_psp,
		    double **r_psi_prime_psp,
		    double *rho_psp,
		    double *rho_semicore,
		    double **V_psp, double *eall_psp,
		    double *eh_psp, double *ph_psp,
		    double *ex_psp, double *px_psp,
		    double *ec_psp, double *pc_psp)
{
  int istate, i, l, k, p, s2, match, mch, Ngrid;
  double al, amesh, rmax, Zion;
  double gamma, gpr, nu0;
  double ldpsi_match;
  double el, eeig;
  double ph, px, pc, eh, ex, ec;

  double *ul, *ul_prime;
  double *wl, *wl_prime;
  double *r, *Vh, *Vx, *Vc, *rho_total, *Vall, *Vl;


  /* Allocate Grids */
  Vall = Vall_Atom ();

  r = r_LogGrid ();
  Ngrid = N_LogGrid ();
  al = log_amesh_LogGrid ();
  amesh = amesh_LogGrid ();

  Zion = 0.0;
  for (k = 0; k < Ngrid; ++k)
    rho_psp[k] = 0.0;


  if (debug_print ())
    {
      printf ("\n\nRelTroullier pseudopotential check\n\n");
      printf
	("l\trcore     rmatch    E in       E psp      norm test slope test\n");
    }

  for (p = 0; p < (num_psp); ++p)
    {
      l = l_psp[p];
      s2 = s_psp[p];
      wl = r_psi_psp[p];
      wl_prime = r_psi_prime_psp[p];
      Vl = V_psp[p];

	/*******************************************/
      /* Solve for scattering state if necessary */
	/*******************************************/
      if (fill_psp[p] < 1.e-15)
	{
	  rmax = 10.0;
	  solve_Scattering_State_Atom (n_psp[p], l_psp[p], e_psp[p], rmax);

	  /* scattering state saved at the end of the atom list */
	  istate = Nvalence_Atom () + Ncore_Atom ();
	  if (s2 < 0)
	    istate += 1;
	  mch = (int) rint (log (rmax / r[0]) / al);
	  ul = r_psi_Atom (istate);
	  ul_prime = r_psi_prime_Atom (istate);
	  nu0 = Norm_LogGrid (mch, (l + 1.0), ul);
	  nu0 = 1.0 / sqrt (nu0);
	  for (i = 0; i < Ngrid; ++i)
	    {
	      ul[i] = ul[i] * nu0;
	      ul_prime[i] = ul_prime[i] * nu0;
	    }
	}
	/*******************************************/
      /* find state of all-electron wavefunction */
	/*******************************************/
      else
	istate = state_RelAtom (n_psp[p], l_psp[p], s_psp[p]);

	/*************************************/
      /* get the all-electron wavefunction */
	/*************************************/
      ul = r_psi_Atom (istate);
      ul_prime = r_psi_prime_Atom (istate);
      el = e_psp[p];

	/*****************************/
      /* find matching point stuff */
	/*****************************/
      match = (int) rint (log (rcut_psp[p] / r[0]) / al);
      ldpsi_match = ul_prime[match] / ul[match];


      /* make sure that wavefunctions are non-negative at the matching point */
      if (ul[match] < 0.0)
	{
	  nu0 = -1.0;
	  for (i = 0; i < Ngrid; ++i)
	    {
	      ul[i] = ul[i] * nu0;
	      ul_prime[i] = ul_prime[i] * nu0;
	    }
	}

	/**************************************/
      /* generate troullier pseudopotential */
	/**************************************/
      init_xpansion (l, match, fill_psp[p], el, Vall, ul, ul_prime, Vl, wl,
		     wl_prime);
      psi_xpansion ();
      dpsi_xpansion ();
      psp_xpansion ();

	/******************/
      /* verify psp Vl */
	/******************/
	/*******************/
      /* psp bound state */
	/*******************/
      if (fill_psp[p] > 1.e-14)
	{

	  R_Schrodinger (l_psp[p] + 1, l_psp[p], Vl, &mch, &el, wl, wl_prime);

	}
      /* scattering state */
      else
	{
	  R_Schrodinger_Fixed_Logderiv (l_psp[p] + 1, l_psp[p], Vl, match,
					ldpsi_match, &el, wl, wl_prime);
	  R_Schrodinger_Fixed_E (l_psp[p] + 1, l_psp[p], Vl,
				 Ngrid - 1, el, wl, wl_prime);

	  /* normalize the scattering state to mch = 10.0 a.u. */
	  rmax = 10.0;
	  mch = rint (log (rmax / r[0]) / al);
	  nu0 = Norm_LogGrid (mch, (l + 1.0), wl);
	  nu0 = 1.0 / sqrt (nu0);
	  for (i = 0; i < Ngrid; ++i)
	    {
	      wl[i] = wl[i] * nu0;
	      wl_prime[i] = wl_prime[i] * nu0;
	    }
	}

      gamma = fabs (ul[match] / wl[match]);
      gpr = fabs (ul_prime[match] / wl_prime[match]);
      if (debug_print ())
	{
	  /*printf("ul[match] wl[match]: %lf %lf\n",ul[match],wl[match]); */
	  printf ("%d\t%lf  %lf  %lf  %lf  %lf  %lf\n", l_psp[p],
		  rcut_psp[p], r[match], e_psp[p], el, gamma, gpr);
	}

      /* Use the analytic form of pseudopotential */
      el = e_psp[p];
      psi_xpansion ();
      dpsi_xpansion ();
      psp_xpansion ();

      if (fill_psp[p] > 1.e-14)
	{
	  eeig += fill_psp[p] * el;

	  /* accumulate charges */
	  Zion += fill_psp[p];
	  for (k = 0; k < Ngrid; ++k)
	    rho_psp[k] += fill_psp[p] * pow (wl[k] / r[k], 2.0);
	}


    }				/* for p */


    /***************************************/
  /* get the hartree potential an energy */
  /* get the exchange potential and energy */
  /* get the correlation potential and energy */
    /***************************************/
  Vh = alloc_LogGrid ();
  Vx = alloc_LogGrid ();
  Vc = alloc_LogGrid ();
  ph = R_Hartree_DFT (rho_psp, Zion, Vh);
  eh = 0.5 * ph;

  rho_total = alloc_LogGrid ();
  for (k = 0; k < Ngrid; ++k)
    rho_total[k] = rho_psp[k] + rho_semicore[k];

  R_Exchange_DFT (rho_total, Vx, &ex, &px);
  R_Correlation_DFT (rho_total, Vc, &ec, &pc);

  /* recalculate px and pc */
  for (k = 0; k < Ngrid; ++k)
    rho_total[k] = (rho_psp[k]) * Vx[k];
  px = Integrate_LogGrid (rho_total);
  for (k = 0; k < Ngrid; ++k)
    rho_total[k] = (rho_psp[k]) * Vc[k];
  pc = Integrate_LogGrid (rho_total);


  *eall_psp = eeig + eh + ex + ec - ph - px - pc;
  *eh_psp = eh;
  *ph_psp = ph;
  *ex_psp = ex;
  *px_psp = px;
  *ec_psp = ec;
  *pc_psp = pc;
  for (p = 0; p < num_psp; ++p)
    for (k = 0; k < Ngrid; ++k)
      V_psp[p][k] = V_psp[p][k] - Vh[k] - Vx[k] - Vc[k];

  /* deallocate memory */
  dealloc_LogGrid (Vh);
  dealloc_LogGrid (Vx);
  dealloc_LogGrid (Vc);
  dealloc_LogGrid (rho_total);

}				/* solve_Troullier */
Exemplo n.º 18
0
int run_program(Resources * resources){
#if DEBUG
    const char* instructions_symbols[64];
    instructions_symbols[0] = "EQ_INT_MEM_MEM";
    instructions_symbols[1] = "EQ_DBL_MEM_MEM";
    instructions_symbols[2] = "G_INT_MEM_MEM";
    instructions_symbols[3] = "G_DBL_MEM_MEM";
    instructions_symbols[4] = "L_INT_MEM_MEM";
    instructions_symbols[5] = "L_DBL_MEM_MEM";
    instructions_symbols[6] = "GE_INT_MEM_MEM";
    instructions_symbols[7] = "GE_DBL_MEM_MEM";
    instructions_symbols[8] = "LE_INT_MEM_MEM";
    instructions_symbols[9] = "LE_DBL_MEM_MEM";
    instructions_symbols[10] = "NE_INT_MEM_MEM";
    instructions_symbols[11] = "NE_DBL_MEM_MEM";
    instructions_symbols[12] = "ADD_INT_MEM_MEM";
    instructions_symbols[13] = "ADD_DBL_MEM_MEM";
    instructions_symbols[14] = "SUB_INT_MEM_MEM";
    instructions_symbols[15] = "SUB_DBL_MEM_MEM";
    instructions_symbols[16] = "MUL_INT_MEM_MEM";
    instructions_symbols[17] = "MUL_DBL_MEM_MEM";
    instructions_symbols[18] = "DIV_INT_MEM_MEM";
    instructions_symbols[19] = "DIV_DBL_MEM_MEM";
    instructions_symbols[20] = "EQ_STR_MEM_MEM";
    instructions_symbols[21] = "G_STR_MEM_MEM";
    instructions_symbols[22] = "L_STR_MEM_MEM";
    instructions_symbols[23] = "GE_STR_MEM_MEM";
    instructions_symbols[24] = "LE_STR_MEM_MEM";
    instructions_symbols[25] = "NE_STR_MEM_MEM";
    instructions_symbols[26] = "MOV_TOP_MEM";
    instructions_symbols[27] = "MOV_INT_MEM";
    instructions_symbols[28] = "MOV_INT_CONST";
    instructions_symbols[29] = "MOV_DBL_MEM";
    instructions_symbols[30] = "MOV_DBL_CONST";
    instructions_symbols[31] = "CAST_INT_MEM";
    instructions_symbols[32] = "CAST_DBL_MEM";
    instructions_symbols[33] = "PUSH_EMPTY";
    instructions_symbols[34] = "PUSH_INT_CONST";
    instructions_symbols[35] = "PUSH_DBL_CONST";
    instructions_symbols[36] = "PUSH_INDEX_CONST";
    instructions_symbols[37] = "PUSH_INT_MEM";
    instructions_symbols[38] = "PUSH_DBL_MEM";
    instructions_symbols[39] = "PUSH_INDEX_MEM";
    instructions_symbols[40] = "POP_EMPTY";
    instructions_symbols[41] = "JMP_MEM";
    instructions_symbols[42] = "JMP_TRUE_MEM";
    instructions_symbols[43] = "JMP_FALSE_MEM";
    instructions_symbols[44] = "JMP_FUNC";
    instructions_symbols[45] = "FCE_CALL";
    instructions_symbols[46] = "FCE_RETURN";
    instructions_symbols[47] = "CIN_INT";
    instructions_symbols[48] = "CIN_DOUBLE";
    instructions_symbols[49] = "CIN_STRING";
    instructions_symbols[50] = "CONCAT_MEM_MEM";
    instructions_symbols[51] = "SUBSTR_MEM_MEM";
    instructions_symbols[52] = "LENGTH_MEM";
    instructions_symbols[53] = "FIND_MEM_MEM";
    instructions_symbols[54] = "SORT_MEM";  
    instructions_symbols[55] = "COUT_MEM_TYPE"; 
    instructions_symbols[56] = "NO_RETURN";
    instructions_symbols[57] = "SET TYPE";
    instructions_symbols[58] = "HALT";

	debug_print("%s\n", "CREATING VISUALIZATION OF INSTRUCTION BUFFER");
    FILE *fp;
    int ins_num;
    if ((fp = fopen("instruction_buffer_content", "w")) == NULL) {
        debug_print("%s\n", "Failed to open instruction buffer debug file");
    } else {
        fprintf(fp, "INDEX    INSTRUCTION\n");
        for(index_t tmp_ip = 1 ; tmp_ip < resources->instruction_buffer.next_free ; tmp_ip++){
			ins_num = access(resources->instruction_buffer.buffer, TInstruction, tmp_ip)->ins;
            fprintf(fp, " %lu      %s\n", tmp_ip, instructions_symbols[ins_num]);
        }
        
        fclose(fp);
    }
#endif

	debug_print("%s\n", "INIT_INTERPRET");
	args_assert(resources != NULL, INTERNAL_ERROR);
	int iRet = RETURN_OK;
    register int instruction_ret;

	if (resources->start_main == ZERO_INDEX){
		iRet = SEMANTIC_ERROR;
		goto DEFAULT;
	}

	resources->ip = 1;
    resources->bp = 1;
    resources->tmp_bp = 1;
	access(resources->instruction_buffer.buffer, TInstruction, 1)->dest.index = 2;
    access(resources->instruction_buffer.buffer, TInstruction, 2)->dest.index = resources->start_main;

	debug_print("%s :%lu\n", "START POINT", resources->start_main);

	TInstruction * instruction;
	do {
        dereference_structure(&(resources->instruction_buffer), resources->ip, (void**)&instruction);
        debug_print("%s: %lu, %s: %d\n", "IP", resources->ip, "INSTRUCTION", instruction->ins);
    
        instruction_ret = execute_instruction[instruction->ins](resources, instruction);
    
        debug_print("%s: %d\n", "INSTRUCT RET", instruction_ret);
        resources->ip++;

#if DEBUG
        for (index_t i = 1; i < 10; i++) {
                if (i == resources->runtime_stack.next_free - 1 && i == resources->bp) 
                    debug_print("%s: %d %lf %s\n", "CONTENT", access(resources->runtime_stack.buffer, TStack_variable, i )->value.i, 
                                                              access(resources->runtime_stack.buffer, TStack_variable, i )->value.d, "<-- STACK TOP  <-- BP");
                else if (i == resources->runtime_stack.next_free -1) 
                    debug_print("%s: %d %lf %s\n", "CONTENT", access(resources->runtime_stack.buffer, TStack_variable, i )->value.i,
                                                              access(resources->runtime_stack.buffer, TStack_variable, i )->value.d, "<-- STACK TOP");
                else if (i == resources->bp)
                    debug_print("%s: %d %lf %s\n", "CONTENT", access(resources->runtime_stack.buffer, TStack_variable, i )->value.i,
                                                              access(resources->runtime_stack.buffer, TStack_variable, i )->value.d, "<-- BP");
                else
                    debug_print("%s: %d %lf \n", "CONTENT", access(resources->runtime_stack.buffer, TStack_variable, i)->value.i,
                                                            access(resources->runtime_stack.buffer, TStack_variable, i )->value.d);
        }
#endif
    } while (instruction_ret == RETURN_OK);

    iRet = (instruction_ret == HALT ? RETURN_OK : instruction_ret);
	

DEFAULT:
	debug_print("%s %d\n", "INTERPRET_RETURN", iRet);
	return iRet;
}
Exemplo n.º 19
0
Arquivo: font.c Projeto: shiver/vectir
// creates the texture for the font
// TODO (robertva#1#): Handle glyph sizes better. Each glyph has a unique width
// + height...
int _createFontTexture() {

  SDL_Surface *surface;
  SDL_Surface *surface_texture;
  SDL_Rect srcrect, dstrect;
  int start = 32;
  int count = 94;
  int x, y;
  float xval, yval;
  char c[2];

  int tw, th;
	Glyph *first, *current, *row;
	int per_row;
	int width, height;
	SDL_Color color_fg, color_bg;

	// set vars
	memset(c, '\0', sizeof(c));
	per_row = 0;
  width = 0;
  height = 0;
	debug_print("Getting glyph info.");
	first = font_getGlyphInfo(start, count);
	first->x = 0;
	first->y = 0;
	current = first;
	row = current;

	// todo: make colour settable
  color_fg.r = 255;
  color_fg.g = 255;
  color_fg.b = 255;
  color_bg.r = 0;
  color_bg.g = 0;
  color_bg.b = 0;

  if (!font) {
    error_print("_createFontTexture: Font not open.");
    return 0;
  }

  // determine the dimensions required to fit all glyphs and
	// number of characters in a row
	debug_print("Getting font texture dimensions.");
	per_row = round(sqrt(count)); // rounds up. remember to cater for fewer characters
	font_determineDimensions(start, count, &tw, &th, &per_row);
	// set texture width and height to nearest power of two
	tw = power_of_two(tw);
	th = power_of_two(th);
	printf("dims: %d %d\n", tw, th);

  // generate a place for the final surface
	debug_print("Creating new surface for font texture.");
  surface_texture = SDL_CreateRGBSurface(SDL_SWSURFACE, tw, th, 32, 0, 0, 0, 0);
  if (!surface_texture) {
    error_print("Failed to create new surface for font.");
    return 0;
  }

  for (y = 0; y < per_row; y++) {
		// store the glyph at the beginning of the row
		row = current;
		height = 0;

		// need to first get the max height out of the glyphs in this row
		for (x = 0; x < per_row; x++) {
			if (current) {
				if (current->h + (GLYPH_PADDING * 2) > height) {
					height = current->h + (GLYPH_PADDING * 2);
				}
			}
			current = current->next;
		}

		// go back to the beginning of the row
		current = row;

		// now do the actual rendering and applying to the finial surface
    for (x = 0; x < per_row; x++) {
			if (x + (y * per_row) < count) { // correction for rounding of per_row
				if (current) {
					// render next character
		      c[0] = start + x + (y * per_row);
		      surface = TTF_RenderText_Shaded(font, c, color_fg, color_bg);

					current->w = surface->w;
					current->h = surface->h;

					// set the src dimensions
					srcrect.x = 0;
					srcrect.y = 0;
					srcrect.w = surface->w;
					srcrect.h = surface->h;

					// set the destination location for the new char
			    dstrect.x = current->x + GLYPH_PADDING;
				  dstrect.y = current->y + GLYPH_PADDING;
					dstrect.w = surface->w;
					dstrect.h = current->h;

				  // copy the row to the final surface
					SDL_BlitSurface(surface, &srcrect, surface_texture, &dstrect);

					SDL_FreeSurface(surface);

					// set the top left corner of the next glyph
					if (current->next) {
						if (x + 1 < per_row) { // if we're still on the same row
							((Glyph*)current->next)->x = current->x + current->w + (GLYPH_PADDING * 2);
							((Glyph*)current->next)->y = current->y;
						}
						else { // on the next row
							((Glyph*)current->next)->x = 0;
							((Glyph*)current->next)->y = current->y + current->h + (GLYPH_PADDING * 2);
						}
					}
					current = current->next;
				}
			}
    }
  }

  // create an opengl texture from the surface
  font_texture = graphics_createTextureFromSurface(surface_texture);
  //SDL_SaveBMP(surface_texture, "font.bmp"); // used for debugging
  SDL_FreeSurface(surface_texture);

  // reset the glyph info list
  current = first;

  debug_print("Generating font display lists...");
  font_base = glGenLists(count); // create opengl display list

  for (y = 0; y < per_row; y++ ) {
    for (x = 0; x < per_row; x++ ) {
      if (x + (y * per_row) < count) {
        if (current) {
          glNewList(font_base + x + (y * per_row), GL_COMPILE); // new char
            glBegin(GL_QUADS);
              // texture 0, 0
              xval = current->x / (float)tw;
              yval = current->y / (float)th;
              glTexCoord2f(xval, yval);
              glVertex2i(0, 0);

              // texture 1, 0
              xval = ((current->x + current->w + (GLYPH_PADDING * 2)) / (float)tw);
              yval = current->y / (float)th;
              glTexCoord2f(xval, yval);
              glVertex2i(current->w + (GLYPH_PADDING * 2), 0);

              // texture 1, 1
              xval = ((current->x + current->w + (GLYPH_PADDING * 2)) / (float)tw);
              yval = (current->y / (float)th) + (current->h / (float)th);
              glTexCoord2f(xval, yval);
              glVertex2i(current->w + (GLYPH_PADDING * 2), current->h);

              // texture 0, 1

              xval = current->x / (float)tw;
              yval = (current->y / (float)th) + (current->h / (float)th);
              glTexCoord2f(xval, yval);
              glVertex2i(0, current->h);
            glEnd();
            glTranslatef(current->w + (GLYPH_PADDING), 0, 0.0f); // move to next place
          glEndList();

          current = current->next;
        }
      }
    }
  }

	font_destroyGlyphInfo(first);
	return 1;
}
Exemplo n.º 20
0
/**
 * Implement Go-Back-N sliding windows to receive the data packets.
 **/
void recv_file(int sock_num, struct sockaddr_in * p_cli_addr, u_int file_len, u_int buffer_sz, FILE * p_file) {
    u_int   last_pkt_ackd = INIT_SEQ_NUM;
    u_int   next_pkt = last_pkt_ackd + 1;
    u_int   total_seqs = ((int) ceil((double) file_len / (double) buffer_sz)) + INIT_SEQ_NUM;
    
    //debug_max("------------- receive file -------------\n");
    //debug_max("recv_file(): total_seqs = %i\n", total_seqs);
    
    /* Start receiving packets */
    data_pkt_t * p_data_pkt = NULL;
    
    int i = 0;
    
    while (next_pkt <= total_seqs) { // we still have packets to receive
        i++;
        //debug_max("recv_file(): round = %i\n", i);
        //debug_max("recv_file(): next_pkt = %i <= total_seq = %i\n", next_pkt, total_seqs);
        
        if (select_call(sock_num, SRV_WAIT_SECS, 0)) {
            p_data_pkt = recv_data(sock_num, p_cli_addr);
            
            //debug_max("\trecv_file(): p_data_pkt->hdr.chk_sum = %i\n", p_data_pkt->hdr.chk_sum);
            //debug_max("\trecv_file(): p_data_pkt->hdr.seq_num = %i -v- next_pkt = %i\n", p_data_pkt->hdr.seq_num, next_pkt);

            if (p_data_pkt->hdr.chk_sum !=0 ) {
                // packet is corrupt, don't use
                //debug_max("\trecv_file(): check sum error\n");
                send_ack(sock_num, p_cli_addr, next_pkt, NAK_PKT_TYPE);
            } else if (p_data_pkt->hdr.seq_num == next_pkt) {
                // this is the one we're looking for
                // check the check sum to decide what to do
                //debug_max("\trecv_file(): send ack seq_num = %i\n", p_data_pkt->hdr.seq_num);
                // packet is uncorrupted, write to file and ACK
                fwrite(p_data_pkt->data, sizeof(char), p_data_pkt->hdr.buffer_sz, p_file);
                send_ack(sock_num, p_cli_addr, p_data_pkt->hdr.seq_num, ACK_PKT_TYPE);
                last_pkt_ackd = p_data_pkt->hdr.seq_num;
                next_pkt = last_pkt_ackd + 1;
            } else if (p_data_pkt->hdr.seq_num == 1) {
                // catch the case where the init packet gets resent
                // and simply re-ACK
                send_ack(sock_num, p_cli_addr, INIT_PKT_TYPE, ACK_PKT_TYPE);
            } else if (p_data_pkt->hdr.seq_num < next_pkt) { 
                // we've already seen, re-ack
                //debug_max("\t\trecv_file(): re-acking %i\n", p_data_pkt->hdr.seq_num);
                send_ack(sock_num, p_cli_addr, last_pkt_ackd, ACK_PKT_TYPE);
            } else {    
                // too high, we must have missed one, NAK what we were looking for
                //debug_max("\t\trecv_file(): NAKing... p_data_pkt->hdr.chk_sum = %hu\n", p_data_pkt->hdr.chk_sum);
                send_ack(sock_num, p_cli_addr, next_pkt, NAK_PKT_TYPE);
            }
            
        } else {
            // heard nothing from the client
            debug_errors("recv_file(): heard nothing from client; exiting\n");
            break;
        }
        
    }
    
    debug_print("recv_file(): finished receiving file from client\n");
}
Exemplo n.º 21
0
static void prefs_ok_cb(GtkWidget *widget, gpointer data)
{
  gchar *rcpath;
  const gchar *address;
  gboolean startup;
  gboolean unreadonly;
  GtkTreeModel *model;
  gint nfolder;
  gchar **folders;
  GtkTreeIter iter;
  gboolean valid;
  int nindex;
  gchar *folder;
  gsize sz;
  gchar *buf;
  
  rcpath  = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "autoforwardrc", NULL);
g_keyfile = g_key_file_new();
  g_key_file_load_from_file(g_keyfile, rcpath, G_KEY_FILE_KEEP_COMMENTS, NULL);

  address = gtk_entry_get_text(GTK_ENTRY(g_address));
  if (address!=NULL){
    g_key_file_set_string (g_keyfile, "forward", "to", address);
  }
  startup = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(g_startup));
  g_key_file_set_boolean (g_keyfile, "forward", "startup", startup);
  debug_print("startup:%s\n", startup ? "true" : "false");

  unreadonly = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(g_unreadonly));
  g_key_file_set_boolean (g_keyfile, "forward", "unreadonly", unreadonly);
  debug_print("unread only:%s\n", g_unreadonly_flg ? "true" : "false");

  g_key_file_set_boolean (g_keyfile, "forward", "all", g_forward_flg);
  debug_print("forward all:%s\n", g_forward_flg ? "true" : "false");

  /**/
  model = GTK_TREE_MODEL(g_folders);
  nfolder = gtk_tree_model_iter_n_children(model, NULL);
  if (nfolder > 0){
    folders = malloc(sizeof(gchar*)*nfolder);
    nindex = 0;
    for (valid = gtk_tree_model_get_iter_first(model, &iter); valid;
         valid = gtk_tree_model_iter_next(model, &iter)) {
      gtk_tree_model_get(model, &iter, 0, &folder, -1);
      folders[nindex] = folder;
      g_print("%d:%s\n", nindex, folder);
      nindex++;
    }
    g_key_file_set_string_list(g_keyfile, "forward", "folder",
                               (const gchar * const*)folders, nfolder);
  }else{
    g_key_file_remove_key(g_keyfile, "forward", "folder", NULL);
  }
    
  buf=g_key_file_to_data(g_keyfile, &sz, NULL);
  g_file_set_contents(rcpath, buf, sz, NULL);
    
  g_free(rcpath);

  gtk_widget_destroy(GTK_WIDGET(data));
}
Exemplo n.º 22
0
//deep node string and pattern should parsed
void run_deep_lv(LV_ENTITY *lv, DI *di, char *pattern, size_t pattern_len, int max_error)
{
	int mark_no_vis = -1;

	//lp should inside [INT] range
	if (pattern_len > INT_MAX)
	{
		fprintf(stderr, "len of pattern [%lu] out of range try small len\n", pattern_len);
		return;
	}
	int lp = (int)pattern_len;

	if (init_lv(lv, (di->n_l), max_error, lp, (di->the_deep), mark_no_vis) == -1)
	{
		fprintf(stderr, "run lv error\n");
		return;
	}
	

    int find_d = 0;
	int global_reach = -2;

	int the_b = 0, the_e = 0, the_d = 0;
	int the_ek = the_e + 1, the_dk = the_d+lp+1;

	// init the LV[0][0][0] = 0
	// (lv->LV)[the_b][the_ek][the_dk] = 0;

	//tmp var 
	deep_node *bn;
	int ek, dk, best, last_best;
	//len of text , text begin in deep code
	int lt;
	size_t tbegin;

	char *p, *pb, *t, *pend;
    int extend_len = 0;

    int the_deep = 0, base_deep, cur_deep, action, next_action;

	for (int e = 0; e<=max_error && find_d==0; ++e)
	{
		//mark_bit mean if lv == no vis 
		//mark_bit = 1 lv can succeed from d+1 or == -d then extend 0 error
		//mark_bit = 2 lv can succeed then extend 1 error
		for (int dp = 0; dp <= the_deep; ++dp)
		{
			for (int i=0; i<lp; ++i)
			{
				if (dp==0)
					if (i<=e) (lv->mark_bit)[dp][i] = e-i+1;
					else (lv->mark_bit)[dp][i] = 0;
				else
					(lv->mark_bit)[dp][i] = 0;
			}	
		}

		base_deep = -1;

		debug_print("\ne: %d\n", e);
		if ((di->n_l) > 0)
		// for (int b = 0; b<(di->n_l) && ((di->all_node[b]).deep <= the_deep); ++b)
		for (int b = 0; b<(di->n_l) && ((di->all_node[b]).deep <= the_deep) && find_d==0; ++b)
		{
			// if ((di->all_node[b]).deep == cur_deep) continue;
			bn = &(di->all_node[b]);
			lt = (int)MN(bn->len, INT_MAX);
			tbegin = bn->begin;
			cur_deep = bn->deep;

			debug_print("$ deep: %d the node : %d len: %d \n", cur_deep, b, lt);
			// printf("$ deep: %d the node : %d len: %d \n", cur_deep, b, lt);

			for (size_t i=0; i<lp; ++i)	debug_print((i==lp-1) ? "%d\n":"%d-", (lv->mark_bit)[cur_deep][i]);

			//if the block have no element,just succeed the mark value
			// if (lt == 0 && cur_deep+1 < (di->the_deep))
   //          {
   //          	if (the_deep < cur_deep+1)
   //          	{
   //          		the_deep = cur_deep+1;
   //          		for (size_t i=0; i<lp; ++i)	(lv->mark_bit)[cur_deep+1][i] = 0;
   //          		debug_print(" ** undate deep: cur %d the_deep %d\n", cur_deep, the_deep);
   //          	}
   //          	for (size_t i=0; i<lp; ++i)
   //          		(lv->mark_bit)[cur_deep+1][i] = MX((lv->mark_bit)[cur_deep+1][i], (lv->mark_bit)[cur_deep][i]);
   //          	// if ((lv->mark_bit)[cur_deep+1][best] > 1)
   //          	// {
   //          	// 	if (best+1 > 0 && best+1<lp) (lv->mark_bit)[cur_deep+1][best+1] = MX((lv->mark_bit)[cur_deep+1][best+1], 1);
   //          	// 	if (best-1 > 0 && best-1<lp) (lv->mark_bit)[cur_deep+1][best-1] = MX((lv->mark_bit)[cur_deep+1][best-1], 1);
   //          	// }
			// 	for (size_t i=0; i<lp; ++i)	debug_print((i==lp-1) ? "%d\n":"%d-", (lv->mark_bit)[cur_deep+1][i]);
   //          }
			

			for (int d = -lp+1, ek; d<(int)(MN( e+1, MN(lt+1, lp))); ++d)
			{
				ek = e + 1;
				dk = d + lp + 1;
				
				// if ((lv->Far_reach)[b][dk]==1) continue;
				if ((lv->Far_reach)[cur_deep][lt-d]==1) continue;

				best = MX((lv->LV)[b][ek-1][dk], (lv->LV)[b][ek][dk]);
				// debug_print("d: %d : best %d\n", d, best);

				// best =(lv->LV)[b][e ][dk];
				if (best != mark_no_vis) action = 2;
				else if (d <= 0) 
				{
					action = (lv->mark_bit)[cur_deep][-d];
					if (action > 0) 
					{
						// printf("-- %d %d %d\n", (lv->LV)[b][ek-1][dk+1], (lv->LV)[b][ek-1][dk-1], best);
						if ((lv->LV)[b][ek-1][dk+1] != mark_no_vis)
							best = MX(best, (lv->LV)[b][ek-1][dk+1] + 1);
						if ((lv->LV)[b][ek-1][dk-1] != mark_no_vis)
							best = MX(best, (lv->LV)[b][ek-1][dk-1]);
						best = MX(-d, best);
					}
				}
				else if ((lv->LV)[b][ek-1][dk-1] != mark_no_vis) action = 2;
				else action = 0;


				if (best == mark_no_vis && action == 0) continue;

				debug_print("action: %d\n", action);
				debug_print("d: %d : best %d\n", d, best);

				next_action = 0;
				
				//error 0 extend
				//only can extend from left side
				if (action >= 1 && (lv->LV)[b][ek-1][dk] == mark_no_vis && d<=0)
				{
					pb = pattern + best;
					p = pattern + best;
		    		t = di->deep_s + tbegin + best + d;
		    		last_best = best;

		    		extend_len = MN(lt-MX(0, d), lp-MX(0, -d));
		    		pend = pattern + MX(0, -d) + extend_len;
		    		// debug_print("extend_len, %d\n", extend_len);
					// printf("1t: ");
					// print_bit4((*p));
					// printf("-");
					// print_bit4((*t));
					if ( p < pend && ((*p) & (*t)))
					{
						while (p < pend) 
						{
			                uint64_t x = (~ *((uint64_t*) t) ) & *((uint64_t*) p);
		    		        if (x) {
		    		            unsigned long zeroes;
		    		            CountTrailingZeroes(x, zeroes);
		    		            zeroes >>= 3;
								debug_print("* %lu: ", zeroes);
		    		            best = MN((int)(p - pb) + (int)zeroes + last_best, MX(0, -d) + extend_len);
		    		            
		    		            break;
		    		        }
		    		        p += 8;
		    		        t += 8;
		    		        if (p >= pend) 
		    		        {
		    		        	debug_print("@ %d: ", extend_len);
		                        best = MX(0, -d) + extend_len;
		                        break;
		                    }
		    		    }
					}
					if (best != last_best)
					{
						(lv->LV)[b][ek][dk] = best;
					}
					// else
					// {
					// 	if (d <= 0 && best == -d)
					// 		best = mark_no_vis;
					// }

					if (best + d >= lt)
					{
						next_action = action;
					}
					
				}
				debug_print("--d: %d : best %d\n", d, best);

	    		//error 1 extend
	    		if (action >= 2 && next_action == 0)
	    		{
	    			if (best != mark_no_vis) 
	    				best = best + 1;

					if ((lv->LV)[b][ek-1][dk] != mark_no_vis)
						best = MX(best, (lv->LV)[b][ek-1][dk] + 1);

					if ((lv->LV)[b][ek-1][dk+1] != mark_no_vis)
						best = MX(best, (lv->LV)[b][ek-1][dk+1] + 1);

					if ((lv->LV)[b][ek-1][dk-1] != mark_no_vis)
						best = MX(best, (lv->LV)[b][ek-1][dk-1]);


					if (best == (lv->LV)[b][ek-1][dk] + 1 && best + d > lt)
					{
						next_action = 2;
					}
					if (next_action == 0 && best == (lv->LV)[b][ek-1][dk+1] + 1 && best + d > lt)
					{
						next_action = 1;
					}
					if (next_action == 0 && best == (lv->LV)[b][ek-1][dk-1] && best + d > lt)
					{
						next_action = 1;
					}
					debug_print("d: %d : best %d\n", d, best);

					pb = pattern + best;
					p = pattern + best;
		    		t = di->deep_s + tbegin + best + d;
		    		last_best = best;

		    		extend_len = MN(lt-MX(0, d), lp-MX(0, -d));
		    		// debug_print("extend_len, %d\n", extend_len);
		    		pend = pattern + MX(0, -d) + extend_len;
					
					// printf("t: ");
					// print_bit4((*p));
					// printf("-");
					// print_bit4((*t));

					if ( p < pend && ((*p) & (*t)))
					{
						// printf("try match");
						// print_bit4((*p));
						// printf("-");
						// print_bit4((*t));
						// printf("\n");
						while (p < pend) 
						{
			                uint64_t x = (~ *((uint64_t*) t) ) & *((uint64_t*) p);
		    		        if (x) {
		    		            unsigned long zeroes;
		    		            CountTrailingZeroes(x, zeroes);
		    		            zeroes >>= 3;
		    		            best = MN((int)(p - pb) + (int)zeroes + last_best, MX(0, -d) + extend_len);
		    		            
		    		            break;
		    		        }
		    		        p += 8;
		    		        t += 8;
		    		        if (p >= pend) 
		    		        {
		                        best = MX(0, -d) + extend_len;
		                        break;
		                    }
		    		    }
					}
					if (best != last_best)
					{
						(lv->LV)[b][ek][dk] = best;
					}

					if (next_action == 0 && best + d == lt)
					{
						next_action = 1;
					}

					if (next_action == 0 && best + d > lt)
					{
						next_action = 2;
					}
	    			
	    		}

				if (best == mark_no_vis) continue;

				best = MN(best, lt - d);
				
				debug_print("d: %d : best %d\n", d, best);


				// if (best <= (lv->LV)[b][ek-1][dk])
				if (best+d >= lt)
				{
					// (lv->Far_reach)[b][dk] = 1;
					(lv->Far_reach)[cur_deep][lt-d] = 1;
					debug_print("Far reach at b: %d deep: %d d: %d lv: %d\n", b, cur_deep, d, best);
				}


	            // if (best > global_reach || (best == global_reach && d > the_d) )
	            if (best > global_reach)
	            {
	            	global_reach = best;
	            	the_b = b;
	                the_e = e;
	                the_d = d;
	            }

	            (lv->LV)[b][ek][dk] = best;
				debug_print("-> b: %d e:%d d:%d lV:%d\n", b, e, d, best);

	            if (best + d >= lt && cur_deep+1 < (di->the_deep))
	            {
	            	if (the_deep < cur_deep+1)
	            	{
	            		the_deep = cur_deep+1;
	            		for (size_t i=0; i<lp; ++i)	(lv->mark_bit)[cur_deep+1][i] = 0;
	            		debug_print(" ** undate deep: cur %d the_deep %d\n", cur_deep, the_deep);
	            	}
	            	(lv->mark_bit)[cur_deep+1][best] = MX((lv->mark_bit)[cur_deep+1][best], next_action);
	            	// if ((lv->mark_bit)[cur_deep+1][best] > 1)
	            	// {
	            	// 	if (best+1 > 0 && best+1<lp) (lv->mark_bit)[cur_deep+1][best+1] = MX((lv->mark_bit)[cur_deep+1][best+1], 1);
	            	// 	if (best-1 > 0 && best-1<lp) (lv->mark_bit)[cur_deep+1][best-1] = MX((lv->mark_bit)[cur_deep+1][best-1], 1);
	            	// }
					for (size_t i=0; i<lp; ++i)	debug_print((i==lp-1) ? "%d\n":"%d-", (lv->mark_bit)[cur_deep+1][i]);
	            }

				
				if (best == lp)
	            {
	            	the_b = b;
	                the_e = e;
	                the_d = d;
	                if (find_d==1) break;
	                find_d = 1;
	                // printf(" *** find lv: in error: %d b: %d deep: %d d: %d\n", e, b, cur_deep, d);
	                // break;
	            }
			}
		}
		
	}
Exemplo n.º 23
0
void exec_autoforward_cb(GObject *obj, FolderItem *item, const gchar *file, guint num)
{
  PrefsCommon *prefs_common;
  PrefsAccount *ac;

  gchar *rcpath;
  GSList* to_list=NULL;

  gchar *to;
  GError *errval;
  gboolean forward_all;

  gsize gz=0;
  gchar **folders;
  gboolean bmatch;
  int nindex;
  
  if (g_enable!=TRUE){
    return;
  }
  if (item->stype != F_NORMAL && item->stype != F_INBOX){
    return;
  }

  prefs_common = prefs_common_get();
  if (prefs_common->online_mode != TRUE){
    return;
  }

  ac = (PrefsAccount*)account_get_default();
  g_return_if_fail(ac != NULL);

  /* check item->path for filter */
  g_print("[DEBUG] %s:%s name:%s\n", G_STRLOC, G_STRFUNC, item->name);
  g_print("[DEBUG] %s:%s path:%s\n", G_STRLOC, G_STRFUNC,  item->path);

#if 0
  MsgInfo *msginfo = folder_item_get_msginfo(item, num);
  debug_print("[DEBUG] flags:%08x UNREAD:%08x NEW:%08x MARKED:%08x ", msginfo->flags, MSG_UNREAD, MSG_NEW, MSG_MARKED);
  debug_print("[DEBUG] perm_flags:%08x \n", msginfo->flags.perm_flags);
  debug_print("[DEBUG] tmp_flags:%08x \n", msginfo->flags.tmp_flags);
  if ( g_unreadonly_flg != FALSE){
    debug_print("[DEBUG] unreadonly flag:%s\n", g_unreadonly_flg ? "true" : "false");
    if (MSG_IS_UNREAD(msginfo->flags)){
      debug_print("[DEBUG] MSG_IS_UNREAD:true");
    } else {
      return;
    }
  }
#endif    

  rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "autoforwardrc", NULL);

  g_keyfile = g_key_file_new();
  g_key_file_load_from_file(g_keyfile, rcpath, G_KEY_FILE_KEEP_COMMENTS, NULL);
  
  to=g_key_file_get_string (g_keyfile, "forward", "to", NULL);
  debug_print("[DEBUG] to:%s", to);
  to_list = address_list_append(to_list, to);


  forward_all = g_key_file_get_boolean (g_keyfile, "forward", "all", &errval);
  if (forward_all != TRUE){
    if (errval) {
      switch (errval->code){
      case G_KEY_FILE_ERROR_INVALID_VALUE:
      case G_KEY_FILE_ERROR_KEY_NOT_FOUND:
        forward_all=TRUE;
        break;
      default:
        break;
      }
    }
  }

  bmatch = FALSE;
  if (forward_all != TRUE){
    folders = g_key_file_get_string_list(g_keyfile, "forward", "folder", &gz, NULL);
    if (gz != 0) {
      /* match or not */
      nindex = 0;
      for (nindex = 0; nindex < gz; nindex++){
        if (g_strcmp0(folders[nindex], item->path) == 0){
          bmatch = TRUE;
          debug_print("[DEBUG] %s %s => match\n", folders[nindex], item->path);
        }
      }
    } else {
      bmatch = FALSE;
    }
  }else{
    bmatch = TRUE;
  }
  g_free(rcpath);
  g_return_if_fail(to_list != NULL);

  g_print("[DEBUG] item->path:%s\n", item->path);
  g_print("[DEBUG] bmatch:%d\n", bmatch);
    
  g_return_if_fail(bmatch == TRUE);

  syl_plugin_send_message_set_forward_flags(ac->address);
  syl_plugin_send_message(file, ac, to_list);
}
Exemplo n.º 24
0
static void prefs_custom_header_create(void)
{
	GtkWidget *window;
	GtkWidget *vbox;

	GtkWidget *ok_btn;
	GtkWidget *cancel_btn;

	GtkWidget *confirm_area;

	GtkWidget *vbox1;

	GtkWidget *table1;
	GtkWidget *hdr_label;
	GtkWidget *hdr_combo;
	GtkWidget *val_label;
	GtkWidget *val_entry;
	GtkWidget *val_btn;

	GtkWidget *reg_hbox;
	GtkWidget *btn_hbox;
	GtkWidget *arrow;
	GtkWidget *add_btn;
	GtkWidget *del_btn;
	GtkWidget *preview;

	GtkWidget *ch_hbox;
	GtkWidget *ch_scrolledwin;
	GtkWidget *list_view;

	GtkWidget *btn_vbox;
	GtkWidget *up_btn;
	GtkWidget *down_btn;

	debug_print("Creating custom header setting window...\n");

	window = gtkut_window_new(GTK_WINDOW_TOPLEVEL, "prefs_customheader");
	gtk_container_set_border_width (GTK_CONTAINER (window), 8);
	gtk_window_set_position (GTK_WINDOW (window), GTK_WIN_POS_CENTER);
	gtk_window_set_resizable(GTK_WINDOW (window), TRUE);

	vbox = gtk_vbox_new (FALSE, 6);
	gtk_widget_show (vbox);
	gtk_container_add (GTK_CONTAINER (window), vbox);

	gtkut_stock_button_set_create(&confirm_area, &cancel_btn, GTK_STOCK_CANCEL,
				      &ok_btn, GTK_STOCK_OK,
				      NULL, NULL);
	gtk_widget_show (confirm_area);
	gtk_box_pack_end (GTK_BOX(vbox), confirm_area, FALSE, FALSE, 0);
	gtk_widget_grab_default (ok_btn);

	gtk_window_set_title (GTK_WINDOW(window), _("Custom header configuration"));
	MANAGE_WINDOW_SIGNALS_CONNECT (window);
	g_signal_connect (G_OBJECT(window), "delete_event",
			  G_CALLBACK(prefs_custom_header_deleted),
			  NULL);
	g_signal_connect (G_OBJECT(window), "key_press_event",
			  G_CALLBACK(prefs_custom_header_key_pressed),
			  NULL);
	g_signal_connect (G_OBJECT(ok_btn), "clicked",
			  G_CALLBACK(prefs_custom_header_ok), NULL);
	g_signal_connect (G_OBJECT(cancel_btn), "clicked",
			  G_CALLBACK(prefs_custom_header_cancel), NULL);

	vbox1 = gtk_vbox_new (FALSE, VSPACING);
	gtk_widget_show (vbox1);
	gtk_box_pack_start (GTK_BOX (vbox), vbox1, TRUE, TRUE, 0);
	gtk_container_set_border_width (GTK_CONTAINER (vbox1), 2);

	table1 = gtk_table_new (3, 2, FALSE);
	gtk_widget_show (table1);
	gtk_box_pack_start (GTK_BOX (vbox1), table1,
			    FALSE, FALSE, 0);
	gtk_table_set_row_spacings (GTK_TABLE (table1), 8);
	gtk_table_set_col_spacings (GTK_TABLE (table1), 8);

	hdr_label = gtk_label_new (_("Header"));
	gtk_widget_show (hdr_label);
	gtk_table_attach (GTK_TABLE (table1), hdr_label, 0, 1, 0, 1,
			  GTK_EXPAND | GTK_SHRINK | GTK_FILL,
			  0, 0, 0);
	gtk_misc_set_alignment (GTK_MISC (hdr_label), 0, 0.5);
	
	hdr_combo = combobox_text_new(TRUE, "User-Agent", "Face", "X-Face",
				      "X-Operating-System", NULL);
	gtk_table_attach (GTK_TABLE (table1), hdr_combo, 0, 1, 1, 2,
			  GTK_EXPAND | GTK_SHRINK | GTK_FILL,
			  0, 0, 0);
	gtk_widget_set_size_request (hdr_combo, 150, -1);

	val_label = gtk_label_new (_("Value"));
	gtk_widget_show (val_label);
	gtk_table_attach (GTK_TABLE (table1), val_label, 1, 2, 0, 1,
			  GTK_EXPAND | GTK_SHRINK | GTK_FILL,
			  0, 0, 0);
	gtk_misc_set_alignment (GTK_MISC (val_label), 0, 0.5);
	
	val_entry = gtk_entry_new ();
	gtk_widget_show (val_entry);
	gtk_table_attach (GTK_TABLE (table1), val_entry, 1, 2, 1, 2,
			  GTK_EXPAND | GTK_SHRINK | GTK_FILL,
			  0, 0, 0);
	gtk_widget_set_size_request (val_entry, 200, -1);

	val_btn = gtkut_get_browse_file_btn(_("Bro_wse"));
	gtk_widget_show (val_btn);
	gtk_table_attach (GTK_TABLE (table1), val_btn, 2, 3, 1, 2,
			  GTK_EXPAND | GTK_SHRINK | GTK_FILL,
			  0, 0, 0);
	g_signal_connect (G_OBJECT (val_btn), "clicked",
			  G_CALLBACK (prefs_custom_header_val_from_file_cb),
			  NULL);

	/* add / delete */

	reg_hbox = gtk_hbox_new (FALSE, 4);
	gtk_widget_show (reg_hbox);
	gtk_box_pack_start (GTK_BOX (vbox1), reg_hbox, FALSE, FALSE, 0);

	arrow = gtk_arrow_new (GTK_ARROW_DOWN, GTK_SHADOW_OUT);
	gtk_widget_show (arrow);
	gtk_box_pack_start (GTK_BOX (reg_hbox), arrow, FALSE, FALSE, 0);
	gtk_widget_set_size_request (arrow, -1, 16);

	btn_hbox = gtk_hbox_new (TRUE, 4);
	gtk_widget_show (btn_hbox);
	gtk_box_pack_start (GTK_BOX (reg_hbox), btn_hbox, FALSE, FALSE, 0);

	add_btn = gtk_button_new_from_stock (GTK_STOCK_ADD);
	gtk_widget_show (add_btn);
	gtk_box_pack_start (GTK_BOX (btn_hbox), add_btn, FALSE, TRUE, 0);
	g_signal_connect (G_OBJECT (add_btn), "clicked",
			  G_CALLBACK (prefs_custom_header_add_cb),
			  NULL);

	del_btn = gtk_button_new_from_stock (GTK_STOCK_DELETE);
	gtk_widget_show (del_btn);
	gtk_box_pack_start (GTK_BOX (btn_hbox), del_btn, FALSE, TRUE, 0);
	g_signal_connect (G_OBJECT (del_btn), "clicked",
			  G_CALLBACK (prefs_custom_header_delete_cb),
			  NULL);


	ch_hbox = gtk_hbox_new (FALSE, 8);
	gtk_widget_show (ch_hbox);
	gtk_box_pack_start (GTK_BOX (vbox1), ch_hbox, TRUE, TRUE, 0);

	ch_scrolledwin = gtk_scrolled_window_new (NULL, NULL);
	gtk_widget_set_size_request (ch_scrolledwin, -1, 200);
	gtk_widget_show (ch_scrolledwin);
	gtk_box_pack_start (GTK_BOX (ch_hbox), ch_scrolledwin, TRUE, TRUE, 0);
	gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (ch_scrolledwin),
					GTK_POLICY_AUTOMATIC,
					GTK_POLICY_AUTOMATIC);

	list_view = prefs_custom_header_list_view_create();
	gtk_widget_show (list_view);
	gtk_container_add (GTK_CONTAINER (ch_scrolledwin), list_view);

	btn_vbox = gtk_vbox_new (FALSE, 8);
	gtk_widget_show (btn_vbox);
	gtk_box_pack_start (GTK_BOX (ch_hbox), btn_vbox, FALSE, FALSE, 0);

	up_btn = gtk_button_new_from_stock (GTK_STOCK_GO_UP);
	gtk_widget_show (up_btn);
	gtk_box_pack_start (GTK_BOX (btn_vbox), up_btn, FALSE, FALSE, 0);
	g_signal_connect (G_OBJECT (up_btn), "clicked",
			  G_CALLBACK (prefs_custom_header_up), NULL);

	down_btn = gtk_button_new_from_stock (GTK_STOCK_GO_DOWN);
	gtk_widget_show (down_btn);
	gtk_box_pack_start (GTK_BOX (btn_vbox), down_btn, FALSE, FALSE, 0);
	g_signal_connect (G_OBJECT (down_btn), "clicked",
			  G_CALLBACK (prefs_custom_header_down), NULL);

	preview = gtk_image_new ();
	gtk_widget_show (preview);
	gtk_box_pack_start (GTK_BOX (btn_vbox), preview, FALSE, FALSE, 0);

	gtk_widget_show_all(window);

	customhdr.window     = window;
	customhdr.ok_btn     = ok_btn;
	customhdr.cancel_btn = cancel_btn;
	customhdr.preview = preview;

	customhdr.hdr_combo  = hdr_combo;
	customhdr.hdr_entry  = gtk_bin_get_child(GTK_BIN((hdr_combo)));
	customhdr.val_entry  = val_entry;

	customhdr.list_view   = list_view;
}
Exemplo n.º 25
0
static struct tee_mmap_region *init_xlation_table(struct tee_mmap_region *mm,
			uint64_t base_va, uint64_t *table, unsigned level)
{
	unsigned level_size_shift = L1_XLAT_ADDRESS_SHIFT - (level - 1) *
						XLAT_TABLE_ENTRIES_SHIFT;
	unsigned level_size = 1 << level_size_shift;
	uint64_t level_index_mask = XLAT_TABLE_ENTRIES_MASK << level_size_shift;

	assert(level <= 3);

	debug_print("New xlat table (level %u):", level);

	do  {
		uint64_t desc = UNSET_DESC;

		if (mm->va + mm->size <= base_va) {
			/* Area now after the region so skip it */
			mm++;
			continue;
		}


		if (mm->va >= base_va + level_size) {
			/* Next region is after area so nothing to map yet */
			desc = INVALID_DESC;
			debug_print("%*s%010" PRIx64 " %8x",
					level * 2, "", base_va, level_size);
		} else if (mm->va <= base_va && mm->va + mm->size >=
				base_va + level_size) {
			/* Next region covers all of area */
			int attr = mmap_region_attr(mm, base_va, level_size);

			if (attr >= 0) {
				desc = mmap_desc(attr,
						 base_va - mm->va + mm->pa,
						 level);
				debug_print("%*s%010" PRIx64 " %8x %s-%s-%s-%s",
					level * 2, "", base_va, level_size,
					attr & (TEE_MATTR_CACHE_CACHED <<
						TEE_MATTR_CACHE_SHIFT) ?
						"MEM" : "DEV",
					attr & TEE_MATTR_PW ? "RW" : "RO",
					attr & TEE_MATTR_PX ? "X" : "XN",
					attr & TEE_MATTR_SECURE ? "S" : "NS");
			} else {
				debug_print("%*s%010" PRIx64 " %8x",
					level * 2, "", base_va, level_size);
			}
		}
		/* else Next region only partially covers area, so need */

		if (desc == UNSET_DESC) {
			/* Area not covered by a region so need finer table */
			uint64_t *new_table = xlat_tables[next_xlat++];
			/* Clear table before use */
			memset(new_table, 0, XLAT_TABLE_SIZE);

			assert(next_xlat <= MAX_XLAT_TABLES);
			desc = TABLE_DESC | (uint64_t)(uintptr_t)new_table;

			/* Recurse to fill in new table */
			mm = init_xlation_table(mm, base_va, new_table,
					   level + 1);
		}

		*table++ = desc;
		base_va += level_size;
	} while (mm->size && (base_va & level_index_mask));

	return mm;
}
Exemplo n.º 26
0
static void prefs_custom_header_write_config(PrefsAccount *ac)
{
	gchar *rcpath;
	PrefFile *pfile;
	GSList *cur;
	gchar buf[PREFSBUFSIZE];
	FILE * fp;
	CustomHeader *ch;

	GSList *all_hdrs = NULL;

	debug_print("Writing custom header configuration...\n");

	rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
			     CUSTOM_HEADER_RC, NULL);

	if ((fp = g_fopen(rcpath, "rb")) == NULL) {
		if (ENOENT != errno) FILE_OP_ERROR(rcpath, "fopen");
	} else {
		all_hdrs = NULL;

		while (fgets(buf, sizeof(buf), fp) != NULL) {
			ch = custom_header_read_str(buf);
			if (ch) {
				if (ch->account_id != ac->account_id)
					all_hdrs =
						g_slist_append(all_hdrs, ch);
				else
					custom_header_free(ch);
			}
		}

		fclose(fp);
	}

	if ((pfile = prefs_write_open(rcpath)) == NULL) {
		g_warning("failed to write configuration to file");
		g_free(rcpath);
		return;
	}

	for (cur = all_hdrs; cur != NULL; cur = cur->next) {
 		CustomHeader *hdr = (CustomHeader *)cur->data;
		gchar *chstr;

		chstr = custom_header_get_str(hdr);
		if (fputs(chstr, pfile->fp) == EOF ||
		    fputc('\n', pfile->fp) == EOF) {
			FILE_OP_ERROR(rcpath, "fputs || fputc");
			prefs_file_close_revert(pfile);
			g_free(rcpath);
			g_free(chstr);
			return;
		}
		g_free(chstr);
	}

	for (cur = ac->customhdr_list; cur != NULL; cur = cur->next) {
 		CustomHeader *hdr = (CustomHeader *)cur->data;
		gchar *chstr;

		chstr = custom_header_get_str(hdr);
		if (fputs(chstr, pfile->fp) == EOF ||
		    fputc('\n', pfile->fp) == EOF) {
			FILE_OP_ERROR(rcpath, "fputs || fputc");
			prefs_file_close_revert(pfile);
			g_free(rcpath);
			g_free(chstr);
			return;
		}
		g_free(chstr);
	}

	g_free(rcpath);

 	while (all_hdrs != NULL) {
 		ch = (CustomHeader *)all_hdrs->data;
 		all_hdrs = g_slist_remove(all_hdrs, ch);
 		custom_header_free(ch);
 	}

	if (prefs_file_close(pfile) < 0) {
		g_warning("failed to write configuration to file");
		return;
	}
}
Exemplo n.º 27
0
ExecutableInMemory *LoadSharedLibrary(FileNode *file)
{
  //Read data from file and verify
  if (file == NULL)
  {
    return NULL;
  }
  ExecutableInMemory *sl = calloc(sizeof(ExecutableInMemory));

  ExecutableFileHeader *header = (ExecutableFileHeader *)file->contents;
  if (header->size != file->size)
  {
    debug_print("Invalid file header: size $d != $d\n", header->size, file->size);
    return NULL;
  }
  if (header->magic != EXECUTABLE_FILE_MAGIC)
  {
    debug_print("Invalid file header: magic\n");
    return NULL;
  }
  if ((header->type != EXECUTABLE_TYPE_LIBRARY)&&(header->type != EXECUTABLE_TYPE_EXECUTABLE))
  {
    debug_print("Invalid file header: type\n");
    return NULL;
  }
  if (header->functionCount == 0)
  {
    debug_print("Invalid file header: functions\n");
    return NULL;
  }
  if (header->functionTableOffset != sizeof(ExecutableFileHeader))
  {
    debug_print("Invalid file header: function table offset\n");
    return NULL;
  }
  if (header->resourceCount * sizeof(ResourceEntry) > file->size - sizeof(ExecutableFileHeader) - header->functionCount * sizeof(FunctionTableEntry))
  {
    debug_print("Invalid file header: resource size\n");
    return NULL;
  }
  if (header->resourceOffset > file->size - header->resourceCount * sizeof(ResourceEntry))
  {
    debug_print("Invalid file header: resource offset\n");
    return NULL;
  }
  if (header->functionsSize > file->size - sizeof(ExecutableFileHeader) - header->functionCount * sizeof(FunctionTableEntry) - header->resourceCount * sizeof(ResourceEntry))
  {
    debug_print("Invalid file header: functions size\n");
    return NULL;
  }
  if (header->functionsOffset > file->size - header->functionsSize)
  {
    debug_print("Invalid file header: functions size\n");
    return NULL;
  }
  sl->type = header->type;
  sl->functionCount = header->functionCount;
  sl->functionTable = calloc(header->functionCount * sizeof(FunctionTableEntry));
  cgc_memcpy(sl->functionTable, file->contents + header->functionTableOffset, header->functionCount * sizeof(FunctionTableEntry));
  for (int i = 0; i < sl->functionCount; i++)
  {
    sl->functionTable[i].offset -= header->functionsOffset;
  }
  sl->resourceCount = header->resourceCount;
  sl->resourceTable = calloc(header->resourceCount * sizeof(ResourceEntry));
  cgc_memcpy(sl->resourceTable, file->contents + header->resourceOffset, header->resourceCount * sizeof(ResourceEntry));
  sl->functions = calloc(header->functionsSize);
  cgc_memcpy(sl->functions, file->contents + header->functionsOffset, header->functionsSize);

  uint8_t *mainAddress = GetFunctionAddress("SharedLibraryMain", sl);
  ExecuteFunction(mainAddress);
  return sl;
}
Exemplo n.º 28
0
EXPORT int check_comps_at_nodes(
	INTERFACE	*intfc,
	O_NODE		**onode_list)
{
	NODE		**n;
	O_NODE		O_node;
	O_NODE		*onode, *on;
	COMPONENT	compi, compj;
	int		i, j;
	int		num_inconsistent = 0;

	debug_print("ccn","Entered check_comps_at_nodes()\n");
	O_node.prev = O_node.next = NULL;
	on = &O_node;
	
	if (intfc->dim != 2)
	    return 0;
	for (n = intfc->nodes; n && *n; ++n)
	{
	    onode = make_onode(*n);
	    for (i = 0; i < onode->num_c; ++i)
	    {
	    	j = (i + 1) % onode->num_c;
	    	if (onode->orient[i] == POSITIVE_ORIENTATION)
	    	    compi = negative_component(onode->nc[i]);
	    	else
	    	    compi = positive_component(onode->nc[i]);
	    	if (onode->orient[j] == POSITIVE_ORIENTATION)
	    	    compj = positive_component(onode->nc[j]);
	    	else
	    	    compj = negative_component(onode->nc[j]);
	    	
	    	if (compi != compj)
	    	{
		    if (debugging("inconsis"))
		    {
		    	char xname[100];
			double radius = 3.0*topological_grid(intfc).h[0];
			print_node(*n);
		    	sprintf(xname,"inconsis_comp-%d-%d",pp_mynode(),
					num_inconsistent);
			xgraph_2d_intfc_within_range(xname,intfc,
					Coords((*n)->posn),radius,NO);
		    }
	    	    ++num_inconsistent;
	    	    on->next = onode;
	    	    onode->prev = on;
	    	    on = onode;
	    	    break;
	    	}
	    }
	}
	if (onode_list!= NULL)
	{
	    *onode_list = O_node.next;
	    if (*onode_list)
	    	(*onode_list)->prev = NULL;
	}
	if ((num_inconsistent > 0) && debugging("ccn"))
	{
	    (void) printf("Inconsistent components found at nodes\n");
	    for (onode = *onode_list; onode != NULL; onode = onode->next)
	    	print_onode(onode);
	    print_interface(intfc);
	}
	debug_print("ccn","Left check_comps_at_nodes(), num_inconsistent = %d\n",
	      num_inconsistent);
	return num_inconsistent;
}		/*end check_comps_at_node*/
Exemplo n.º 29
0
static mmap_region_t *init_xlation_table(mmap_region_t *mm,
					unsigned long base_va,
					unsigned long *table, unsigned level)
{
	unsigned level_size_shift = L1_XLAT_ADDRESS_SHIFT - (level - 1) *
						XLAT_TABLE_ENTRIES_SHIFT;
	unsigned level_size = 1 << level_size_shift;
	unsigned long level_index_mask = XLAT_TABLE_ENTRIES_MASK << level_size_shift;

	assert(level <= 3);

	debug_print("New xlat table:\n");

	do  {
		unsigned long desc = UNSET_DESC;

		if (!mm->size) {
			/* Done mapping regions; finish zeroing the table */
			desc = INVALID_DESC;
		} else if (mm->base_va + mm->size <= base_va) {
			/* Area now after the region so skip it */
			++mm;
			continue;
		}

		debug_print("%s VA:0x%lx size:0x%x ", get_level_spacer(level),
				base_va, level_size);

		if (mm->base_va >= base_va + level_size) {
			/* Next region is after area so nothing to map yet */
			desc = INVALID_DESC;
		} else if (mm->base_va <= base_va && mm->base_va + mm->size >=
				base_va + level_size) {
			/* Next region covers all of area */
			int attr = mmap_region_attr(mm, base_va, level_size);
			if (attr >= 0)
				desc = mmap_desc(attr,
					base_va - mm->base_va + mm->base_pa,
					level);
		}
		/* else Next region only partially covers area, so need */

		if (desc == UNSET_DESC) {
			/* Area not covered by a region so need finer table */
			unsigned long *new_table = xlat_tables[next_xlat++];
			assert(next_xlat <= MAX_XLAT_TABLES);
			desc = TABLE_DESC | (unsigned long)new_table;

			/* Recurse to fill in new table */
			mm = init_xlation_table(mm, base_va,
						new_table, level+1);
		}

		debug_print("\n");

		*table++ = desc;
		base_va += level_size;
	} while ((base_va & level_index_mask) && (base_va < ADDR_SPACE_SIZE));

	return mm;
}
Exemplo n.º 30
0
/* Return CENTERING_ERROR if failed */
static Centering get_centering(double correction_mat[3][3],
			       SPGCONST int transform_mat[3][3],
			       const Laue laue)
{
  int det;
  double trans_corr_mat[3][3];
  Centering centering;

  mat_copy_matrix_d3(correction_mat, identity);
  det = abs(mat_get_determinant_i3(transform_mat));
  debug_print("laue class: %d\n", laue);
  debug_print("multiplicity: %d\n", det);

  switch (det) {

  case 1:
    centering = PRIMITIVE;
    break;

  case 2:
    centering = get_base_center(transform_mat);
    if (centering == A_FACE) {
      if (laue == LAUE2M) {
	debug_print("Monocli A to C\n");
	mat_copy_matrix_d3(correction_mat, monocli_a2c);
      } else {
	mat_copy_matrix_d3(correction_mat, a2c);
      }
      centering = C_FACE;
    }
    if (centering == B_FACE) {
      mat_copy_matrix_d3(correction_mat, b2c);
      centering = C_FACE;
    }
    if (laue == LAUE2M && centering == BODY) {
      debug_print("Monocli I to C\n");
      mat_copy_matrix_d3(correction_mat, monocli_i2c);
      centering = C_FACE;
    }
    break;

  case 3:
    /* hP (a=b) but not hR (a=b=c) */
    centering = R_CENTER;
    mat_multiply_matrix_id3(trans_corr_mat, transform_mat, rhombo_obverse);
    if (mat_is_int_matrix(trans_corr_mat, INT_PREC)) {
      mat_copy_matrix_d3(correction_mat, rhombo_obverse);
      debug_print("R-center observe setting\n");
      debug_print_matrix_d3(trans_corr_mat);
    }
    mat_multiply_matrix_id3(trans_corr_mat, transform_mat, rhomb_reverse);
    if (mat_is_int_matrix(trans_corr_mat, INT_PREC)) {
      mat_copy_matrix_d3(correction_mat, rhomb_reverse);
      debug_print("R-center reverse setting\n");
      debug_print_matrix_d3(trans_corr_mat);
    }
    break;

  case 4:
    centering = FACE;
    break;

  default:
    centering = CENTERING_ERROR;
    break;
  }

  return centering;
}