Commit ca9124e4 authored by Raul Tambre's avatar Raul Tambre Committed by Commit Bot

tools: Use Python 3 style print statements [9/9]

Initial conversion performed using '2to3 -f print .'.
Imports added and duplicate parentheses removed manually.
Manually converted files, comments and inline code that 2to3 missed.
Afterwards ran "git cl format --python" and cherry-picked the formatting changes.

There are no intended behavioural changes.

Bug: 941669
Change-Id: Ib7b47c4294679b5091faf4b56486cd5946f78377
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1818520
Commit-Queue: Raul Tambre <raul@tambre.ee>
Auto-Submit: Raul Tambre <raul@tambre.ee>
Reviewed-by: default avatarNico Weber <thakis@chromium.org>
Cr-Commit-Position: refs/heads/master@{#700582}
parent 02325e8e
...@@ -4,6 +4,8 @@ ...@@ -4,6 +4,8 @@
"""Helpers for dealing with translation files.""" """Helpers for dealing with translation files."""
from __future__ import print_function
import ast import ast
import os import os
import re import re
...@@ -236,5 +238,5 @@ def _parse_translation_expectations(path): ...@@ -236,5 +238,5 @@ def _parse_translation_expectations(path):
return grd_to_langs, untranslated_grds, internal_grds return grd_to_langs, untranslated_grds, internal_grds
except Exception: except Exception:
print 'Error: failed to parse', path print('Error: failed to parse', path)
raise raise
...@@ -16,6 +16,8 @@ files, so it doesn't know whether an image file corresponds to a message or not. ...@@ -16,6 +16,8 @@ files, so it doesn't know whether an image file corresponds to a message or not.
It will attempt to upload the image anyways. It will attempt to upload the image anyways.
""" """
from __future__ import print_function
import argparse import argparse
import sys import sys
import os import os
...@@ -71,14 +73,14 @@ def query_yes_no(question, default='no'): ...@@ -71,14 +73,14 @@ def query_yes_no(question, default='no'):
valid = {'yes': True, 'y': True, 'ye': True, 'no': False, 'n': False} valid = {'yes': True, 'y': True, 'ye': True, 'no': False, 'n': False}
while True: while True:
print question, prompt print(question, prompt)
choice = raw_input().lower() choice = raw_input().lower()
if default is not None and choice == '': if default is not None and choice == '':
return valid[default] return valid[default]
elif choice in valid: elif choice in valid:
return valid[choice] return valid[choice]
else: else:
print "Please respond with 'yes' or 'no' (or 'y' or 'n')." print("Please respond with 'yes' or 'no' (or 'y' or 'n').")
def list_grds_in_repository(repo_path): def list_grds_in_repository(repo_path):
...@@ -134,7 +136,7 @@ def find_screenshots(repo_root, translation_expectations): ...@@ -134,7 +136,7 @@ def find_screenshots(repo_root, translation_expectations):
if f in ('OWNERS', 'README.md') or f.endswith('.sha1'): if f in ('OWNERS', 'README.md') or f.endswith('.sha1'):
continue continue
if not f.endswith('.png'): if not f.endswith('.png'):
print 'File with unexpected extension: %s in %s' % (f, screenshots_dir) print('File with unexpected extension: %s in %s' % (f, screenshots_dir))
continue continue
screenshots.append(os.path.join(screenshots_dir, f)) screenshots.append(os.path.join(screenshots_dir, f))
return screenshots return screenshots
...@@ -162,10 +164,10 @@ def main(): ...@@ -162,10 +164,10 @@ def main():
"this script can pick up its screenshot directory.") "this script can pick up its screenshot directory.")
exit(0) exit(0)
print 'Found %d updated screenshot(s): ' % len(screenshots) print('Found %d updated screenshot(s): ' % len(screenshots))
for s in screenshots: for s in screenshots:
print ' %s' % s print(' %s' % s)
print print()
if not query_yes_no( if not query_yes_no(
'Do you want to upload these to Google Cloud Storage?\n\n' 'Do you want to upload these to Google Cloud Storage?\n\n'
'FILES WILL BE PUBLIC, DO NOT UPLOAD ANYTHING CONFIDENTIAL.'): 'FILES WILL BE PUBLIC, DO NOT UPLOAD ANYTHING CONFIDENTIAL.'):
...@@ -190,13 +192,13 @@ def main(): ...@@ -190,13 +192,13 @@ def main():
'`download_from_google_storage --config`.') '`download_from_google_storage --config`.')
exit(1) exit(1)
print print()
print 'Images are uploaded and their signatures are calculated:' print('Images are uploaded and their signatures are calculated:')
signatures = ['%s.sha1' % s for s in screenshots] signatures = ['%s.sha1' % s for s in screenshots]
for s in signatures: for s in signatures:
print ' %s' % s print(' %s' % s)
print print()
# Always ask if the .sha1 files should be added to the CL, even if they are # Always ask if the .sha1 files should be added to the CL, even if they are
# already part of the CL. If the files are not modified, adding again is a # already part of the CL. If the files are not modified, adding again is a
...@@ -208,7 +210,7 @@ def main(): ...@@ -208,7 +210,7 @@ def main():
if not args.dry_run: if not args.dry_run:
git_add(signatures, src_path) git_add(signatures, src_path)
print 'DONE.' print('DONE.')
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -17,6 +17,8 @@ and run this script on it: ...@@ -17,6 +17,8 @@ and run this script on it:
./tools/unused-symbols-report.py buildlog > report.html ./tools/unused-symbols-report.py buildlog > report.html
""" """
from __future__ import print_function
import cgi import cgi
import optparse import optparse
import os import os
...@@ -31,7 +33,7 @@ def Demangle(sym): ...@@ -31,7 +33,7 @@ def Demangle(sym):
if cppfilt_proc is None: if cppfilt_proc is None:
cppfilt_proc = subprocess.Popen(['c++filt'], stdin=subprocess.PIPE, cppfilt_proc = subprocess.Popen(['c++filt'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE) stdout=subprocess.PIPE)
print >>cppfilt_proc.stdin, sym print(sym, file=cppfilt_proc.stdin)
return cppfilt_proc.stdout.readline().strip() return cppfilt_proc.stdout.readline().strip()
...@@ -73,7 +75,7 @@ def Parse(input, skip_paths=None, only_paths=None): ...@@ -73,7 +75,7 @@ def Parse(input, skip_paths=None, only_paths=None):
continue continue
match = path_re.match(path) match = path_re.match(path)
if not match: if not match:
print >>sys.stderr, "Skipping weird path", path print("Skipping weird path", path, file=sys.stderr)
continue continue
target, path = match.groups() target, path = match.groups()
yield target, path, symbol yield target, path, symbol
...@@ -130,23 +132,23 @@ def Output(iter): ...@@ -130,23 +132,23 @@ def Output(iter):
entries = targets.setdefault(target, []) entries = targets.setdefault(target, [])
entries.append((symbol, path)) entries.append((symbol, path))
print TEMPLATE_HEADER print(TEMPLATE_HEADER)
print "<p>jump to target:" print("<p>jump to target:")
print "<select onchange='document.location.hash = this.value'>" print("<select onchange='document.location.hash = this.value'>")
for target in sorted(targets.keys()): for target in sorted(targets.keys()):
print "<option>%s</option>" % target print("<option>%s</option>" % target)
print "</select></p>" print("</select></p>")
for target in sorted(targets.keys()): for target in sorted(targets.keys()):
print "<h2>%s" % target print("<h2>%s" % target)
print "<a class=permalink href='#%s' name='%s'>#</a>" % (target, target) print("<a class=permalink href='#%s' name='%s'>#</a>" % (target, target))
print "</h2>" print("</h2>")
print "<table width=100% cellspacing=0>" print("<table width=100% cellspacing=0>")
for symbol, path in sorted(targets[target]): for symbol, path in sorted(targets[target]):
htmlsymbol = cgi.escape(symbol).replace('::', '::<wbr>') htmlsymbol = cgi.escape(symbol).replace('::', '::<wbr>')
print "<tr><td><div class=symbol>%s</div></td>" % htmlsymbol print("<tr><td><div class=symbol>%s</div></td>" % htmlsymbol)
print "<td valign=top><div class=file>%s</div></td></tr>" % path print("<td valign=top><div class=file>%s</div></td></tr>" % path)
print "</table>" print("</table>")
def main(): def main():
......
...@@ -4,6 +4,8 @@ ...@@ -4,6 +4,8 @@
"""Package entry-point.""" """Package entry-point."""
from __future__ import print_function
import argparse import argparse
import netifaces import netifaces
...@@ -60,7 +62,7 @@ def main(): ...@@ -60,7 +62,7 @@ def main():
server.http_server.listen(server.port) server.http_server.listen(server.port)
ioloop.IOLoop.instance().start() ioloop.IOLoop.instance().start()
print 'Exiting...' print('Exiting...')
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -5,6 +5,8 @@ ...@@ -5,6 +5,8 @@
"""Generic USB gadget functionality. """Generic USB gadget functionality.
""" """
from __future__ import print_function
import struct import struct
import msos20_descriptors import msos20_descriptors
...@@ -266,8 +268,8 @@ class Gadget(object): ...@@ -266,8 +268,8 @@ class Gadget(object):
desc_index = value & 0xff desc_index = value & 0xff
desc_lang = index desc_lang = index
print 'GetDescriptor(recipient={}, type={}, index={}, lang={})'.format( print('GetDescriptor(recipient={}, type={}, index={}, lang={})'.format(
recipient, desc_type, desc_index, desc_lang) recipient, desc_type, desc_index, desc_lang))
return self.GetDescriptor(recipient, desc_type, desc_index, desc_lang, return self.GetDescriptor(recipient, desc_type, desc_index, desc_lang,
length) length)
...@@ -519,7 +521,7 @@ class Gadget(object): ...@@ -519,7 +521,7 @@ class Gadget(object):
Returns: Returns:
True on success, None on error to stall the pipe. True on success, None on error to stall the pipe.
""" """
print 'SetConfiguration({})'.format(index) print('SetConfiguration({})'.format(index))
for endpoint_addrs in self._active_endpoints.values(): for endpoint_addrs in self._active_endpoints.values():
for endpoint_addr in endpoint_addrs: for endpoint_addr in endpoint_addrs:
...@@ -559,7 +561,7 @@ class Gadget(object): ...@@ -559,7 +561,7 @@ class Gadget(object):
Returns: Returns:
True on success, None on error to stall the pipe. True on success, None on error to stall the pipe.
""" """
print 'SetInterface({}, {})'.format(interface, alt_setting) print('SetInterface({}, {})'.format(interface, alt_setting))
config_desc = self.GetConfigurationDescriptor() config_desc = self.GetConfigurationDescriptor()
interface_desc = None interface_desc = None
......
...@@ -10,6 +10,8 @@ own Report ID and will be called upon to answer get/set input/output/feature ...@@ -10,6 +10,8 @@ own Report ID and will be called upon to answer get/set input/output/feature
report requests as necessary. report requests as necessary.
""" """
from __future__ import print_function
import math import math
import struct import struct
import uuid import uuid
...@@ -157,8 +159,8 @@ class HidCompositeFeature(composite_gadget.CompositeFeature): ...@@ -157,8 +159,8 @@ class HidCompositeFeature(composite_gadget.CompositeFeature):
if request == hid_constants.Request.GET_REPORT: if request == hid_constants.Request.GET_REPORT:
report_type, report_id = value >> 8, value & 0xFF report_type, report_id = value >> 8, value & 0xFF
print ('GetReport(type={}, id={}, length={})' print('GetReport(type={}, id={}, length={})'.format(
.format(report_type, report_id, length)) report_type, report_id, length))
return self.GetReport(report_type, report_id, length) return self.GetReport(report_type, report_id, length)
def ClassControlWrite(self, recipient, request, value, index, data): def ClassControlWrite(self, recipient, request, value, index, data):
......
...@@ -10,6 +10,8 @@ ABI is documented here: ...@@ -10,6 +10,8 @@ ABI is documented here:
https://github.com/torvalds/linux/blob/master/drivers/usb/gadget/inode.c https://github.com/torvalds/linux/blob/master/drivers/usb/gadget/inode.c
""" """
from __future__ import print_function
import errno import errno
import multiprocessing import multiprocessing
import os import os
...@@ -124,7 +126,7 @@ class LinuxGadgetfs(object): ...@@ -124,7 +126,7 @@ class LinuxGadgetfs(object):
event_type, = struct.unpack_from('=I', buf, 8) event_type, = struct.unpack_from('=I', buf, 8)
if event_type == GADGETFS_NOP: if event_type == GADGETFS_NOP:
print 'NOP' print('NOP')
elif event_type == GADGETFS_CONNECT: elif event_type == GADGETFS_CONNECT:
speed, = struct.unpack('=Ixxxxxxxx', buf) speed, = struct.unpack('=Ixxxxxxxx', buf)
self.Connected(speed) self.Connected(speed)
...@@ -135,31 +137,31 @@ class LinuxGadgetfs(object): ...@@ -135,31 +137,31 @@ class LinuxGadgetfs(object):
'<BBHHHxxxx', buf) '<BBHHHxxxx', buf)
self.HandleSetup(request_type, request, value, index, length) self.HandleSetup(request_type, request, value, index, length)
elif event_type == GADGETFS_SUSPEND: elif event_type == GADGETFS_SUSPEND:
print 'SUSPEND' print('SUSPEND')
else: else:
print 'Unknown gadgetfs event type:', event_type print('Unknown gadgetfs event type:', event_type)
def Connected(self, speed): def Connected(self, speed):
print 'CONNECT speed={}'.format(speed) print('CONNECT speed={}'.format(speed))
self._gadget.Connected(self, speed) self._gadget.Connected(self, speed)
def Disconnected(self): def Disconnected(self):
print 'DISCONNECT' print('DISCONNECT')
for endpoint_addr in self._ep_fds.keys(): for endpoint_addr in self._ep_fds.keys():
self.StopEndpoint(endpoint_addr) self.StopEndpoint(endpoint_addr)
self._ep_fds.clear() self._ep_fds.clear()
self._gadget.Disconnected() self._gadget.Disconnected()
def HandleSetup(self, request_type, request, value, index, length): def HandleSetup(self, request_type, request, value, index, length):
print ('SETUP bmRequestType=0x{:02X} bRequest=0x{:02X} wValue=0x{:04X} ' print('SETUP bmRequestType=0x{:02X} bRequest=0x{:02X} wValue=0x{:04X} '
'wIndex=0x{:04X} wLength={}' 'wIndex=0x{:04X} wLength={}'.format(request_type, request, value,
.format(request_type, request, value, index, length)) index, length))
if request_type & usb_constants.Dir.IN: if request_type & usb_constants.Dir.IN:
data = self._gadget.ControlRead( data = self._gadget.ControlRead(
request_type, request, value, index, length) request_type, request, value, index, length)
if data is None: if data is None:
print 'SETUP STALL' print('SETUP STALL')
try: try:
os.read(self._fd, 0) # Backwards I/O stalls the pipe. os.read(self._fd, 0) # Backwards I/O stalls the pipe.
except OSError, e: except OSError, e:
...@@ -175,7 +177,7 @@ class LinuxGadgetfs(object): ...@@ -175,7 +177,7 @@ class LinuxGadgetfs(object):
result = self._gadget.ControlWrite( result = self._gadget.ControlWrite(
request_type, request, value, index, data) request_type, request, value, index, data)
if result is None: if result is None:
print 'SETUP STALL' print('SETUP STALL')
try: try:
os.write(self._fd, '') # Backwards I/O stalls the pipe. os.write(self._fd, '') # Backwards I/O stalls the pipe.
except OSError, e: except OSError, e:
...@@ -269,7 +271,7 @@ class LinuxGadgetfs(object): ...@@ -269,7 +271,7 @@ class LinuxGadgetfs(object):
self._ep_fds[endpoint_addr] = fd, child, pipe_r self._ep_fds[endpoint_addr] = fd, child, pipe_r
child.start() child.start()
print 'Started endpoint 0x{:02X}.'.format(endpoint_addr) print('Started endpoint 0x{:02X}.'.format(endpoint_addr))
def StopEndpoint(self, endpoint_addr): def StopEndpoint(self, endpoint_addr):
"""Deactivate the given endpoint.""" """Deactivate the given endpoint."""
...@@ -280,7 +282,7 @@ class LinuxGadgetfs(object): ...@@ -280,7 +282,7 @@ class LinuxGadgetfs(object):
if not endpoint_addr & usb_constants.Dir.IN: if not endpoint_addr & usb_constants.Dir.IN:
self._io_loop.remove_handler(pipe_fd) self._io_loop.remove_handler(pipe_fd)
os.close(fd) os.close(fd)
print 'Stopped endpoint 0x{:02X}.'.format(endpoint_addr) print('Stopped endpoint 0x{:02X}.'.format(endpoint_addr))
def SendPacket(self, endpoint_addr, data): def SendPacket(self, endpoint_addr, data):
"""Send a packet on the given endpoint.""" """Send a packet on the given endpoint."""
......
...@@ -5,6 +5,8 @@ ...@@ -5,6 +5,8 @@
"""WSGI application to manage a USB gadget. """WSGI application to manage a USB gadget.
""" """
from __future__ import print_function
import datetime import datetime
import hashlib import hashlib
import re import re
...@@ -83,7 +85,7 @@ class UpdateHandler(web.RequestHandler): ...@@ -83,7 +85,7 @@ class UpdateHandler(web.RequestHandler):
if claimed_by is not None: if claimed_by is not None:
args.extend(['--start-claimed', claimed_by]) args.extend(['--start-claimed', claimed_by])
print 'Reloading with version {}...'.format(md5sum) print('Reloading with version {}...'.format(md5sum))
global http_server global http_server
if chip.IsConfigured(): if chip.IsConfigured():
......
...@@ -24,6 +24,8 @@ chrome://version/?show-variations-cmd. ...@@ -24,6 +24,8 @@ chrome://version/?show-variations-cmd.
Run with --help to get a complete list of options this script runs with. Run with --help to get a complete list of options this script runs with.
""" """
from __future__ import print_function
import logging import logging
import optparse import optparse
import os import os
...@@ -248,7 +250,7 @@ def Bisect(browser_type, url, extra_browser_args, variations_file, output_dir): ...@@ -248,7 +250,7 @@ def Bisect(browser_type, url, extra_browser_args, variations_file, output_dir):
runs = [variations_file] runs = [variations_file]
while runs: while runs:
run = runs[0] run = runs[0]
print 'Run Chrome with variations file', run print('Run Chrome with variations file', run)
variations_args = _LoadVariations(run) variations_args = _LoadVariations(run)
exit_status, stdout, stderr = _RunVariations( exit_status, stdout, stderr = _RunVariations(
browser_path=browser_path, url=url, browser_path=browser_path, url=url,
...@@ -260,7 +262,7 @@ def Bisect(browser_type, url, extra_browser_args, variations_file, output_dir): ...@@ -260,7 +262,7 @@ def Bisect(browser_type, url, extra_browser_args, variations_file, output_dir):
runs = split_variations_cmd.SplitVariationsCmdFromFile(run, output_dir) runs = split_variations_cmd.SplitVariationsCmdFromFile(run, output_dir)
if len(runs) == 1: if len(runs) == 1:
# Can divide no further. # Can divide no further.
print 'Bisecting succeeded:', ' '.join(variations_args) print('Bisecting succeeded:', ' '.join(variations_args))
return return
elif answer == 'n': elif answer == 'n':
if len(runs) == 1: if len(runs) == 1:
......
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
from __future__ import print_function
import json import json
import sys import sys
...@@ -78,11 +80,11 @@ def GenerateArgs(config_path, platforms): ...@@ -78,11 +80,11 @@ def GenerateArgs(config_path, platforms):
param_list.append(param['key']) param_list.append(param['key'])
param_list.append(param['value']) param_list.append(param['value'])
if len(param_list): if len(param_list):
# Escape the variables for the command-line. # Escape the variables for the command-line.
selected_study = [_escape(x) for x in selected_study] selected_study = [_escape(x) for x in selected_study]
param_list = [_escape(x) for x in param_list] param_list = [_escape(x) for x in param_list]
param = '%s:%s' % ('.'.join(selected_study), '/'.join(param_list)) param = '%s:%s' % ('.'.join(selected_study), '/'.join(param_list))
params.append(param) params.append(param)
for feature in experiment.get('enable_features', []): for feature in experiment.get('enable_features', []):
enable_features.append(feature + '<' + study_name) enable_features.append(feature + '<' + study_name)
for feature in experiment.get('disable_features', []): for feature in experiment.get('disable_features', []):
...@@ -102,24 +104,25 @@ def GenerateArgs(config_path, platforms): ...@@ -102,24 +104,25 @@ def GenerateArgs(config_path, platforms):
def main(): def main():
if len(sys.argv) < 3: if len(sys.argv) < 3:
print 'Usage: fieldtrial_util.py [config_path] [platform]' print('Usage: fieldtrial_util.py [config_path] [platform]')
print 'Optionally pass \'shell_cmd\' as an extra argument to print' print('Optionally pass \'shell_cmd\' as an extra argument to print')
print 'quoted command line arguments.' print('quoted command line arguments.')
exit(-1) exit(-1)
print_shell_cmd = len(sys.argv) >= 4 and sys.argv[3] == 'shell_cmd' print_shell_cmd = len(sys.argv) >= 4 and sys.argv[3] == 'shell_cmd'
supported_platforms = ['android', 'android_webview', 'chromeos', 'ios', supported_platforms = ['android', 'android_webview', 'chromeos', 'ios',
'linux', 'mac', 'windows'] 'linux', 'mac', 'windows']
if sys.argv[2] not in supported_platforms: if sys.argv[2] not in supported_platforms:
print ('\'%s\' is an unknown platform. Supported platforms: %s' % print('\'%s\' is an unknown platform. Supported platforms: %s' %
(sys.argv[2], supported_platforms)) (sys.argv[2], supported_platforms))
exit(-1) exit(-1)
generated_args = GenerateArgs(sys.argv[1], [sys.argv[2]]) generated_args = GenerateArgs(sys.argv[1], [sys.argv[2]])
if print_shell_cmd: if print_shell_cmd:
print " ".join(map((lambda arg: '"{0}"'.format(arg)), generated_args)) print(" ".join(map((lambda arg: '"{0}"'.format(arg)), generated_args)))
else: else:
print generated_args print(generated_args)
if __name__ == '__main__': if __name__ == '__main__':
main() main()
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
from __future__ import print_function
import sys import sys
import os import os
import itertools import itertools
......
...@@ -14,6 +14,8 @@ Usage: ...@@ -14,6 +14,8 @@ Usage:
compact_blocklist.py <gatt_blocklist.txt> compact_blocklist.py <gatt_blocklist.txt>
""" """
from __future__ import print_function
import collections import collections
import string import string
import sys import sys
......
...@@ -3,6 +3,8 @@ ...@@ -3,6 +3,8 @@
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
from __future__ import print_function
import glob import glob
import os import os
import shutil import shutil
...@@ -16,11 +18,11 @@ BUILD_DIR = 'build' ...@@ -16,11 +18,11 @@ BUILD_DIR = 'build'
def run_with_vsvars(cmd, tmpdir=None): def run_with_vsvars(cmd, tmpdir=None):
fd, filename = tempfile.mkstemp('.bat', text=True) fd, filename = tempfile.mkstemp('.bat', text=True)
with os.fdopen(fd, 'w') as f: with os.fdopen(fd, 'w') as f:
print >> f, '@echo off' print('@echo off', file=f)
print >> f, r'call "%VS100COMNTOOLS%\vsvars32.bat"' print(r'call "%VS100COMNTOOLS%\vsvars32.bat"', file=f)
if tmpdir: if tmpdir:
print >> f, r'cd %s' % tmpdir print(r'cd %s' % tmpdir, file=f)
print >> f, cmd print(cmd, file=f)
try: try:
p = subprocess.Popen([filename], shell=True, stdout=subprocess.PIPE, p = subprocess.Popen([filename], shell=True, stdout=subprocess.PIPE,
universal_newlines=True) universal_newlines=True)
...@@ -45,17 +47,17 @@ def build(infile): ...@@ -45,17 +47,17 @@ def build(infile):
outpath = os.path.join(BUILD_DIR, outfile) outpath = os.path.join(BUILD_DIR, outfile)
cpptime = os.path.getmtime(infile) cpptime = os.path.getmtime(infile)
if not os.path.exists(outpath) or cpptime > os.path.getmtime(outpath): if not os.path.exists(outpath) or cpptime > os.path.getmtime(outpath):
print 'Building %s...' % outfile print('Building %s...' % outfile)
rc, out = run_with_vsvars( rc, out = run_with_vsvars(
'cl /nologo /Ox /Zi /W4 /WX /D_UNICODE /DUNICODE' 'cl /nologo /Ox /Zi /W4 /WX /D_UNICODE /DUNICODE'
' /D_CRT_SECURE_NO_WARNINGS /EHsc %s /link /out:%s' ' /D_CRT_SECURE_NO_WARNINGS /EHsc %s /link /out:%s'
% (os.path.join('..', infile), outfile), BUILD_DIR) % (os.path.join('..', infile), outfile), BUILD_DIR)
if rc: if rc:
print out print(out)
print 'Failed to build %s' % outfile print('Failed to build %s' % outfile)
sys.exit(1) sys.exit(1)
else: else:
print '%s already built' % outfile print('%s already built' % outfile)
return outpath return outpath
...@@ -74,7 +76,7 @@ def main(): ...@@ -74,7 +76,7 @@ def main():
if not vcdir: if not vcdir:
vcdir = get_vc_dir() vcdir = get_vc_dir()
if not vcdir: if not vcdir:
print 'Could not get VCINSTALLDIR. Run vsvars32.bat?' print('Could not get VCINSTALLDIR. Run vsvars32.bat?')
return 1 return 1
os.environ['PATH'] += (';' + os.path.join(vcdir, 'bin') + os.environ['PATH'] += (';' + os.path.join(vcdir, 'bin') +
';' + os.path.join(vcdir, r'..\Common7\IDE')) ';' + os.path.join(vcdir, r'..\Common7\IDE'))
...@@ -82,15 +84,15 @@ def main(): ...@@ -82,15 +84,15 @@ def main():
# Verify that we can find link.exe. # Verify that we can find link.exe.
link = os.path.join(vcdir, 'bin', 'link.exe') link = os.path.join(vcdir, 'bin', 'link.exe')
if not os.path.exists(link): if not os.path.exists(link):
print 'link.exe not found at %s' % link print('link.exe not found at %s' % link)
return 1 return 1
exe_name = build('limiter.cc') exe_name = build('limiter.cc')
for shim_exe in ('lib.exe', 'link.exe'): for shim_exe in ('lib.exe', 'link.exe'):
newpath = '%s__LIMITER.exe' % shim_exe newpath = '%s__LIMITER.exe' % shim_exe
shutil.copyfile(exe_name, newpath) shutil.copyfile(exe_name, newpath)
print '%s shim built. Use with msbuild like: "/p:LinkToolExe=%s"' \ print('%s shim built. Use with msbuild like: "/p:LinkToolExe=%s"' \
% (shim_exe, os.path.abspath(newpath)) % (shim_exe, os.path.abspath(newpath)))
return 0 return 0
......
...@@ -66,6 +66,8 @@ common.lib(content_message_generator.obj).obj pulled in for symbol ... ...@@ -66,6 +66,8 @@ common.lib(content_message_generator.obj).obj pulled in for symbol ...
Command-line obj file: url_loader.mojom.obj Command-line obj file: url_loader.mojom.obj
""" """
from __future__ import print_function
import io import io
import pdb import pdb
import re import re
...@@ -165,9 +167,9 @@ def TrackObj(cross_refs, cross_refed_symbols, obj_name): ...@@ -165,9 +167,9 @@ def TrackObj(cross_refs, cross_refed_symbols, obj_name):
targets.append(obj_name) targets.append(obj_name)
# Print what we are searching for. # Print what we are searching for.
if len(targets) == 1: if len(targets) == 1:
print 'Searching for %s' % targets[0] print('Searching for %s' % targets[0])
else: else:
print 'Searching for %s' % targets print('Searching for %s' % targets)
printed = False printed = False
# Follow the chain of references up to an arbitrary maximum level, which has # Follow the chain of references up to an arbitrary maximum level, which has
# so far never been approached. # so far never been approached.
...@@ -179,28 +181,28 @@ def TrackObj(cross_refs, cross_refed_symbols, obj_name): ...@@ -179,28 +181,28 @@ def TrackObj(cross_refs, cross_refed_symbols, obj_name):
if target in cross_refs.keys(): if target in cross_refs.keys():
symbol = cross_refed_symbols[target] symbol = cross_refed_symbols[target]
printed = True printed = True
print '%s.obj pulled in for symbol "%s" by' % (target, symbol) print('%s.obj pulled in for symbol "%s" by' % (target, symbol))
for ref in cross_refs[target]: for ref in cross_refs[target]:
print '\t%s' % ref print('\t%s' % ref)
new_targets[ref] = True new_targets[ref] = True
if len(new_targets) == 0: if len(new_targets) == 0:
break break
print print()
targets = new_targets.keys() targets = new_targets.keys()
if not printed: if not printed:
print ('No references to %s found. Directly specified in sources or a ' print('No references to %s found. Directly specified in sources or a '
'source_set?' % obj_name) 'source_set?' % obj_name)
def main(): def main():
if len(sys.argv) < 3: if len(sys.argv) < 3:
print r'Usage: %s <verbose_output_file> <objfile>' % sys.argv[0] print(r'Usage: %s <verbose_output_file> <objfile>' % sys.argv[0])
print r'Sample: %s chrome_dll_verbose.txt SkTLS' % sys.argv[0] print(r'Sample: %s chrome_dll_verbose.txt SkTLS' % sys.argv[0])
return 0 return 0
cross_refs, cross_refed_symbols = ParseVerbose(sys.argv[1]) cross_refs, cross_refed_symbols = ParseVerbose(sys.argv[1])
print 'Database loaded - %d xrefs found' % len(cross_refs) print('Database loaded - %d xrefs found' % len(cross_refs))
if not len(cross_refs): if not len(cross_refs):
print 'No data found to analyze. Exiting' print('No data found to analyze. Exiting')
return 0 return 0
TrackObj(cross_refs, cross_refed_symbols, sys.argv[2]) TrackObj(cross_refs, cross_refed_symbols, sys.argv[2])
......
...@@ -18,6 +18,8 @@ Typical output from ShowGlobals.exe is lines like these: ...@@ -18,6 +18,8 @@ Typical output from ShowGlobals.exe is lines like these:
1 1824 0 0 LcidToLocaleNameTable chrome.dll.pdb 1 1824 0 0 LcidToLocaleNameTable chrome.dll.pdb
""" """
from __future__ import print_function
import os import os
import subprocess import subprocess
import sys import sys
...@@ -32,7 +34,7 @@ def LoadSymbols(pdb_name): ...@@ -32,7 +34,7 @@ def LoadSymbols(pdb_name):
elif extension in ['.txt']: elif extension in ['.txt']:
lines = open(pdb_name).readlines() lines = open(pdb_name).readlines()
else: else:
print 'Unrecognized extension in %s' % pdb_name print('Unrecognized extension in %s' % pdb_name)
return result return result
for line in lines: for line in lines:
parts = line.split('\t') parts = line.split('\t')
...@@ -45,17 +47,17 @@ def LoadSymbols(pdb_name): ...@@ -45,17 +47,17 @@ def LoadSymbols(pdb_name):
def ShowExtras(symbols_A, symbols_B, name_A, name_B): def ShowExtras(symbols_A, symbols_B, name_A, name_B):
print 'Symbols that are in %s but not in %s' % (name_A, name_B) print('Symbols that are in %s but not in %s' % (name_A, name_B))
for key in symbols_A: for key in symbols_A:
if not key in symbols_B: if not key in symbols_B:
# Print all the numerical data, followed by the symbol name, separated by # Print all the numerical data, followed by the symbol name, separated by
# tabs. # tabs.
print '\t'.join(symbols_A[key] + [key]) print('\t'.join(symbols_A[key] + [key]))
print print()
def ShowDifferences(symbols_A, symbols_B, name_A, name_B): def ShowDifferences(symbols_A, symbols_B, name_A, name_B):
print 'Symbols that are changed from %s to %s' % (name_A, name_B) print('Symbols that are changed from %s to %s' % (name_A, name_B))
for key in symbols_A: for key in symbols_A:
if key in symbols_B: if key in symbols_B:
value_a = symbols_A[key] value_a = symbols_A[key]
...@@ -63,10 +65,10 @@ def ShowDifferences(symbols_A, symbols_B, name_A, name_B): ...@@ -63,10 +65,10 @@ def ShowDifferences(symbols_A, symbols_B, name_A, name_B):
if value_a != value_b: if value_a != value_b:
# Print the symbol name and then the two versions of the numerical data, # Print the symbol name and then the two versions of the numerical data,
# indented. # indented.
print '%s changed from/to:' % key print('%s changed from/to:' % key)
print '\t' + '\t'.join(value_a) print('\t' + '\t'.join(value_a))
print '\t' + '\t'.join(value_b) print('\t' + '\t'.join(value_b))
print print()
def main(): def main():
...@@ -74,14 +76,14 @@ def main(): ...@@ -74,14 +76,14 @@ def main():
symbols_2 = LoadSymbols(sys.argv[2]) symbols_2 = LoadSymbols(sys.argv[2])
if len(symbols_1) == 0: if len(symbols_1) == 0:
print 'No data found in %s - fastlink?' % sys.argv[1] print('No data found in %s - fastlink?' % sys.argv[1])
return return
if len(symbols_2) == 0: if len(symbols_2) == 0:
print 'No data found in %s - fastlink?' % sys.argv[2] print('No data found in %s - fastlink?' % sys.argv[2])
return return
print ('%d interesting globals in %s, %d interesting globals in %s' % print('%d interesting globals in %s, %d interesting globals in %s' %
(len(symbols_1), sys.argv[1], len(symbols_2), sys.argv[2])) (len(symbols_1), sys.argv[1], len(symbols_2), sys.argv[2]))
ShowExtras(symbols_1, symbols_2, sys.argv[1], sys.argv[2]) ShowExtras(symbols_1, symbols_2, sys.argv[1], sys.argv[2])
ShowExtras(symbols_2, symbols_1, sys.argv[2], sys.argv[1]) ShowExtras(symbols_2, symbols_1, sys.argv[2], sys.argv[1])
......
...@@ -52,6 +52,8 @@ process is loaded. Other sections, such as .data, produce private pages and are ...@@ -52,6 +52,8 @@ process is loaded. Other sections, such as .data, produce private pages and are
therefore objectively 'worse' than the others. therefore objectively 'worse' than the others.
""" """
from __future__ import print_function
import os import os
import subprocess import subprocess
import sys import sys
...@@ -66,9 +68,9 @@ def _FindSection(section_list, section_name): ...@@ -66,9 +68,9 @@ def _FindSection(section_list, section_name):
def main(): def main():
if len(sys.argv) < 2: if len(sys.argv) < 2:
print r'Usage: %s PEFileName [OtherPeFileNames...]' % sys.argv[0] print(r'Usage: %s PEFileName [OtherPeFileNames...]' % sys.argv[0])
print r'Sample: %s chrome.dll' % sys.argv[0] print(r'Sample: %s chrome.dll' % sys.argv[0])
print r'Sample: %s chrome.dll original\chrome.dll' % sys.argv[0] print(r'Sample: %s chrome.dll original\chrome.dll' % sys.argv[0])
return 0 return 0
# Track the name of the last PE (Portable Executable) file to be processed - # Track the name of the last PE (Portable Executable) file to be processed -
...@@ -78,11 +80,11 @@ def main(): ...@@ -78,11 +80,11 @@ def main():
for pe_path in sys.argv[1:]: for pe_path in sys.argv[1:]:
results = [] results = []
if not os.path.exists(pe_path): if not os.path.exists(pe_path):
print '%s does not exist!' % pe_path print('%s does not exist!' % pe_path)
continue continue
print 'Size of %s is %1.6f MB' % (pe_path, os.path.getsize(pe_path) / 1e6) print('Size of %s is %1.6f MB' % (pe_path, os.path.getsize(pe_path) / 1e6))
print '%10s: %9s , %9s' % ('name', 'mem size', 'disk size') print('%10s: %9s , %9s' % ('name', 'mem size', 'disk size'))
sections = None sections = None
# Pass the undocumented /nopdb header to avoid hitting symbol servers for # Pass the undocumented /nopdb header to avoid hitting symbol servers for
...@@ -108,10 +110,10 @@ def main(): ...@@ -108,10 +110,10 @@ def main():
# understand - 33.199959 is easier to read than 33199959. Decimal MB # understand - 33.199959 is easier to read than 33199959. Decimal MB
# is used to allow simple conversions to a precise number of bytes. # is used to allow simple conversions to a precise number of bytes.
if abs(memory_size - disk_size) < 512: if abs(memory_size - disk_size) < 512:
print '%10s: %9.6f MB' % (name, memory_size / 1e6) print('%10s: %9.6f MB' % (name, memory_size / 1e6))
else: else:
print '%10s: %9.6f MB, %9.6f MB' % (name, memory_size / 1e6, print('%10s: %9.6f MB, %9.6f MB' % (name, memory_size / 1e6,
disk_size / 1e6) disk_size / 1e6))
results.append((name, memory_size)) results.append((name, memory_size))
sections = None sections = None
except WindowsError as error: except WindowsError as error:
...@@ -120,14 +122,14 @@ def main(): ...@@ -120,14 +122,14 @@ def main():
r'Visual Studio\2017\Professional\VC\Auxiliary\Build' r'Visual Studio\2017\Professional\VC\Auxiliary\Build'
r'\vcvarsall.bat amd64" or similar to add dumpbin to the path.') r'\vcvarsall.bat amd64" or similar to add dumpbin to the path.')
else: else:
print error print(error)
break break
print print()
pe_filepart = os.path.split(pe_path)[1] pe_filepart = os.path.split(pe_path)[1]
if pe_filepart.lower() == last_pe_filepart.lower(): if pe_filepart.lower() == last_pe_filepart.lower():
# Print out the section-by-section size changes, for memory sizes only. # Print out the section-by-section size changes, for memory sizes only.
print 'Memory size change from %s to %s' % (last_pe_path, pe_path) print('Memory size change from %s to %s' % (last_pe_path, pe_path))
total_delta = 0 total_delta = 0
for i in range(len(results)): for i in range(len(results)):
section_name = results[i][0] section_name = results[i][0]
...@@ -140,7 +142,7 @@ def main(): ...@@ -140,7 +142,7 @@ def main():
delta -= last_results[last_i][1] delta -= last_results[last_i][1]
total_delta += delta total_delta += delta
if delta: if delta:
print '%12s: %7d bytes change' % (section_name, delta) print('%12s: %7d bytes change' % (section_name, delta))
for last_i in range(len(last_results)): for last_i in range(len(last_results)):
section_name = last_results[last_i][0] section_name = last_results[last_i][0]
# Find sections that exist only in last_results. # Find sections that exist only in last_results.
...@@ -148,8 +150,8 @@ def main(): ...@@ -148,8 +150,8 @@ def main():
if i < 0: if i < 0:
delta = -last_results[last_i][1] delta = -last_results[last_i][1]
total_delta += delta total_delta += delta
print '%12s: %7d bytes change' % (section_name, delta) print('%12s: %7d bytes change' % (section_name, delta))
print 'Total change: %7d bytes' % total_delta print('Total change: %7d bytes' % total_delta)
last_pe_filepart = pe_filepart last_pe_filepart = pe_filepart
last_pe_path = pe_path last_pe_path = pe_path
last_results = results last_results = results
......
...@@ -6,6 +6,8 @@ ...@@ -6,6 +6,8 @@
Helper script to do the heavy lifting for setenv.bat. Helper script to do the heavy lifting for setenv.bat.
""" """
from __future__ import print_function
import os import os
import sys import sys
...@@ -17,13 +19,13 @@ import vs_toolchain ...@@ -17,13 +19,13 @@ import vs_toolchain
if bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', '1'))): if bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', '1'))):
win_sdk_dir = vs_toolchain.SetEnvironmentAndGetSDKDir() win_sdk_dir = vs_toolchain.SetEnvironmentAndGetSDKDir()
print os.path.normpath(os.path.join(win_sdk_dir, 'bin/SetEnv.cmd')) print(os.path.normpath(os.path.join(win_sdk_dir, 'bin/SetEnv.cmd')))
else: else:
vs_version = vs_toolchain.GetVisualStudioVersion() vs_version = vs_toolchain.GetVisualStudioVersion()
vs_path = vs_toolchain.DetectVisualStudioPath() vs_path = vs_toolchain.DetectVisualStudioPath()
if vs_version == '2017': if vs_version == '2017':
print os.path.join(vs_path, r'VC\Auxiliary\Build\vcvarsall.bat') print(os.path.join(vs_path, r'VC\Auxiliary\Build\vcvarsall.bat'))
elif vs_version == '2015': elif vs_version == '2015':
print os.path.join(vs_path, r'VC\vcvarsall.bat') print(os.path.join(vs_path, r'VC\vcvarsall.bat'))
else: else:
raise Exception('Unknown VS version %s' % vs_version) raise Exception('Unknown VS version %s' % vs_version)
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
from __future__ import print_function
import base64 import base64
import codecs import codecs
import json import json
...@@ -84,7 +86,7 @@ def main(): ...@@ -84,7 +86,7 @@ def main():
for dll in ('chrome.dll', 'chrome_child.dll')] for dll in ('chrome.dll', 'chrome_child.dll')]
for dll_path in dlls: for dll_path in dlls:
if os.path.exists(dll_path): if os.path.exists(dll_path):
print 'Tallying %s...' % dll_path print('Tallying %s...' % dll_path)
json_path = dll_path + '.json' json_path = dll_path + '.json'
Run(os.path.join(BASE_DIR, '..', '..', '..', 'third_party', 'syzygy', Run(os.path.join(BASE_DIR, '..', '..', '..', 'third_party', 'syzygy',
'binaries', 'exe', 'experimental', 'code_tally.exe'), 'binaries', 'exe', 'experimental', 'code_tally.exe'),
...@@ -93,9 +95,10 @@ def main(): ...@@ -93,9 +95,10 @@ def main():
'--output-file=' + json_path) '--output-file=' + json_path)
jsons.append(json_path) jsons.append(json_path)
if not jsons: if not jsons:
print 'Couldn\'t find dlls.' print('Couldn\'t find dlls.')
print 'Pass fully qualified dll name(s) if you want to use something other ' print(
print 'than out\\Release\\chrome.dll and chrome_child.dll.' 'Pass fully qualified dll name(s) if you want to use something other ')
print('than out\\Release\\chrome.dll and chrome_child.dll.')
return 1 return 1
# Munge the code_tally json format into an easier-to-view format. # Munge the code_tally json format into an easier-to-view format.
...@@ -103,7 +106,7 @@ def main(): ...@@ -103,7 +106,7 @@ def main():
with open(json_name, 'r') as jsonf: with open(json_name, 'r') as jsonf:
all_data = json.load(jsonf) all_data = json.load(jsonf)
html_path = os.path.splitext(json_name)[0] + '.html' html_path = os.path.splitext(json_name)[0] + '.html'
print 'Generating %s... (standlone)' % html_path print('Generating %s... (standlone)' % html_path)
by_source = {} by_source = {}
symbols_index = {} symbols_index = {}
symbols = [] symbols = []
......
...@@ -7,6 +7,8 @@ This script converts two %time% compatible strings passed to it into seconds, ...@@ -7,6 +7,8 @@ This script converts two %time% compatible strings passed to it into seconds,
subtracts them, and prints the difference. That's it. It's used by timeit.bat. subtracts them, and prints the difference. That's it. It's used by timeit.bat.
""" """
from __future__ import print_function
import re import re
import sys import sys
...@@ -17,5 +19,6 @@ def ParseTime(time_string): ...@@ -17,5 +19,6 @@ def ParseTime(time_string):
hours, minutes, seconds, fraction = map(int, match.groups()) hours, minutes, seconds, fraction = map(int, match.groups())
return hours * 3600 + minutes * 60 + seconds + fraction * .01 return hours * 3600 + minutes * 60 + seconds + fraction * .01
print "%1.2f seconds elapsed time" % (ParseTime(sys.argv[1]) -
ParseTime(sys.argv[2])) print("%1.2f seconds elapsed time" %
(ParseTime(sys.argv[1]) - ParseTime(sys.argv[2])))
...@@ -2,12 +2,14 @@ ...@@ -2,12 +2,14 @@
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
from __future__ import print_function
import sys import sys
def YesNo(prompt): def YesNo(prompt):
"""Prompts with a yes/no question, returns True if yes.""" """Prompts with a yes/no question, returns True if yes."""
print prompt, print(prompt, end=' ')
sys.stdout.flush() sys.stdout.flush()
# http://code.activestate.com/recipes/134892/ # http://code.activestate.com/recipes/134892/
if sys.platform == 'win32': if sys.platform == 'win32':
...@@ -24,5 +26,5 @@ def YesNo(prompt): ...@@ -24,5 +26,5 @@ def YesNo(prompt):
ch = sys.stdin.read(1) ch = sys.stdin.read(1)
finally: finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
print ch print(ch)
return ch in ('Y', 'y') return ch in ('Y', 'y')
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment