Exemple #1
0
graph_t *mkGraphABCDE()
{
    graph_t *g = graph_new(streq);
    graph_add_node(g, strdup("A"));
    graph_add_node(g, strdup("B"));
    graph_add_node(g, strdup("C"));
    graph_add_node(g, strdup("D"));
    graph_add_node(g, strdup("E"));
    return g;
}
Exemple #2
0
graph_s *border_graph(msw_s *ms)
{
	graph_s *n = graph_new();
	int *r = ms->revealed;
	int *graph_perm = malloc(ms->g->nodes * sizeof(int));
	int j = 0;
	for(int i = 0; i < ms->g->nodes;i++){
		if (r[i] == 0){
			graph_add_node(n,ms->g->node_list[i]);
			graph_perm[i]=j;
			j++;
		}
	}
	int neighb;
	for(int i = 0; i < ms->g->nodes;i++){
		for(int j = 0; j < ms->g->neighb_count[i]; j++){
			neighb = ms->g->neighb_list[i][j]; 
			if (r[i] > 0 && r[neighb] == 0){
				graph_add_arc(n,graph_perm[neighb],i);
			}
		}
	}
	free(graph_perm);
	return n;
}
Exemple #3
0
static sexpr sexpr_to_graph (sexpr sx)
{
    sexpr g = graph_create ();
    sexpr c = car(sx);

    while (consp(c))
    {
        sexpr cx    = car (c);
        sexpr cxcar = car (cx);

        graph_add_node (g, cxcar);

        c = cdr (c);
    }

    c = cdr(sx);

    while (consp(c))
    {
        sexpr cx     = car (c);
        sexpr cxcar  = car (cx);
        sexpr cxcdr  = cdr (cx);
        sexpr cxcadr = car (cxcdr);
        sexpr cxcddr = cdr (cxcdr);

        struct graph_node *ns = graph_search_node (g, cxcar);
        struct graph_node *nt = graph_search_node (g, cxcadr);

        if ((ns != (struct graph_node *)0) && (nt != (struct graph_node *)0))
        {
            graph_node_add_edge (ns, nt, cxcddr);
        }

        c = cdr (c);
    }

    c = car(sx);

    while (consp(c))
    {
        sexpr cx    = car (c);
        sexpr cxcar = car (cx);
        sexpr cxcdr = cdr (cx);

        struct graph_node *n = graph_search_node (g, cxcar);

        if (n != (struct graph_node *)0)
        {
            n->label = cxcdr;
        }

        c = cdr (c);
    }

    return g;
}
Exemple #4
0
/* Abre el archivo `filename` y crea un grafo con la lista de adyacencia
 * inscrita en el. Cada linea del archivo debe cumplir la siguiente expresion
 * regular (con BL como el BUFFER_LEN): '\d{1,BL}:( \d{1,BL})*\n'
 * Retorno: Un grafo G (descrito en structures.h)*/
struct graph *file_to_graph(const char * filename)
{
  char ch  = '\0', 
       buffer[BUFFER_LEN] = ""; // Se puede calcular por el nro de lineas.
  unsigned int  i, id, size, *tmp;
  struct list *last_list;
  struct node *last_node;
  struct graph *G;

  FILE *fp = fopen(filename, "r");
  if(fp == NULL){
    fprintf(stderr,"No se puede leer el archivo \"%s\".\n", filename);
    return NULL;
  }

  size = count_lines(fp);
  G = new_graph(size);
  IDC = (int*) calloc(size, sizeof(int));
  ODC = (int*) malloc(size * sizeof(int));

  while (1) {
    i = 0;
    do {
      ch = getc(fp);
      if (ch == EOF) {
        fclose(fp);
        return G;
      } else if (ch == ':') {
        id = atoi(buffer);
        last_list = new_list();
        ch = getc(fp);
        if (ch == '\n'){
          break;
        }
        i = 0;
        memset(buffer, 0, BUFFER_LEN);
      } else if (ch == ' ' || ch == '\n') {
        tmp = (int *) malloc(sizeof(int));
        buffer[i] = '\0';
        *tmp = atoi(buffer);
        list_add(last_list, tmp);
        IDC[*tmp]++;
        i = 0;
        memset(buffer, 0, BUFFER_LEN);
      } else {
        buffer[i++] = ch;
      } 
    } while (ch != '\n');
    ODC[id] = last_list->size;
    last_node = new_node(id, last_list);
    graph_add_node(G, last_node);
    last_node = NULL;
    last_list = NULL;
  }
}
int main(int argc, char **argv){

  // user didn't specify the input file name containing the graph structure
  if(argc != 2){
     printf("Usage: ./main <file_name>..\n");
     return(1);
  }

  FILE *fpr = NULL;
  char line[LEN];
  int i, j, node_value, edges, list_value, weight;
  int num_nodes = 8;
  graph *gr = NULL;


  // graph initialization
  gr = graph_init(num_nodes);
  if(gr == NULL){
     return(1);
  }

  // open the file again
  fpr = open_file(argv[1], "r");
  i = 0;
  while(fscanf(fpr, "%d %d", &node_value, &edges) != EOF){

     gr->nodes[i]->value = node_value;
     
     // read all the node adjacent to the current one
     for(j = 0; j<edges; j++){
        fscanf(fpr, "%d %d", &list_value, &weight);
        gr = graph_add_node(gr, i, list_value, weight);
        if(gr == NULL){
           return(1);
        }
     }
     i++;
  }

  fclose(fpr);

  //print_graph(gr);

  //depth_first_search(gr, 0);
  //breadth_first_search(gr);
  dijkstra(gr, 0);

  for(j=0; j<gr->num_nodes; j++){
    printf("Node: %d\tweight: %d\n", gr->nodes[j]->value, gr->nodes[j]->distance);
  }
 
  return (0);
}
Exemple #6
0
int main(int argc, char **argv) {
	GRAPH *g = graph_new(NODES_MAX);
	int i;
	names = calloc(NODES_MAX, sizeof(char **));

	srand(time(NULL));

	for (i = 0; i < NODES_MAX; i++)
		graph_add_node(g);
	for (i = 0; i < NODES_MAX; i++) {
		graph_add_link(g, i, i / 4, 1, 1);
	}
		

	fprintf(stderr, "Found %i nodes\n", determine_links(g, 0));

	return 0;
}
int
main (void)
{
  Graph *test_graph = graph_new ();

  GraphNode *a = graph_add_node (test_graph, NULL);
  GraphNode *b = graph_add_node (test_graph, NULL);
  GraphNode *c = graph_add_node (test_graph, NULL);
  GraphNode *c1 = graph_add_node (test_graph, NULL);
  GraphNode *c2 = graph_add_node (test_graph, NULL);
  GraphNode *c11 = graph_add_node (test_graph, NULL);
  GraphNode *d = graph_add_node (test_graph, NULL);

  GraphEdge *ab = graph_add_edge (test_graph, a, b, NULL);
  GraphEdge *bc = graph_add_edge (test_graph, b, c, NULL);
  GraphEdge *cd = graph_add_edge (test_graph, c, d, NULL);
  GraphEdge *da = graph_add_edge (test_graph, d, a, NULL);

  graph_add_edge (test_graph, c, c1, NULL);
  graph_add_edge (test_graph, c1, c11, NULL);
  graph_add_edge (test_graph, c, c2, NULL);

  graph_dump_by_edges (test_graph, "test_graph.dot", NULL);

  GQueue *path;
  gboolean result = graph_node_in_cycle (test_graph, a, &path);
  g_assert (result);
  g_assert (g_queue_peek_head (path) == da);
  g_assert (g_queue_peek_nth (path, 1) == cd);
  g_assert (g_queue_peek_nth (path, 2) == bc);
  g_assert (g_queue_peek_tail (path) == ab);

  g_queue_free (path);

  exit (EXIT_SUCCESS);
}
Exemple #8
0
int rdis_user_function (struct _rdis * rdis, uint64_t address)
{
    // get a tree of all functions reachable at this address
    struct _map * functions = loader_function_address(rdis->loader,
                                                      rdis->memory,
                                                      address);

    // add in this address as a new function as well
    struct _function * function = function_create(address);
    map_insert(functions, function->address, function);
    object_delete(function);

    // for each newly reachable function
    struct _map_it * mit;
    for (mit = map_iterator(functions); mit != NULL; mit = map_it_next(mit)) {
        struct _function * function = map_it_data(mit);
        uint64_t fitaddress = function->address;

        // if we already have this function, skip it
        if (map_fetch(rdis->functions, function->address) != NULL)
            continue;

        // add this function to the rdis->function_tree
        map_insert(rdis->functions, function->address, function);

        // add label
        struct _label * label = loader_label_address(rdis->loader,
                                                     rdis->memory,
                                                     fitaddress);
        map_insert(rdis->labels, fitaddress, label);
        object_delete(label);

        // if this function is already in our graph, all we need to do is make
        // sure its a separate node and then remove function predecessors
        struct _graph_node * node = graph_fetch_node_max(rdis->graph, fitaddress);
        if (node != NULL) {

            // already a node, remove function predecessors
            if (node->index == address) {
                remove_function_predecessors(rdis->graph, rdis->functions);
                continue;
            }

            // search for instruction with given address
            struct _list    * ins_list = node->data;
            struct _list_it * it;
            for (it = list_iterator(ins_list); it != NULL; it = it->next) {
                struct _ins * ins = it->data;
                // found instruction
                if (ins->address == fitaddress) {
                    // create a new instruction list.
                    // add remaining instructions to new list while removing them from
                    // the current list
                    struct _list * new_ins_list = list_create();
                    while (1) {
                        list_append(new_ins_list, it->data);
                        it = list_remove(ins_list, it);
                        if (it == NULL)
                            break;
                    }
                    // create a new graph node for this new function
                    graph_add_node(rdis->graph, fitaddress, new_ins_list);
                    // all graph successors from old node are added to new node
                    struct _queue   * queue      = queue_create();
                    struct _list    * successors = graph_node_successors(node);
                    struct _list_it * sit;
                    for (sit = list_iterator(successors);
                         sit != NULL;
                         sit = sit->next) {
                        struct _graph_edge * edge = sit->data;
                        graph_add_edge(rdis->graph,
                                       fitaddress,
                                       edge->tail,
                                       edge->data);
                        queue_push(queue, edge);
                    }
                    object_delete(successors);

                    // and removed from old node
                    while (queue->size > 0) {
                        struct _graph_edge * edge = queue_peek(queue);
                        graph_remove_edge(rdis->graph, edge->head, edge->tail);
                        queue_pop(queue);
                    }
                    object_delete(queue);

                    // that was easy
                    break;
                }
            }
            if (it != NULL)
                continue;
        }

        // we need to create a new graph for this node
        struct _graph * graph = loader_graph_address(rdis->loader,
                                                     rdis->memory,
                                                     fitaddress);
        graph_merge(rdis->graph, graph);
        object_delete(graph);
    }

    object_delete(functions);

    rdis_callback(rdis, RDIS_CALLBACK_ALL);

    return 0;
}
Exemple #9
0
int main(){
	struct graph* 	graph;
	struct graph* 	clone;
	char 			node_desc[NODE_DESCRIPTION_LENGTH];
	char 			edge_desc[EDGE_DESCRIPTION_LENGTH];
	struct node* 	node_asterix;
	struct node* 	node_obelix;
	struct node* 	node_idefix;
	struct node* 	node_abraracourcix;

	graph = graph_create(NODE_DESCRIPTION_LENGTH, EDGE_DESCRIPTION_LENGTH);
	graph_register_dotPrint_callback(graph, NULL, asterix_dotPrint_node, asterix_dotPrint_edge, NULL)

	/* add nodes */
	snprintf(node_desc, NODE_DESCRIPTION_LENGTH, "asterix");
	node_asterix = graph_add_node(graph, &node_desc);
	if (node_asterix == NULL){
		log_err("unable to add node to graph");
	}

	snprintf(node_desc, NODE_DESCRIPTION_LENGTH, "obelix");
	node_obelix = graph_add_node(graph, &node_desc);
	if (node_obelix == NULL){
		log_err("unable to add node to graph");
	}

	snprintf(node_desc, NODE_DESCRIPTION_LENGTH, "idefix");
	node_idefix = graph_add_node(graph, &node_desc);
	if (node_idefix == NULL){
		log_err("unable to add node to graph");
	}

	snprintf(node_desc, NODE_DESCRIPTION_LENGTH, "abraracourcix");
	node_abraracourcix = graph_add_node(graph, &node_desc);
	if (node_abraracourcix == NULL){
		log_err("unable to add node to graph");
	}

	/* add edges */
	snprintf(edge_desc, EDGE_DESCRIPTION_LENGTH, "friend");
	if (graph_add_edge(graph, node_obelix, node_asterix, &edge_desc) == NULL){
		log_err("unable to add edge to graph");
	}

	snprintf(edge_desc, EDGE_DESCRIPTION_LENGTH, "obey");
	if (graph_add_edge(graph, node_idefix, node_obelix, &edge_desc) == NULL){
		log_err("unable to add edge to graph");
	}

	snprintf(edge_desc, EDGE_DESCRIPTION_LENGTH, "rule");
	if (graph_add_edge(graph, node_abraracourcix, node_obelix, &edge_desc) == NULL){
		log_err("unable to add edge to graph");
	}

	snprintf(edge_desc, EDGE_DESCRIPTION_LENGTH, "rule");
	if (graph_add_edge(graph, node_abraracourcix, node_asterix, &edge_desc) == NULL){
		log_err("unable to add edge to graph");
	}

	clone = graph_clone(graph, asterix_copy_node, asterix_copy_edge, NULL);

	graph_delete(graph);

	/* print graph */
	if (graphPrintDot_print(clone, "asterix.dot", NULL)){
		log_err("unable to print graph to dot format");
	}

	graph_delete(clone);

	return 0;
}
Exemple #10
0
static void
handle_graph_message(UiConnection *self, const gchar *command, JsonObject *payload,
                SoupWebsocketConnection *ws)
{
    g_return_if_fail(payload);

    Graph *graph = NULL;
    if (g_strcmp0(command, "clear") != 0) {
        // All other commands must have graph
        // TODO: change FBP protocol to use 'graph' instead of 'id'?
        const gchar *graph_id = json_object_get_string_member(payload, "graph");
        Network *net = (graph_id) ? g_hash_table_lookup(self->network_map, graph_id) : NULL;
        graph = (net) ? net->graph : NULL;
        g_return_if_fail(graph);
    }

    if (g_strcmp0(command, "clear") == 0) {
        const gchar *graph_id = json_object_get_string_member(payload, "id");
        Graph *graph = graph_new(graph_id, self->component_lib);

        Network *network = network_new(graph);
        ui_connection_add_network(self, graph_id, network);
    } else if (g_strcmp0(command, "addnode") == 0) {
        graph_add_node(graph,
            json_object_get_string_member(payload, "id"),
            json_object_get_string_member(payload, "component")
        );
    } else if (g_strcmp0(command, "removenode") == 0) {
        graph_remove_node(graph,
            json_object_get_string_member(payload, "id")
        );
    } else if (g_strcmp0(command, "changenode") == 0) {
        // Just metadata, ignored
    } else if (g_strcmp0(command, "addinitial") == 0) {
        JsonObject *tgt = json_object_get_object_member(payload, "tgt");
        JsonObject *src = json_object_get_object_member(payload, "src");
        GValue data = G_VALUE_INIT;
        json_node_get_value(json_object_get_member(src, "data"), &data);
        graph_add_iip(graph,
            json_object_get_string_member(tgt, "node"),
            json_object_get_string_member(tgt, "port"),
            &data
        );
        g_value_unset(&data);
    } else if (g_strcmp0(command, "removeinitial") == 0) {
        JsonObject *tgt = json_object_get_object_member(payload, "tgt");
        graph_remove_iip(graph,
            json_object_get_string_member(tgt, "node"),
            json_object_get_string_member(tgt, "port")
        );
    } else if (g_strcmp0(command, "addedge") == 0) {
        JsonObject *src = json_object_get_object_member(payload, "src");
        JsonObject *tgt = json_object_get_object_member(payload, "tgt");
        graph_add_edge(graph,
            json_object_get_string_member(src, "node"),
            json_object_get_string_member(src, "port"),
            json_object_get_string_member(tgt, "node"),
            json_object_get_string_member(tgt, "port")
        );
    } else if (g_strcmp0(command, "removeedge") == 0) {
        JsonObject *src = json_object_get_object_member(payload, "src");
        JsonObject *tgt = json_object_get_object_member(payload, "tgt");
        graph_remove_edge(graph,
            json_object_get_string_member(src, "node"),
            json_object_get_string_member(src, "port"),
            json_object_get_string_member(tgt, "node"),
            json_object_get_string_member(tgt, "port")
        );
    } else if (g_strcmp0(command, "changeedge") == 0) {
        // Just metadata, ignored
    } else {
        imgflo_warning("Unhandled message on protocol 'graph', command='%s'", command);
    }
}
Exemple #11
0
int main(int argc, char *argv[]) {

	int nv, ne, i, ind1, ind2, len;
	double mf;
	FILE *fp, *fp_meas;
	int tt;

	char str1[256] = "";
	char *sg;
	char *ms_f;
	char *of;
	int legacy = 0;
	int ii = 1;

	sf *sf;

	if (argc < 4) {
		printf(
				"Usage: exampleProgram nameSizeGraph nameFileValues outputFile \n");
		exit(-1);
	}
	if (argc >= 4){
		if (!strcmp("-l",argv[ii])){
			legacy = 1;
			ii++;
			printf("Legacy output mode\n");
		}
	}
	sg = argv[ii++];
	ms_f = argv[ii++];
	of = argv[ii++];
	if ((fp = fopen(sg, "r")) == NULL) {
		printf("Error (Reading): unable to open .size!\n");
		return (0);
	}
	if ((fp_meas = fopen(ms_f, "r")) == NULL) {
		printf("Error (Reading): unable to open measuring function file!\n");
		return (0);
	}

	tt = fscanf(fp, "%d\n %d\n", &nv, &ne);

	Graph *G = new_graph(nv);

	for (i = 0; i < nv; i++) {
		tt = fscanf(fp_meas, "%lf", &mf);
		graph_add_node(G,mf);
	}

	printf("Done\n");

	int x, y;
	for (i = 0; i < ne; i++) {
		tt = fscanf(fp, "%d %d \n", &ind1, &ind2);
		x = ind1;
		y = ind2;
		add_new_edge_graph(G,x,y);
	}

	fclose(fp);
	fclose(fp_meas);

	sf = newDeltaStarReductionAlgorithm(G);

	printf("Delta star reduction: done\n");

	destroy_graph(G);

	write_ang_pt(sf, of, legacy);

	printf("Sf printed\n");

	sf_destroy(sf);

	return 0;

}
/**
 * Builds a snp graph from the snps array
 */
graph *graph_from_snps(GapIO *io, snp_t *snp, int nsnps, double c_offset) {
    graph *g = NULL;
    int i, j;
    int ntemplates, *templates = NULL;
    node **tmpl_map = NULL;
    int lookup[256];

    if (verbosity)
	puts("Building graph");

    /* lookup table for fast base to index conversion */
    for (i = 0; i < 256; i++)
	lookup[i] = 0;
    lookup['A'] = lookup['a'] = 1;
    lookup['C'] = lookup['c'] = 2;
    lookup['G'] = lookup['g'] = 3;
    lookup['T'] = lookup['t'] = 4;
    lookup['*'] = 5;

    g = graph_create();
    g->correlation_offset = c_offset;

    /*
     * Obtain a list of unique template numbers, by collecting and sorting.
     * For each unique template we initialise the graph node.
     *
     * At the end of this we have ntemplates unique templates and
     * tmpl_map[] indexed by Gap4 template number maps us to the
     * node in the graph.
     */
    for (ntemplates = i = 0; i < nsnps; i++) {
	ntemplates += snp[i].nseqs;
    }
    templates = (int *)malloc(ntemplates * sizeof(int));
    for (ntemplates = i = 0; i < nsnps; i++) {
	for (j = 0; j < snp[i].nseqs; j++) {
	    templates[ntemplates++] = snp[i].seqs[j].tmplate;
	}
    }
    tmpl_map = (node **)xcalloc(Ntemplates(io)+1, sizeof(*tmpl_map));
    qsort(templates, ntemplates, sizeof(int), int_compare);
    for (i = j = 0; i < ntemplates; j++) {
	tmpl_map[templates[i]] = graph_add_node(g);
	tmpl_map[templates[i]]->number = j;
	tmpl_map[templates[i]]->tname  =
	    strdup(get_template_name(io, templates[i]));

	do {
	    i++;
	} while (i < ntemplates && templates[i] == templates[i-1]);
    }
    xfree(templates);
    ntemplates = j;

    g->nsnps = nsnps;
    g->ntemplates = ntemplates;


    /*
     * The matrix is of size nsnps by ntemplates. It initially will consist
     * of entirely empty vectors.
     */
    g->matrix = (int (*)[6])malloc(ntemplates * nsnps * sizeof(*g->matrix));
    memset(&g->matrix[0][0], 0, ntemplates * nsnps * 6 * sizeof(int));
    for (i = j = 0; j < ntemplates; i++) {
	if (!tmpl_map[i])
	    continue;

	tmpl_map[i]->matrix = &g->matrix[j * nsnps];
	j++;
    }


    /* Create the snp_score array */
    g->snp_scores = (double *)malloc(nsnps * sizeof(*g->snp_scores));
    for (i = 0; i < nsnps; i++) {
	g->snp_scores[i] = snp[i].score;
    }

    /* Now add basecalls to the matrix from snp info */
    for (i = 0; i < nsnps; i++) {
	for (j = 0; j < snp[i].nseqs; j++) {
	    node *n = tmpl_map[snp[i].seqs[j].tmplate];
	    n->matrix[i][lookup[snp[i].seqs[j].base]]++; 
	    n->tscore = snp[i].seqs[j].tscore; 
	    /* FIXME: confidence not yet used */
	}

	for (j = 0; j < ntemplates; j++) {
	    if (!g->nodes->node[j]->matrix[i][1] &&
		!g->nodes->node[j]->matrix[i][2] &&
		!g->nodes->node[j]->matrix[i][3] &&
		!g->nodes->node[j]->matrix[i][4] &&
		!g->nodes->node[j]->matrix[i][5])
 		g->nodes->node[j]->matrix[i][0]++;
	}
    }

    return g;
}
Exemple #13
0
/*
* This is the initial phase, used to populate the graph with all reachable
* nodes. We will worry about fixing edges from jmp-like mnemonics later.
*/
void x8664_graph_0 (struct _graph * graph,
                    uint64_t        address,
                    struct _map *   memory)
{
    ud_t            ud_obj;
    int             continue_disassembling = 1;
    uint64_t        last_address = -1;
    int             edge_type = INS_EDGE_NORMAL;

