]> rtime.felk.cvut.cz Git - linux-conf-perf.git/blob - scripts/configurations.py
aae7a6fad35e5575bd0f284d46ff46ab2f1be4c8
[linux-conf-perf.git] / scripts / configurations.py
1 import os
2 import sys
3 import tempfile
4 import shutil
5 import subprocess
6 import time
7 import hashlib
8
9 import utils
10 from conf import conf
11 from conf import sf
12 import exceptions
13 import database
14
15 def __buildtempcnf__(variable_count, files, strlines):
16         """ Builds temporally file for cnf formulas
17           variable_count - number of variables in formulas
18           files          - list of files with formulas
19           strlines       - list of string lines with formulas"""
20         lines = set()
21         # Copy strlines
22         for ln in strlines:
23                 lines.add(ln)
24         # Files
25         for file in files:
26                 with open(file, 'r') as f:
27                         for ln in f:
28                                 lines.add(ln.rstrip())
29
30         first_line = "p cnf " + str(variable_count) + " " + str(len(lines))
31
32         wfile = tempfile.NamedTemporaryFile(delete=False)
33         wfile.write(bytes(first_line + '\n', 'UTF-8'))
34         for ln in lines:
35                 wfile.write(bytes(ln + ' 0\n', 'UTF-8'))
36         wfile.close()
37         return wfile.name
38
39 def __exec_sat__(file, args):
40         """Executes SAT solver and returns configuration."""
41         picosat_cmd = [sf(conf.picosat), file]
42         picosat_cmd += conf.picosat_args
43         stdout = utils.callsubprocess('picosat', picosat_cmd, conf.picosat_output,
44                         True, allow_all_exit_codes = True)
45
46         rtn = []
47         solut = []
48         for line in stdout:
49                 if line[0] == 's':
50                         try:
51                                 solut.remove(0)
52                                 rtn.append(solut)
53                         except ValueError:
54                                 pass
55                         solut = []
56                         if not line.rstrip() == 's SATISFIABLE':
57                                 raise exceptions.NoSolution()
58                 elif line[0] == 'v':
59                         for sl in line[2:].split():
60                                 solut.append(int(sl))
61         try:
62                 solut.remove(0)
63                 rtn.append(solut)
64         except ValueError:
65                 pass
66         return rtn
67
68 def __txt_config__(con, conf_num):
69         # Ensure smap existence
70         utils.build_symbol_map()
71         # Write temporally file
72         txt = ''
73         for s in con:
74                 if s < 0:
75                         nt = True
76                         s *= -1
77                 else:
78                         nt = False
79                 if s > int(conf_num):
80                         break;
81                 if 'NONAMEGEN' in utils.smap[s]: # ignore generated names
82                         continue
83                 txt += 'CONFIG_' + utils.smap[s] + '='
84                 if not nt:
85                         txt += 'y'
86                 else:
87                         txt += 'n'
88                 txt += '\n'
89         return txt
90
91 def __write_temp_config_file__(con, conf_num):
92         wfile = tempfile.NamedTemporaryFile(delete=False)
93         txt = __txt_config__(con, conf_num)
94         wfile.write(bytes(txt, sys.getdefaultencoding()))
95         wfile.close()
96         return wfile.name
97
98 def __load_config_text__(txt):
99         rtn = dict()
100         for ln in txt:
101                 if ln[0] == '#' or not '=' in ln:
102                         continue
103                 indx = ln.index('=')
104                 if (ln[indx + 1] == 'y'):
105                         rtn[ln[7:indx]] = True
106                 else:
107                         rtn[ln[7:indx]] = False
108         return rtn
109
110
111 def __load_config_file__(file):
112         f = open(file, 'r')
113         rtn = __load_config_text__(f)
114         f.close()
115         return rtn
116
117 def __calchash__(con):
118         dt = database.database()
119         csort = dt.get_configsort()
120
121         cstr = ""
122         for c in csort:
123                 try:
124                         if con[c]:
125                                 cstr += c
126                 except ValueError:
127                         pass
128
129         # Add missing
130         for key, val in con.items():
131                 try:
132                         csort.index(key)
133                 except ValueError:
134                         indx = len(csort)
135                         csort.append(key)
136                         dt.add_configsort(key)
137                         if val:
138                                 cstr += key
139
140         hsh = hashlib.md5(bytes(cstr, 'UTF-8'))
141         return hsh.hexdigest()
142
143
144 def __calchash_file__(file):
145         """Calculates hash from configuration file"""
146         con = __load_config_file__(file)
147         return __calchash__(con)
148
149 def __register_conf__(con, conf_num, generator):
150         dtb = database.database()
151         # Solution to configuration
152         txtconfig = __txt_config__(con, conf_num)
153         hsh = __calchash__(con)
154         cconf = dtb.get_configration(hsh)
155         for cc in cconf:
156                 print('hash: ' + hsh)
157                 if compare_text(cc, txtconfig):
158                         print("I: Generated existing configuration.")
159                         return False
160                 else:
161                         print("W: Generated configuration with collision hash.")
162                         # TODO this might have to be tweaked
163                         raise Exception()
164         dtb.add_configuration(hsh, txtconfig, generator)
165         return True
166
167 def __generate_single__(var_num, conf_num):
168         measure_list = set()
169         if not os.path.isfile(sf(conf.single_generated_file)):
170                 with open(sf(conf.measure_file), 'r') as fi:
171                         for ln in fi:
172                                 measure_list.add(int(ln))
173         else:
174                 with open(sf(conf.single_generated_file), 'r') as f:
175                         for ln in f:
176                                 measure_list.add(int(ln))
177         if not measure_list:
178                 return False
179         tfile = __buildtempcnf__(var_num, (sf(conf.rules_file),
180                 sf(conf.fixed_file)), [str(measure_list.pop())])
181         with open(sf(conf.single_generated_file), 'w') as fo:
182                 for ln in measure_list:
183                         fo.write(str(ln) + '\n')
184         try:
185                 confs = __exec_sat__(tfile, ['-i', '0'])
186                 for con in confs:
187                         __register_conf__(con, conf_num, 'single-sat')
188         except exceptions.NoSolution:
189                 return __generate_single__(var_num, conf_num)
190         finally:
191                 os.remove(tfile)
192         return True
193
194 def __generate_random__(var_num, conf_num):
195         tfile = __buildtempcnf__(var_num, (sf(conf.rules_file), sf(conf.fixed_file)), set())
196         try:
197                 confs = __exec_sat__(tfile, ['-i', '3'])
198                 for con in confs:
199                         if not __register_conf__(con, conf_num, 'random-sat'):
200                                 __generate_random__(var_num, conf_num)
201         finally:
202                 os.remove(tfile)
203         return True
204
205 def generate():
206         """Collect boolean equations from files rules and required
207         And get solution with picosat
208         """
209         # Check if rules_file exist. If it was generated.
210         if not os.path.isfile(sf(conf.rules_file)):
211                 raise exceptions.MissingFile(conf.rules_file,"Run parse_kconfig.")
212         if not os.path.isfile(sf(conf.fixed_file)):
213                 raise exceptions.MissingFile(conf.required_file,"Run allconfig and initialization process.")
214
215         # Load variable count
216         with open(sf(conf.variable_count_file)) as f:
217                 var_num = f.readline().rstrip()
218                 conf_num = f.readline().rstrip()
219
220         if __generate_single__(var_num, conf_num):
221                 return
222         elif __generate_random__(var_num, conf_num):
223                 return
224
225         raise exceptions.NoNewConfiguration()
226
227 def compare(conf1, conf2):
228         # This is not exactly best comparison method
229         for key, val in conf1.items():
230                 try:
231                         if conf2[key] != val:
232                                 return False
233                 except ValueError:
234                         return False
235         for key, val in conf2.items():
236                 try:
237                         if conf1[key] != val:
238                                 return False
239                 except ValueError:
240                         return False
241         return True
242
243 def compare_text(text1, text2):
244         conf1 = __load_config_text__(text1)
245         conf2 = __load_config_text__(text2)
246         return compare_file(conf1, conf2)
247
248 def compare_file(file1, file2):
249         """Compared two configuration"""
250         conf1 = __load_config_file__(file1)
251         conf2 = __load_config_file__(file2)
252         return compare_file(conf1, conf2)