wsdiff.py revision 598cc7dfe526c1fa47f03934c5c6fa6508961296
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
#
# wsdiff(1) is a tool that can be used to determine which compiled objects
# have changed as a result of a given source change. Developers backporting
# new features, RFEs and bug fixes need to be able to identify the set of
#
# and without the source changes.
#
# Using wsdiff(1) is fairly simple:
# - Bringover to a fresh workspace
# - Perform a full non-debug build (clobber if workspace isn't fresh)
# - Move the proto area aside, call it proto.old, or something.
# - Integrate your changes to the workspace
# - Perform another full non-debug clobber build.
# - Use wsdiff(1) to see what changed:
# $ wsdiff proto.old proto
#
# By default, wsdiff will print the list of changed objects / deliverables to
# stdout. If a results file is specified via -r, the list of differing objects,
# and details about why wsdiff(1) thinks they are different will be logged to
# the results file.
#
# By invoking nightly(1) with the -w option to NIGHTLY_FLAGS, nightly(1) will use
# wsdiff(1) to report on what objects changed since the last build.
#
# For patch deliverable purposes, it's advised to have nightly do a clobber,
# non-debug build.
#
# Think about the results. Was something flagged that you don't expect? Go look
# at the results file to see details about the differences.
#
# Use the -i option in conjunction with -v and -V to dive deeper and have wsdiff(1)
# report with more verbosity.
#
# Usage: wsdiff [-vVt] [-r results ] [-i filelist ] old new
#
# Where "old" is the path to the proto area build without the changes, and
# "new" is the path to the proto area built with the changes. The following
# options are supported:
#
# -v Do not truncate observed diffs in results
# -V Log *all* ELF sect diffs vs. logging the first diff found
# -r Log results and observed differences
# -i Tell wsdiff which objects to compare via an input file list
from stat import *
# Human readable diffs truncated by default if longer than this
# Specifying -v on the command line will override
diffs_sz_thresh = 4096
# Lock name Provides exclusive access to
# --------------+------------------------------------------------
# output_lock standard output or temporary file (difference())
# log_lock the results file (log_difference())
# wset_lock changedFiles list (workerThread())
# Variable for thread control
# Default search path for wsdiff
wsdiff_path = [ "/usr/bin",
# These are objects that wsdiff will notice look different, but will not report.
# Existence of an exceptions list, and adding things here is *dangerous*,
# and therefore the *only* reasons why anything would be listed here is because
# the objects do not build deterministically, yet we *cannot* fix this.
#
# These perl libraries use __DATE__ and therefore always look different.
# Ideally, we would purge use the use of __DATE__ from the source, but because
# this is source we wish to distribute with Solaris "unchanged", we cannot modify.
#
wsdiff_exceptions = [ "usr/perl5/5.8.4/lib/sun4-solaris-64int/CORE/libperl.so.1",
"usr/perl5/5.6.1/lib/sun4-solaris-64int/CORE/libperl.so.1",
"usr/perl5/5.8.4/lib/i86pc-solaris-64int/CORE/libperl.so.1",
"usr/perl5/5.6.1/lib/i86pc-solaris-64int/CORE/libperl.so.1"
]
#####
# Logging routines
#
# Debug message to be printed to the screen, and the log file
# Add prefix to highlight debugging message
if debugon :
if logging :
# Informational message to be printed to the screen, and the log file
if logging :
# Error message to be printed to the screen, and the log file
if logging :
# Informational message to be printed only to the log, if there is one.
if logging :
#
# Flag a detected file difference
# Display the fileName to stdout, and log the difference
#
if f in wsdiff_exceptions :
return
if sorted :
else:
#
# Do the actual logging of the difference to the results file
#
if logging :
print >> log, f
if difflen > 0 :
print >> log
print >> log, \
"... truncated due to length: " \
"use -v to override ..."
else :
print >> log, "\n"
#####
# diff generating routines
#
#
# Return human readable diffs from two temporary files
#
# Filter the data through od(1) if the data is detected
# as being binary
try:
# Remove the temp files as we no longer need them.
if binaries :
try:
except OSError, e:
error("diffFileData: unlink failed %s" % e)
try:
except OSError, e:
error("diffFileData: unlink failed %s" % e)
except:
# Send exception for the failed command up
raise
return
return data
#
# Return human readable diffs betweeen two datasets
#
t = threading.currentThread()
try:
except:
cleanup(1)
try:
except:
cleanup(1)
#####
# Misc utility functions
#
# Prune off the leading prefix from string s
def str_prefix_trunc(s, prefix) :
return s[snipLen:]
#
# Prune off leading proto path goo (if there is one) to yield
# the deliverable's eventual path relative to root
# e.g. proto.base/root_sparc/usr/src/cmd/prstat => usr/src/cmd/prstat
#
if pos == -1 :
return fn
if pos == -1 :
return fn
#####
# Usage / argument processing
#
#
# Display usage message
#
def usage() :
-d Print debug messages about the progress
-v Do not truncate observed diffs in results
-V Log *all* ELF sect diffs vs. logging the first diff found
-r Log results and observed differences
-s Produce sorted list of differences
-i Tell wsdiff which objects to compare via an input file list"""
#
# Process command line options
#
def args() :
global debugon
global logging
global vdiffs
global reportAllSects
global sorted
validOpts = 'di:r:vVst?'
baseRoot = ""
ptchRoot = ""
fileNamesFile = ""
results = ""
# getopt.getopt() returns:
# a list of remaining non-option arguments
#
# A correct wsdiff invocation will have exactly two non option
# arguments, the paths to the base (old), ptch (new) proto areas
try:
usage()
usage();
if opt == '-d' :
elif opt == '-i' :
elif opt == '-r' :
elif opt == '-s' :
elif opt == '-v' :
elif opt == '-V' :
elif opt == '-t':
else:
usage()
usage()
usage()
error("The -v option requires a results file (-r)")
if reportAllSects and not logging :
error("The -V option requires a results file (-r)")
# alphabetical order
#####
# File identification
#
#
# Identify the file type.
# If it's not ELF, use the file extension to identify
# certain file types that require special handling to
# compare. Otherwise just return a basic "ASCII" type.
#
def getTheFileType(f) :
'jar' : 'Java Archive',
'html' : 'HTML',
'ln' : 'Lint Library',
'db' : 'Sqlite Database' }
try:
return 'ASCII'
except:
error("failed to stat " + f)
return 'Error'
if isELF(f) == 1 :
return 'ELF'
return extensions[extension]
return 'ASCII'
#
# Return non-zero if "f" is an ELF file
#
elfmagic = '\177ELF'
def isELF(f) :
try:
except:
error("failed to open: " + f)
return 0
return 1
return 0
#
# Return non-zero is "f" is binary.
# Consider the file to be binary if it contains any null characters
#
def isBinary(f) :
try:
except:
error("failed to open: " + f)
return 0
return 0
else :
return 1
#####
# Directory traversal and file finding
#
#
# Return a sorted list of files found under the specified directory
#
def findFiles(d) :
#
# Examine all files in base, ptch
#
# Return a list of files appearing in both proto areas,
# a list of new files (files found only in ptch) and
# a list of deleted files (files found only in base)
#
compFiles = [] # List of files in both proto areas
ptchList = [] # List of file in patch proto area
newFiles = [] # New files detected
deletedFiles = [] # Deleted files
debug("Getting the list of files in the base area");
debug("Getting the list of files in the patch area");
# Inventory files in the base proto area
debug("Determining the list of regular files in the base area");
for fn in baseFilesList :
continue
# Inventory files in the patch proto area
debug("Determining the list of regular files in the patch area");
for fn in ptchFilesList :
continue
# Deleted files appear in the base area, but not the patch area
debug("Searching for deleted files by comparing the lists")
# Eliminate "deleted" files from the list of objects appearing
# in both the base and patch proto areas
debug("Eliminating deleted files from the list of objects")
for fileName in deletedFiles :
try:
except:
error("filelist.remove() failed")
+ " files")
# New files appear in the patch area, but not the base
debug("Getting the list of newly added files")
#
# Examine the files listed in the input file list
#
# Return a list of files appearing in both proto areas,
# a list of new files (files found only in ptch) and
# a list of deleted files (files found only in base)
#
compFiles = [] # List of files in both proto areas
newFiles = [] # New files detected
deletedFiles = [] # Deleted files
try:
except:
cleanup(1)
files = []
for f in files :
if f == '\n' :
continue
# the fileNames have a trailing '\n'
f = f.rstrip()
# The objects in the file list have paths relative
# the command line.
# If it's relative to $ROOT, we'll need to add back the
# root_`uname -p` goo we stripped off in fnFormat()
fn = f;
else :
if base_present :
else :
fn = f
else :
if base_present and ptch_present :
elif base_present :
elif ptch_present :
else :
continue
error(f + " in file list, but not in either tree. " + \
"Skipping...")
#
# Consider the default system locations. For onbld tools, if
# the -t option was specified, we'll try to use built tools in $SRC tools,
#
# First, check what was passed
return tool
# Next try in wsdiff path
for pdir in wsdiff_path :
return location + " "
return location + " "
#####
# ELF file comparison helper routines
#
#
# Return a dictionary of ELF section types keyed by section name
#
def get_elfheader(f) :
header = {}
error("Failed to dump ELF header for " + f)
raise
return
# elfdump(1) dumps the section headers with the section name
# following "sh_name:", and the section type following "sh_type:"
if datap == -1 :
continue
if datap == -1 :
" in " + f)
return header
#
# Extract data in the specified ELF section from the given file
#
def extract_elf_section(f, section) :
" of " + f)
raise
return
# dump(1) displays the file name to start...
# get past it to the data itself
return (data)
#
# Return a (hopefully meaningful) human readable set of diffs
# for the specified ELF section between f1 and f2
#
# Depending on the section, various means for dumping and diffing
# the data may be employed.
#
t = threading.currentThread()
elif (section == ".group") :
elif (section == ".hash") :
elif (section == ".dynamic") :
elif (section == ".got") :
elif (section == ".SUNW_cap") :
elif (section == ".interp") :
" > " + tmpFile1
" > " + tmpFile2
elif (section in text_sections) :
# dis sometimes complains when it hits something it doesn't
# know how to disassemble. Just ignore it, as the output
# being generated here is human readable, and we've already
# correctly flagged the difference.
else :
# remove temp files as we no longer need them
try:
except OSError, e:
error("diff_elf_section: unlink failed %s" % e)
try:
except OSError, e:
error("diff_elf_section: unlink failed %s" % e)
return (data)
#
# compare the relevant sections of two ELF binaries
# and report any differences
#
# Returns: 1 if any differenes found
# 0 if no differences found
# -1 on error
#
# Sections deliberately not considered when comparing two ELF
# binaries. Differences observed in these sections are not considered
# significant where patch deliverable identification is concerned.
sections_to_skip = [ ".SUNW_signature",
".comment",
".SUNW_ctf",
".debug",
".plt",
".rela.bss",
".rela.plt",
".line",
".note",
".compcom",
]
sections_preferred = [ ".rodata.str1.8",
".rodata.str1.1",
".rodata",
".data1",
".data",
".text",
]
global logging
try:
except:
return
try:
except:
return
e1_only_sections = []
# Derive the list of ELF sections found only in
# either e1 or e2.
if not sect in e2_only_sections :
else :
if quiet :
return 1
data = ""
if logging :
slist = ""
for sect in e1_only_sections :
data = "ELF sections found in " + \
"\n\n" + slist
return 1
if quiet :
return 1
data = ""
if logging :
slist = ""
for sect in e2_only_sections :
data = "ELF sections found in " + \
"\n\n" + slist
return 1
# Look for preferred sections, and put those at the
# top of the list of sections to compare
for psect in sections_preferred :
# Compare ELF sections
if sect in sections_to_skip :
continue
try:
except:
return
try:
except:
return
if not quiet:
# If all ELF sections are being reported, then
# invoke difference() to flag the file name to
# stdout only once. Any other section differences
# should be logged to the results file directly
if not first_section :
else :
data)
if not reportAllSects :
return 1
return 0
#####
# recursively remove 2 directories
#
# Used for removal of temporary directory strucures (ignores any errors).
#
#####
# Archive object comparison
#
# Returns 1 if difference detected
# 0 if no difference detected
# -1 on error
#
t = threading.currentThread()
#
# Be optimistic and first try a straight file compare
# as it will allow us to finish up quickly.
#
return 0
try:
except OSError, e:
error("compareArchives: makedir failed %s" % e)
return -1
try:
except OSError, e:
error("compareArchives: makedir failed %s" % e)
return -1
# copy over the objects to the temp areas, and
# unpack them
if status != 0 :
return -1
if status != 0 :
return -1
if fileType == "Java Archive" :
elif fileType == "ELF Object Archive" :
else :
return -1
flist = []
flist = []
return 1
return 1
if differs :
return 1
return 0
#####
# (Basic) file comparison
#
# There's some special case code here for Javadoc HTML files
#
# Returns 1 if difference detected
# 0 if no difference detected
# -1 on error
#
return 1
try:
except:
return -1
try:
except:
return -1
if fileType == "HTML" :
toSnipBeginStr = "<!-- Generated by javadoc"
toSnipEndStr = "-->\n"
if needToSnip :
if toSnipBegin != -1 :
toSnipEndStr) + \
if quiet :
return 1
else :
return 1
return 0
#####
# Compare two objects by producing a data dump from
# each object, and then comparing the dump data
#
# Returns: 1 if a difference is detected
# 0 if no difference detected
# -1 upon error
#
t = threading.currentThread()
if fileType == "Lint Library" :
" | egrep -v '(LINTOBJ|LINTMOD):'" + \
" | grep -v PASS[1-3]:" + \
" > " + tmpFile1
" | egrep -v '(LINTOBJ|LINTMOD):'" + \
" | grep -v PASS[1-3]:" + \
" > " + tmpFile2
elif fileType == "Sqlite Database" :
try:
except:
return
try:
except:
return
if not quiet :
try:
except OSError, e:
error("compareByDumping: unlink failed %s" % e)
try:
except OSError, e:
error("compareByDumping: unlink failed %s" % e)
return 1
# Remove the temporary files now.
try:
except OSError, e:
error("compareByDumping: unlink failed %s" % e)
try:
except OSError, e:
error("compareByDumping: unlink failed %s" % e)
return 0
#####
#
# SIGINT signal handler. Changes thread control variable to tell the threads
# to finish their current job and exit.
#
global keep_processing
return 0
#####
#
# worker thread for changedFiles processing
#
global wset_lock
global changedFiles
global baseRoot
global ptchRoot
global keep_processing
while (keep_processing) :
# grab the lock to changedFiles and remove one member
# and process it
try :
except IndexError :
# there is nothing more to do
return
#####
# Compare two objects. Detect type changes.
# Vector off to the appropriate type specific
# compare routine based on the type.
#
# Verify the file types.
# If they are different, indicate this and move on
return -1
if not quiet :
return 1
else :
if (fileType == 'ELF') :
elif (fileType == 'HTML') :
elif ( fileType == 'Lint Library' ) :
elif ( fileType == 'Sqlite Database' ) :
else :
# it has to be some variety of text file
# Cleanup and self-terminate
if logging :
def main() :
# Log file handle
global log
# Globals relating to command line options
# Named temporary files / directories
# Command paths
# Default search path
global wsdiff_path
# Essentially "uname -p"
global arch
# changed files for worker thread processing
global changedFiles
global baseRoot
global ptchRoot
# Sort the list of files from a temporary file
global sorted
global differentFiles
# Debugging indicator
global debugon
# Some globals need to be initialized
# Process command line arguments
# Return values are returned from args() in alpha order
# (Yes, python functions can return multiple values (ewww))
# Note that args() also set the globals:
# logging to True if verbose logging (to a file) was enabled
# vdiffs to True if logged differences aren't to be truncated
# reportAllSects to True if all ELF section differences are to be reported
#
#
#
if logging :
try:
except:
v_info("# This file was produced by wsdiff")
# Changed files (used only for the sorted case)
if sorted :
differentFiles = []
#
# Build paths to the tools required tools
#
# was specified
#
if localTools :
try:
except:
src = ""
#
# Set resource limit for number of open files as high as possible.
# This might get handy with big number of threads.
#
try:
except:
error("cannot set resource limits for number of open files")
#
# validate the base and patch paths
#
baseRoot += '/'
ptchRoot += '/'
" does not exist")
#
# log some information identifying the run
#
#
# Set up the temporary directories / files
# Could use python's tmpdir routines, but these should
# be easier to identify / keep around for debugging
try:
except OSError, e:
error("main: makedir failed %s" % e)
try:
except OSError, e:
error("main: makedir failed %s" % e)
# Derive a catalog of new, deleted, and to-be-compared objects
# either from the specified base and patch proto areas, or from
# from an input file list
if fileNamesFile != "" :
else :
info("\nNew objects found: ")
if sorted :
info("\nObjects removed: ")
if sorted :
for fn in deletedFiles :
if newOrDeleted :
info("\nChanged objects: ")
if sorted :
debug("The list will appear after the processing is done")
# Here's where all the heavy lifting happens
# Perform a comparison on each object appearing in
# both proto areas. compareOneFile will examine the
# file types of each object, and will vector off to
# the appropriate comparison routine, where the compare
# will happen, and any differences will be reported / logged
# determine maximum number of worker threads by using
# DMAKE_MAX_JOBS environment variable set by nightly(1)
# or get number of CPUs in the system
try:
except:
# If we cannot get number of online CPUs in the system
# run unparallelized otherwise bump the number up 20%
# to achieve best results.
if max_threads == -1 :
max_threads = 1
else :
# Set signal handler to attempt graceful exit
debug("Setting signal handler")
# Create and unleash the threads
# Only at most max_threads must be running at any moment
mythreads = []
for i in range(max_threads) :
thread = workerThread()
# Wait for the threads to finish and do cleanup if interrupted
debug("Waiting for the threads to finish")
while True:
break
else:
# Some threads are still going
# Interrupted by SIGINT
if keep_processing == False :
cleanup(1)
# If the list of differences was sorted it is stored in an array
if sorted :
for f in differentFiles :
# We're done, cleanup.
cleanup(0)
if __name__ == '__main__' :
try:
main()
except KeyboardInterrupt :
cleanup(1);