    struct _buffer * buffer = map_fetch_max(memory, address);

    if (buffer == NULL)
        return;

    uint64_t base_address   = map_fetch_max_key(memory, address);

    if (base_address + buffer->size < address)
        return;

    uint64_t offset = address - base_address;

    ud_init      (&ud_obj);
    ud_set_mode  (&ud_obj, 64);
    ud_set_syntax(&ud_obj, UD_SYN_INTEL);
    ud_set_input_buffer(&ud_obj, &(buffer->bytes[offset]), buffer->size - offset);

    while (continue_disassembling == 1) {
        size_t bytes_disassembled = ud_disassemble(&ud_obj);
        if (bytes_disassembled == 0) {
            break;
        }

        // even if we have already added this node, make sure we add the edge
        // from the preceeding node, in case this node was added from a jump
        // previously. otherwise we won't have an edge from its preceeding
        // instruction
        if (graph_fetch_node(graph, address) != NULL) {
            if (last_address != -1) {
                // not concerned if this call fails
                struct _ins_edge * ins_edge = ins_edge_create(edge_type);
                graph_add_edge(graph, last_address, address, ins_edge);
                object_delete(ins_edge);
            }
            break;
        }

        // create graph node for this instruction
        struct _ins * ins = x8664_ins(address, &ud_obj);
        struct _list * ins_list = list_create();
        list_append(ins_list, ins);
        graph_add_node(graph, address, ins_list);
        object_delete(ins_list);
        object_delete(ins);

        // add edge from previous instruction to this instruction
        if (last_address != -1) {
            struct _ins_edge * ins_edge = ins_edge_create(edge_type);
            graph_add_edge(graph, last_address, address, ins_edge);
            object_delete(ins_edge);
        }

        // these mnemonics cause us to continue disassembly somewhere else
        struct ud_operand * operand;
        switch (ud_obj.mnemonic) {
        case UD_Ijo   :
        case UD_Ijno  :
        case UD_Ijb   :
        case UD_Ijae  :
        case UD_Ijz   :
        case UD_Ijnz  :
        case UD_Ijbe  :
        case UD_Ija   :
        case UD_Ijs   :
        case UD_Ijns  :
        case UD_Ijp   :
        case UD_Ijnp  :
        case UD_Ijl   :
        case UD_Ijge  :
        case UD_Ijle  :
        case UD_Ijg   :
        case UD_Ijmp  :
        case UD_Iloop :
        //case UD_Icall :
            operand = &(ud_obj.operand[0]);

            if (operand->type != UD_OP_JIMM)
                break;

            if (ud_obj.mnemonic == UD_Icall)
                edge_type = INS_EDGE_NORMAL;
            else if (ud_obj.mnemonic == UD_Ijmp)
                edge_type = INS_EDGE_NORMAL; // not important, will terminate
            else
                edge_type = INS_EDGE_JCC_FALSE;

            if (operand->type == UD_OP_JIMM) {
                x8664_graph_0(graph,
                              address
                                + ud_insn_len(&ud_obj)
                                + udis86_sign_extend_lval(operand),
                              memory);
            }
            break;
        default :
            edge_type = INS_EDGE_NORMAL;
            break;
        }

        // these mnemonics cause disassembly to stop
        switch (ud_obj.mnemonic) {
        case UD_Iret :
        case UD_Ihlt :
        case UD_Ijmp :
            continue_disassembling = 0;
            break;
        default :
            break;
        }

        last_address = address;
        address += bytes_disassembled;
    }
}
Exemple #14
0
struct _graph * redis_x86_graph (uint64_t address, struct _map * memory)
{
    uint64_t next_index = 1;
    uint64_t this_index = 0;
    uint64_t last_index = 0;

