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.
26 class UnsupportedConversion(Exception):
30 class NoSourceFile(Exception):
34 class UnsupportedArch(Exception):
35 unsupported
= ('aarch64', 'arm', 'ebc', 'ipf')
40 # Version and Copyright
41 VersionNumber
= "0.01"
42 __version__
= "%prog Version " + VersionNumber
43 __copyright__
= "Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved."
44 __usage__
= "%prog [options] source.asm [destination.nasm]"
46 def __init__(self
, clone
=None):
48 self
.args
= self
.ProcessCommandLine()
50 self
.args
= clone
.args
52 self
.unsupportedSyntaxSeen
= False
53 self
.src
= self
.args
.source
54 assert(os
.path
.exists(self
.src
))
55 self
.dirmode
= os
.path
.isdir(self
.src
)
56 srcExt
= os
.path
.splitext(self
.src
)[1]
57 assert (self
.dirmode
or srcExt
!= '.nasm')
58 self
.infmode
= not self
.dirmode
and srcExt
== '.inf'
59 self
.diff
= self
.args
.diff
60 self
.git
= self
.args
.git
61 self
.force
= self
.args
.force
64 self
.rootdir
= os
.getcwd()
67 self
.rootdir
= clone
.rootdir
68 self
.gitdir
= clone
.gitdir
69 self
.gitemail
= clone
.gitemail
71 def ProcessCommandLine(self
):
72 parser
= argparse
.ArgumentParser(description
=self
.__copyright
__)
73 parser
.add_argument('--version', action
='version',
74 version
='%(prog)s ' + self
.VersionNumber
)
75 parser
.add_argument("-q", "--quiet", action
="store_true",
76 help="Disable all messages except FATAL ERRORS.")
77 parser
.add_argument("--git", action
="store_true",
78 help="Use git to create commits for each file converted")
79 parser
.add_argument("--diff", action
="store_true",
80 help="Show diff of conversion")
81 parser
.add_argument("-f", "--force", action
="store_true",
82 help="Force conversion even if unsupported")
83 parser
.add_argument('source', help='MASM input file')
84 parser
.add_argument('dest', nargs
='?',
85 help='NASM output file (default=input.nasm; - for stdout)')
87 return parser
.parse_args()
89 def RootRelative(self
, path
):
91 if result
.startswith(self
.rootdir
):
92 result
= result
[len(self
.rootdir
):]
93 while len(result
) > 0 and result
[0] in '/\\':
97 def MatchAndSetMo(self
, regexp
, string
):
98 self
.mo
= regexp
.match(string
)
99 return self
.mo
is not None
101 def SearchAndSetMo(self
, regexp
, string
):
102 self
.mo
= regexp
.search(string
)
103 return self
.mo
is not None
105 def ReplacePreserveSpacing(self
, string
, find
, replace
):
106 if len(find
) >= len(replace
):
107 padded
= replace
+ (' ' * (len(find
) - len(replace
)))
108 return string
.replace(find
, padded
)
109 elif find
.find(replace
) >= 0:
110 return string
.replace(find
, replace
)
112 lenDiff
= len(replace
) - len(find
)
114 for i
in range(lenDiff
, -1, -1):
115 padded
= find
+ (' ' * i
)
116 result
= result
.replace(padded
, replace
)
120 lastpath
= os
.path
.realpath(self
.src
)
123 path
= os
.path
.split(lastpath
)[0]
127 candidate
= os
.path
.join(path
, '.git')
128 if os
.path
.isdir(candidate
):
129 self
.gitdir
= candidate
130 self
.gitemail
= self
.FormatGitEmailAddress()
134 def FormatGitEmailAddress(self
):
135 if not self
.git
or not self
.gitdir
:
138 cmd
= ('git', 'config', 'user.name')
139 name
= self
.RunAndCaptureOutput(cmd
).strip()
140 cmd
= ('git', 'config', 'user.email')
141 email
= self
.RunAndCaptureOutput(cmd
).strip()
142 if name
.find(',') >= 0:
143 name
= '"' + name
+ '"'
144 return name
+ ' <' + email
+ '>'
146 def RunAndCaptureOutput(self
, cmd
, checkExitCode
=True, pipeIn
=None):
148 subpStdin
= subprocess
.PIPE
151 p
= subprocess
.Popen(args
=cmd
, stdout
=subprocess
.PIPE
, stdin
=subpStdin
)
152 (stdout
, stderr
) = p
.communicate(pipeIn
)
154 if p
.returncode
!= 0:
155 print 'command:', ' '.join(cmd
)
156 print 'stdout:', stdout
157 print 'stderr:', stderr
158 print 'return:', p
.returncode
159 assert p
.returncode
== 0
162 def FileUpdated(self
, path
):
163 if not self
.git
or not self
.gitdir
:
166 cmd
= ('git', 'add', path
)
167 self
.RunAndCaptureOutput(cmd
)
169 def FileAdded(self
, path
):
170 self
.FileUpdated(path
)
172 def RemoveFile(self
, path
):
173 if not self
.git
or not self
.gitdir
:
176 cmd
= ('git', 'rm', path
)
177 self
.RunAndCaptureOutput(cmd
)
179 def FileConversionFinished(self
, pkg
, module
, src
, dst
):
180 if not self
.git
or not self
.gitdir
:
183 if not self
.args
.quiet
:
184 print 'Committing: Conversion of', dst
186 prefix
= ' '.join(filter(lambda a
: a
, [pkg
, module
]))
188 if self
.unsupportedSyntaxSeen
:
190 message
+= '%s: Convert %s to NASM\n' % (prefix
, src
)
192 message
+= 'The %s script was used to convert\n' % sys
.argv
[0]
193 message
+= '%s to %s\n' % (src
, dst
)
195 message
+= 'Contributed-under: TianoCore Contribution Agreement 1.0\n'
196 assert(self
.gitemail
is not None)
197 message
+= 'Signed-off-by: %s\n' % self
.gitemail
199 cmd
= ('git', 'commit', '-F', '-')
200 self
.RunAndCaptureOutput(cmd
, pipeIn
=message
)
203 class ConvertAsmFile(CommonUtils
):
205 def __init__(self
, src
, dst
, clone
):
206 CommonUtils
.__init
__(self
, clone
)
207 self
.ConvertAsmFile(src
, dst
)
211 def ConvertAsmFile(self
, inputFile
, outputFile
=None):
213 self
.unsupportedSyntaxSeen
= False
214 self
.inputFilename
= inputFile
216 outputFile
= os
.path
.splitext(inputFile
)[0] + '.nasm'
217 self
.outputFilename
= outputFile
219 fullSrc
= os
.path
.realpath(inputFile
)
220 srcParentDir
= os
.path
.basename(os
.path
.split(fullSrc
)[0])
221 maybeArch
= srcParentDir
.lower()
222 if maybeArch
in UnsupportedArch
.unsupported
:
223 raise UnsupportedArch
224 self
.ia32
= maybeArch
== 'ia32'
225 self
.x64
= maybeArch
== 'x64'
227 self
.inputFileBase
= os
.path
.basename(self
.inputFilename
)
228 self
.outputFileBase
= os
.path
.basename(self
.outputFilename
)
229 if self
.outputFilename
== '-' and not self
.diff
:
230 self
.output
= sys
.stdout
232 self
.output
= StringIO
.StringIO()
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
= open(self
.inputFilename
).readlines()
240 if self
.outputFilename
== '-':
242 sys
.stdout
.write(self
.output
.getvalue())
245 f
= open(self
.outputFilename
, 'wb')
246 f
.write(self
.output
.getvalue())
250 endOfLineRe
= re
.compile(r
'''
253 re
.VERBOSE | re
.MULTILINE
255 begOfLineRe
= re
.compile(r
'''
261 def Convert(self
, lines
):
263 self
.anonLabelCount
= -1
265 self
.oldAsmEmptyLineCount
= 0
266 self
.newAsmEmptyLineCount
= 0
268 mo
= self
.begOfLineRe
.search(line
)
269 assert mo
is not None
270 self
.indent
= mo
.group()
271 lineWithoutBeginning
= line
[len(self
.indent
):]
272 mo
= self
.endOfLineRe
.search(lineWithoutBeginning
)
276 endOfLine
= mo
.group()
277 oldAsm
= line
[len(self
.indent
):len(line
) - len(endOfLine
)]
278 self
.originalLine
= line
.rstrip()
279 if line
.strip() == '':
280 self
.oldAsmEmptyLineCount
+= 1
281 self
.TranslateAsm(oldAsm
, endOfLine
)
282 if line
.strip() != '':
283 self
.oldAsmEmptyLineCount
= 0
285 procDeclRe
= re
.compile(r
'''
288 (?: \s+ NEAR | FAR )?
290 (?: \s+ (PUBLIC | PRIVATE) )?
291 (?: \s+ USES ( (?: \s+ \w[\w0-9]* )+ ) )?
294 re
.VERBOSE | re
.IGNORECASE
297 procEndRe
= re
.compile(r
'''
302 re
.VERBOSE | re
.IGNORECASE
305 varAndTypeSubRe
= r
' (?: [\w@][\w@0-9]* ) (?: \s* : \s* \w+ )? '
306 publicRe
= re
.compile(r
'''
308 ( %s (?: \s* , \s* %s )* )
310 ''' % (varAndTypeSubRe
, varAndTypeSubRe
),
311 re
.VERBOSE | re
.IGNORECASE
314 varAndTypeSubRe
= re
.compile(varAndTypeSubRe
, re
.VERBOSE | re
.IGNORECASE
)
316 macroDeclRe
= re
.compile(r
'''
321 re
.VERBOSE | re
.IGNORECASE
324 sectionDeclRe
= re
.compile(r
'''
329 re
.VERBOSE | re
.IGNORECASE
332 externRe
= re
.compile(r
'''
333 EXTE?RN \s+ (?: C \s+ )?
334 ([\w@][\w@0-9]*) \s* : \s* (\w+)
337 re
.VERBOSE | re
.IGNORECASE
340 externdefRe
= re
.compile(r
'''
341 EXTERNDEF \s+ (?: C \s+ )?
342 ([\w@][\w@0-9]*) \s* : \s* (\w+)
345 re
.VERBOSE | re
.IGNORECASE
348 protoRe
= re
.compile(r
'''
354 re
.VERBOSE | re
.IGNORECASE
357 defineDataRe
= re
.compile(r
'''
359 ( db | dw | dd | dq ) \s+
363 re
.VERBOSE | re
.IGNORECASE
366 equRe
= re
.compile(r
'''
367 ([\w@][\w@0-9]*) \s+ EQU \s+ (\S.*?)
370 re
.VERBOSE | re
.IGNORECASE
373 ignoreRe
= re
.compile(r
'''
385 re
.VERBOSE | re
.IGNORECASE
388 whitespaceRe
= re
.compile(r
'\s+', re
.MULTILINE
)
390 def TranslateAsm(self
, oldAsm
, endOfLine
):
391 assert(oldAsm
.strip() == oldAsm
)
393 endOfLine
= endOfLine
.replace(self
.inputFileBase
, self
.outputFileBase
)
395 oldOp
= oldAsm
.split()
403 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
404 elif oldOp
in ('#include', ):
406 self
.EmitLine(oldAsm
+ endOfLine
)
407 elif oldOp
.lower() in ('end', 'title', 'text'):
409 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
410 elif oldAsm
.lower() == '@@:':
411 self
.anonLabelCount
+= 1
412 self
.EmitLine(self
.anonLabel(self
.anonLabelCount
) + ':')
413 elif self
.MatchAndSetMo(self
.ignoreRe
, oldAsm
):
415 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
416 elif oldAsm
.lower() == 'ret':
417 for i
in range(len(self
.uses
) - 1, -1, -1):
418 register
= self
.uses
[i
]
419 self
.EmitNewContent('pop ' + register
)
421 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
423 elif oldOp
.lower() == 'lea':
424 newAsm
= self
.ConvertLea(oldAsm
)
425 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
426 elif oldAsm
.lower() == 'end':
428 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
430 elif self
.MatchAndSetMo(self
.equRe
, oldAsm
):
431 equ
= self
.mo
.group(1)
432 newAsm
= '%%define %s %s' % (equ
, self
.mo
.group(2))
433 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
434 elif self
.MatchAndSetMo(self
.externRe
, oldAsm
) or \
435 self
.MatchAndSetMo(self
.protoRe
, oldAsm
):
436 extern
= self
.mo
.group(1)
437 self
.NewGlobal(extern
)
438 newAsm
= 'extern ' + extern
439 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
440 elif self
.MatchAndSetMo(self
.externdefRe
, oldAsm
):
442 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
443 elif self
.MatchAndSetMo(self
.macroDeclRe
, oldAsm
):
444 newAsm
= '%%macro %s 0' % self
.mo
.group(1)
445 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
446 elif oldOp
.lower() == 'endm':
447 newAsm
= r
'%endmacro'
448 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
449 elif self
.MatchAndSetMo(self
.sectionDeclRe
, oldAsm
):
450 name
= self
.mo
.group(1)
451 ty
= self
.mo
.group(2)
452 if ty
.lower() == 'section':
456 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
457 elif self
.MatchAndSetMo(self
.procDeclRe
, oldAsm
):
458 proc
= self
.proc
= self
.mo
.group(1)
459 visibility
= self
.mo
.group(2)
460 if visibility
is None:
463 visibility
= visibility
.lower()
464 if visibility
!= 'private':
465 self
.NewGlobal(self
.proc
)
466 proc
= 'ASM_PFX(' + proc
+ ')'
467 self
.EmitNewContent('global ' + proc
)
469 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
470 uses
= self
.mo
.group(3)
472 uses
= filter(None, uses
.split())
476 for register
in self
.uses
:
477 self
.EmitNewContent(' push ' + register
)
478 elif self
.MatchAndSetMo(self
.procEndRe
, oldAsm
):
480 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
481 elif self
.MatchAndSetMo(self
.publicRe
, oldAsm
):
482 publics
= re
.findall(self
.varAndTypeSubRe
, self
.mo
.group(1))
483 publics
= map(lambda p
: p
.split(':')[0].strip(), publics
)
484 for i
in range(len(publics
) - 1):
486 self
.EmitNewContent('global ASM_PFX(%s)' % publics
[i
])
490 newAsm
= 'global ASM_PFX(%s)' % name
491 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
492 elif self
.MatchAndSetMo(self
.defineDataRe
, oldAsm
):
493 name
= self
.mo
.group(1)
494 ty
= self
.mo
.group(2)
495 value
= self
.mo
.group(3)
498 newAsm
= '%s: %s %s' % (name
, ty
, value
)
499 newAsm
= self
.CommonConversions(newAsm
)
500 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
502 newAsm
= self
.CommonConversions(oldAsm
)
503 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
505 def NewGlobal(self
, name
):
506 regex
= re
.compile(r
'(?<![_\w\d])(?<!ASM_PFX\()(' + re
.escape(name
) +
508 self
.globals.add(regex
)
510 def ConvertAnonymousLabels(self
, oldAsm
):
512 anonLabel
= self
.anonLabel(self
.anonLabelCount
)
513 newAsm
= newAsm
.replace('@b', anonLabel
)
514 newAsm
= newAsm
.replace('@B', anonLabel
)
515 anonLabel
= self
.anonLabel(self
.anonLabelCount
+ 1)
516 newAsm
= newAsm
.replace('@f', anonLabel
)
517 newAsm
= newAsm
.replace('@F', anonLabel
)
520 def anonLabel(self
, count
):
523 def EmitString(self
, string
):
524 self
.output
.write(string
)
526 def EmitLineWithDiff(self
, old
, new
):
527 newLine
= (self
.indent
+ new
).rstrip()
530 print '+%s' % newLine
533 print '+%s' % newLine
537 self
.newAsmEmptyLineCount
= 0
538 self
.EmitString(newLine
+ '\r\n')
540 def EmitLine(self
, string
):
541 self
.EmitLineWithDiff(self
.originalLine
, string
)
543 def EmitNewContent(self
, string
):
544 self
.EmitLineWithDiff(None, string
)
546 def EmitAsmReplaceOp(self
, oldAsm
, oldOp
, newOp
, endOfLine
):
547 newAsm
= oldAsm
.replace(oldOp
, newOp
, 1)
548 self
.EmitAsmWithComment(oldAsm
, newAsm
, endOfLine
)
550 hexNumRe
= re
.compile(r
'0*((?=[\da-f])\d*(?<=\d)[\da-f]*)h', re
.IGNORECASE
)
552 def EmitAsmWithComment(self
, oldAsm
, newAsm
, endOfLine
):
553 for glblRe
in self
.globals:
554 newAsm
= glblRe
.sub(r
'ASM_PFX(\1)', newAsm
)
556 newAsm
= self
.hexNumRe
.sub(r
'0x\1', newAsm
)
558 newLine
= newAsm
+ endOfLine
559 emitNewLine
= ((newLine
.strip() != '') or
560 ((oldAsm
+ endOfLine
).strip() == ''))
561 if emitNewLine
and newLine
.strip() == '':
562 self
.newAsmEmptyLineCount
+= 1
563 if self
.newAsmEmptyLineCount
> 1:
566 self
.EmitLine(newLine
.rstrip())
568 print '-%s' % self
.originalLine
570 leaRe
= re
.compile(r
'''
571 (lea \s+) ([\w@][\w@0-9]*) \s* , \s* (\S (?:.*\S)?)
574 re
.VERBOSE | re
.IGNORECASE
577 def ConvertLea(self
, oldAsm
):
579 if self
.MatchAndSetMo(self
.leaRe
, oldAsm
):
580 lea
= self
.mo
.group(1)
581 dst
= self
.mo
.group(2)
582 src
= self
.mo
.group(3)
583 if src
.find('[') < 0:
584 src
= '[' + src
+ ']'
585 newAsm
= lea
+ dst
+ ', ' + src
586 newAsm
= self
.CommonConversions(newAsm
)
589 ptrRe
= re
.compile(r
'''
591 ([dfq]?word|byte) \s+ (?: ptr ) (\s*)
594 re
.VERBOSE | re
.IGNORECASE
597 def ConvertPtr(self
, oldAsm
):
599 while self
.SearchAndSetMo(self
.ptrRe
, newAsm
):
600 ty
= self
.mo
.group(1)
601 if ty
.lower() == 'fword':
604 ty
+= self
.mo
.group(2)
605 newAsm
= newAsm
[:self
.mo
.start(0)] + ty
+ newAsm
[self
.mo
.end(0):]
608 labelByteRe
= re
.compile(r
'''
609 (?: \s+ label \s+ (?: [dfq]?word | byte ) )
612 re
.VERBOSE | re
.IGNORECASE
615 def ConvertLabelByte(self
, oldAsm
):
617 if self
.SearchAndSetMo(self
.labelByteRe
, newAsm
):
618 newAsm
= newAsm
[:self
.mo
.start(0)] + ':' + newAsm
[self
.mo
.end(0):]
621 unaryBitwiseOpRe
= re
.compile(r
'''
625 re
.VERBOSE | re
.IGNORECASE
627 binaryBitwiseOpRe
= re
.compile(r
'''
629 ( AND | OR | SHL | SHR )
632 re
.VERBOSE | re
.IGNORECASE
634 bitwiseOpReplacements
= {
642 def ConvertBitwiseOp(self
, oldAsm
):
644 while self
.SearchAndSetMo(self
.binaryBitwiseOpRe
, newAsm
):
645 prefix
= self
.mo
.group(1)
646 op
= self
.bitwiseOpReplacements
[self
.mo
.group(2).lower()]
647 newAsm
= newAsm
[:self
.mo
.start(0)] + prefix
+ op
+ \
648 newAsm
[self
.mo
.end(0):]
649 while self
.SearchAndSetMo(self
.unaryBitwiseOpRe
, newAsm
):
650 op
= self
.bitwiseOpReplacements
[self
.mo
.group(1).lower()]
651 newAsm
= newAsm
[:self
.mo
.start(0)] + op
+ newAsm
[self
.mo
.end(0):]
654 sectionRe
= re
.compile(r
'''
661 re
.VERBOSE | re
.IGNORECASE
664 segmentRe
= re
.compile(r
'''
671 re
.VERBOSE | re
.IGNORECASE
674 def ConvertSection(self
, oldAsm
):
676 if self
.MatchAndSetMo(self
.sectionRe
, newAsm
) or \
677 self
.MatchAndSetMo(self
.segmentRe
, newAsm
):
678 name
= self
.mo
.group(1).lower()
681 self
.EmitLine('DEFAULT REL')
683 newAsm
= 'SECTION .' + name
686 fwordRe
= re
.compile(r
'''
691 re
.VERBOSE | re
.IGNORECASE
694 def FwordUnsupportedCheck(self
, oldAsm
):
696 if self
.SearchAndSetMo(self
.fwordRe
, newAsm
):
697 newAsm
= self
.Unsupported(newAsm
, 'fword used')
700 __common_conversion_routines__
= (
701 ConvertAnonymousLabels
,
703 FwordUnsupportedCheck
,
709 def CommonConversions(self
, oldAsm
):
711 for conv
in self
.__common
_conversion
_routines
__:
712 newAsm
= conv(self
, newAsm
)
715 def Unsupported(self
, asm
, message
=None):
717 raise UnsupportedConversion
719 self
.unsupportedSyntaxSeen
= True
720 newAsm
= '%error conversion unsupported'
722 newAsm
+= '; ' + message
727 class ConvertInfFile(CommonUtils
):
729 def __init__(self
, inf
, clone
):
730 CommonUtils
.__init
__(self
, clone
)
732 self
.ScanInfAsmFiles()
734 self
.ConvertInfAsmFiles()
736 infSrcRe
= re
.compile(r
'''
738 ( [\w@][\w@0-9/]* \.(asm|s) )
743 re
.VERBOSE | re
.IGNORECASE
746 def GetInfAsmFileMapping(self
):
747 srcToDst
= {'order': []}
748 for line
in self
.lines
:
750 if self
.MatchAndSetMo(self
.infSrcRe
, line
):
751 src
= self
.mo
.group(1)
752 srcExt
= self
.mo
.group(2)
753 dst
= os
.path
.splitext(src
)[0] + '.nasm'
754 if src
not in srcToDst
:
756 srcToDst
['order'].append(src
)
759 def ScanInfAsmFiles(self
):
761 assert os
.path
.isfile(src
)
763 self
.lines
= f
.readlines()
766 path
= os
.path
.realpath(self
.inf
)
767 (self
.dir, inf
) = os
.path
.split(path
)
768 parent
= os
.path
.normpath(self
.dir)
769 (lastpath
, self
.moduleName
) = os
.path
.split(parent
)
770 self
.packageName
= None
772 lastpath
= os
.path
.normpath(lastpath
)
773 (parent
, basename
) = os
.path
.split(lastpath
)
774 if parent
== lastpath
:
776 if basename
.endswith('Pkg'):
777 self
.packageName
= basename
781 self
.srcToDst
= self
.GetInfAsmFileMapping()
783 self
.dstToSrc
= {'order': []}
784 for src
in self
.srcToDst
['order']:
785 srcExt
= os
.path
.splitext(src
)[1]
786 dst
= self
.srcToDst
[src
]
787 if dst
not in self
.dstToSrc
:
788 self
.dstToSrc
[dst
] = [src
]
789 self
.dstToSrc
['order'].append(dst
)
791 self
.dstToSrc
[dst
].append(src
)
794 return len(self
.dstToSrc
['order'])
797 return iter(self
.dstToSrc
['order'])
799 def ConvertInfAsmFiles(self
):
801 unsupportedArchCount
= 0
804 fileChanged
= self
.UpdateInfAsmFile(dst
)
806 self
.UpdateInfAsmFile(dst
)
808 except UnsupportedConversion
:
809 if not self
.args
.quiet
:
810 print 'MASM=>NASM conversion unsupported for', dst
811 notConverted
.append(dst
)
813 if not self
.args
.quiet
:
814 print 'Source file missing for', reldst
815 notConverted
.append(dst
)
816 except UnsupportedArch
:
817 unsupportedArchCount
+= 1
820 self
.ConversionFinished(dst
)
821 if len(notConverted
) > 0 and not self
.args
.quiet
:
822 for dst
in notConverted
:
823 reldst
= self
.RootRelative(dst
)
824 print 'Unabled to convert', reldst
825 if unsupportedArchCount
> 0 and not self
.args
.quiet
:
826 print 'Skipped', unsupportedArchCount
, 'files based on architecture'
828 def UpdateInfAsmFile(self
, dst
, IgnoreMissingAsm
=False):
829 infPath
= os
.path
.split(os
.path
.realpath(self
.inf
))[0]
830 asmSrc
= os
.path
.splitext(dst
)[0] + '.asm'
831 fullSrc
= os
.path
.join(infPath
, asmSrc
)
832 fullDst
= os
.path
.join(infPath
, dst
)
833 srcParentDir
= os
.path
.basename(os
.path
.split(fullSrc
)[0])
834 if srcParentDir
.lower() in UnsupportedArch
.unsupported
:
835 raise UnsupportedArch
836 elif not os
.path
.exists(fullSrc
):
837 if not IgnoreMissingAsm
:
839 else: # not os.path.exists(fullDst):
840 conv
= ConvertAsmFile(fullSrc
, fullDst
, self
)
841 self
.unsupportedSyntaxSeen
= conv
.unsupportedSyntaxSeen
845 for i
in range(len(self
.lines
)):
846 line
= self
.lines
[i
].rstrip()
848 for src
in self
.dstToSrc
[dst
]:
849 assert self
.srcToDst
[src
] == dst
850 updatedLine
= self
.ReplacePreserveSpacing(
851 updatedLine
, src
, dst
)
853 lineChanged
= updatedLine
!= line
855 if lastLine
.strip() == updatedLine
.strip():
858 self
.lines
[i
] = updatedLine
+ '\r\n'
863 if self
.lines
[i
] is not None:
864 print '+%s' % updatedLine
868 fileChanged |
= lineChanged
869 if self
.lines
[i
] is not None:
870 lastLine
= self
.lines
[i
]
873 self
.lines
= filter(lambda l
: l
is not None, self
.lines
)
875 for src
in self
.dstToSrc
[dst
]:
876 if not src
.endswith('.asm'):
877 fullSrc
= os
.path
.join(infPath
, src
)
878 if os
.path
.exists(fullSrc
):
879 self
.RemoveFile(fullSrc
)
882 f
= open(self
.inf
, 'wb')
883 f
.writelines(self
.lines
)
885 self
.FileUpdated(self
.inf
)
887 def ConversionFinished(self
, dst
):
888 asmSrc
= os
.path
.splitext(dst
)[0] + '.asm'
889 self
.FileConversionFinished(
890 self
.packageName
, self
.moduleName
, asmSrc
, dst
)
893 class ConvertInfFiles(CommonUtils
):
895 def __init__(self
, infs
, clone
):
896 CommonUtils
.__init
__(self
, clone
)
897 infs
= map(lambda i
: ConvertInfFile(i
, self
), infs
)
898 infs
= filter(lambda i
: len(i
) > 0, infs
)
899 dstToInfs
= {'order': []}
902 fulldst
= os
.path
.realpath(os
.path
.join(inf
.dir, dst
))
904 if fulldst
in dstToInfs
:
905 dstToInfs
[fulldst
].append(pair
)
907 dstToInfs
['order'].append(fulldst
)
908 dstToInfs
[fulldst
] = [pair
]
911 unsupportedArchCount
= 0
912 for dst
in dstToInfs
['order']:
915 for inf
, reldst
in dstToInfs
[dst
]:
916 inf
.UpdateInfAsmFile(reldst
, IgnoreMissingAsm
=didSomething
)
918 except UnsupportedConversion
:
919 if not self
.args
.quiet
:
920 print 'MASM=>NASM conversion unsupported for', reldst
921 notConverted
.append(dst
)
923 if not self
.args
.quiet
:
924 print 'Source file missing for', reldst
925 notConverted
.append(dst
)
926 except UnsupportedArch
:
927 unsupportedArchCount
+= 1
930 inf
.ConversionFinished(reldst
)
931 if len(notConverted
) > 0 and not self
.args
.quiet
:
932 for dst
in notConverted
:
933 reldst
= self
.RootRelative(dst
)
934 print 'Unabled to convert', reldst
935 if unsupportedArchCount
> 0 and not self
.args
.quiet
:
936 print 'Skipped', unsupportedArchCount
, 'files based on architecture'
939 class ConvertDirectories(CommonUtils
):
941 def __init__(self
, paths
, clone
):
942 CommonUtils
.__init
__(self
, clone
)
944 self
.ConvertInfAndAsmFiles()
946 def ConvertInfAndAsmFiles(self
):
948 for path
in self
.paths
:
949 assert(os
.path
.exists(path
))
950 for path
in self
.paths
:
951 for root
, dirs
, files
in os
.walk(path
):
952 for d
in ('.svn', '.git'):
956 if f
.lower().endswith('.inf'):
957 inf
= os
.path
.realpath(os
.path
.join(root
, f
))
960 ConvertInfFiles(infs
, self
)
963 class ConvertAsmApp(CommonUtils
):
966 CommonUtils
.__init
__(self
)
968 src
= self
.args
.source
971 ConvertInfFiles(src
, self
)
973 ConvertDirectories((src
,), self
)
974 elif not self
.dirmode
:
975 ConvertAsmFile(src
, dst
, self
)