Skip to content

Commit 7aba1a0

Browse files
committed
bug fix
1 parent e95eca8 commit 7aba1a0

417 files changed

Lines changed: 275 additions & 1154663 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

codeql_setup.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
rm -rf codeql_dir
44
mkdir codeql_dir
55
cd codeql_dir
6-
wget https://github.com/github/codeql-cli-binaries/releases/download/v2.4.1/codeql-linux64.zip
6+
wget https://github.com/github/codeql-cli-binaries/releases/download/v2.5.0/codeql-linux64.zip
77
unzip codeql-linux64.zip
88
git clone https://github.com/github/codeql.git codeql_repo
99

data_prep/graph/build_graph.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,19 @@
55

66
def main(args: List[str]) -> None:
77
if not len(args) == 4:
8-
print('Usage: python3 build_graph.py <facts_dir> <join_filepath> <output_file>')
8+
print('Usage: python3 build_graph.py <tables_dir> <join_filepath> <output_file>')
99
exit(1)
1010

11-
facts_dir = args[1]
11+
tables_dir = args[1]
1212
join_filepath = args[2]
1313
output_file = args[3]
1414

1515
language = 'python'
16-
graph_builder = GraphBuilder(facts_dir, join_filepath, language)
16+
graph_builder = GraphBuilder(tables_dir, join_filepath, language)
1717
# When include_callgraph=True then callgraphs are added to the graph.
1818
# The default is include_callgraph=False.
19-
graph = graph_builder.build(include_callgraph=True)
19+
graph = graph_builder.build(include_callgraph=False)
2020
GraphBuilder.save_gv(graph, output_file + '.gv')
2121

22-
2322
if __name__ == "__main__":
2423
main(sys.argv)

data_prep/graph/graphbuilder.py

Lines changed: 21 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
11
import csv
2+
import json
23
import os
34
import graphviz
5+
import networkx as nx
46
from io import StringIO
57
from data_prep.random_walk.walkutils import WalkUtils, JavaWalkUtils
68
from typing import List, Set, Dict, Tuple
79

810

911
class GraphBuilder:
10-
facts_dir = None # type: str
12+
tables_dir = None # type: str
1113
join_filepath = None # type: str
1214
language = None # type: str
1315

14-
def __init__(self, facts_dir: str, join_filepath: str, language: str):
15-
self.facts_dir = facts_dir
16+
def __init__(self, tables_dir: str, join_filepath: str, language: str):
17+
self.tables_dir = tables_dir
1618
self.join_filepath = join_filepath
1719
self.language = GraphBuilder.parse_language(language)
1820

@@ -33,17 +35,9 @@ def load_columns(self) -> Dict[str, List[str]]:
3335
else:
3436
raise ValueError('Cannot load columns for language:', self.language)
3537

36-
def load_fact_table(self, fact_file: str) -> List[Tuple]:
38+
def load_table(self, table_file: str) -> List[Tuple]:
3739
table = []
38-
with open(self.facts_dir + '/' + fact_file, 'r') as f:
39-
reader = csv.reader(f, delimiter=',')
40-
for line in reader:
41-
table.append(tuple(line))
42-
return table
43-
44-
def load_csv_table(self, fact_file: str) -> List[Tuple]:
45-
table = []
46-
with open(self.facts_dir + '/' + fact_file, 'r') as f:
40+
with open(self.tables_dir + '/' + table_file, 'r') as f:
4741
data = f.read()
4842
data = data.replace('\x00', '**NULLBYTE**', -1)
4943
reader = csv.reader(StringIO(data), delimiter=',')
@@ -88,54 +82,20 @@ def load_joins(self) -> (Dict, Dict):
8882

8983
return joins, keys
9084

91-
def load_db(self, col_dict: Dict) -> Dict[str, List[Tuple]]:
85+
def load_db(self, col_dict: Dict, include_callgraph=False) -> Dict[str, List[Tuple]]:
9286
database = {} # type: Dict[str, List[Tuple]]
93-
for fact_file in os.listdir(self.facts_dir):
94-
if fact_file.endswith('.csv.facts'):
95-
table_name = fact_file[:-10] # remove ".csv.facts"
96-
if table_name in col_dict:
97-
database[table_name] = self.load_fact_table(fact_file)
98-
elif fact_file.endswith('.bqrs.csv'):
99-
table_name = fact_file[:-9] # remove ".bqrs.csv"
100-
if table_name in col_dict:
101-
database[table_name] = self.load_csv_table(fact_file)
102-
elif fact_file.endswith('.csv'):
103-
table_name = fact_file[:-4] # remove ".csv"
87+
for table_file in os.listdir(self.tables_dir):
88+
if table_file.endswith('.csv'):
89+
if 'call_graph' in table_file and not include_callgraph:
90+
continue # skip the call_graph if call graph is not requested.
91+
elif 'call_graph' in table_file and include_callgraph:
92+
table_name = 'call_graph'
93+
else:
94+
table_name = table_file[:table_file.find('.')] # remove suffixes
10495
if table_name in col_dict:
105-
database[table_name] = self.load_csv_table(fact_file)
96+
database[table_name] = self.load_table(table_file)
10697
return database
10798