    struct _redis_x86 * redis_x86 = redis_x86_create();
    redis_x86_mem_from_mem_map(redis_x86, memory);
    redis_x86->regs[RED_EIP] = address;
    redis_x86_false_stack(redis_x86);

    struct _map * ins_map = map_create();
    struct _graph * graph = graph_create();

    while (redis_x86_step(redis_x86) == REDIS_SUCCESS) {
        uint64_t address = redis_x86->ins_addr;

        // do we have an instruction at this address already?
        struct _index * index = map_fetch(ins_map, address);
        // we have an instruction, fetch it, make sure it matches
        if (index) {
            struct _graph_node * node = graph_fetch_node(graph, index->index);
            struct _ins * ins = list_first(node->data);

            // instructions diverge, create new instruction
            if (    (ins->size != redis_x86->ins_size)
                 || (memcmp(ins->bytes, redis_x86->ins_bytes, redis_x86->ins_size))) {
                ins = redis_x86_create_ins(redis_x86);
                if (ins == NULL) {
                    fprintf(stderr, "could not create ins, eip=%llx\n",
                            (unsigned long long) redis_x86->ins_addr);
                    break;
                }

                struct _list * list = list_create();
                list_append(list, ins);
                object_delete(ins);

                graph_add_node(graph, next_index, list);
                object_delete(list);

                map_remove(ins_map, redis_x86->ins_addr);
                index = index_create(next_index++);
                map_insert(ins_map, redis_x86->ins_addr, index);
                this_index = index->index;
                object_delete(index);
            }
            else
                this_index = index->index;
        }
        // no instruction at this address, create it
        else {
            struct _ins * ins = redis_x86_create_ins(redis_x86);
            if (ins == NULL) {
                fprintf(stderr, "could not create ins eip=%llx\n",
                        (unsigned long long) redis_x86->ins_addr);
                break;
            }
            struct _list * list = list_create();
            list_append(list, ins);
            object_delete(ins);

            graph_add_node(graph, next_index, list);
            object_delete(list);

            index = index_create(next_index++);
            map_insert(ins_map, redis_x86->ins_addr, index);
            this_index = index->index;
            object_delete(index);
        }

        /*
        * create an edge from last index to this index
        * because our graph library enforces both the condition that the head
        * and tail nodes are valid, and that there exists only one edge per
        * head->tail combination, we can blindly add edges here and let the
        * graph library work out the details
        */
        printf("[edge] %llx -> %llx\n",
               (unsigned long long) last_index,
               (unsigned long long) this_index);
        struct _ins_edge * ins_edge = ins_edge_create(INS_EDGE_NORMAL);
        graph_add_edge(graph, last_index, this_index, ins_edge);
        object_delete(ins_edge);
        last_index = this_index;
        printf("%llx -> %llx\n",
               (unsigned long long) last_index,
               (unsigned long long) this_index);
    }

