1 # @file ConvertMasmToNasm.py
2 # This script assists with conversion of MASM assembly syntax to NASM
4 # Copyright (c) 2007 - 2016, Intel Corporation. All rights reserved.<BR>
6 # This program and the accompanying materials
7 # are licensed and made available under the terms and conditions of the BSD License
8 # which accompanies this distribution. The full text of the license may be found at
9 # http://opensource.org/licenses/bsd-license.php
11 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
15 from __future__
import print_function
28 class UnsupportedConversion(Exception):
32 class NoSourceFile(Exception):
36 class UnsupportedArch(Exception):
37 unsupported
= ('aarch64', 'arm', 'ebc', 'ipf')
42 # Version and Copyright
43 VersionNumber
= "0.01"
44 __version__
= "%prog Version " + VersionNumber
45 __copyright__
= "Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved."
46 __usage__
= "%prog [options] source.asm [destination.nasm]"
48 def __init__(self
, clone
=None):
50 self
.args
= self
.ProcessCommandLine()
52 self
.args
= clone
.args
54 self
.unsupportedSyntaxSeen
= False
55 self
.src
= self
.args
.source
56 assert(os
.path
.exists(self
.src
))
57 self
.dirmode
= os
.path
.isdir(self
.src
)
58 srcExt
= os
.path
.splitext(self
.src
)[1]
59 assert (self
.dirmode
or srcExt
!= '.nasm')
60 self
.infmode
= not self
.dirmode
and srcExt
== '.inf'
61 self
.diff
= self
.args
.diff
62 self
.git
= self
.args
.git
63 self
.force
= self
.args
.force
66 self
.rootdir
= os
.getcwd()
69 self
.rootdir
= clone
.rootdir
70 self
.gitdir
= clone
.gitdir
71 self
.gitemail
= clone
.gitemail
73 def ProcessCommandLine(self
):
74 parser
= argparse
.ArgumentParser(description
=self
.__copyright
__)
75 parser
.add_argument('--version', action
='version',
76 version
='%(prog)s ' + self
.VersionNumber
)
77 parser
.add_argument("-q", "--quiet", action
="store_true",
78 help="Disable all messages except FATAL ERRORS.")
79 parser
.add_argument("--git", action
="store_true",
80 help="Use git to create commits for each file converted")
81 parser
.add_argument("--diff", action
="store_true",
82 help="Show diff of conversion")
83 parser
.add_argument("-f", "--force", action
="store_true",
84 help="Force conversion even if unsupported")
85 parser
.add_argument('source', help='MASM input file')
86 parser
.add_argument('dest', nargs
='?',
87 help='NASM output file (default=input.nasm; - for stdout)')
89 return parser
.parse_args()
91 def RootRelative(self
, path
):
93 if result
.startswith(self
.rootdir
):
94 result
= result
[len(self
.rootdir
):]
95 while len(result
) > 0 and result
[0] in '/\\':
99 def MatchAndSetMo(self
, regexp
, string
):
100 self
.mo
= regexp
.match(string
)
101 return self
.mo
is not None
103 def SearchAndSetMo(self
, regexp
, string
):
104 self
.mo
= regexp
.search(string
)
105 return self
.mo
is not None
107 def ReplacePreserveSpacing(self
, string
, find
, replace
):
108 if len(find
) >= len(replace
):
109 padded
= replace
+ (' ' * (len(find
) - len(replace
)))
110 return string
.replace(find
, padded
)
111 elif find
.find(replace
) >= 0:
112 return string
.replace(find
, replace
)
114 lenDiff
= len(replace
) - len(find
)
116 for i
in range(lenDiff
, -1, -1):
117 padded
= find
+ (' ' * i
)
118 result
= result
.replace(padded
, replace
)
122 lastpath
= os
.path
.realpath(self
.src
)
125 path
= os
.path
.split(lastpath
)[0]
129 candidate
= os
.path
.join(path
, '.git')
130 if os
.path
.isdir(candidate
):
131 self
.gitdir
= candidate
132 self
.gitemail
= self
.FormatGitEmailAddress()
136 def FormatGitEmailAddress(self
):
137 if not self
.git
or not self
.gitdir
:
140 cmd
= ('git', 'config', 'user.name')
141 name
= self
.RunAndCaptureOutput(cmd
).strip()
142 cmd
= ('git', 'config', 'user.email')
143 email
= self
.RunAndCaptureOutput(cmd
).strip()
144 if name
.find(',') >= 0:
145 name
= '"' + name
+ '"'
146 return name
+ ' <' + email
+ '>'
148 def RunAndCaptureOutput(self
, cmd
, checkExitCode
=True, pipeIn
=None):
150 subpStdin
= subprocess
.PIPE
153 p
= subprocess
.Popen(args
=cmd
, stdout
=subprocess
.PIPE
, stdin
=subpStdin
)
154 (stdout
, stderr
) = p
.communicate(pipeIn
)
156 if p
.returncode
!= 0:
157 print('command:', ' '.join(cmd
))
158 print('stdout:', stdout
)
159 print('stderr:', stderr
)
160 print('return:', p
.returncode
)
161 assert p
.returncode
== 0
162 return stdout
.decode('utf-8', 'ignore')
164 def FileUpdated(self
, path
):
165 if not self
.git
or not self
.gitdir
:
168 cmd
= ('git', 'add', path
)
169 self
.RunAndCaptureOutput(cmd
)
171 def FileAdded(self
, path
):
172 self
.FileUpdated(path
)
174 def RemoveFile(self
, path
):
175 if not self
.git
or not self
.gitdir
:
178 cmd
= ('git', 'rm', path
)
179 self
.RunAndCaptureOutput(cmd
)
181 def FileConversionFinished(self
, pkg
, module
, src
, dst
):
182 if not self
.git
or not self
.gitdir
:
185 if not self
.args
.quiet
:
186 print('Committing: Conversion of', dst
)
188 prefix
= ' '.join(filter(lambda a
: a
, [pkg
, module
]))
190 if self
.unsupportedSyntaxSeen
:
192 message
+= '%s: Convert %s to NASM\n' % (prefix
, src
)
194 message
+= 'The %s script was used to convert\n' % sys
.argv
[0]
195 message
+= '%s to %s\n' % (src
, dst
)
197 message
+= 'Contributed-under: TianoCore Contribution Agreement 1.0\n'
198 assert(self
.gitemail
is not None)
199 message
+= 'Signed-off-by: %s\n' % self
.gitemail
200 message
= message
.encode('utf-8', 'ignore')
202 cmd
= ('git', 'commit', '-F', '-')
203 self
.RunAndCaptureOutput(cmd
, pipeIn
=message
)
206 class ConvertAsmFile(CommonUtils
):
208 def __init__(self
, src
, dst
, clone
):
209 CommonUtils
.__init
__(self
, clone
)
210 self
.ConvertAsmFile(src
, dst
)
214 def ConvertAsmFile(self
, inputFile
, outputFile
=None):
216 self
.unsupportedSyntaxSeen
= False
217 self
.inputFilename
= inputFile
219 outputFile
= os
.path
.splitext(inputFile
)[0] + '.nasm'
220 self
.outputFilename
= outputFile
222 fullSrc
= os
.path
.realpath(inputFile
)
223 srcParentDir
= os
.path
.basename(os
.path
.split(fullSrc
)[0])
224 maybeArch
= srcParentDir
.lower()
225 if maybeArch
in UnsupportedArch
.unsupported
:
226 raise UnsupportedArch
227 self
.ia32
= maybeArch
== 'ia32'
228 self
.x64
= maybeArch
== 'x64'
230 self
.inputFileBase
= os
.path
.basename(self
.inputFilename
)
231 self
.outputFileBase
= os
.path
.basename(self
.outputFilename
)
232 self
.output
= io
.BytesIO()
233 if not self
.args
.quiet
:
234 dirpath
, src
= os
.path
.split(self
.inputFilename
)
235 dirpath
= self
.RootRelative(dirpath
)
236 dst
= os
.path
.basename(self
.outputFilename
)
237 print('Converting:', dirpath
, src
, '->', dst
)
238 lines
= io
.open(self
.inputFilename
).readlines()
240 if self
.outputFilename
== '-' and not self
.diff
:
241 output_data
= self
.output
.getvalue()
242 if sys
.version_info
>= (3, 0):
243 output_data
= output_data
.decode('utf-8', 'ignore')
244 sys
.stdout
.write(output_data
)
247 f
= io
.open(self
.outputFilename
, 'wb')
248 f
.write(self
.output
.getvalue())
252 endOfLineRe
= re
.compile(r
'''
255 re
.VERBOSE | re
.MULTILINE
257 begOfLineRe
= re
.compile(r
'''
263 def Convert(self
, lines
):
265 self
.anonLabelCount
= -1
267 self
.oldAsmEmptyLineCount
= 0
268 self
.newAsmEmptyLineCount
= 0
270 mo
= self
.begOfLineRe
.search(line
)
271 assert mo
is not None
272 self
.indent
= mo
.group()
273 lineWithoutBeginning
= line
[len(self
.indent
):]
274 mo
= self
.endOfLineRe
.search(lineWithoutBeginning
)
278 endOfLine
= mo
.group()
279 oldAsm
= line
[len(self
.indent
):len(line
) - len(endOfLine
)]
280 self
.originalLine
= line
.rstrip()
281 if line
.strip() == '':
282 self
.oldAsmEmptyLineCount
+= 1
283 self
.TranslateAsm(oldAsm
, endOfLine
)
284 if line
.strip() != '':
285 self
.oldAsmEmptyLineCount
= 0
287 procDeclRe
= re
.compile(r
'''
288 (?: ASM_PFX \s* [(] \s* )?
292 (?: \s+ NEAR | FAR )?
294 (?: \s+ (PUBLIC | PRIVATE) )?
295 (?: \s+ USES ( (?: \s+ \w[\w0-9]* )+ ) )?
298 re
.VERBOSE | re
.IGNORECASE
301 procEndRe
= re
.compile(r
'''
306 re
.VERBOSE | re
.IGNORECASE
309 varAndTypeSubRe
= r
' (?: [\w@][\w@0-9]* ) (?: \s* : \s* \w+ )? '
310 publicRe
= re
.compile(r
'''
312 ( %s (?: \s* , \s* %s )* )
314 ''' % (varAndTypeSubRe
, varAndTypeSubRe
),
315 re
.VERBOSE | re
.IGNORECASE
318 varAndTypeSubRe
= re
.compile(varAndTypeSubRe
, re
.VERBOSE | re
.IGNORECASE
)
320 macroDeclRe
= re
.compile(r
'''
325 re
.VERBOSE | re
.IGNORECASE
328 sectionDeclRe
= re
.compile(r
'''
333 re
.VERBOSE | re
.IGNORECASE
336 externRe
= re
.compile(r
'''
337 EXTE?RN \s+ (?: C \s+ )?
338 ([\w@][\w@0-9]*) \s* : \s* (\w+)
341 re
.VERBOSE | re
.IGNORECASE
344 externdefRe
= re
.compile(r
'''
345 EXTERNDEF \s+ (?: C \s+ )?
346 ([\w@][\w@0-9]*) \s* : \s* (\w+)
349 re
.VERBOSE | re
.IGNORECASE
352 protoRe
= re
.compile(r
'''
358 re
.VERBOSE | re
.IGNORECASE
361 defineDataRe
= re
.compile(r
'''
363 ( db | dw | dd | dq ) \s+
367 re
.VERBOSE | re
.IGNORECASE
370 equRe
= re
.compile(r
'''
371 ([\w@][\w@0-9]*) \s+ EQU \s+ (\S.*?)
374 re
.VERBOSE | re
.IGNORECASE
377 ignoreRe
= re
.compile(r
'''
389 re
.VERBOSE | re
.IGNORECASE
392 whitespaceRe
= re
.compile(r
'\s+', re
.MULTILINE
)
394 def TranslateAsm(self
, oldAsm
, endOfLine
):
395 assert(oldAsm
.strip() == oldAsm
)
397 endOfLine
= endOfLine
.replace(self
.inputFileBase
, self
.outputFileBase
)
399 oldOp
= oldAsm
.split()
407 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
408 elif oldOp
in ('#include', ):
410 self
.EmitLine(oldAsm
+ endOfLine
)
411 elif oldOp
.lower() in ('end', 'title', 'text'):
413 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
414 elif oldAsm
.lower() == '@@:':
415 self
.anonLabelCount
+= 1
416 self
.EmitLine(self
.anonLabel(self
.anonLabelCount
) + ':')
417 elif self
.MatchAndSetMo(self
.ignoreRe
, oldAsm
):
419 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
420 elif oldAsm
.lower() == 'ret':
421 for i
in range(len(self
.uses
) - 1, -1, -1):
422 register
= self
.uses
[i
]
423 self
.EmitNewContent('pop ' + register
)
425 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
427 elif oldOp
.lower() == 'lea':
428 newAsm
= self
.ConvertLea(oldAsm
)
429 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
430 elif oldAsm
.lower() == 'end':
432 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
434 elif self
.MatchAndSetMo(self
.equRe
, oldAsm
):
435 equ
= self
.mo
.group(1)
436 newAsm
= '%%define %s %s' % (equ
, self
.mo
.group(2))
437 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
438 elif self
.MatchAndSetMo(self
.externRe
, oldAsm
) or \
439 self
.MatchAndSetMo(self
.protoRe
, oldAsm
):
440 extern
= self
.mo
.group(1)
441 self
.NewGlobal(extern
)
442 newAsm
= 'extern ' + extern
443 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
444 elif self
.MatchAndSetMo(self
.externdefRe
, oldAsm
):
446 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
447 elif self
.MatchAndSetMo(self
.macroDeclRe
, oldAsm
):
448 newAsm
= '%%macro %s 0' % self
.mo
.group(1)
449 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
450 elif oldOp
.lower() == 'endm':
451 newAsm
= r
'%endmacro'
452 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
453 elif self
.MatchAndSetMo(self
.sectionDeclRe
, oldAsm
):
454 name
= self
.mo
.group(1)
455 ty
= self
.mo
.group(2)
456 if ty
.lower() == 'section':
460 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
461 elif self
.MatchAndSetMo(self
.procDeclRe
, oldAsm
):
462 proc
= self
.proc
= self
.mo
.group(1)
463 visibility
= self
.mo
.group(2)
464 if visibility
is None:
467 visibility
= visibility
.lower()
468 if visibility
!= 'private':
469 self
.NewGlobal(self
.proc
)
470 proc
= 'ASM_PFX(' + proc
+ ')'
471 self
.EmitNewContent('global ' + proc
)
473 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
474 uses
= self
.mo
.group(3)
476 uses
= filter(None, uses
.split())
480 for register
in self
.uses
:
481 self
.EmitNewContent(' push ' + register
)
482 elif self
.MatchAndSetMo(self
.procEndRe
, oldAsm
):
484 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
485 elif self
.MatchAndSetMo(self
.publicRe
, oldAsm
):
486 publics
= re
.findall(self
.varAndTypeSubRe
, self
.mo
.group(1))
487 publics
= map(lambda p
: p
.split(':')[0].strip(), publics
)
488 for i
in range(len(publics
) - 1):
490 self
.EmitNewContent('global ASM_PFX(%s)' % publics
[i
])
494 newAsm
= 'global ASM_PFX(%s)' % name
495 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
496 elif self
.MatchAndSetMo(self
.defineDataRe
, oldAsm
):
497 name
= self
.mo
.group(1)
498 ty
= self
.mo
.group(2)
499 value
= self
.mo
.group(3)
502 newAsm
= '%s: %s %s' % (name
, ty
, value
)
503 newAsm
= self
.CommonConversions(newAsm
)
504 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
506 newAsm
= self
.CommonConversions(oldAsm
)
507 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
509 def NewGlobal(self
, name
):
510 regex
= re
.compile(r
'(?<![_\w\d])(?<!ASM_PFX\()(' + re
.escape(name
) +
512 self
.globals.add(regex
)
514 def ConvertAnonymousLabels(self
, oldAsm
):
516 anonLabel
= self
.anonLabel(self
.anonLabelCount
)
517 newAsm
= newAsm
.replace('@b', anonLabel
)
518 newAsm
= newAsm
.replace('@B', anonLabel
)
519 anonLabel
= self
.anonLabel(self
.anonLabelCount
+ 1)
520 newAsm
= newAsm
.replace('@f', anonLabel
)
521 newAsm
= newAsm
.replace('@F', anonLabel
)
524 def anonLabel(self
, count
):
527 def EmitString(self
, string
):
528 self
.output
.write(string
.encode('utf-8', 'ignore'))
530 def EmitLineWithDiff(self
, old
, new
):
531 newLine
= (self
.indent
+ new
).rstrip()
534 print('+%s' % newLine
)
537 print('+%s' % newLine
)
541 self
.newAsmEmptyLineCount
= 0
542 self
.EmitString(newLine
+ '\r\n')
544 def EmitLine(self
, string
):
545 self
.EmitLineWithDiff(self
.originalLine
, string
)
547 def EmitNewContent(self
, string
):
548 self
.EmitLineWithDiff(None, string
)
550 def EmitAsmReplaceOp(self
, oldAsm
, oldOp
, newOp
, endOfLine
):
551 newAsm
= oldAsm
.replace(oldOp
, newOp
, 1)
552 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
554 hexNumRe
= re
.compile(r
'0*((?=[\da-f])\d*(?<=\d)[\da-f]*)h', re
.IGNORECASE
)
556 def EmitAsmWithComment(self
, oldAsm
, newAsm
, endOfLine
):
557 for glblRe
in self
.globals:
558 newAsm
= glblRe
.sub(r
'ASM_PFX(\1)', newAsm
)
560 newAsm
= self
.hexNumRe
.sub(r
'0x\1', newAsm
)
562 newLine
= newAsm
+ endOfLine
563 emitNewLine
= ((newLine
.strip() != '') or
564 ((oldAsm
+ endOfLine
).strip() == ''))
565 if emitNewLine
and newLine
.strip() == '':
566 self
.newAsmEmptyLineCount
+= 1
567 if self
.newAsmEmptyLineCount
> 1:
570 self
.EmitLine(newLine
.rstrip())
572 print('-%s' % self
.originalLine
)
574 leaRe
= re
.compile(r
'''
575 (lea \s+) ([\w@][\w@0-9]*) \s* , \s* (\S (?:.*\S)?)
578 re
.VERBOSE | re
.IGNORECASE
581 def ConvertLea(self
, oldAsm
):
583 if self
.MatchAndSetMo(self
.leaRe
, oldAsm
):
584 lea
= self
.mo
.group(1)
585 dst
= self
.mo
.group(2)
586 src
= self
.mo
.group(3)
587 if src
.find('[') < 0:
588 src
= '[' + src
+ ']'
589 newAsm
= lea
+ dst
+ ', ' + src
590 newAsm
= self
.CommonConversions(newAsm
)
593 ptrRe
= re
.compile(r
'''
595 ([dfq]?word|byte) \s+ (?: ptr ) (\s*)
598 re
.VERBOSE | re
.IGNORECASE
601 def ConvertPtr(self
, oldAsm
):
603 while self
.SearchAndSetMo(self
.ptrRe
, newAsm
):
604 ty
= self
.mo
.group(1)
605 if ty
.lower() == 'fword':
608 ty
+= self
.mo
.group(2)
609 newAsm
= newAsm
[:self
.mo
.start(0)] + ty
+ newAsm
[self
.mo
.end(0):]
612 labelByteRe
= re
.compile(r
'''
613 (?: \s+ label \s+ (?: [dfq]?word | byte ) )
616 re
.VERBOSE | re
.IGNORECASE
619 def ConvertLabelByte(self
, oldAsm
):
621 if self
.SearchAndSetMo(self
.labelByteRe
, newAsm
):
622 newAsm
= newAsm
[:self
.mo
.start(0)] + ':' + newAsm
[self
.mo
.end(0):]
625 unaryBitwiseOpRe
= re
.compile(r
'''
629 re
.VERBOSE | re
.IGNORECASE
631 binaryBitwiseOpRe
= re
.compile(r
'''
633 ( AND | OR | SHL | SHR )
636 re
.VERBOSE | re
.IGNORECASE
638 bitwiseOpReplacements
= {
646 def ConvertBitwiseOp(self
, oldAsm
):
648 while self
.SearchAndSetMo(self
.binaryBitwiseOpRe
, newAsm
):
649 prefix
= self
.mo
.group(1)
650 op
= self
.bitwiseOpReplacements
[self
.mo
.group(2).lower()]
651 newAsm
= newAsm
[:self
.mo
.start(0)] + prefix
+ op
+ \
652 newAsm
[self
.mo
.end(0):]
653 while self
.SearchAndSetMo(self
.unaryBitwiseOpRe
, newAsm
):
654 op
= self
.bitwiseOpReplacements
[self
.mo
.group(1).lower()]
655 newAsm
= newAsm
[:self
.mo
.start(0)] + op
+ newAsm
[self
.mo
.end(0):]
658 sectionRe
= re
.compile(r
'''
665 re
.VERBOSE | re
.IGNORECASE
668 segmentRe
= re
.compile(r
'''
675 re
.VERBOSE | re
.IGNORECASE
678 def ConvertSection(self
, oldAsm
):
680 if self
.MatchAndSetMo(self
.sectionRe
, newAsm
) or \
681 self
.MatchAndSetMo(self
.segmentRe
, newAsm
):
682 name
= self
.mo
.group(1).lower()
685 self
.EmitLine('DEFAULT REL')
687 newAsm
= 'SECTION .' + name
690 fwordRe
= re
.compile(r
'''
695 re
.VERBOSE | re
.IGNORECASE
698 def FwordUnsupportedCheck(self
, oldAsm
):
700 if self
.SearchAndSetMo(self
.fwordRe
, newAsm
):
701 newAsm
= self
.Unsupported(newAsm
, 'fword used')
704 __common_conversion_routines__
= (
705 ConvertAnonymousLabels
,
707 FwordUnsupportedCheck
,
713 def CommonConversions(self
, oldAsm
):
715 for conv
in self
.__common
_conversion
_routines
__:
716 newAsm
= conv(self
, newAsm
)
719 def Unsupported(self
, asm
, message
=None):
721 raise UnsupportedConversion
723 self
.unsupportedSyntaxSeen
= True
724 newAsm
= '%error conversion unsupported'
726 newAsm
+= '; ' + message
731 class ConvertInfFile(CommonUtils
):
733 def __init__(self
, inf
, clone
):
734 CommonUtils
.__init
__(self
, clone
)
736 self
.ScanInfAsmFiles()
738 self
.ConvertInfAsmFiles()
740 infSrcRe
= re
.compile(r
'''
742 ( [\w@][\w@0-9/]* \.(asm|s) )
747 re
.VERBOSE | re
.IGNORECASE
750 def GetInfAsmFileMapping(self
):
751 srcToDst
= {'order': []}
752 for line
in self
.lines
:
754 if self
.MatchAndSetMo(self
.infSrcRe
, line
):
755 src
= self
.mo
.group(1)
756 srcExt
= self
.mo
.group(2)
757 dst
= os
.path
.splitext(src
)[0] + '.nasm'
758 if src
not in srcToDst
:
760 srcToDst
['order'].append(src
)
763 def ScanInfAsmFiles(self
):
765 assert os
.path
.isfile(src
)
766 f
= io
.open(src
, 'rt')
767 self
.lines
= f
.readlines()
770 path
= os
.path
.realpath(self
.inf
)
771 (self
.dir, inf
) = os
.path
.split(path
)
772 parent
= os
.path
.normpath(self
.dir)
773 (lastpath
, self
.moduleName
) = os
.path
.split(parent
)
774 self
.packageName
= None
776 lastpath
= os
.path
.normpath(lastpath
)
777 (parent
, basename
) = os
.path
.split(lastpath
)
778 if parent
== lastpath
:
780 if basename
.endswith('Pkg'):
781 self
.packageName
= basename
785 self
.srcToDst
= self
.GetInfAsmFileMapping()
787 self
.dstToSrc
= {'order': []}
788 for src
in self
.srcToDst
['order']:
789 srcExt
= os
.path
.splitext(src
)[1]
790 dst
= self
.srcToDst
[src
]
791 if dst
not in self
.dstToSrc
:
792 self
.dstToSrc
[dst
] = [src
]
793 self
.dstToSrc
['order'].append(dst
)
795 self
.dstToSrc
[dst
].append(src
)
798 return len(self
.dstToSrc
['order'])
801 return iter(self
.dstToSrc
['order'])
803 def ConvertInfAsmFiles(self
):
805 unsupportedArchCount
= 0
809 self
.UpdateInfAsmFile(dst
)
811 except UnsupportedConversion
:
812 if not self
.args
.quiet
:
813 print('MASM=>NASM conversion unsupported for', dst
)
814 notConverted
.append(dst
)
816 if not self
.args
.quiet
:
817 print('Source file missing for', reldst
)
818 notConverted
.append(dst
)
819 except UnsupportedArch
:
820 unsupportedArchCount
+= 1
823 self
.ConversionFinished(dst
)
824 if len(notConverted
) > 0 and not self
.args
.quiet
:
825 for dst
in notConverted
:
826 reldst
= self
.RootRelative(dst
)
827 print('Unabled to convert', reldst
)
828 if unsupportedArchCount
> 0 and not self
.args
.quiet
:
829 print('Skipped', unsupportedArchCount
, 'files based on architecture')
831 def UpdateInfAsmFile(self
, dst
, IgnoreMissingAsm
=False):
832 infPath
= os
.path
.split(os
.path
.realpath(self
.inf
))[0]
833 asmSrc
= os
.path
.splitext(dst
)[0] + '.asm'
834 fullSrc
= os
.path
.join(infPath
, asmSrc
)
835 fullDst
= os
.path
.join(infPath
, dst
)
836 srcParentDir
= os
.path
.basename(os
.path
.split(fullSrc
)[0])
837 if srcParentDir
.lower() in UnsupportedArch
.unsupported
:
838 raise UnsupportedArch
839 elif not os
.path
.exists(fullSrc
):
840 if not IgnoreMissingAsm
:
842 else: # not os.path.exists(fullDst):
843 conv
= ConvertAsmFile(fullSrc
, fullDst
, self
)
844 self
.unsupportedSyntaxSeen
= conv
.unsupportedSyntaxSeen
849 for line
in self
.lines
:
852 for src
in self
.dstToSrc
[dst
]:
853 assert self
.srcToDst
[src
] == dst
854 updatedLine
= self
.ReplacePreserveSpacing(
855 updatedLine
, src
, dst
)
857 lineChanged
= updatedLine
!= line
859 if lastLine
.strip() == updatedLine
.strip():
862 self
.lines
[i
] = updatedLine
+ '\n'
867 if self
.lines
[i
] is not None:
868 print('+%s' % updatedLine
)
872 fileChanged |
= lineChanged
873 if self
.lines
[i
] is not None:
874 lastLine
= self
.lines
[i
]
879 self
.lines
= list(filter(lambda l
: l
is not None, self
.lines
))
881 for src
in self
.dstToSrc
[dst
]:
882 if not src
.endswith('.asm'):
883 fullSrc
= os
.path
.join(infPath
, src
)
884 if os
.path
.exists(fullSrc
):
885 self
.RemoveFile(fullSrc
)
888 f
= io
.open(self
.inf
, 'w', newline
='\r\n')
889 f
.writelines(self
.lines
)
891 self
.FileUpdated(self
.inf
)
893 def ConversionFinished(self
, dst
):
894 asmSrc
= os
.path
.splitext(dst
)[0] + '.asm'
895 self
.FileConversionFinished(
896 self
.packageName
, self
.moduleName
, asmSrc
, dst
)
899 class ConvertInfFiles(CommonUtils
):
901 def __init__(self
, infs
, clone
):
902 CommonUtils
.__init
__(self
, clone
)
903 infs
= map(lambda i
: ConvertInfFile(i
, self
), infs
)
904 infs
= filter(lambda i
: len(i
) > 0, infs
)
905 dstToInfs
= {'order': []}
908 fulldst
= os
.path
.realpath(os
.path
.join(inf
.dir, dst
))
910 if fulldst
in dstToInfs
:
911 dstToInfs
[fulldst
].append(pair
)
913 dstToInfs
['order'].append(fulldst
)
914 dstToInfs
[fulldst
] = [pair
]
917 unsupportedArchCount
= 0
918 for dst
in dstToInfs
['order']:
921 for inf
, reldst
in dstToInfs
[dst
]:
922 inf
.UpdateInfAsmFile(reldst
, IgnoreMissingAsm
=didSomething
)
924 except UnsupportedConversion
:
925 if not self
.args
.quiet
:
926 print('MASM=>NASM conversion unsupported for', reldst
)
927 notConverted
.append(dst
)
929 if not self
.args
.quiet
:
930 print('Source file missing for', reldst
)
931 notConverted
.append(dst
)
932 except UnsupportedArch
:
933 unsupportedArchCount
+= 1
936 inf
.ConversionFinished(reldst
)
937 if len(notConverted
) > 0 and not self
.args
.quiet
:
938 for dst
in notConverted
:
939 reldst
= self
.RootRelative(dst
)
940 print('Unabled to convert', reldst
)
941 if unsupportedArchCount
> 0 and not self
.args
.quiet
:
942 print('Skipped', unsupportedArchCount
, 'files based on architecture')
945 class ConvertDirectories(CommonUtils
):
947 def __init__(self
, paths
, clone
):
948 CommonUtils
.__init
__(self
, clone
)
950 self
.ConvertInfAndAsmFiles()
952 def ConvertInfAndAsmFiles(self
):
954 for path
in self
.paths
:
955 assert(os
.path
.exists(path
))
956 for path
in self
.paths
:
957 for root
, dirs
, files
in os
.walk(path
):
958 for d
in ('.svn', '.git'):
962 if f
.lower().endswith('.inf'):
963 inf
= os
.path
.realpath(os
.path
.join(root
, f
))
966 ConvertInfFiles(infs
, self
)
969 class ConvertAsmApp(CommonUtils
):
972 CommonUtils
.__init
__(self
)
974 src
= self
.args
.source
977 ConvertInfFiles((src
,), self
)
979 ConvertDirectories((src
,), self
)
980 elif not self
.dirmode
:
981 ConvertAsmFile(src
, dst
, self
)