108-
def load_callgraph(self):
109-
if self.language == 'python':
110-
call_graph = []
111-
if 'one_hop_call_graph.csv.facts' in os.listdir(self.facts_dir):
112-
callgraph_file = 'one_hop_call_graph.csv.facts'
113-
elif 'full_call_graph.csv.facts' in os.listdir(self.facts_dir):
114-
callgraph_file = 'full_call_graph.csv.facts'
115-
elif 'one_hop_call_graph.csv' in os.listdir(self.facts_dir):
116-
callgraph_file = 'one_hop_call_graph.csv'
117-
elif 'full_call_graph.csv' in os.listdir(self.facts_dir):
118-
callgraph_file = 'full_call_graph.csv'
119-
elif 'one_hop_call_graph.bqrs.csv' in os.listdir(self.facts_dir):
120-
callgraph_file = 'one_hop_call_graph.bqrs.csv'
121-
elif 'full_call_graph.bqrs.csv' in os.listdir(self.facts_dir):
122-
callgraph_file = 'full_call_graph.bqrs.csv'
123-
else:
124-
return []
125-
126-
with open(os.path.join(self.facts_dir, callgraph_file), 'r') as cf:
127-
for line in cf.readlines():
128-
call_edge = line.split(',')
129-
call_graph.append([s.strip() for s in call_edge])
130-
if callgraph_file.endswith('facts'):
131-
return call_graph
132-
else:
133-
return call_graph [1:]
134-
elif self.language == 'java':
135-
raise NotImplementedError
136-
else:
137-
raise ValueError('Cannot load the call graph for langauge:', self.language)
138-
13999
@staticmethod
140100
def build_value_to_tuple_map(db: Dict, keys: Dict) -> Dict[str, Set[Tuple[Tuple, str]]]:
141101
val_tuple_map = {} # type: Dict[str, Set[Tuple[Tuple, str]]]
@@ -182,7 +142,7 @@ def labels_if_joinable(joins: Dict, columns: Dict, l_rel: str, l_tuple: Tuple, r
182142
labels.append(GraphBuilder.edb_edge_label(l_rel, l_col, r_rel, r_col))
183143
return labels
184144

185-
def build_graph(self, db: Dict, joins: Dict, keys: Dict, columns: Dict, call_graph: List) -> graphviz.Graph:
145+
def build_graph(self, db: Dict, joins: Dict, keys: Dict, columns: Dict) -> graphviz.Graph:
186146
val_tuple_map = self.build_value_to_tuple_map(db, keys) # type: Dict[str, Set[Tuple[Tuple, str]]]
187147
tuple_index_map = {} # type: Dict[str, Dict[Tuple, int]]
188148
index_rel_map = {} # type: Dict[int, str]
@@ -199,6 +159,7 @@ def build_graph(self, db: Dict, joins: Dict, keys: Dict, columns: Dict, call_gra
199159
index += 1
200160
# Build the graph
201161
graph = graphviz.Graph()
162+
202163
for i in index_tuple_map:
203164
graph.node(str(i), self.edb_tuple_label(index_tuple_map[i], index_rel_map[i]))
204165
for val in val_tuple_map:
@@ -216,33 +177,13 @@ def build_graph(self, db: Dict, joins: Dict, keys: Dict, columns: Dict, call_gra
216177
for edge_label in edge_labels:
217178
graph.edge(str(index_i), str(index_j), edge_label)
218179

219-
def search_py_exprs(expr_id):
220-
indices = []
221-
for i in index_rel_map:
222-
if index_rel_map[i] == 'py_exprs':
223-
indices.append(i)
224-
for i in indices:
225-
if index_tuple_map[i][0] == expr_id:
226-
return i
227-
return None
228-
229-
for call_edge in call_graph:
230-
function1_expr_id = search_py_exprs(call_edge[0])
231-
function2_expr_id = search_py_exprs(call_edge[1])
232-
edge_label = '(callgraph.0,call_graph.1)'
233-
if function1_expr_id and function2_expr_id:
234-
graph.edge(str(function1_expr_id), str(function2_expr_id), edge_label)
235180
return graph
236181

237182
def build(self, include_callgraph=False) -> graphviz.Graph:
238183
columns = self.load_columns()
239-
db = self.load_db(columns)
240-
if include_callgraph:
241-
callgraph = self.load_callgraph()
242-
else:
243-
callgraph = []
184+
db = self.load_db(columns, include_callgraph)
244185
joins, keys = self.load_joins()
245-
graph = self.build_graph(db, joins, keys, columns, callgraph)
186+
graph = self.build_graph(db, joins, keys, columns)
246187
return graph
247188

248189
@staticmethod

data_prep/random_walk/datapoint.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,4 +85,4 @@ def to_dict(self) -> Dict:
8585

8686
def dump_json(self, filepath: str) -> None:
8787
with open(filepath, 'w') as outfile:
88-
json.dump(self.to_dict(), outfile, indent=4)
88+
json.dump(self.to_dict(), outfile)

data_prep/random_walk/randomwalk.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,10 @@
33
from random import choice, choices, randint
44
from typing import List, Dict, Set
55
from data_prep.random_walk.walkutils import WalkUtils, JavaWalkUtils
6-
import time
7-
8-
def ms():
9-
return round(time.time() * 1000)
106

117
class RandomWalker:
128
BIAS_WEIGHT = 5
13-
PYTHON_BIAS_TABLES = {'py_exprs', 'py_stmts', 'variable', 'py_variables'}
9+
PYTHON_BIAS_TABLES = {'py_exprs', 'py_stmts', 'py_variables'}
1410
JAVA_BIAS_TABLES = {'exprs', 'stmts'}
1511

1612
language = None # type: str
@@ -123,8 +119,9 @@ def build_node_map(graph: AGraph, language: str) -> Dict[Node, str]:
123119

124120
@staticmethod
125121
def load_graph_from_gv(path: str) -> AGraph:
126-
graph = AGraph(path, directed=False)
127-
return nx.nx_agraph.from_agraph(graph)
122+
g = AGraph()
123+
g.read(path)
124+
return nx.nx_agraph.from_agraph(g)
128125

129126
# Padding the given list to size `num` by duplicating elements that are
130127
# selected from the list at random.

data_prep/random_walk/walkutils.py

Lines changed: 2 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ class WalkUtils:
4545
'py_ssa_phi': ['phi', 'arg'],
4646
'py_ssa_var': ['id', 'var'],
4747
'py_ssa_use': ['node', 'var'],
48-
'py_ssa_defn': ['id', 'node']
48+
'py_ssa_defn': ['id', 'node'],
49+
'call_graph': ['f1def', 'f2def', 'f1', 'f2', 'call']
4950
}
5051

5152
expr_kinds = { # type: Dict[int, str]
@@ -122,11 +123,6 @@ class WalkUtils:
122123
def gen_node_type_value(rel_name: str, values: List[str]):
123124
node_type = rel_name
124125
node_value = ''
125-
# Compute node values
126-
if rel_name == 'py_bytes':
127-
node_value = values[0]
128-
if rel_name == 'py_numbers':
129-
node_value = values[0]
130126
if rel_name == 'variable':
131127
node_type = 'v_' + values[0]
132128
node_value = values[2]
@@ -138,19 +134,6 @@ def gen_node_type_value(rel_name: str, values: List[str]):
138134
if rel_name == 'py_stmts':
139135
kind = int(values[1])
140136
node_type = 'stmt_' + WalkUtils.stmt_kinds[kind]
141-
142-
##### uncomment the following lines for more node values #####
143-
#if rel_name == 'py_boolops':
144-
# node_value = values[1]
145-
#if rel_name == 'py_cmpops':
146-
# node_value = values[1]
147-
#if rel_name == 'py_dict_items':
148-
# node_value = values[1]
149-
#if rel_name == 'py_operators':
150-
# node_value = values[1]
151-
#if rel_name == 'py_unaryops':
152-
# node_value = values[1]
153-
###############################################################
154137

155138
# Otherwise, use relation name as the label
156139
return node_type, node_value

dbwalk/data_util/cook_from_gv_stub.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@
7373
json_name = cand + sep + '.'.join(tmp.split('.')[:-1]) + '.json'
7474
if json_name in json_files:
7575
break
76+
# meta_data_list contains the parsed contents of *.json file.
7677
with open(os.path.join(folder, json_name), 'r') as f:
7778
meta_data_list = json.load(f)
7879
for meta_data in meta_data_list:
@@ -84,15 +85,15 @@
8485
pbar.set_description('#n: %d, #e: %d, #v: %d, #t: %d' % (len(node_types), len(edge_types), max_num_vars, len(token_vocab)))
8586
if len(gh):
8687
gh.dump(os.path.join(out_folder, 'chunk_%d' % chunk_idx))
87-
88+
8889
print('# node types', len(node_types))
8990
print('# edge types', len(edge_types))
9091
print('max # vars per program', max_num_vars)
9192
print('# tokens', len(token_vocab))
9293

9394
var_dict = {}
9495
var_reverse_dict = {}
95-
max_num_vars = min(max_num_vars, 100)
96+
#max_num_vars = min(max_num_vars, 200)
9697
for i in range(max_num_vars):
9798
val = get_or_add(node_types, var_idx2name(i))
9899
var_dict[i] = val
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,4 @@ py_variables.1 <----> py_exprs.0
8585
variable.1 <----> py_Classes.0
8686
variable.1 <----> py_Functions.0
8787
variable.1 <----> py_Modules.0
88+
call_graph.0 <----> call_graph.1

0 commit comments

Comments
 (0)