    object_delete(ins_map);
    object_delete(redis_x86);

    return graph;
}
Exemple #15
0
struct _graph * recursive_disassemble (const struct _map * mem_map,
                                       uint64_t entry,
                struct _ins * (* ins_callback) (const struct _map *, uint64_t))
{
    struct _queue * queue = queue_create();
    struct _map * map     = map_create();

    struct _index * index = index_create(entry);
    queue_push(queue, index);
    object_delete(index);

    while (queue->size > 0) {
        struct _index * index = queue_peek(queue);

        if (map_fetch(map, index->index)) {
            queue_pop(queue);
            continue;
        }

        struct _ins * ins = ins_callback(mem_map, index->index);
        if (ins == NULL) {
            queue_pop(queue);
            continue;
        }
        map_insert(map, index->index, ins);

        struct _list_it * lit;
        for (lit = list_iterator(ins->successors); lit != NULL; lit = lit->next) {
            struct _ins_value * successor = lit->data;
            if (successor->type == INS_SUC_CALL)
                continue;
            struct _index * index = index_create(successor->address);
            queue_push(queue, index);
            object_delete(index);
        }

        queue_pop(queue);
    }

    object_delete(queue);

    // create graph nodes
    struct _graph * graph = graph_create();

    struct _map_it * mit;
    for (mit = map_iterator(map); mit != NULL; mit = map_it_next(mit)) {
        graph_add_node(graph, map_it_key(mit), map_it_data(mit));
    }

