util: Remove Python 2.7 glue code
[gem5.git] / util / cpt_upgrader.py
1 #!/usr/bin/env python3
2
3 # Copyright (c) 2012-2013,2015-2016, 2020 ARM Limited
4 # All rights reserved
5 #
6 # The license below extends only to copyright in the software and shall
7 # not be construed as granting a license to any other intellectual
8 # property including but not limited to intellectual property relating
9 # to a hardware implementation of the functionality of the software
10 # licensed hereunder. You may use the software subject to the license
11 # terms below provided that you ensure that this notice is replicated
12 # unmodified and in its entirety in all distributions of the software,
13 # modified or unmodified, in source code or in binary form.
14 #
15 # Redistribution and use in source and binary forms, with or without
16 # modification, are permitted provided that the following conditions are
17 # met: redistributions of source code must retain the above copyright
18 # notice, this list of conditions and the following disclaimer;
19 # redistributions in binary form must reproduce the above copyright
20 # notice, this list of conditions and the following disclaimer in the
21 # documentation and/or other materials provided with the distribution;
22 # neither the name of the copyright holders nor the names of its
23 # contributors may be used to endorse or promote products derived from
24 # this software without specific prior written permission.
25 #
26 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
29 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
30 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
31 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
32 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
36 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37
38 # This python code is used to migrate checkpoints that were created in one
39 # version of the simulator to newer version. As features are added or bugs are
40 # fixed some of the state that needs to be checkpointed can change. If you have
41 # many historic checkpoints that you use, manually editing them to fix them is
42 # both time consuming and error-prone.
43
44 # This script provides a way to migrate checkpoints to the newer repository in
45 # a programmatic way. It can be imported into another script or used on the
46 # command line. From the command line the script will either migrate every
47 # checkpoint it finds recursively (-r option) or a single checkpoint. When a
48 # change is made to the gem5 repository that breaks previous checkpoints an
49 # upgrade() method should be implemented in its own .py file and placed in
50 # src/util/cpt_upgraders/. For each upgrader whose tag is not present in
51 # the checkpoint tag list, the upgrade() method will be run, passing in a
52 # ConfigParser object which contains the open file. As these operations can
53 # be isa specific the method can verify the isa and use regexes to find the
54 # correct sections that need to be updated.
55
56 # It is also possible to use this mechanism to revert prior tags. In this
57 # case, implement a downgrade() method instead. Dependencies should still
58 # work naturally - a tag depending on a tag with a downgrader means that it
59 # insists on the other tag being removed and its downgrader executed before
60 # its upgrader (or downgrader) can run. It is still the case that a tag
61 # can only be used once.
62
63 # Dependencies between tags are expressed by two variables at the top-level
64 # of the upgrader script: "depends" can be either a string naming another
65 # tag that it depends upon or a list of such strings; and "fwd_depends"
66 # accepts the same datatypes but it reverses the sense of the dependency
67 # arrow(s) -- it expresses that that tag depends upon the tag of the current
68 # upgrader. This can be especially valuable when maintaining private
69 # upgraders in private branches.
70
71
72 import configparser
73 import glob, types, sys, os
74 import os.path as osp
75
76 verbose_print = False
77
78 def verboseprint(*args):
79 if not verbose_print:
80 return
81 for arg in args:
82 print(arg, end=' ')
83 print("\n")
84
85 class Upgrader:
86 tag_set = set()
87 untag_set = set() # tags to remove by downgrading
88 by_tag = {}
89 legacy = {}
90 def __init__(self, filename):
91 self.filename = filename
92 exec(open(filename).read(), {}, self.__dict__)
93
94 if not hasattr(self, 'tag'):
95 self.tag = osp.basename(filename)[:-3]
96 if not hasattr(self, 'depends'):
97 self.depends = []
98 elif isinstance(self.depends, str):
99 self.depends = [self.depends]
100
101 if not isinstance(self.depends, list):
102 print("Error: 'depends' for {} is the wrong type".format(self.tag))
103 sys.exit(1)
104
105 if hasattr(self, 'fwd_depends'):
106 if isinstance(self.fwd_depends, str):
107 self.fwd_depends = [self.fwd_depends]
108 else:
109 self.fwd_depends = []
110
111 if not isinstance(self.fwd_depends, list):
112 print("Error: 'fwd_depends' for {} is the wrong type".format(
113 self.tag))
114 sys.exit(1)
115
116 if hasattr(self, 'upgrader'):
117 if not isinstance(self.upgrader, types.FunctionType):
118 print("Error: 'upgrader' for {} is {}, not function".format(
119 self.tag, type(self)))
120 sys.exit(1)
121 Upgrader.tag_set.add(self.tag)
122 elif hasattr(self, 'downgrader'):
123 if not isinstance(self.downgrader, types.FunctionType):
124 print("Error: 'downgrader' for {} is {}, not function".format(
125 self.tag, type(self)))
126 sys.exit(1)
127 Upgrader.untag_set.add(self.tag)
128 else:
129 print("Error: no upgrader or downgrader method for".format(
130 self.tag))
131 sys.exit(1)
132
133 if hasattr(self, 'legacy_version'):
134 Upgrader.legacy[self.legacy_version] = self
135
136 Upgrader.by_tag[self.tag] = self
137
138 def ready(self, tags):
139 for dep in self.depends:
140 if dep not in tags:
141 return False
142 return True
143
144 def update(self, cpt, tags):
145 if hasattr(self, 'upgrader'):
146 self.upgrader(cpt)
147 tags.add(self.tag)
148 verboseprint("applied upgrade for", self.tag)
149 else:
150 self.downgrader(cpt)
151 tags.remove(self.tag)
152 verboseprint("applied downgrade for", self.tag)
153
154 @staticmethod
155 def get(tag):
156 return Upgrader.by_tag[tag]
157
158 @staticmethod
159 def load_all():
160 util_dir = osp.dirname(osp.abspath(__file__))
161
162 for py in glob.glob(util_dir + '/cpt_upgraders/*.py'):
163 Upgrader(py)
164
165 # make linear dependences for legacy versions
166 i = 3
167 while i in Upgrader.legacy:
168 Upgrader.legacy[i].depends = [Upgrader.legacy[i-1].tag]
169 i = i + 1
170
171 # resolve forward dependencies and audit normal dependencies
172 for tag, upg in list(Upgrader.by_tag.items()):
173 for fd in upg.fwd_depends:
174 if fd not in Upgrader.by_tag:
175 print("Error: '{}' cannot (forward) depend on "
176 "nonexistent tag '{}'".format(fd, tag))
177 sys.exit(1)
178 Upgrader.by_tag[fd].depends.append(tag)
179 for dep in upg.depends:
180 if dep not in Upgrader.by_tag:
181 print("Error: '{}' cannot depend on "
182 "nonexistent tag '{}'".format(tag, dep))
183 sys.exit(1)
184
185 def process_file(path, **kwargs):
186 if not osp.isfile(path):
187 import errno
188 raise IOError(ennro.ENOENT, "No such file", path)
189
190 verboseprint("Processing file %s...." % path)
191
192 if kwargs.get('backup', True):
193 import shutil
194 shutil.copyfile(path, path + '.bak')
195
196 cpt = configparser.SafeConfigParser()
197
198 # gem5 is case sensitive with paramaters
199 cpt.optionxform = str
200
201 # Read the current data
202 cpt_file = file(path, 'r')
203 cpt.readfp(cpt_file)
204 cpt_file.close()
205
206 change = False
207
208 # Make sure we know what we're starting from
209 if cpt.has_option('root','cpt_ver'):
210 cpt_ver = cpt.getint('root','cpt_ver')
211
212 # Legacy linear checkpoint version
213 # convert to list of tags before proceeding
214 tags = set([])
215 for i in range(2, cpt_ver+1):
216 tags.add(Upgrader.legacy[i].tag)
217 verboseprint("performed legacy version -> tags conversion")
218 change = True
219
220 cpt.remove_option('root', 'cpt_ver')
221 elif cpt.has_option('Globals','version_tags'):
222 tags = set((''.join(cpt.get('Globals','version_tags'))).split())
223 else:
224 print("fatal: no version information in checkpoint")
225 exit(1)
226
227 verboseprint("has tags", ' '.join(tags))
228 # If the current checkpoint has a tag we don't know about, we have
229 # a divergence that (in general) must be addressed by (e.g.) merging
230 # simulator support for its changes.
231 unknown_tags = tags - (Upgrader.tag_set | Upgrader.untag_set)
232 if unknown_tags:
233 print("warning: upgrade script does not recognize the following "
234 "tags in this checkpoint:", ' '.join(unknown_tags))
235
236 # Apply migrations for tags not in checkpoint and tags present for which
237 # downgraders are present, respecting dependences
238 to_apply = (Upgrader.tag_set - tags) | (Upgrader.untag_set & tags)
239 while to_apply:
240 ready = set([ t for t in to_apply if Upgrader.get(t).ready(tags) ])
241 if not ready:
242 print("could not apply these upgrades:", ' '.join(to_apply))
243 print("update dependences impossible to resolve; aborting")
244 exit(1)
245
246 for tag in ready:
247 Upgrader.get(tag).update(cpt, tags)
248 change = True
249
250 to_apply -= ready
251
252 if not change:
253 verboseprint("...nothing to do")
254 return
255
256 cpt.set('Globals', 'version_tags', ' '.join(tags))
257
258 # Write the old data back
259 verboseprint("...completed")
260 cpt.write(file(path, 'w'))
261
262 if __name__ == '__main__':
263 from optparse import OptionParser, SUPPRESS_HELP
264 parser = OptionParser("usage: %prog [options] <filename or directory>")
265 parser.add_option("-r", "--recurse", action="store_true",
266 help="Recurse through all subdirectories modifying "\
267 "each checkpoint that is found")
268 parser.add_option("-N", "--no-backup", action="store_false",
269 dest="backup", default=True,
270 help="Do no backup each checkpoint before modifying it")
271 parser.add_option("-v", "--verbose", action="store_true",
272 help="Print out debugging information as")
273 parser.add_option("--get-cc-file", action="store_true",
274 # used during build; generate src/sim/tags.cc and exit
275 help=SUPPRESS_HELP)
276
277 (options, args) = parser.parse_args()
278 verbose_print = options.verbose
279
280 Upgrader.load_all()
281
282 if options.get_cc_file:
283 print("// this file is auto-generated by util/cpt_upgrader.py")
284 print("#include <string>")
285 print("#include <set>")
286 print()
287 print("std::set<std::string> version_tags = {")
288 for tag in Upgrader.tag_set:
289 print(" \"{}\",".format(tag))
290 print("};")
291 exit(0)
292 elif len(args) != 1:
293 parser.error("You must specify a checkpoint file to modify or a "\
294 "directory of checkpoints to recursively update")
295
296 # Deal with shell variables and ~
297 path = osp.expandvars(osp.expanduser(args[0]))
298
299 # Process a single file if we have it
300 if osp.isfile(path):
301 process_file(path, **vars(options))
302 # Process an entire directory
303 elif osp.isdir(path):
304 cpt_file = osp.join(path, 'm5.cpt')
305 if options.recurse:
306 # Visit very file and see if it matches
307 for root,dirs,files in os.walk(path):
308 for name in files:
309 if name == 'm5.cpt':
310 process_file(osp.join(root,name), **vars(options))
311 for dir in dirs:
312 pass
313 # Maybe someone passed a cpt.XXXXXXX directory and not m5.cpt
314 elif osp.isfile(cpt_file):
315 process_file(cpt_file, **vars(options))
316 else:
317 print("Error: checkpoint file not found in {} ".format(path))
318 print("and recurse not specified")
319 sys.exit(1)
320 sys.exit(0)
321