    // create graph edges
    for (mit = map_iterator(map); mit != NULL; mit = map_it_next(mit)) {
        struct _ins * ins = map_it_data(mit);
        struct _list_it * lit;
        for (lit = list_iterator(ins->successors); lit != NULL; lit = lit->next) {
            struct _ins_value * successor = lit->data;
            // don't add call edges
            if (successor->type == INS_SUC_CALL)
                continue;
            graph_add_edge(graph, ins->address, successor->address, successor);
        }
    }

    object_delete(map);

    return graph;
}
Exemple #16
0
node_t *graph_add_sam(graph_t *g, bam1_t *b, ref_t *ref, int32_t use_threads)
{
	bam_aln_t *aln = NULL;
	int32_t aln_start, aln_index, ref_index, aln_ref_index;
	int32_t i;
	node_t *prev_node=NULL, *cur_node=NULL, *ret_node=NULL;
	uint8_t type, strand;

	aln_start = b->core.pos+1;
	aln_ref_index = b->core.tid;
	aln = bam_aln_init(b, ref);
	strand =  bam1_strand(b);

	// --- SYNC ON --- 
	if(1 == use_threads) pthread_mutex_lock(&graph_mutex); // synchronize start
	if(aln_start < g->position_start) {
		int32_t diff = g->position_start - aln_start;
		graph_nodes_realloc(g, g->position_end - aln_start + 1); // alloc more memory if needed
		// shift up
		for(i=g->position_end-g->position_start;0<=i;i--) {
			// swap
			node_list_t *list = g->nodes[i+diff];
			g->nodes[i+diff] = g->nodes[i];
			g->nodes[i] = list;
		}
		g->position_start = aln_start;
	}

	if(1 == g->is_empty) {
		for(i=0;i<g->position_end - g->position_start + 1;i++) {
			node_list_clear(g->nodes[i]);
			assert(0 == g->nodes[i]->length); // DEBUG
		}
		g->position_start = aln_start;
		if(ALN_GAP == aln->ref[0]) {
			g->position_start--;
		}
		g->position_end = g->position_start;
		g->contig = aln_ref_index + 1;
		g->is_empty = 0;
	}
	if(1 == use_threads) pthread_mutex_unlock(&graph_mutex); // synchronize end 
	// --- SYNC OFF --- 
	
	for(aln_index=0,ref_index=-1;aln_index<aln->length;aln_index++,prev_node=cur_node) {

		// Skip over a deletion
		while(ALN_GAP == aln->read[aln_index]) {
			aln_index++;
			ref_index++;
		}

		if(aln->read[aln_index] == aln->ref[aln_index]) { // match
			type = NODE_MATCH;
		}
		else if(aln->ref[aln_index] == ALN_GAP) { // insertion
			type = NODE_INSERTION;
		}
		else { // mismatch
			type = NODE_MISMATCH;
		}
		if(NULL == prev_node || NODE_INSERTION != __node_type(prev_node)) { // previous was an insertion, already on the position
			ref_index++;
		}

		cur_node = graph_add_node(g, 
				node_init(aln->read[aln_index], type, g->contig, aln_start + ref_index, prev_node),
				prev_node,
				use_threads);
	
		if(NULL == prev_node && 0 == strand) { // first node and forward strand
			ret_node = cur_node;
		}
	}

	if(1 == strand) {
		ret_node = cur_node;
	}

	bam_aln_free(aln);
	
	return ret_node;
}