diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/README b/AppPkg/Applications/Python/Python-2.7.2/Demo/README
new file mode 100644
index 0000000000..ce362eeb6e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/README
@@ -0,0 +1,40 @@
+This directory contains various demonstrations of what you can do with
+Python. They were all written by me except where explicitly stated
+otherwise -- in general, demos contributed by others ends up in the
+../Contrib directory, unless I think they're of utmost general
+importance (like Matt Conway's Tk demos).
+
+A fair number of utilities that are useful when while developing
+Python code can be found in the ../Tools directory -- some of these
+can also be considered good examples of how to write Python code.
+
+Finally, in order to save disk space and net bandwidth, not all
+subdirectories listed here are distributed. They are listed just
+in case I change my mind about them.
+
+
+cgi CGI examples (see also ../Tools/faqwiz/.)
+
+classes Some examples of how to use classes.
+
+comparisons A set of responses to a really old language-comparison
+ challenge.
+
+md5test Test program for the optional md5 module.
+
+metaclasses The code from the 1.5 metaclasses paper on the web.
+
+parser Example using the parser module.
+
+pdist Old, unfinished code messing with CVS, RCS and remote
+ files.
+
+scripts Some useful Python scripts that I put in my bin
+ directory. No optional built-in modules needed.
+
+sockets Examples for the new built-in module 'socket'.
+
+xml Some XML demos.
+
+zlib Some demos for the zlib module (see also the standard
+ library module gzip.py).
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/README b/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/README
new file mode 100644
index 0000000000..90d6c9bbe5
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/README
@@ -0,0 +1,11 @@
+CGI Examples
+------------
+
+Here are some example CGI programs. For a larger example, see
+../../Tools/faqwiz/.
+
+cgi0.sh -- A shell script to test your server is configured for CGI
+cgi1.py -- A Python script to test your server is configured for CGI
+cgi2.py -- A Python script showing how to parse a form
+cgi3.py -- A Python script for driving an arbitrary CGI application
+wiki.py -- Sample CGI application: a minimal Wiki implementation
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi0.sh b/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi0.sh
new file mode 100644
index 0000000000..ee353755a7
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi0.sh
@@ -0,0 +1,8 @@
+#! /bin/sh
+
+# If you can't get this to work, your web server isn't set up right
+
+echo Content-type: text/plain
+echo
+echo Hello world
+echo This is cgi0.sh
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi1.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi1.py
new file mode 100644
index 0000000000..3a0c604e23
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi1.py
@@ -0,0 +1,14 @@
+#!/usr/bin/env python
+
+"""CGI test 1 - check server setup."""
+
+# Until you get this to work, your web server isn't set up right or
+# your Python isn't set up right.
+
+# If cgi0.sh works but cgi1.py doesn't, check the #! line and the file
+# permissions. The docs for the cgi.py module have debugging tips.
+
+print "Content-type: text/html"
+print
+print "
Hello world
"
+print "
This is cgi1.py"
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi2.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi2.py
new file mode 100644
index 0000000000..1ed9f5501b
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi2.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python
+
+"""CGI test 2 - basic use of cgi module."""
+
+import cgitb; cgitb.enable()
+
+import cgi
+
+def main():
+ form = cgi.FieldStorage()
+ print "Content-type: text/html"
+ print
+ if not form:
+ print "
No Form Keys
"
+ else:
+ print "
Form Keys
"
+ for key in form.keys():
+ value = form[key].value
+ print "
", cgi.escape(key), ":", cgi.escape(value)
+
+if __name__ == "__main__":
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi3.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi3.py
new file mode 100644
index 0000000000..224fc83fef
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi3.py
@@ -0,0 +1,10 @@
+#!/usr/bin/env python
+
+"""CGI test 3 (persistent data)."""
+
+import cgitb; cgitb.enable()
+
+from wiki import main
+
+if __name__ == "__main__":
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/wiki.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/wiki.py
new file mode 100644
index 0000000000..990c2e6721
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/wiki.py
@@ -0,0 +1,123 @@
+"""Wiki main program. Imported and run by cgi3.py."""
+
+import os, re, cgi, sys, tempfile
+escape = cgi.escape
+
+def main():
+ form = cgi.FieldStorage()
+ print "Content-type: text/html"
+ print
+ cmd = form.getvalue("cmd", "view")
+ page = form.getvalue("page", "FrontPage")
+ wiki = WikiPage(page)
+ method = getattr(wiki, 'cmd_' + cmd, None) or wiki.cmd_view
+ method(form)
+
+class WikiPage:
+
+ homedir = tempfile.gettempdir()
+ scripturl = os.path.basename(sys.argv[0])
+
+ def __init__(self, name):
+ if not self.iswikiword(name):
+ raise ValueError, "page name is not a wiki word"
+ self.name = name
+ self.load()
+
+ def cmd_view(self, form):
+ print "
", escape(self.splitwikiword(self.name)), "
"
+ print "
"
+ for line in self.data.splitlines():
+ line = line.rstrip()
+ if not line:
+ print "
"
+ else:
+ print self.formatline(line)
+ print "
"
+ print "
", self.mklink("edit", self.name, "Edit this page") + ";"
+ print self.mklink("view", "FrontPage", "go to front page") + "."
+
+ def formatline(self, line):
+ words = []
+ for word in re.split('(\W+)', line):
+ if self.iswikiword(word):
+ if os.path.isfile(self.mkfile(word)):
+ word = self.mklink("view", word, word)
+ else:
+ word = self.mklink("new", word, word + "*")
+ else:
+ word = escape(word)
+ words.append(word)
+ return "".join(words)
+
+ def cmd_edit(self, form, label="Change"):
+ print "
An error occurred while attempting to write the file:"
+ print "
", escape(error)
+ else:
+ # Use a redirect directive, to avoid "reload page" problems
+ print "
"
+ s = ''
+ print s % (self.scripturl + "?cmd=view&page=" + self.name)
+ print ""
+ print "
OK
"
+ print "
If nothing happens, please click here:",
+ print self.mklink("view", self.name, self.name)
+
+ def cmd_new(self, form):
+ self.cmd_edit(form, label="Create")
+
+ def iswikiword(self, word):
+ return re.match("[A-Z][a-z]+([A-Z][a-z]*)+", word)
+
+ def splitwikiword(self, word):
+ chars = []
+ for c in word:
+ if chars and c.isupper():
+ chars.append(' ')
+ chars.append(c)
+ return "".join(chars)
+
+ def mkfile(self, name=None):
+ if name is None:
+ name = self.name
+ return os.path.join(self.homedir, name + ".txt")
+
+ def mklink(self, cmd, page, text):
+ link = self.scripturl + "?cmd=" + cmd + "&page=" + page
+ return '%s' % (link, text)
+
+ def load(self):
+ try:
+ f = open(self.mkfile())
+ data = f.read().strip()
+ f.close()
+ except IOError:
+ data = ""
+ self.data = data
+
+ def store(self):
+ data = self.data
+ try:
+ f = open(self.mkfile(), "w")
+ f.write(data)
+ if data and not data.endswith('\n'):
+ f.write('\n')
+ f.close()
+ return ""
+ except IOError, err:
+ return "IOError: %s" % str(err)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Complex.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Complex.py
new file mode 100644
index 0000000000..9d631b8739
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Complex.py
@@ -0,0 +1,320 @@
+# Complex numbers
+# ---------------
+
+# [Now that Python has a complex data type built-in, this is not very
+# useful, but it's still a nice example class]
+
+# This module represents complex numbers as instances of the class Complex.
+# A Complex instance z has two data attribues, z.re (the real part) and z.im
+# (the imaginary part). In fact, z.re and z.im can have any value -- all
+# arithmetic operators work regardless of the type of z.re and z.im (as long
+# as they support numerical operations).
+#
+# The following functions exist (Complex is actually a class):
+# Complex([re [,im]) -> creates a complex number from a real and an imaginary part
+# IsComplex(z) -> true iff z is a complex number (== has .re and .im attributes)
+# ToComplex(z) -> a complex number equal to z; z itself if IsComplex(z) is true
+# if z is a tuple(re, im) it will also be converted
+# PolarToComplex([r [,phi [,fullcircle]]]) ->
+# the complex number z for which r == z.radius() and phi == z.angle(fullcircle)
+# (r and phi default to 0)
+# exp(z) -> returns the complex exponential of z. Equivalent to pow(math.e,z).
+#
+# Complex numbers have the following methods:
+# z.abs() -> absolute value of z
+# z.radius() == z.abs()
+# z.angle([fullcircle]) -> angle from positive X axis; fullcircle gives units
+# z.phi([fullcircle]) == z.angle(fullcircle)
+#
+# These standard functions and unary operators accept complex arguments:
+# abs(z)
+# -z
+# +z
+# not z
+# repr(z) == `z`
+# str(z)
+# hash(z) -> a combination of hash(z.re) and hash(z.im) such that if z.im is zero
+# the result equals hash(z.re)
+# Note that hex(z) and oct(z) are not defined.
+#
+# These conversions accept complex arguments only if their imaginary part is zero:
+# int(z)
+# long(z)
+# float(z)
+#
+# The following operators accept two complex numbers, or one complex number
+# and one real number (int, long or float):
+# z1 + z2
+# z1 - z2
+# z1 * z2
+# z1 / z2
+# pow(z1, z2)
+# cmp(z1, z2)
+# Note that z1 % z2 and divmod(z1, z2) are not defined,
+# nor are shift and mask operations.
+#
+# The standard module math does not support complex numbers.
+# The cmath modules should be used instead.
+#
+# Idea:
+# add a class Polar(r, phi) and mixed-mode arithmetic which
+# chooses the most appropriate type for the result:
+# Complex for +,-,cmp
+# Polar for *,/,pow
+
+import math
+import sys
+
+twopi = math.pi*2.0
+halfpi = math.pi/2.0
+
+def IsComplex(obj):
+ return hasattr(obj, 're') and hasattr(obj, 'im')
+
+def ToComplex(obj):
+ if IsComplex(obj):
+ return obj
+ elif isinstance(obj, tuple):
+ return Complex(*obj)
+ else:
+ return Complex(obj)
+
+def PolarToComplex(r = 0, phi = 0, fullcircle = twopi):
+ phi = phi * (twopi / fullcircle)
+ return Complex(math.cos(phi)*r, math.sin(phi)*r)
+
+def Re(obj):
+ if IsComplex(obj):
+ return obj.re
+ return obj
+
+def Im(obj):
+ if IsComplex(obj):
+ return obj.im
+ return 0
+
+class Complex:
+
+ def __init__(self, re=0, im=0):
+ _re = 0
+ _im = 0
+ if IsComplex(re):
+ _re = re.re
+ _im = re.im
+ else:
+ _re = re
+ if IsComplex(im):
+ _re = _re - im.im
+ _im = _im + im.re
+ else:
+ _im = _im + im
+ # this class is immutable, so setting self.re directly is
+ # not possible.
+ self.__dict__['re'] = _re
+ self.__dict__['im'] = _im
+
+ def __setattr__(self, name, value):
+ raise TypeError, 'Complex numbers are immutable'
+
+ def __hash__(self):
+ if not self.im:
+ return hash(self.re)
+ return hash((self.re, self.im))
+
+ def __repr__(self):
+ if not self.im:
+ return 'Complex(%r)' % (self.re,)
+ else:
+ return 'Complex(%r, %r)' % (self.re, self.im)
+
+ def __str__(self):
+ if not self.im:
+ return repr(self.re)
+ else:
+ return 'Complex(%r, %r)' % (self.re, self.im)
+
+ def __neg__(self):
+ return Complex(-self.re, -self.im)
+
+ def __pos__(self):
+ return self
+
+ def __abs__(self):
+ return math.hypot(self.re, self.im)
+
+ def __int__(self):
+ if self.im:
+ raise ValueError, "can't convert Complex with nonzero im to int"
+ return int(self.re)
+
+ def __long__(self):
+ if self.im:
+ raise ValueError, "can't convert Complex with nonzero im to long"
+ return long(self.re)
+
+ def __float__(self):
+ if self.im:
+ raise ValueError, "can't convert Complex with nonzero im to float"
+ return float(self.re)
+
+ def __cmp__(self, other):
+ other = ToComplex(other)
+ return cmp((self.re, self.im), (other.re, other.im))
+
+ def __rcmp__(self, other):
+ other = ToComplex(other)
+ return cmp(other, self)
+
+ def __nonzero__(self):
+ return not (self.re == self.im == 0)
+
+ abs = radius = __abs__
+
+ def angle(self, fullcircle = twopi):
+ return (fullcircle/twopi) * ((halfpi - math.atan2(self.re, self.im)) % twopi)
+
+ phi = angle
+
+ def __add__(self, other):
+ other = ToComplex(other)
+ return Complex(self.re + other.re, self.im + other.im)
+
+ __radd__ = __add__
+
+ def __sub__(self, other):
+ other = ToComplex(other)
+ return Complex(self.re - other.re, self.im - other.im)
+
+ def __rsub__(self, other):
+ other = ToComplex(other)
+ return other - self
+
+ def __mul__(self, other):
+ other = ToComplex(other)
+ return Complex(self.re*other.re - self.im*other.im,
+ self.re*other.im + self.im*other.re)
+
+ __rmul__ = __mul__
+
+ def __div__(self, other):
+ other = ToComplex(other)
+ d = float(other.re*other.re + other.im*other.im)
+ if not d: raise ZeroDivisionError, 'Complex division'
+ return Complex((self.re*other.re + self.im*other.im) / d,
+ (self.im*other.re - self.re*other.im) / d)
+
+ def __rdiv__(self, other):
+ other = ToComplex(other)
+ return other / self
+
+ def __pow__(self, n, z=None):
+ if z is not None:
+ raise TypeError, 'Complex does not support ternary pow()'
+ if IsComplex(n):
+ if n.im:
+ if self.im: raise TypeError, 'Complex to the Complex power'
+ else: return exp(math.log(self.re)*n)
+ n = n.re
+ r = pow(self.abs(), n)
+ phi = n*self.angle()
+ return Complex(math.cos(phi)*r, math.sin(phi)*r)
+
+ def __rpow__(self, base):
+ base = ToComplex(base)
+ return pow(base, self)
+
+def exp(z):
+ r = math.exp(z.re)
+ return Complex(math.cos(z.im)*r,math.sin(z.im)*r)
+
+
+def checkop(expr, a, b, value, fuzz = 1e-6):
+ print ' ', a, 'and', b,
+ try:
+ result = eval(expr)
+ except:
+ result = sys.exc_type
+ print '->', result
+ if isinstance(result, str) or isinstance(value, str):
+ ok = (result == value)
+ else:
+ ok = abs(result - value) <= fuzz
+ if not ok:
+ print '!!\t!!\t!! should be', value, 'diff', abs(result - value)
+
+def test():
+ print 'test constructors'
+ constructor_test = (
+ # "expect" is an array [re,im] "got" the Complex.
+ ( (0,0), Complex() ),
+ ( (0,0), Complex() ),
+ ( (1,0), Complex(1) ),
+ ( (0,1), Complex(0,1) ),
+ ( (1,2), Complex(Complex(1,2)) ),
+ ( (1,3), Complex(Complex(1,2),1) ),
+ ( (0,0), Complex(0,Complex(0,0)) ),
+ ( (3,4), Complex(3,Complex(4)) ),
+ ( (-1,3), Complex(1,Complex(3,2)) ),
+ ( (-7,6), Complex(Complex(1,2),Complex(4,8)) ) )
+ cnt = [0,0]
+ for t in constructor_test:
+ cnt[0] += 1
+ if ((t[0][0]!=t[1].re)or(t[0][1]!=t[1].im)):
+ print " expected", t[0], "got", t[1]
+ cnt[1] += 1
+ print " ", cnt[1], "of", cnt[0], "tests failed"
+ # test operators
+ testsuite = {
+ 'a+b': [
+ (1, 10, 11),
+ (1, Complex(0,10), Complex(1,10)),
+ (Complex(0,10), 1, Complex(1,10)),
+ (Complex(0,10), Complex(1), Complex(1,10)),
+ (Complex(1), Complex(0,10), Complex(1,10)),
+ ],
+ 'a-b': [
+ (1, 10, -9),
+ (1, Complex(0,10), Complex(1,-10)),
+ (Complex(0,10), 1, Complex(-1,10)),
+ (Complex(0,10), Complex(1), Complex(-1,10)),
+ (Complex(1), Complex(0,10), Complex(1,-10)),
+ ],
+ 'a*b': [
+ (1, 10, 10),
+ (1, Complex(0,10), Complex(0, 10)),
+ (Complex(0,10), 1, Complex(0,10)),
+ (Complex(0,10), Complex(1), Complex(0,10)),
+ (Complex(1), Complex(0,10), Complex(0,10)),
+ ],
+ 'a/b': [
+ (1., 10, 0.1),
+ (1, Complex(0,10), Complex(0, -0.1)),
+ (Complex(0, 10), 1, Complex(0, 10)),
+ (Complex(0, 10), Complex(1), Complex(0, 10)),
+ (Complex(1), Complex(0,10), Complex(0, -0.1)),
+ ],
+ 'pow(a,b)': [
+ (1, 10, 1),
+ (1, Complex(0,10), 1),
+ (Complex(0,10), 1, Complex(0,10)),
+ (Complex(0,10), Complex(1), Complex(0,10)),
+ (Complex(1), Complex(0,10), 1),
+ (2, Complex(4,0), 16),
+ ],
+ 'cmp(a,b)': [
+ (1, 10, -1),
+ (1, Complex(0,10), 1),
+ (Complex(0,10), 1, -1),
+ (Complex(0,10), Complex(1), -1),
+ (Complex(1), Complex(0,10), 1),
+ ],
+ }
+ for expr in sorted(testsuite):
+ print expr + ':'
+ t = (expr,)
+ for item in testsuite[expr]:
+ checkop(*(t+item))
+
+
+if __name__ == '__main__':
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Dates.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Dates.py
new file mode 100644
index 0000000000..9c13f4c11d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Dates.py
@@ -0,0 +1,227 @@
+# Class Date supplies date objects that support date arithmetic.
+#
+# Date(month,day,year) returns a Date object. An instance prints as,
+# e.g., 'Mon 16 Aug 1993'.
+#
+# Addition, subtraction, comparison operators, min, max, and sorting
+# all work as expected for date objects: int+date or date+int returns
+# the date `int' days from `date'; date+date raises an exception;
+# date-int returns the date `int' days before `date'; date2-date1 returns
+# an integer, the number of days from date1 to date2; int-date raises an
+# exception; date1 < date2 is true iff date1 occurs before date2 (&
+# similarly for other comparisons); min(date1,date2) is the earlier of
+# the two dates and max(date1,date2) the later; and date objects can be
+# used as dictionary keys.
+#
+# Date objects support one visible method, date.weekday(). This returns
+# the day of the week the date falls on, as a string.
+#
+# Date objects also have 4 read-only data attributes:
+# .month in 1..12
+# .day in 1..31
+# .year int or long int
+# .ord the ordinal of the date relative to an arbitrary staring point
+#
+# The Dates module also supplies function today(), which returns the
+# current date as a date object.
+#
+# Those entranced by calendar trivia will be disappointed, as no attempt
+# has been made to accommodate the Julian (etc) system. On the other
+# hand, at least this package knows that 2000 is a leap year but 2100
+# isn't, and works fine for years with a hundred decimal digits .
+
+# Tim Peters tim@ksr.com
+# not speaking for Kendall Square Research Corp
+
+# Adapted to Python 1.1 (where some hacks to overcome coercion are unnecessary)
+# by Guido van Rossum
+
+# Note that as of Python 2.3, a datetime module is included in the stardard
+# library.
+
+# vi:set tabsize=8:
+
+_MONTH_NAMES = [ 'January', 'February', 'March', 'April', 'May',
+ 'June', 'July', 'August', 'September', 'October',
+ 'November', 'December' ]
+
+_DAY_NAMES = [ 'Friday', 'Saturday', 'Sunday', 'Monday',
+ 'Tuesday', 'Wednesday', 'Thursday' ]
+
+_DAYS_IN_MONTH = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
+
+_DAYS_BEFORE_MONTH = []
+dbm = 0
+for dim in _DAYS_IN_MONTH:
+ _DAYS_BEFORE_MONTH.append(dbm)
+ dbm = dbm + dim
+del dbm, dim
+
+_INT_TYPES = type(1), type(1L)
+
+def _is_leap(year): # 1 if leap year, else 0
+ if year % 4 != 0: return 0
+ if year % 400 == 0: return 1
+ return year % 100 != 0
+
+def _days_in_year(year): # number of days in year
+ return 365 + _is_leap(year)
+
+def _days_before_year(year): # number of days before year
+ return year*365L + (year+3)//4 - (year+99)//100 + (year+399)//400
+
+def _days_in_month(month, year): # number of days in month of year
+ if month == 2 and _is_leap(year): return 29
+ return _DAYS_IN_MONTH[month-1]
+
+def _days_before_month(month, year): # number of days in year before month
+ return _DAYS_BEFORE_MONTH[month-1] + (month > 2 and _is_leap(year))
+
+def _date2num(date): # compute ordinal of date.month,day,year
+ return _days_before_year(date.year) + \
+ _days_before_month(date.month, date.year) + \
+ date.day
+
+_DI400Y = _days_before_year(400) # number of days in 400 years
+
+def _num2date(n): # return date with ordinal n
+ if type(n) not in _INT_TYPES:
+ raise TypeError, 'argument must be integer: %r' % type(n)
+
+ ans = Date(1,1,1) # arguments irrelevant; just getting a Date obj
+ del ans.ord, ans.month, ans.day, ans.year # un-initialize it
+ ans.ord = n
+
+ n400 = (n-1)//_DI400Y # # of 400-year blocks preceding
+ year, n = 400 * n400, n - _DI400Y * n400
+ more = n // 365
+ dby = _days_before_year(more)
+ if dby >= n:
+ more = more - 1
+ dby = dby - _days_in_year(more)
+ year, n = year + more, int(n - dby)
+
+ try: year = int(year) # chop to int, if it fits
+ except (ValueError, OverflowError): pass
+
+ month = min(n//29 + 1, 12)
+ dbm = _days_before_month(month, year)
+ if dbm >= n:
+ month = month - 1
+ dbm = dbm - _days_in_month(month, year)
+
+ ans.month, ans.day, ans.year = month, n-dbm, year
+ return ans
+
+def _num2day(n): # return weekday name of day with ordinal n
+ return _DAY_NAMES[ int(n % 7) ]
+
+
+class Date:
+ def __init__(self, month, day, year):
+ if not 1 <= month <= 12:
+ raise ValueError, 'month must be in 1..12: %r' % (month,)
+ dim = _days_in_month(month, year)
+ if not 1 <= day <= dim:
+ raise ValueError, 'day must be in 1..%r: %r' % (dim, day)
+ self.month, self.day, self.year = month, day, year
+ self.ord = _date2num(self)
+
+ # don't allow setting existing attributes
+ def __setattr__(self, name, value):
+ if self.__dict__.has_key(name):
+ raise AttributeError, 'read-only attribute ' + name
+ self.__dict__[name] = value
+
+ def __cmp__(self, other):
+ return cmp(self.ord, other.ord)
+
+ # define a hash function so dates can be used as dictionary keys
+ def __hash__(self):
+ return hash(self.ord)
+
+ # print as, e.g., Mon 16 Aug 1993
+ def __repr__(self):
+ return '%.3s %2d %.3s %r' % (
+ self.weekday(),
+ self.day,
+ _MONTH_NAMES[self.month-1],
+ self.year)
+
+ # Python 1.1 coerces neither int+date nor date+int
+ def __add__(self, n):
+ if type(n) not in _INT_TYPES:
+ raise TypeError, 'can\'t add %r to date' % type(n)
+ return _num2date(self.ord + n)
+ __radd__ = __add__ # handle int+date
+
+ # Python 1.1 coerces neither date-int nor date-date
+ def __sub__(self, other):
+ if type(other) in _INT_TYPES: # date-int
+ return _num2date(self.ord - other)
+ else:
+ return self.ord - other.ord # date-date
+
+ # complain about int-date
+ def __rsub__(self, other):
+ raise TypeError, 'Can\'t subtract date from integer'
+
+ def weekday(self):
+ return _num2day(self.ord)
+
+def today():
+ import time
+ local = time.localtime(time.time())
+ return Date(local[1], local[2], local[0])
+
+class DateTestError(Exception):
+ pass
+
+def test(firstyear, lastyear):
+ a = Date(9,30,1913)
+ b = Date(9,30,1914)
+ if repr(a) != 'Tue 30 Sep 1913':
+ raise DateTestError, '__repr__ failure'
+ if (not a < b) or a == b or a > b or b != b:
+ raise DateTestError, '__cmp__ failure'
+ if a+365 != b or 365+a != b:
+ raise DateTestError, '__add__ failure'
+ if b-a != 365 or b-365 != a:
+ raise DateTestError, '__sub__ failure'
+ try:
+ x = 1 - a
+ raise DateTestError, 'int-date should have failed'
+ except TypeError:
+ pass
+ try:
+ x = a + b
+ raise DateTestError, 'date+date should have failed'
+ except TypeError:
+ pass
+ if a.weekday() != 'Tuesday':
+ raise DateTestError, 'weekday() failure'
+ if max(a,b) is not b or min(a,b) is not a:
+ raise DateTestError, 'min/max failure'
+ d = {a-1:b, b:a+1}
+ if d[b-366] != b or d[a+(b-a)] != Date(10,1,1913):
+ raise DateTestError, 'dictionary failure'
+
+ # verify date<->number conversions for first and last days for
+ # all years in firstyear .. lastyear
+
+ lord = _days_before_year(firstyear)
+ y = firstyear
+ while y <= lastyear:
+ ford = lord + 1
+ lord = ford + _days_in_year(y) - 1
+ fd, ld = Date(1,1,y), Date(12,31,y)
+ if (fd.ord,ld.ord) != (ford,lord):
+ raise DateTestError, ('date->num failed', y)
+ fd, ld = _num2date(ford), _num2date(lord)
+ if (1,1,y,12,31,y) != \
+ (fd.month,fd.day,fd.year,ld.month,ld.day,ld.year):
+ raise DateTestError, ('num->date failed', y)
+ y = y + 1
+
+if __name__ == '__main__':
+ test(1850, 2150)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Dbm.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Dbm.py
new file mode 100644
index 0000000000..7bcb2572ce
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Dbm.py
@@ -0,0 +1,66 @@
+# A wrapper around the (optional) built-in class dbm, supporting keys
+# and values of almost any type instead of just string.
+# (Actually, this works only for keys and values that can be read back
+# correctly after being converted to a string.)
+
+
+class Dbm:
+
+ def __init__(self, filename, mode, perm):
+ import dbm
+ self.db = dbm.open(filename, mode, perm)
+
+ def __repr__(self):
+ s = ''
+ for key in self.keys():
+ t = repr(key) + ': ' + repr(self[key])
+ if s: t = ', ' + t
+ s = s + t
+ return '{' + s + '}'
+
+ def __len__(self):
+ return len(self.db)
+
+ def __getitem__(self, key):
+ return eval(self.db[repr(key)])
+
+ def __setitem__(self, key, value):
+ self.db[repr(key)] = repr(value)
+
+ def __delitem__(self, key):
+ del self.db[repr(key)]
+
+ def keys(self):
+ res = []
+ for key in self.db.keys():
+ res.append(eval(key))
+ return res
+
+ def has_key(self, key):
+ return self.db.has_key(repr(key))
+
+
+def test():
+ d = Dbm('@dbm', 'rw', 0600)
+ print d
+ while 1:
+ try:
+ key = input('key: ')
+ if d.has_key(key):
+ value = d[key]
+ print 'currently:', value
+ value = input('value: ')
+ if value is None:
+ del d[key]
+ else:
+ d[key] = value
+ except KeyboardInterrupt:
+ print ''
+ print d
+ except EOFError:
+ print '[eof]'
+ break
+ print d
+
+
+test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/README b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/README
new file mode 100644
index 0000000000..8fc839a475
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/README
@@ -0,0 +1,12 @@
+Examples of classes that implement special operators (see reference manual):
+
+Complex.py Complex numbers
+Dates.py Date manipulation package by Tim Peters
+Dbm.py Wrapper around built-in dbm, supporting arbitrary values
+Range.py Example of a generator: re-implement built-in range()
+Rev.py Yield the reverse of a sequence
+Vec.py A simple vector class
+bitvec.py A bit-vector class by Jan-Hein B\"uhrman
+
+(For straightforward examples of basic class features, such as use of
+methods and inheritance, see the library code.)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Range.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Range.py
new file mode 100644
index 0000000000..b0ce5cbf46
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Range.py
@@ -0,0 +1,93 @@
+"""Example of a generator: re-implement the built-in range function
+without actually constructing the list of values.
+
+OldStyleRange is coded in the way required to work in a 'for' loop before
+iterators were introduced into the language; using __getitem__ and __len__ .
+
+"""
+def handleargs(arglist):
+ """Take list of arguments and extract/create proper start, stop, and step
+ values and return in a tuple"""
+ try:
+ if len(arglist) == 1:
+ return 0, int(arglist[0]), 1
+ elif len(arglist) == 2:
+ return int(arglist[0]), int(arglist[1]), 1
+ elif len(arglist) == 3:
+ if arglist[2] == 0:
+ raise ValueError("step argument must not be zero")
+ return tuple(int(x) for x in arglist)
+ else:
+ raise TypeError("range() accepts 1-3 arguments, given", len(arglist))
+ except TypeError:
+ raise TypeError("range() arguments must be numbers or strings "
+ "representing numbers")
+
+def genrange(*a):
+ """Function to implement 'range' as a generator"""
+ start, stop, step = handleargs(a)
+ value = start
+ while value < stop:
+ yield value
+ value += step
+
+class oldrange:
+ """Class implementing a range object.
+ To the user the instances feel like immutable sequences
+ (and you can't concatenate or slice them)
+
+ Done using the old way (pre-iterators; __len__ and __getitem__) to have an
+ object be used by a 'for' loop.
+
+ """
+
+ def __init__(self, *a):
+ """ Initialize start, stop, and step values along with calculating the
+ nubmer of values (what __len__ will return) in the range"""
+ self.start, self.stop, self.step = handleargs(a)
+ self.len = max(0, (self.stop - self.start) // self.step)
+
+ def __repr__(self):
+ """implement repr(x) which is also used by print"""
+ return 'range(%r, %r, %r)' % (self.start, self.stop, self.step)
+
+ def __len__(self):
+ """implement len(x)"""
+ return self.len
+
+ def __getitem__(self, i):
+ """implement x[i]"""
+ if 0 <= i <= self.len:
+ return self.start + self.step * i
+ else:
+ raise IndexError, 'range[i] index out of range'
+
+
+def test():
+ import time, __builtin__
+ #Just a quick sanity check
+ correct_result = __builtin__.range(5, 100, 3)
+ oldrange_result = list(oldrange(5, 100, 3))
+ genrange_result = list(genrange(5, 100, 3))
+ if genrange_result != correct_result or oldrange_result != correct_result:
+ raise Exception("error in implementation:\ncorrect = %s"
+ "\nold-style = %s\ngenerator = %s" %
+ (correct_result, oldrange_result, genrange_result))
+ print "Timings for range(1000):"
+ t1 = time.time()
+ for i in oldrange(1000):
+ pass
+ t2 = time.time()
+ for i in genrange(1000):
+ pass
+ t3 = time.time()
+ for i in __builtin__.range(1000):
+ pass
+ t4 = time.time()
+ print t2-t1, 'sec (old-style class)'
+ print t3-t2, 'sec (generator)'
+ print t4-t3, 'sec (built-in)'
+
+
+if __name__ == '__main__':
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Rev.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Rev.py
new file mode 100644
index 0000000000..a509e70800
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Rev.py
@@ -0,0 +1,95 @@
+'''
+A class which presents the reverse of a sequence without duplicating it.
+From: "Steven D. Majewski"
+
+It works on mutable or inmutable sequences.
+
+>>> chars = list(Rev('Hello World!'))
+>>> print ''.join(chars)
+!dlroW olleH
+
+The .forw is so you can use anonymous sequences in __init__, and still
+keep a reference the forward sequence. )
+If you give it a non-anonymous mutable sequence, the reverse sequence
+will track the updated values. ( but not reassignment! - another
+good reason to use anonymous values in creating the sequence to avoid
+confusion. Maybe it should be change to copy input sequence to break
+the connection completely ? )
+
+>>> nnn = range(3)
+>>> rnn = Rev(nnn)
+>>> for n in rnn: print n
+...
+2
+1
+0
+>>> for n in range(4, 6): nnn.append(n) # update nnn
+...
+>>> for n in rnn: print n # prints reversed updated values
+...
+5
+4
+2
+1
+0
+>>> nnn = nnn[1:-1]
+>>> nnn
+[1, 2, 4]
+>>> for n in rnn: print n # prints reversed values of old nnn
+...
+5
+4
+2
+1
+0
+
+#
+>>> WH = Rev('Hello World!')
+>>> print WH.forw, WH.back
+Hello World! !dlroW olleH
+>>> nnn = Rev(range(1, 10))
+>>> print nnn.forw
+[1, 2, 3, 4, 5, 6, 7, 8, 9]
+>>> print nnn.back
+[9, 8, 7, 6, 5, 4, 3, 2, 1]
+
+>>> rrr = Rev(nnn)
+>>> rrr
+<1, 2, 3, 4, 5, 6, 7, 8, 9>
+
+'''
+
+class Rev:
+ def __init__(self, seq):
+ self.forw = seq
+ self.back = self
+
+ def __len__(self):
+ return len(self.forw)
+
+ def __getitem__(self, j):
+ return self.forw[-(j + 1)]
+
+ def __repr__(self):
+ seq = self.forw
+ if isinstance(seq, list):
+ wrap = '[]'
+ sep = ', '
+ elif isinstance(seq, tuple):
+ wrap = '()'
+ sep = ', '
+ elif isinstance(seq, str):
+ wrap = ''
+ sep = ''
+ else:
+ wrap = '<>'
+ sep = ', '
+ outstrs = [str(item) for item in self.back]
+ return wrap[:1] + sep.join(outstrs) + wrap[-1:]
+
+def _test():
+ import doctest, Rev
+ return doctest.testmod(Rev)
+
+if __name__ == "__main__":
+ _test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Vec.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Vec.py
new file mode 100644
index 0000000000..a5834e933e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Vec.py
@@ -0,0 +1,68 @@
+class Vec:
+ """ A simple vector class
+
+ Instances of the Vec class can be constructed from numbers
+
+ >>> a = Vec(1, 2, 3)
+ >>> b = Vec(3, 2, 1)
+
+ added
+ >>> a + b
+ Vec(4, 4, 4)
+
+ subtracted
+ >>> a - b
+ Vec(-2, 0, 2)
+
+ and multiplied by a scalar on the left
+ >>> 3.0 * a
+ Vec(3.0, 6.0, 9.0)
+
+ or on the right
+ >>> a * 3.0
+ Vec(3.0, 6.0, 9.0)
+ """
+ def __init__(self, *v):
+ self.v = list(v)
+
+ @classmethod
+ def fromlist(cls, v):
+ if not isinstance(v, list):
+ raise TypeError
+ inst = cls()
+ inst.v = v
+ return inst
+
+ def __repr__(self):
+ args = ', '.join(repr(x) for x in self.v)
+ return 'Vec({0})'.format(args)
+
+ def __len__(self):
+ return len(self.v)
+
+ def __getitem__(self, i):
+ return self.v[i]
+
+ def __add__(self, other):
+ # Element-wise addition
+ v = [x + y for x, y in zip(self.v, other.v)]
+ return Vec.fromlist(v)
+
+ def __sub__(self, other):
+ # Element-wise subtraction
+ v = [x - y for x, y in zip(self.v, other.v)]
+ return Vec.fromlist(v)
+
+ def __mul__(self, scalar):
+ # Multiply by scalar
+ v = [x * scalar for x in self.v]
+ return Vec.fromlist(v)
+
+ __rmul__ = __mul__
+
+
+def test():
+ import doctest
+ doctest.testmod()
+
+test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/bitvec.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/bitvec.py
new file mode 100644
index 0000000000..86805e18aa
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/bitvec.py
@@ -0,0 +1,333 @@
+#
+# this is a rather strict implementation of a bit vector class
+# it is accessed the same way as an array of python-ints, except
+# the value must be 0 or 1
+#
+
+import sys; rprt = sys.stderr.write #for debugging
+
+class error(Exception):
+ pass
+
+
+def _check_value(value):
+ if type(value) != type(0) or not 0 <= value < 2:
+ raise error, 'bitvec() items must have int value 0 or 1'
+
+
+import math
+
+def _compute_len(param):
+ mant, l = math.frexp(float(param))
+ bitmask = 1L << l
+ if bitmask <= param:
+ raise RuntimeError('(param, l) = %r' % ((param, l),))
+ while l:
+ bitmask = bitmask >> 1
+ if param & bitmask:
+ break
+ l = l - 1
+ return l
+
+
+def _check_key(len, key):
+ if type(key) != type(0):
+ raise TypeError, 'sequence subscript not int'
+ if key < 0:
+ key = key + len
+ if not 0 <= key < len:
+ raise IndexError, 'list index out of range'
+ return key
+
+def _check_slice(len, i, j):
+ #the type is ok, Python already checked that
+ i, j = max(i, 0), min(len, j)
+ if i > j:
+ i = j
+ return i, j
+
+
+class BitVec:
+
+ def __init__(self, *params):
+ self._data = 0L
+ self._len = 0
+ if not len(params):
+ pass
+ elif len(params) == 1:
+ param, = params
+ if type(param) == type([]):
+ value = 0L
+ bit_mask = 1L
+ for item in param:
+ # strict check
+ #_check_value(item)
+ if item:
+ value = value | bit_mask
+ bit_mask = bit_mask << 1
+ self._data = value
+ self._len = len(param)
+ elif type(param) == type(0L):
+ if param < 0:
+ raise error, 'bitvec() can\'t handle negative longs'
+ self._data = param
+ self._len = _compute_len(param)
+ else:
+ raise error, 'bitvec() requires array or long parameter'
+ elif len(params) == 2:
+ param, length = params
+ if type(param) == type(0L):
+ if param < 0:
+ raise error, \
+ 'can\'t handle negative longs'
+ self._data = param
+ if type(length) != type(0):
+ raise error, 'bitvec()\'s 2nd parameter must be int'
+ computed_length = _compute_len(param)
+ if computed_length > length:
+ print 'warning: bitvec() value is longer than the length indicates, truncating value'
+ self._data = self._data & \
+ ((1L << length) - 1)
+ self._len = length
+ else:
+ raise error, 'bitvec() requires array or long parameter'
+ else:
+ raise error, 'bitvec() requires 0 -- 2 parameter(s)'
+
+
+ def append(self, item):
+ #_check_value(item)
+ #self[self._len:self._len] = [item]
+ self[self._len:self._len] = \
+ BitVec(long(not not item), 1)
+
+
+ def count(self, value):
+ #_check_value(value)
+ if value:
+ data = self._data
+ else:
+ data = (~self)._data
+ count = 0
+ while data:
+ data, count = data >> 1, count + (data & 1 != 0)
+ return count
+
+
+ def index(self, value):
+ #_check_value(value):
+ if value:
+ data = self._data
+ else:
+ data = (~self)._data
+ index = 0
+ if not data:
+ raise ValueError, 'list.index(x): x not in list'
+ while not (data & 1):
+ data, index = data >> 1, index + 1
+ return index
+
+
+ def insert(self, index, item):
+ #_check_value(item)
+ #self[index:index] = [item]
+ self[index:index] = BitVec(long(not not item), 1)
+
+
+ def remove(self, value):
+ del self[self.index(value)]
+
+
+ def reverse(self):
+ #ouch, this one is expensive!
+ #for i in self._len>>1: self[i], self[l-i] = self[l-i], self[i]
+ data, result = self._data, 0L
+ for i in range(self._len):
+ if not data:
+ result = result << (self._len - i)
+ break
+ result, data = (result << 1) | (data & 1), data >> 1
+ self._data = result
+
+
+ def sort(self):
+ c = self.count(1)
+ self._data = ((1L << c) - 1) << (self._len - c)
+
+
+ def copy(self):
+ return BitVec(self._data, self._len)
+
+
+ def seq(self):
+ result = []
+ for i in self:
+ result.append(i)
+ return result
+
+
+ def __repr__(self):
+ ##rprt('.' + '__repr__()\n')
+ return 'bitvec(%r, %r)' % (self._data, self._len)
+
+ def __cmp__(self, other, *rest):
+ #rprt('%r.__cmp__%r\n' % (self, (other,) + rest))
+ if type(other) != type(self):
+ other = apply(bitvec, (other, ) + rest)
+ #expensive solution... recursive binary, with slicing
+ length = self._len
+ if length == 0 or other._len == 0:
+ return cmp(length, other._len)
+ if length != other._len:
+ min_length = min(length, other._len)
+ return cmp(self[:min_length], other[:min_length]) or \
+ cmp(self[min_length:], other[min_length:])
+ #the lengths are the same now...
+ if self._data == other._data:
+ return 0
+ if length == 1:
+ return cmp(self[0], other[0])
+ else:
+ length = length >> 1
+ return cmp(self[:length], other[:length]) or \
+ cmp(self[length:], other[length:])
+
+
+ def __len__(self):
+ #rprt('%r.__len__()\n' % (self,))
+ return self._len
+
+ def __getitem__(self, key):
+ #rprt('%r.__getitem__(%r)\n' % (self, key))
+ key = _check_key(self._len, key)
+ return self._data & (1L << key) != 0
+
+ def __setitem__(self, key, value):
+ #rprt('%r.__setitem__(%r, %r)\n' % (self, key, value))
+ key = _check_key(self._len, key)
+ #_check_value(value)
+ if value:
+ self._data = self._data | (1L << key)
+ else:
+ self._data = self._data & ~(1L << key)
+
+ def __delitem__(self, key):
+ #rprt('%r.__delitem__(%r)\n' % (self, key))
+ key = _check_key(self._len, key)
+ #el cheapo solution...
+ self._data = self[:key]._data | self[key+1:]._data >> key
+ self._len = self._len - 1
+
+ def __getslice__(self, i, j):
+ #rprt('%r.__getslice__(%r, %r)\n' % (self, i, j))
+ i, j = _check_slice(self._len, i, j)
+ if i >= j:
+ return BitVec(0L, 0)
+ if i:
+ ndata = self._data >> i
+ else:
+ ndata = self._data
+ nlength = j - i
+ if j != self._len:
+ #we'll have to invent faster variants here
+ #e.g. mod_2exp
+ ndata = ndata & ((1L << nlength) - 1)
+ return BitVec(ndata, nlength)
+
+ def __setslice__(self, i, j, sequence, *rest):
+ #rprt('%s.__setslice__%r\n' % (self, (i, j, sequence) + rest))
+ i, j = _check_slice(self._len, i, j)
+ if type(sequence) != type(self):
+ sequence = apply(bitvec, (sequence, ) + rest)
+ #sequence is now of our own type
+ ls_part = self[:i]
+ ms_part = self[j:]
+ self._data = ls_part._data | \
+ ((sequence._data | \
+ (ms_part._data << sequence._len)) << ls_part._len)
+ self._len = self._len - j + i + sequence._len
+
+ def __delslice__(self, i, j):
+ #rprt('%r.__delslice__(%r, %r)\n' % (self, i, j))
+ i, j = _check_slice(self._len, i, j)
+ if i == 0 and j == self._len:
+ self._data, self._len = 0L, 0
+ elif i < j:
+ self._data = self[:i]._data | (self[j:]._data >> i)
+ self._len = self._len - j + i
+
+ def __add__(self, other):
+ #rprt('%r.__add__(%r)\n' % (self, other))
+ retval = self.copy()
+ retval[self._len:self._len] = other
+ return retval
+
+ def __mul__(self, multiplier):
+ #rprt('%r.__mul__(%r)\n' % (self, multiplier))
+ if type(multiplier) != type(0):
+ raise TypeError, 'sequence subscript not int'
+ if multiplier <= 0:
+ return BitVec(0L, 0)
+ elif multiplier == 1:
+ return self.copy()
+ #handle special cases all 0 or all 1...
+ if self._data == 0L:
+ return BitVec(0L, self._len * multiplier)
+ elif (~self)._data == 0L:
+ return ~BitVec(0L, self._len * multiplier)
+ #otherwise el cheapo again...
+ retval = BitVec(0L, 0)
+ while multiplier:
+ retval, multiplier = retval + self, multiplier - 1
+ return retval
+
+ def __and__(self, otherseq, *rest):
+ #rprt('%r.__and__%r\n' % (self, (otherseq,) + rest))
+ if type(otherseq) != type(self):
+ otherseq = apply(bitvec, (otherseq, ) + rest)
+ #sequence is now of our own type
+ return BitVec(self._data & otherseq._data, \
+ min(self._len, otherseq._len))
+
+
+ def __xor__(self, otherseq, *rest):
+ #rprt('%r.__xor__%r\n' % (self, (otherseq,) + rest))
+ if type(otherseq) != type(self):
+ otherseq = apply(bitvec, (otherseq, ) + rest)
+ #sequence is now of our own type
+ return BitVec(self._data ^ otherseq._data, \
+ max(self._len, otherseq._len))
+
+
+ def __or__(self, otherseq, *rest):
+ #rprt('%r.__or__%r\n' % (self, (otherseq,) + rest))
+ if type(otherseq) != type(self):
+ otherseq = apply(bitvec, (otherseq, ) + rest)
+ #sequence is now of our own type
+ return BitVec(self._data | otherseq._data, \
+ max(self._len, otherseq._len))
+
+
+ def __invert__(self):
+ #rprt('%r.__invert__()\n' % (self,))
+ return BitVec(~self._data & ((1L << self._len) - 1), \
+ self._len)
+
+ def __coerce__(self, otherseq, *rest):
+ #needed for *some* of the arithmetic operations
+ #rprt('%r.__coerce__%r\n' % (self, (otherseq,) + rest))
+ if type(otherseq) != type(self):
+ otherseq = apply(bitvec, (otherseq, ) + rest)
+ return self, otherseq
+
+ def __int__(self):
+ return int(self._data)
+
+ def __long__(self):
+ return long(self._data)
+
+ def __float__(self):
+ return float(self._data)
+
+
+bitvec = BitVec
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/README b/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/README
new file mode 100644
index 0000000000..af86febbe9
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/README
@@ -0,0 +1,60 @@
+Subject: Re: What language would you use?
+From: Tom Christiansen
+Date: 6 Nov 1994 15:14:51 GMT
+Newsgroups: comp.lang.python,comp.lang.tcl,comp.lang.scheme,comp.lang.misc,comp.lang.perl
+Message-Id: <39irtb$3t4@csnews.cs.Colorado.EDU>
+References: <39b7ha$j9v@zeno.nscf.org> <39hhjp$lgn@csnews.cs.Colorado.EDU> <39hvsu$dus@mathserv.mps.ohio-state.edu>
+
+[...]
+If you're really into benchmarks, I'd love it if someone were to code up
+the following problems in tcl, python, and scheme (and whatever else you'd
+like). Separate versions (one optimized for speed, one for beauty :-) are
+ok. Post your code so we can time it on our own systems.
+
+0) Factorial Test (numerics and function calls)
+
+ (we did this already)
+
+1) Regular Expressions Test
+
+ Read a file of (extended per egrep) regular expressions (one per line),
+ and apply those to all files whose names are listed on the command line.
+ Basically, an 'egrep -f' simulator. Test it with 20 "vt100" patterns
+ against a five /etc/termcap files. Tests using more elaborate patters
+ would also be interesting. Your code should not break if given hundreds
+ of regular expressions or binary files to scan.
+
+2) Sorting Test
+
+ Sort an input file that consists of lines like this
+
+ var1=23 other=14 ditto=23 fred=2
+
+ such that each output line is sorted WRT to the number. Order
+ of output lines does not change. Resolve collisions using the
+ variable name. e.g.
+
+ fred=2 other=14 ditto=23 var1=23
+
+ Lines may be up to several kilobytes in length and contain
+ zillions of variables.
+
+3) System Test
+
+ Given a list of directories, report any bogus symbolic links contained
+ anywhere in those subtrees. A bogus symbolic link is one that cannot
+ be resolved because it points to a nonexistent or otherwise
+ unresolvable file. Do *not* use an external find executable.
+ Directories may be very very deep. Print a warning immediately if the
+ system you're running on doesn't support symbolic links.
+
+
+I'll post perl solutions if people post the others.
+
+
+--tom
+--
+Tom Christiansen Perl Consultant, Gamer, Hiker tchrist@mox.perl.com
+
+ "But Billy! A *small* allowance prepares you for a lifetime of small
+ salaries and for your Social Security payments." --Family Circus
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/patterns b/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/patterns
new file mode 100644
index 0000000000..11ec3faa2f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/patterns
@@ -0,0 +1,4 @@
+^def
+^class
+^import
+^from
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/regextest.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/regextest.py
new file mode 100644
index 0000000000..19617a3ce0
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/regextest.py
@@ -0,0 +1,47 @@
+#! /usr/bin/env python
+
+# 1) Regular Expressions Test
+#
+# Read a file of (extended per egrep) regular expressions (one per line),
+# and apply those to all files whose names are listed on the command line.
+# Basically, an 'egrep -f' simulator. Test it with 20 "vt100" patterns
+# against a five /etc/termcap files. Tests using more elaborate patters
+# would also be interesting. Your code should not break if given hundreds
+# of regular expressions or binary files to scan.
+
+# This implementation:
+# - combines all patterns into a single one using ( ... | ... | ... )
+# - reads patterns from stdin, scans files given as command line arguments
+# - produces output in the format ::
+# - is only about 2.5 times as slow as egrep (though I couldn't run
+# Tom's test -- this system, a vanilla SGI, only has /etc/terminfo)
+
+import string
+import sys
+import re
+
+def main():
+ pats = map(chomp, sys.stdin.readlines())
+ bigpat = '(' + '|'.join(pats) + ')'
+ prog = re.compile(bigpat)
+
+ for file in sys.argv[1:]:
+ try:
+ fp = open(file, 'r')
+ except IOError, msg:
+ print "%s: %s" % (file, msg)
+ continue
+ lineno = 0
+ while 1:
+ line = fp.readline()
+ if not line:
+ break
+ lineno = lineno + 1
+ if prog.search(line):
+ print "%s:%s:%s" % (file, lineno, line),
+
+def chomp(s):
+ return s.rstrip('\n')
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/sortingtest.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/sortingtest.py
new file mode 100644
index 0000000000..e19f63eb52
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/sortingtest.py
@@ -0,0 +1,45 @@
+#! /usr/bin/env python
+
+# 2) Sorting Test
+#
+# Sort an input file that consists of lines like this
+#
+# var1=23 other=14 ditto=23 fred=2
+#
+# such that each output line is sorted WRT to the number. Order
+# of output lines does not change. Resolve collisions using the
+# variable name. e.g.
+#
+# fred=2 other=14 ditto=23 var1=23
+#
+# Lines may be up to several kilobytes in length and contain
+# zillions of variables.
+
+# This implementation:
+# - Reads stdin, writes stdout
+# - Uses any amount of whitespace to separate fields
+# - Allows signed numbers
+# - Treats illegally formatted fields as field=0
+# - Outputs the sorted fields with exactly one space between them
+# - Handles blank input lines correctly
+
+import re
+import sys
+
+def main():
+ prog = re.compile('^(.*)=([-+]?[0-9]+)')
+ def makekey(item, prog=prog):
+ match = prog.match(item)
+ if match:
+ var, num = match.groups()
+ return int(num), var
+ else:
+ # Bad input -- pretend it's a var with value 0
+ return 0, item
+ for line in sys.stdin:
+ items = sorted(makekey(item) for item in line.split())
+ for num, var in items:
+ print "%s=%s" % (var, num),
+ print
+
+main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/systemtest.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/systemtest.py
new file mode 100644
index 0000000000..a715fe0d42
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/systemtest.py
@@ -0,0 +1,74 @@
+#! /usr/bin/env python
+
+# 3) System Test
+#
+# Given a list of directories, report any bogus symbolic links contained
+# anywhere in those subtrees. A bogus symbolic link is one that cannot
+# be resolved because it points to a nonexistent or otherwise
+# unresolvable file. Do *not* use an external find executable.
+# Directories may be very very deep. Print a warning immediately if the
+# system you're running on doesn't support symbolic links.
+
+# This implementation:
+# - takes one optional argument, using the current directory as default
+# - uses chdir to increase performance
+# - sorts the names per directory
+# - prints output lines of the form "path1 -> path2" as it goes
+# - prints error messages about directories it can't list or chdir into
+
+import os
+import sys
+from stat import *
+
+def main():
+ try:
+ # Note: can't test for presence of lstat -- it's always there
+ dummy = os.readlink
+ except AttributeError:
+ print "This system doesn't have symbolic links"
+ sys.exit(0)
+ if sys.argv[1:]:
+ prefix = sys.argv[1]
+ else:
+ prefix = ''
+ if prefix:
+ os.chdir(prefix)
+ if prefix[-1:] != '/': prefix = prefix + '/'
+ reportboguslinks(prefix)
+ else:
+ reportboguslinks('')
+
+def reportboguslinks(prefix):
+ try:
+ names = os.listdir('.')
+ except os.error, msg:
+ print "%s%s: can't list: %s" % (prefix, '.', msg)
+ return
+ names.sort()
+ for name in names:
+ if name == os.curdir or name == os.pardir:
+ continue
+ try:
+ mode = os.lstat(name)[ST_MODE]
+ except os.error:
+ print "%s%s: can't stat: %s" % (prefix, name, msg)
+ continue
+ if S_ISLNK(mode):
+ try:
+ os.stat(name)
+ except os.error:
+ print "%s%s -> %s" % \
+ (prefix, name, os.readlink(name))
+ elif S_ISDIR(mode):
+ try:
+ os.chdir(name)
+ except os.error, msg:
+ print "%s%s: can't chdir: %s" % \
+ (prefix, name, msg)
+ continue
+ try:
+ reportboguslinks(prefix + name + '/')
+ finally:
+ os.chdir('..')
+
+main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/README b/AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/README
new file mode 100644
index 0000000000..69f62649f2
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/README
@@ -0,0 +1,10 @@
+This is the Python version of the MD5 test program from the MD5
+Internet Draft (Rivest and Dusse, The MD5 Message-Digest Algorithm, 10
+July 1991). The file "foo" contains the string "abc" with no trailing
+newline.
+
+When called without arguments, it acts as a filter. When called with
+"-x", it executes a self-test, and the output should literally match
+the output given in the RFC.
+
+Code by Jan-Hein B\"uhrman after the original in C.
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/foo b/AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/foo
new file mode 100644
index 0000000000..f2ba8f84ab
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/foo
@@ -0,0 +1 @@
+abc
\ No newline at end of file
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/md5driver.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/md5driver.py
new file mode 100644
index 0000000000..ec4323cb2d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/md5driver.py
@@ -0,0 +1,123 @@
+import string
+import md5
+from sys import argv
+
+def MDPrint(str):
+ outstr = ''
+ for i in str:
+ o = ord(i)
+ outstr = (outstr
+ + string.hexdigits[(o >> 4) & 0xF]
+ + string.hexdigits[o & 0xF])
+ print outstr,
+
+
+from time import time
+
+def makestr(start, end):
+ result = ''
+ for i in range(start, end + 1):
+ result = result + chr(i)
+
+ return result
+
+
+def MDTimeTrial():
+ TEST_BLOCK_SIZE = 1000
+ TEST_BLOCKS = 10000
+
+ TEST_BYTES = TEST_BLOCK_SIZE * TEST_BLOCKS
+
+ # initialize test data, need temporary string filler
+
+ filsiz = 1 << 8
+ filler = makestr(0, filsiz-1)
+ data = filler * (TEST_BLOCK_SIZE // filsiz)
+ data = data + filler[:(TEST_BLOCK_SIZE % filsiz)]
+
+ del filsiz, filler
+
+
+ # start timer
+ print 'MD5 time trial. Processing', TEST_BYTES, 'characters...'
+ t1 = time()
+
+ mdContext = md5.new()
+
+ for i in range(TEST_BLOCKS):
+ mdContext.update(data)
+
+ str = mdContext.digest()
+ t2 = time()
+
+ MDPrint(str)
+ print 'is digest of test input.'
+ print 'Seconds to process test input:', t2 - t1
+ print 'Characters processed per second:', TEST_BYTES / (t2 - t1)
+
+
+def MDString(str):
+ MDPrint(md5.new(str).digest())
+ print '"' + str + '"'
+
+
+def MDFile(filename):
+ f = open(filename, 'rb')
+ mdContext = md5.new()
+
+ while 1:
+ data = f.read(1024)
+ if not data:
+ break
+ mdContext.update(data)
+
+ MDPrint(mdContext.digest())
+ print filename
+
+
+import sys
+
+def MDFilter():
+ mdContext = md5.new()
+
+ while 1:
+ data = sys.stdin.read(16)
+ if not data:
+ break
+ mdContext.update(data)
+
+ MDPrint(mdContext.digest())
+ print
+
+
+def MDTestSuite():
+ print 'MD5 test suite results:'
+ MDString('')
+ MDString('a')
+ MDString('abc')
+ MDString('message digest')
+ MDString(makestr(ord('a'), ord('z')))
+ MDString(makestr(ord('A'), ord('Z'))
+ + makestr(ord('a'), ord('z'))
+ + makestr(ord('0'), ord('9')))
+ MDString((makestr(ord('1'), ord('9')) + '0') * 8)
+
+ # Contents of file foo are "abc"
+ MDFile('foo')
+
+
+# I don't wanna use getopt(), since I want to use the same i/f...
+def main():
+ if len(argv) == 1:
+ MDFilter()
+ for arg in argv[1:]:
+ if arg[:2] == '-s':
+ MDString(arg[2:])
+ elif arg == '-t':
+ MDTimeTrial()
+ elif arg == '-x':
+ MDTestSuite()
+ else:
+ MDFile(arg)
+
+main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Eiffel.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Eiffel.py
new file mode 100644
index 0000000000..732c7beecd
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Eiffel.py
@@ -0,0 +1,113 @@
+"""Support Eiffel-style preconditions and postconditions.
+
+For example,
+
+class C:
+ def m1(self, arg):
+ require arg > 0
+ return whatever
+ ensure Result > arg
+
+can be written (clumsily, I agree) as:
+
+class C(Eiffel):
+ def m1(self, arg):
+ return whatever
+ def m1_pre(self, arg):
+ assert arg > 0
+ def m1_post(self, Result, arg):
+ assert Result > arg
+
+Pre- and post-conditions for a method, being implemented as methods
+themselves, are inherited independently from the method. This gives
+much of the same effect of Eiffel, where pre- and post-conditions are
+inherited when a method is overridden by a derived class. However,
+when a derived class in Python needs to extend a pre- or
+post-condition, it must manually merge the base class' pre- or
+post-condition with that defined in the derived class', for example:
+
+class D(C):
+ def m1(self, arg):
+ return arg**2
+ def m1_post(self, Result, arg):
+ C.m1_post(self, Result, arg)
+ assert Result < 100
+
+This gives derived classes more freedom but also more responsibility
+than in Eiffel, where the compiler automatically takes care of this.
+
+In Eiffel, pre-conditions combine using contravariance, meaning a
+derived class can only make a pre-condition weaker; in Python, this is
+up to the derived class. For example, a derived class that takes away
+the requirement that arg > 0 could write:
+
+ def m1_pre(self, arg):
+ pass
+
+but one could equally write a derived class that makes a stronger
+requirement:
+
+ def m1_pre(self, arg):
+ require arg > 50
+
+It would be easy to modify the classes shown here so that pre- and
+post-conditions can be disabled (separately, on a per-class basis).
+
+A different design would have the pre- or post-condition testing
+functions return true for success and false for failure. This would
+make it possible to implement automatic combination of inherited
+and new pre-/post-conditions. All this is left as an exercise to the
+reader.
+
+"""
+
+from Meta import MetaClass, MetaHelper, MetaMethodWrapper
+
+class EiffelMethodWrapper(MetaMethodWrapper):
+
+ def __init__(self, func, inst):
+ MetaMethodWrapper.__init__(self, func, inst)
+ # Note that the following causes recursive wrappers around
+ # the pre-/post-condition testing methods. These are harmless
+ # but inefficient; to avoid them, the lookup must be done
+ # using the class.
+ try:
+ self.pre = getattr(inst, self.__name__ + "_pre")
+ except AttributeError:
+ self.pre = None
+ try:
+ self.post = getattr(inst, self.__name__ + "_post")
+ except AttributeError:
+ self.post = None
+
+ def __call__(self, *args, **kw):
+ if self.pre:
+ apply(self.pre, args, kw)
+ Result = apply(self.func, (self.inst,) + args, kw)
+ if self.post:
+ apply(self.post, (Result,) + args, kw)
+ return Result
+
+class EiffelHelper(MetaHelper):
+ __methodwrapper__ = EiffelMethodWrapper
+
+class EiffelMetaClass(MetaClass):
+ __helper__ = EiffelHelper
+
+Eiffel = EiffelMetaClass('Eiffel', (), {})
+
+
+def _test():
+ class C(Eiffel):
+ def m1(self, arg):
+ return arg+1
+ def m1_pre(self, arg):
+ assert arg > 0, "precondition for m1 failed"
+ def m1_post(self, Result, arg):
+ assert Result > arg
+ x = C()
+ x.m1(12)
+## x.m1(-1)
+
+if __name__ == '__main__':
+ _test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Enum.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Enum.py
new file mode 100644
index 0000000000..204f308584
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Enum.py
@@ -0,0 +1,169 @@
+"""Enumeration metaclass.
+
+XXX This is very much a work in progress.
+
+"""
+
+import string
+
+class EnumMetaClass:
+ """Metaclass for enumeration.
+
+ To define your own enumeration, do something like
+
+ class Color(Enum):
+ red = 1
+ green = 2
+ blue = 3
+
+ Now, Color.red, Color.green and Color.blue behave totally
+ different: they are enumerated values, not integers.
+
+ Enumerations cannot be instantiated; however they can be
+ subclassed.
+
+ """
+
+ def __init__(self, name, bases, dict):
+ """Constructor -- create an enumeration.
+
+ Called at the end of the class statement. The arguments are
+ the name of the new class, a tuple containing the base
+ classes, and a dictionary containing everything that was
+ entered in the class' namespace during execution of the class
+ statement. In the above example, it would be {'red': 1,
+ 'green': 2, 'blue': 3}.
+
+ """
+ for base in bases:
+ if base.__class__ is not EnumMetaClass:
+ raise TypeError, "Enumeration base class must be enumeration"
+ bases = filter(lambda x: x is not Enum, bases)
+ self.__name__ = name
+ self.__bases__ = bases
+ self.__dict = {}
+ for key, value in dict.items():
+ self.__dict[key] = EnumInstance(name, key, value)
+
+ def __getattr__(self, name):
+ """Return an enumeration value.
+
+ For example, Color.red returns the value corresponding to red.
+
+ XXX Perhaps the values should be created in the constructor?
+
+ This looks in the class dictionary and if it is not found
+ there asks the base classes.
+
+ The special attribute __members__ returns the list of names
+ defined in this class (it does not merge in the names defined
+ in base classes).
+
+ """
+ if name == '__members__':
+ return self.__dict.keys()
+
+ try:
+ return self.__dict[name]
+ except KeyError:
+ for base in self.__bases__:
+ try:
+ return getattr(base, name)
+ except AttributeError:
+ continue
+
+ raise AttributeError, name
+
+ def __repr__(self):
+ s = self.__name__
+ if self.__bases__:
+ s = s + '(' + string.join(map(lambda x: x.__name__,
+ self.__bases__), ", ") + ')'
+ if self.__dict:
+ list = []
+ for key, value in self.__dict.items():
+ list.append("%s: %s" % (key, int(value)))
+ s = "%s: {%s}" % (s, string.join(list, ", "))
+ return s
+
+
+class EnumInstance:
+ """Class to represent an enumeration value.
+
+ EnumInstance('Color', 'red', 12) prints as 'Color.red' and behaves
+ like the integer 12 when compared, but doesn't support arithmetic.
+
+ XXX Should it record the actual enumeration rather than just its
+ name?
+
+ """
+
+ def __init__(self, classname, enumname, value):
+ self.__classname = classname
+ self.__enumname = enumname
+ self.__value = value
+
+ def __int__(self):
+ return self.__value
+
+ def __repr__(self):
+ return "EnumInstance(%r, %r, %r)" % (self.__classname,
+ self.__enumname,
+ self.__value)
+
+ def __str__(self):
+ return "%s.%s" % (self.__classname, self.__enumname)
+
+ def __cmp__(self, other):
+ return cmp(self.__value, int(other))
+
+
+# Create the base class for enumerations.
+# It is an empty enumeration.
+Enum = EnumMetaClass("Enum", (), {})
+
+
+def _test():
+
+ class Color(Enum):
+ red = 1
+ green = 2
+ blue = 3
+
+ print Color.red
+ print dir(Color)
+
+ print Color.red == Color.red
+ print Color.red == Color.blue
+ print Color.red == 1
+ print Color.red == 2
+
+ class ExtendedColor(Color):
+ white = 0
+ orange = 4
+ yellow = 5
+ purple = 6
+ black = 7
+
+ print ExtendedColor.orange
+ print ExtendedColor.red
+
+ print Color.red == ExtendedColor.red
+
+ class OtherColor(Enum):
+ white = 4
+ blue = 5
+
+ class MergedColor(Color, OtherColor):
+ pass
+
+ print MergedColor.red
+ print MergedColor.white
+
+ print Color
+ print ExtendedColor
+ print OtherColor
+ print MergedColor
+
+if __name__ == '__main__':
+ _test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Meta.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Meta.py
new file mode 100644
index 0000000000..b262a8021c
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Meta.py
@@ -0,0 +1,118 @@
+"""Generic metaclass.
+
+XXX This is very much a work in progress.
+
+"""
+
+import types
+
+class MetaMethodWrapper:
+
+ def __init__(self, func, inst):
+ self.func = func
+ self.inst = inst
+ self.__name__ = self.func.__name__
+
+ def __call__(self, *args, **kw):
+ return apply(self.func, (self.inst,) + args, kw)
+
+class MetaHelper:
+
+ __methodwrapper__ = MetaMethodWrapper # For derived helpers to override
+
+ def __helperinit__(self, formalclass):
+ self.__formalclass__ = formalclass
+
+ def __getattr__(self, name):
+ # Invoked for any attr not in the instance's __dict__
+ try:
+ raw = self.__formalclass__.__getattr__(name)
+ except AttributeError:
+ try:
+ ga = self.__formalclass__.__getattr__('__usergetattr__')
+ except (KeyError, AttributeError):
+ raise AttributeError, name
+ return ga(self, name)
+ if type(raw) != types.FunctionType:
+ return raw
+ return self.__methodwrapper__(raw, self)
+
+class MetaClass:
+
+ """A generic metaclass.
+
+ This can be subclassed to implement various kinds of meta-behavior.
+
+ """
+
+ __helper__ = MetaHelper # For derived metaclasses to override
+
+ __inited = 0
+
+ def __init__(self, name, bases, dict):
+ try:
+ ga = dict['__getattr__']
+ except KeyError:
+ pass
+ else:
+ dict['__usergetattr__'] = ga
+ del dict['__getattr__']
+ self.__name__ = name
+ self.__bases__ = bases
+ self.__realdict__ = dict
+ self.__inited = 1
+
+ def __getattr__(self, name):
+ try:
+ return self.__realdict__[name]
+ except KeyError:
+ for base in self.__bases__:
+ try:
+ return base.__getattr__(name)
+ except AttributeError:
+ pass
+ raise AttributeError, name
+
+ def __setattr__(self, name, value):
+ if not self.__inited:
+ self.__dict__[name] = value
+ else:
+ self.__realdict__[name] = value
+
+ def __call__(self, *args, **kw):
+ inst = self.__helper__()
+ inst.__helperinit__(self)
+ try:
+ init = inst.__getattr__('__init__')
+ except AttributeError:
+ init = lambda: None
+ apply(init, args, kw)
+ return inst
+
+
+Meta = MetaClass('Meta', (), {})
+
+
+def _test():
+ class C(Meta):
+ def __init__(self, *args):
+ print "__init__, args =", args
+ def m1(self, x):
+ print "m1(x=%r)" % (x,)
+ print C
+ x = C()
+ print x
+ x.m1(12)
+ class D(C):
+ def __getattr__(self, name):
+ if name[:2] == '__': raise AttributeError, name
+ return "getattr:%s" % name
+ x = D()
+ print x.foo
+ print x._foo
+## print x.__foo
+## print x.__foo__
+
+
+if __name__ == '__main__':
+ _test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Simple.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Simple.py
new file mode 100644
index 0000000000..5334860732
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Simple.py
@@ -0,0 +1,45 @@
+import types
+
+class Tracing:
+ def __init__(self, name, bases, namespace):
+ """Create a new class."""
+ self.__name__ = name
+ self.__bases__ = bases
+ self.__namespace__ = namespace
+ def __call__(self):
+ """Create a new instance."""
+ return Instance(self)
+
+class Instance:
+ def __init__(self, klass):
+ self.__klass__ = klass
+ def __getattr__(self, name):
+ try:
+ value = self.__klass__.__namespace__[name]
+ except KeyError:
+ raise AttributeError, name
+ if type(value) is not types.FunctionType:
+ return value
+ return BoundMethod(value, self)
+
+class BoundMethod:
+ def __init__(self, function, instance):
+ self.function = function
+ self.instance = instance
+ def __call__(self, *args):
+ print "calling", self.function, "for", self.instance, "with", args
+ return apply(self.function, (self.instance,) + args)
+
+Trace = Tracing('Trace', (), {})
+
+class MyTracedClass(Trace):
+ def method1(self, a):
+ self.a = a
+ def method2(self):
+ return self.a
+
+aninstance = MyTracedClass()
+
+aninstance.method1(10)
+
+print aninstance.method2()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Synch.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Synch.py
new file mode 100644
index 0000000000..d3b3f3893a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Synch.py
@@ -0,0 +1,256 @@
+"""Synchronization metaclass.
+
+This metaclass makes it possible to declare synchronized methods.
+
+"""
+
+import thread
+
+# First we need to define a reentrant lock.
+# This is generally useful and should probably be in a standard Python
+# library module. For now, we in-line it.
+
+class Lock:
+
+ """Reentrant lock.
+
+ This is a mutex-like object which can be acquired by the same
+ thread more than once. It keeps a reference count of the number
+ of times it has been acquired by the same thread. Each acquire()
+ call must be matched by a release() call and only the last
+ release() call actually releases the lock for acquisition by
+ another thread.
+
+ The implementation uses two locks internally:
+
+ __mutex is a short term lock used to protect the instance variables
+ __wait is the lock for which other threads wait
+
+ A thread intending to acquire both locks should acquire __wait
+ first.
+
+ The implementation uses two other instance variables, protected by
+ locking __mutex:
+
+ __tid is the thread ID of the thread that currently has the lock
+ __count is the number of times the current thread has acquired it
+
+ When the lock is released, __tid is None and __count is zero.
+
+ """
+
+ def __init__(self):
+ """Constructor. Initialize all instance variables."""
+ self.__mutex = thread.allocate_lock()
+ self.__wait = thread.allocate_lock()
+ self.__tid = None
+ self.__count = 0
+
+ def acquire(self, flag=1):
+ """Acquire the lock.
+
+ If the optional flag argument is false, returns immediately
+ when it cannot acquire the __wait lock without blocking (it
+ may still block for a little while in order to acquire the
+ __mutex lock).
+
+ The return value is only relevant when the flag argument is
+ false; it is 1 if the lock is acquired, 0 if not.
+
+ """
+ self.__mutex.acquire()
+ try:
+ if self.__tid == thread.get_ident():
+ self.__count = self.__count + 1
+ return 1
+ finally:
+ self.__mutex.release()
+ locked = self.__wait.acquire(flag)
+ if not flag and not locked:
+ return 0
+ try:
+ self.__mutex.acquire()
+ assert self.__tid == None
+ assert self.__count == 0
+ self.__tid = thread.get_ident()
+ self.__count = 1
+ return 1
+ finally:
+ self.__mutex.release()
+
+ def release(self):
+ """Release the lock.
+
+ If this thread doesn't currently have the lock, an assertion
+ error is raised.
+
+ Only allow another thread to acquire the lock when the count
+ reaches zero after decrementing it.
+
+ """
+ self.__mutex.acquire()
+ try:
+ assert self.__tid == thread.get_ident()
+ assert self.__count > 0
+ self.__count = self.__count - 1
+ if self.__count == 0:
+ self.__tid = None
+ self.__wait.release()
+ finally:
+ self.__mutex.release()
+
+
+def _testLock():
+
+ done = []
+
+ def f2(lock, done=done):
+ lock.acquire()
+ print "f2 running in thread %d\n" % thread.get_ident(),
+ lock.release()
+ done.append(1)
+
+ def f1(lock, f2=f2, done=done):
+ lock.acquire()
+ print "f1 running in thread %d\n" % thread.get_ident(),
+ try:
+ f2(lock)
+ finally:
+ lock.release()
+ done.append(1)
+
+ lock = Lock()
+ lock.acquire()
+ f1(lock) # Adds 2 to done
+ lock.release()
+
+ lock.acquire()
+
+ thread.start_new_thread(f1, (lock,)) # Adds 2
+ thread.start_new_thread(f1, (lock, f1)) # Adds 3
+ thread.start_new_thread(f2, (lock,)) # Adds 1
+ thread.start_new_thread(f2, (lock,)) # Adds 1
+
+ lock.release()
+ import time
+ while len(done) < 9:
+ print len(done)
+ time.sleep(0.001)
+ print len(done)
+
+
+# Now, the Locking metaclass is a piece of cake.
+# As an example feature, methods whose name begins with exactly one
+# underscore are not synchronized.
+
+from Meta import MetaClass, MetaHelper, MetaMethodWrapper
+
+class LockingMethodWrapper(MetaMethodWrapper):
+ def __call__(self, *args, **kw):
+ if self.__name__[:1] == '_' and self.__name__[1:] != '_':
+ return apply(self.func, (self.inst,) + args, kw)
+ self.inst.__lock__.acquire()
+ try:
+ return apply(self.func, (self.inst,) + args, kw)
+ finally:
+ self.inst.__lock__.release()
+
+class LockingHelper(MetaHelper):
+ __methodwrapper__ = LockingMethodWrapper
+ def __helperinit__(self, formalclass):
+ MetaHelper.__helperinit__(self, formalclass)
+ self.__lock__ = Lock()
+
+class LockingMetaClass(MetaClass):
+ __helper__ = LockingHelper
+
+Locking = LockingMetaClass('Locking', (), {})
+
+def _test():
+ # For kicks, take away the Locking base class and see it die
+ class Buffer(Locking):
+ def __init__(self, initialsize):
+ assert initialsize > 0
+ self.size = initialsize
+ self.buffer = [None]*self.size
+ self.first = self.last = 0
+ def put(self, item):
+ # Do we need to grow the buffer?
+ if (self.last+1) % self.size != self.first:
+ # Insert the new item
+ self.buffer[self.last] = item
+ self.last = (self.last+1) % self.size
+ return
+ # Double the buffer size
+ # First normalize it so that first==0 and last==size-1
+ print "buffer =", self.buffer
+ print "first = %d, last = %d, size = %d" % (
+ self.first, self.last, self.size)
+ if self.first <= self.last:
+ temp = self.buffer[self.first:self.last]
+ else:
+ temp = self.buffer[self.first:] + self.buffer[:self.last]
+ print "temp =", temp
+ self.buffer = temp + [None]*(self.size+1)
+ self.first = 0
+ self.last = self.size-1
+ self.size = self.size*2
+ print "Buffer size doubled to", self.size
+ print "new buffer =", self.buffer
+ print "first = %d, last = %d, size = %d" % (
+ self.first, self.last, self.size)
+ self.put(item) # Recursive call to test the locking
+ def get(self):
+ # Is the buffer empty?
+ if self.first == self.last:
+ raise EOFError # Avoid defining a new exception
+ item = self.buffer[self.first]
+ self.first = (self.first+1) % self.size
+ return item
+
+ def producer(buffer, wait, n=1000):
+ import time
+ i = 0
+ while i < n:
+ print "put", i
+ buffer.put(i)
+ i = i+1
+ print "Producer: done producing", n, "items"
+ wait.release()
+
+ def consumer(buffer, wait, n=1000):
+ import time
+ i = 0
+ tout = 0.001
+ while i < n:
+ try:
+ x = buffer.get()
+ if x != i:
+ raise AssertionError, \
+ "get() returned %s, expected %s" % (x, i)
+ print "got", i
+ i = i+1
+ tout = 0.001
+ except EOFError:
+ time.sleep(tout)
+ tout = tout*2
+ print "Consumer: done consuming", n, "items"
+ wait.release()
+
+ pwait = thread.allocate_lock()
+ pwait.acquire()
+ cwait = thread.allocate_lock()
+ cwait.acquire()
+ buffer = Buffer(1)
+ n = 1000
+ thread.start_new_thread(consumer, (buffer, cwait, n))
+ thread.start_new_thread(producer, (buffer, pwait, n))
+ pwait.acquire()
+ print "Producer done"
+ cwait.acquire()
+ print "All done"
+ print "buffer size ==", len(buffer.buffer)
+
+if __name__ == '__main__':
+ _testLock()
+ _test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Trace.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Trace.py
new file mode 100644
index 0000000000..b02d05a9e4
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Trace.py
@@ -0,0 +1,144 @@
+"""Tracing metaclass.
+
+XXX This is very much a work in progress.
+
+"""
+
+import types, sys
+
+class TraceMetaClass:
+ """Metaclass for tracing.
+
+ Classes defined using this metaclass have an automatic tracing
+ feature -- by setting the __trace_output__ instance (or class)
+ variable to a file object, trace messages about all calls are
+ written to the file. The trace formatting can be changed by
+ defining a suitable __trace_call__ method.
+
+ """
+
+ __inited = 0
+
+ def __init__(self, name, bases, dict):
+ self.__name__ = name
+ self.__bases__ = bases
+ self.__dict = dict
+ # XXX Can't define __dict__, alas
+ self.__inited = 1
+
+ def __getattr__(self, name):
+ try:
+ return self.__dict[name]
+ except KeyError:
+ for base in self.__bases__:
+ try:
+ return base.__getattr__(name)
+ except AttributeError:
+ pass
+ raise AttributeError, name
+
+ def __setattr__(self, name, value):
+ if not self.__inited:
+ self.__dict__[name] = value
+ else:
+ self.__dict[name] = value
+
+ def __call__(self, *args, **kw):
+ inst = TracingInstance()
+ inst.__meta_init__(self)
+ try:
+ init = inst.__getattr__('__init__')
+ except AttributeError:
+ init = lambda: None
+ apply(init, args, kw)
+ return inst
+
+ __trace_output__ = None
+
+class TracingInstance:
+ """Helper class to represent an instance of a tracing class."""
+
+ def __trace_call__(self, fp, fmt, *args):
+ fp.write((fmt+'\n') % args)
+
+ def __meta_init__(self, klass):
+ self.__class = klass
+
+ def __getattr__(self, name):
+ # Invoked for any attr not in the instance's __dict__
+ try:
+ raw = self.__class.__getattr__(name)
+ except AttributeError:
+ raise AttributeError, name
+ if type(raw) != types.FunctionType:
+ return raw
+ # It's a function
+ fullname = self.__class.__name__ + "." + name
+ if not self.__trace_output__ or name == '__trace_call__':
+ return NotTracingWrapper(fullname, raw, self)
+ else:
+ return TracingWrapper(fullname, raw, self)
+
+class NotTracingWrapper:
+ def __init__(self, name, func, inst):
+ self.__name__ = name
+ self.func = func
+ self.inst = inst
+ def __call__(self, *args, **kw):
+ return apply(self.func, (self.inst,) + args, kw)
+
+class TracingWrapper(NotTracingWrapper):
+ def __call__(self, *args, **kw):
+ self.inst.__trace_call__(self.inst.__trace_output__,
+ "calling %s, inst=%s, args=%s, kw=%s",
+ self.__name__, self.inst, args, kw)
+ try:
+ rv = apply(self.func, (self.inst,) + args, kw)
+ except:
+ t, v, tb = sys.exc_info()
+ self.inst.__trace_call__(self.inst.__trace_output__,
+ "returning from %s with exception %s: %s",
+ self.__name__, t, v)
+ raise t, v, tb
+ else:
+ self.inst.__trace_call__(self.inst.__trace_output__,
+ "returning from %s with value %s",
+ self.__name__, rv)
+ return rv
+
+Traced = TraceMetaClass('Traced', (), {'__trace_output__': None})
+
+
+def _test():
+ global C, D
+ class C(Traced):
+ def __init__(self, x=0): self.x = x
+ def m1(self, x): self.x = x
+ def m2(self, y): return self.x + y
+ __trace_output__ = sys.stdout
+ class D(C):
+ def m2(self, y): print "D.m2(%r)" % (y,); return C.m2(self, y)
+ __trace_output__ = None
+ x = C(4321)
+ print x
+ print x.x
+ print x.m1(100)
+ print x.m1(10)
+ print x.m2(33)
+ print x.m1(5)
+ print x.m2(4000)
+ print x.x
+
+ print C.__init__
+ print C.m2
+ print D.__init__
+ print D.m2
+
+ y = D()
+ print y
+ print y.m1(10)
+ print y.m2(100)
+ print y.x
+
+if __name__ == '__main__':
+ _test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/index.html b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/index.html
new file mode 100644
index 0000000000..88e05a3417
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/index.html
@@ -0,0 +1,605 @@
+
+
+
+Metaclasses in Python 1.5
+
+
+
+
+
Metaclasses in Python 1.5
+
(A.k.a. The Killer Joke :-)
+
+
+
+(Postscript: reading this essay is probably not the best way to
+understand the metaclass hook described here. See a message posted by Vladimir Marangozov
+which may give a gentler introduction to the matter. You may also
+want to search Deja News for messages with "metaclass" in the subject
+posted to comp.lang.python in July and August 1998.)
+
+
+
+
In previous Python releases (and still in 1.5), there is something
+called the ``Don Beaudry hook'', after its inventor and champion.
+This allows C extensions to provide alternate class behavior, thereby
+allowing the Python class syntax to be used to define other class-like
+entities. Don Beaudry has used this in his infamous MESS package; Jim
+Fulton has used it in his Extension
+Classes package. (It has also been referred to as the ``Don
+Beaudry hack,'' but that's a misnomer. There's nothing hackish
+about it -- in fact, it is rather elegant and deep, even though
+there's something dark to it.)
+
+
(On first reading, you may want to skip directly to the examples in
+the section "Writing Metaclasses in Python" below, unless you want
+your head to explode.)
+
+
+
+
+
+
Documentation of the Don Beaudry hook has purposefully been kept
+minimal, since it is a feature of incredible power, and is easily
+abused. Basically, it checks whether the type of the base
+class is callable, and if so, it is called to create the new
+class.
+
+
Note the two indirection levels. Take a simple example:
+
+
+class B:
+ pass
+
+class C(B):
+ pass
+
+
+Take a look at the second class definition, and try to fathom ``the
+type of the base class is callable.''
+
+
(Types are not classes, by the way. See questions 4.2, 4.19 and in
+particular 6.22 in the Python FAQ
+for more on this topic.)
+
+
+
+
+
+
The base class is B; this one's easy.
+
+
Since B is a class, its type is ``class''; so the type of the
+base class is the type ``class''. This is also known as
+types.ClassType, assuming the standard module types has
+been imported.
+
+
Now is the type ``class'' callable? No, because types (in
+core Python) are never callable. Classes are callable (calling a
+class creates a new instance) but types aren't.
+
+
+
+
So our conclusion is that in our example, the type of the base
+class (of C) is not callable. So the Don Beaudry hook does not apply,
+and the default class creation mechanism is used (which is also used
+when there is no base class). In fact, the Don Beaudry hook never
+applies when using only core Python, since the type of a core object
+is never callable.
+
+
So what do Don and Jim do in order to use Don's hook? Write an
+extension that defines at least two new Python object types. The
+first would be the type for ``class-like'' objects usable as a base
+class, to trigger Don's hook. This type must be made callable.
+That's why we need a second type. Whether an object is callable
+depends on its type. So whether a type object is callable depends on
+its type, which is a meta-type. (In core Python there
+is only one meta-type, the type ``type'' (types.TypeType), which is
+the type of all type objects, even itself.) A new meta-type must
+be defined that makes the type of the class-like objects callable.
+(Normally, a third type would also be needed, the new ``instance''
+type, but this is not an absolute requirement -- the new class type
+could return an object of some existing type when invoked to create an
+instance.)
+
+
Still confused? Here's a simple device due to Don himself to
+explain metaclasses. Take a simple class definition; assume B is a
+special class that triggers Don's hook:
+
+
+class C(B):
+ a = 1
+ b = 2
+
+
+This can be though of as equivalent to:
+
+
+C = type(B)('C', (B,), {'a': 1, 'b': 2})
+
+
+If that's too dense for you, here's the same thing written out using
+temporary variables:
+
+
+creator = type(B) # The type of the base class
+name = 'C' # The name of the new class
+bases = (B,) # A tuple containing the base class(es)
+namespace = {'a': 1, 'b': 2} # The namespace of the class statement
+C = creator(name, bases, namespace)
+
+
+This is analogous to what happens without the Don Beaudry hook, except
+that in that case the creator function is set to the default class
+creator.
+
+
In either case, the creator is called with three arguments. The
+first one, name, is the name of the new class (as given at the
+top of the class statement). The bases argument is a tuple of
+base classes (a singleton tuple if there's only one base class, like
+the example). Finally, namespace is a dictionary containing
+the local variables collected during execution of the class statement.
+
+
Note that the contents of the namespace dictionary is simply
+whatever names were defined in the class statement. A little-known
+fact is that when Python executes a class statement, it enters a new
+local namespace, and all assignments and function definitions take
+place in this namespace. Thus, after executing the following class
+statement:
+
+
+class C:
+ a = 1
+ def f(s): pass
+
+
+the class namespace's contents would be {'a': 1, 'f': <function f
+...>}.
+
+
But enough already about writing Python metaclasses in C; read the
+documentation of MESS or Extension
+Classes for more information.
+
+
+
+
+
+
Writing Metaclasses in Python
+
+
In Python 1.5, the requirement to write a C extension in order to
+write metaclasses has been dropped (though you can still do
+it, of course). In addition to the check ``is the type of the base
+class callable,'' there's a check ``does the base class have a
+__class__ attribute.'' If so, it is assumed that the __class__
+attribute refers to a class.
+
+
Let's repeat our simple example from above:
+
+
+class C(B):
+ a = 1
+ b = 2
+
+
+Assuming B has a __class__ attribute, this translates into:
+
+
+C = B.__class__('C', (B,), {'a': 1, 'b': 2})
+
+
+This is exactly the same as before except that instead of type(B),
+B.__class__ is invoked. If you have read FAQ question 6.22 you will understand that while there is a big
+technical difference between type(B) and B.__class__, they play the
+same role at different abstraction levels. And perhaps at some point
+in the future they will really be the same thing (at which point you
+would be able to derive subclasses from built-in types).
+
+
At this point it may be worth mentioning that C.__class__ is the
+same object as B.__class__, i.e., C's metaclass is the same as B's
+metaclass. In other words, subclassing an existing class creates a
+new (meta)inststance of the base class's metaclass.
+
+
Going back to the example, the class B.__class__ is instantiated,
+passing its constructor the same three arguments that are passed to
+the default class constructor or to an extension's metaclass:
+name, bases, and namespace.
+
+
It is easy to be confused by what exactly happens when using a
+metaclass, because we lose the absolute distinction between classes
+and instances: a class is an instance of a metaclass (a
+``metainstance''), but technically (i.e. in the eyes of the python
+runtime system), the metaclass is just a class, and the metainstance
+is just an instance. At the end of the class statement, the metaclass
+whose metainstance is used as a base class is instantiated, yielding a
+second metainstance (of the same metaclass). This metainstance is
+then used as a (normal, non-meta) class; instantiation of the class
+means calling the metainstance, and this will return a real instance.
+And what class is that an instance of? Conceptually, it is of course
+an instance of our metainstance; but in most cases the Python runtime
+system will see it as an instance of a a helper class used by the
+metaclass to implement its (non-meta) instances...
+
+
Hopefully an example will make things clearer. Let's presume we
+have a metaclass MetaClass1. It's helper class (for non-meta
+instances) is callled HelperClass1. We now (manually) instantiate
+MetaClass1 once to get an empty special base class:
+
+
+BaseClass1 = MetaClass1("BaseClass1", (), {})
+
+
+We can now use BaseClass1 as a base class in a class statement:
+
+
+
+At this point, MySpecialClass is defined; it is a metainstance of
+MetaClass1 just like BaseClass1, and in fact the expression
+``BaseClass1.__class__ == MySpecialClass.__class__ == MetaClass1''
+yields true.
+
+
We are now ready to create instances of MySpecialClass. Let's
+assume that no constructor arguments are required:
+
+
+
+The print statement shows that x and y are instances of HelperClass1.
+How did this happen? MySpecialClass is an instance of MetaClass1
+(``meta'' is irrelevant here); when an instance is called, its
+__call__ method is invoked, and presumably the __call__ method defined
+by MetaClass1 returns an instance of HelperClass1.
+
+
Now let's see how we could use metaclasses -- what can we do
+with metaclasses that we can't easily do without them? Here's one
+idea: a metaclass could automatically insert trace calls for all
+method calls. Let's first develop a simplified example, without
+support for inheritance or other ``advanced'' Python features (we'll
+add those later).
+
+
+import types
+
+class Tracing:
+ def __init__(self, name, bases, namespace):
+ """Create a new class."""
+ self.__name__ = name
+ self.__bases__ = bases
+ self.__namespace__ = namespace
+ def __call__(self):
+ """Create a new instance."""
+ return Instance(self)
+
+class Instance:
+ def __init__(self, klass):
+ self.__klass__ = klass
+ def __getattr__(self, name):
+ try:
+ value = self.__klass__.__namespace__[name]
+ except KeyError:
+ raise AttributeError, name
+ if type(value) is not types.FunctionType:
+ return value
+ return BoundMethod(value, self)
+
+class BoundMethod:
+ def __init__(self, function, instance):
+ self.function = function
+ self.instance = instance
+ def __call__(self, *args):
+ print "calling", self.function, "for", self.instance, "with", args
+ return apply(self.function, (self.instance,) + args)
+
+Trace = Tracing('Trace', (), {})
+
+class MyTracedClass(Trace):
+ def method1(self, a):
+ self.a = a
+ def method2(self):
+ return self.a
+
+aninstance = MyTracedClass()
+
+aninstance.method1(10)
+
+print "the answer is %d" % aninstance.method2()
+
+
+Confused already? The intention is to read this from top down. The
+Tracing class is the metaclass we're defining. Its structure is
+really simple.
+
+
+
+
+
+
The __init__ method is invoked when a new Tracing instance is
+created, e.g. the definition of class MyTracedClass later in the
+example. It simply saves the class name, base classes and namespace
+as instance variables.
+
+
The __call__ method is invoked when a Tracing instance is called,
+e.g. the creation of aninstance later in the example. It returns an
+instance of the class Instance, which is defined next.
+
+
+
+
The class Instance is the class used for all instances of classes
+built using the Tracing metaclass, e.g. aninstance. It has two
+methods:
+
+
+
+
+
+
The __init__ method is invoked from the Tracing.__call__ method
+above to initialize a new instance. It saves the class reference as
+an instance variable. It uses a funny name because the user's
+instance variables (e.g. self.a later in the example) live in the same
+namespace.
+
+
The __getattr__ method is invoked whenever the user code
+references an attribute of the instance that is not an instance
+variable (nor a class variable; but except for __init__ and
+__getattr__ there are no class variables). It will be called, for
+example, when aninstance.method1 is referenced in the example, with
+self set to aninstance and name set to the string "method1".
+
+
+
+
The __getattr__ method looks the name up in the __namespace__
+dictionary. If it isn't found, it raises an AttributeError exception.
+(In a more realistic example, it would first have to look through the
+base classes as well.) If it is found, there are two possibilities:
+it's either a function or it isn't. If it's not a function, it is
+assumed to be a class variable, and its value is returned. If it's a
+function, we have to ``wrap'' it in instance of yet another helper
+class, BoundMethod.
+
+
The BoundMethod class is needed to implement a familiar feature:
+when a method is defined, it has an initial argument, self, which is
+automatically bound to the relevant instance when it is called. For
+example, aninstance.method1(10) is equivalent to method1(aninstance,
+10). In the example if this call, first a temporary BoundMethod
+instance is created with the following constructor call: temp =
+BoundMethod(method1, aninstance); then this instance is called as
+temp(10). After the call, the temporary instance is discarded.
+
+
+
+
+
+
The __init__ method is invoked for the constructor call
+BoundMethod(method1, aninstance). It simply saves away its
+arguments.
+
+
The __call__ method is invoked when the bound method instance is
+called, as in temp(10). It needs to call method1(aninstance, 10).
+However, even though self.function is now method1 and self.instance is
+aninstance, it can't call self.function(self.instance, args) directly,
+because it should work regardless of the number of arguments passed.
+(For simplicity, support for keyword arguments has been omitted.)
+
+
+
+
In order to be able to support arbitrary argument lists, the
+__call__ method first constructs a new argument tuple. Conveniently,
+because of the notation *args in __call__'s own argument list, the
+arguments to __call__ (except for self) are placed in the tuple args.
+To construct the desired argument list, we concatenate a singleton
+tuple containing the instance with the args tuple: (self.instance,) +
+args. (Note the trailing comma used to construct the singleton
+tuple.) In our example, the resulting argument tuple is (aninstance,
+10).
+
+
The intrinsic function apply() takes a function and an argument
+tuple and calls the function for it. In our example, we are calling
+apply(method1, (aninstance, 10)) which is equivalent to calling
+method(aninstance, 10).
+
+
From here on, things should come together quite easily. The output
+of the example code is something like this:
+
+
+calling <function method1 at ae8d8> for <Instance instance at 95ab0> with (10,)
+calling <function method2 at ae900> for <Instance instance at 95ab0> with ()
+the answer is 10
+
+
+
That was about the shortest meaningful example that I could come up
+with. A real tracing metaclass (for example, Trace.py discussed below) needs to be more
+complicated in two dimensions.
+
+
First, it needs to support more advanced Python features such as
+class variables, inheritance, __init__ methods, and keyword arguments.
+
+
Second, it needs to provide a more flexible way to handle the
+actual tracing information; perhaps it should be possible to write
+your own tracing function that gets called, perhaps it should be
+possible to enable and disable tracing on a per-class or per-instance
+basis, and perhaps a filter so that only interesting calls are traced;
+it should also be able to trace the return value of the call (or the
+exception it raised if an error occurs). Even the Trace.py example
+doesn't support all these features yet.
+
+
+
+
+
+
Real-life Examples
+
+
Have a look at some very preliminary examples that I coded up to
+teach myself how to write metaclasses:
+
+
This (ab)uses the class syntax as an elegant way to define
+enumerated types. The resulting classes are never instantiated --
+rather, their class attributes are the enumerated values. For
+example:
+
+
+class Color(Enum):
+ red = 1
+ green = 2
+ blue = 3
+print Color.red
+
+
+will print the string ``Color.red'', while ``Color.red==1'' is true,
+and ``Color.red + 1'' raise a TypeError exception.
+
+
The resulting classes work much like standard
+classes, but by setting a special class or instance attribute
+__trace_output__ to point to a file, all calls to the class's methods
+are traced. It was a bit of a struggle to get this right. This
+should probably redone using the generic metaclass below.
+
+
A generic metaclass. This is an attempt at finding out how much
+standard class behavior can be mimicked by a metaclass. The
+preliminary answer appears to be that everything's fine as long as the
+class (or its clients) don't look at the instance's __class__
+attribute, nor at the class's __dict__ attribute. The use of
+__getattr__ internally makes the classic implementation of __getattr__
+hooks tough; we provide a similar hook _getattr_ instead.
+(__setattr__ and __delattr__ are not affected.)
+(XXX Hm. Could detect presence of __getattr__ and rename it.)
+
+
A pattern seems to be emerging: almost all these uses of
+metaclasses (except for Enum, which is probably more cute than useful)
+mostly work by placing wrappers around method calls. An obvious
+problem with that is that it's not easy to combine the features of
+different metaclasses, while this would actually be quite useful: for
+example, I wouldn't mind getting a trace from the test run of the
+Synch module, and it would be interesting to add preconditions to it
+as well. This needs more research. Perhaps a metaclass could be
+provided that allows stackable wrappers...
+
+
+
+
+
+
Things You Could Do With Metaclasses
+
+
There are lots of things you could do with metaclasses. Most of
+these can also be done with creative use of __getattr__, but
+metaclasses make it easier to modify the attribute lookup behavior of
+classes. Here's a partial list.
+
+
+
+
+
+
Enforce different inheritance semantics, e.g. automatically call
+base class methods when a derived class overrides
+
+
Implement class methods (e.g. if the first argument is not named
+'self')
+
+
Implement that each instance is initialized with copies of
+all class variables
+
+
Implement a different way to store instance variables (e.g. in a
+list kept outside the instance but indexed by the instance's id())
+
+
Automatically wrap or trap all or certain methods
+
+
+
+
for tracing
+
+
for precondition and postcondition checking
+
+
for synchronized methods
+
+
for automatic value caching
+
+
+
+
+
When an attribute is a parameterless function, call it on
+reference (to mimic it being an instance variable); same on assignment
+
+
Instrumentation: see how many times various attributes are used
+
+
Different semantics for __setattr__ and __getattr__ (e.g. disable
+them when they are being used recursively)
+
+
Abuse class syntax for other things
+
+
Experiment with automatic type checking
+
+
Delegation (or acquisition)
+
+
Dynamic inheritance patterns
+
+
Automatic caching of methods
+
+
+
+
+
+
+
+
Credits
+
+
Many thanks to David Ascher and Donald Beaudry for their comments
+on earlier draft of this paper. Also thanks to Matt Conway and Tommy
+Burnette for putting a seed for the idea of metaclasses in my
+mind, nearly three years ago, even though at the time my response was
+``you can do that with __getattr__ hooks...'' :-)
+
+
+
+
+
+
+
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/meta-vladimir.txt b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/meta-vladimir.txt
new file mode 100644
index 0000000000..81298a73d1
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/meta-vladimir.txt
@@ -0,0 +1,256 @@
+Subject: Re: The metaclass saga using Python
+From: Vladimir Marangozov
+To: tim_one@email.msn.com (Tim Peters)
+Cc: python-list@cwi.nl
+Date: Wed, 5 Aug 1998 15:59:06 +0200 (DFT)
+
+[Tim]
+>
+> building-on-examples-tends-to-prevent-abstract-thrashing-ly y'rs - tim
+>
+
+OK, I stand corrected. I understand that anybody's interpretation of
+the meta-class concept is likely to be difficult to digest by others.
+
+Here's another try, expressing the same thing, but using the Python
+programming model, examples and, perhaps, more popular terms.
+
+1. Classes.
+
+ This is pure Python of today. Sorry about the tutorial, but it is
+ meant to illustrate the second part, which is the one we're
+ interested in and which will follow the same development scenario.
+ Besides, newbies are likely to understand that the discussion is
+ affordable even for them :-)
+
+ a) Class definition
+
+ A class is meant to define the common properties of a set of objects.
+ A class is a "package" of properties. The assembly of properties
+ in a class package is sometimes called a class structure (which isn't
+ always appropriate).
+
+ >>> class A:
+ attr1 = "Hello" # an attribute of A
+ def method1(self, *args): pass # method1 of A
+ def method2(self, *args): pass # method2 of A
+ >>>
+
+ So far, we defined the structure of the class A. The class A is
+ of type . We can check this by asking Python: "what is A?"
+
+ >>> A # What is A?
+
+
+ b) Class instantiation
+
+ Creating an object with the properties defined in the class A is
+ called instantiation of the class A. After an instantiation of A, we
+ obtain a new object, called an instance, which has the properties
+ packaged in the class A.
+
+ >>> a = A() # 'a' is the 1st instance of A
+ >>> a # What is 'a'?
+ <__main__.A instance at 2022b9d0>
+
+ >>> b = A() # 'b' is another instance of A
+ >>> b # What is 'b'?
+ <__main__.A instance at 2022b9c0>
+
+ The objects, 'a' and 'b', are of type and they both have
+ the same properties. Note, that 'a' and 'b' are different objects.
+ (their adresses differ). This is a bit hard to see, so let's ask Python:
+
+ >>> a == b # Is 'a' the same object as 'b'?
+ 0 # No.
+
+ Instance objects have one more special property, indicating the class
+ they are an instance of. This property is named __class__.
+
+ >>> a.__class__ # What is the class of 'a'?
+ # 'a' is an instance of A
+ >>> b.__class__ # What is the class of 'b'?
+ # 'b' is an instance of A
+ >>> a.__class__ == b.__class__ # Is it really the same class A?
+ 1 # Yes.
+
+ c) Class inheritance (class composition and specialization)
+
+ Classes can be defined in terms of other existing classes (and only
+ classes! -- don't bug me on this now). Thus, we can compose property
+ packages and create new ones. We reuse the property set defined
+ in a class by defining a new class, which "inherits" from the former.
+ In other words, a class B which inherits from the class A, inherits
+ the properties defined in A, or, B inherits the structure of A.
+
+ In the same time, at the definition of the new class B, we can enrich
+ the inherited set of properties by adding new ones and/or modify some
+ of the inherited properties.
+
+ >>> class B(A): # B inherits A's properties
+ attr2 = "World" # additional attr2
+ def method2(self, arg1): pass # method2 is redefined
+ def method3(self, *args): pass # additional method3
+
+ >>> B # What is B?
+
+ >>> B == A # Is B the same class as A?
+ 0 # No.
+
+ Classes define one special property, indicating whether a class
+ inherits the properties of another class. This property is called
+ __bases__ and it contains a list (a tuple) of the classes the new
+ class inherits from. The classes from which a class is inheriting the
+ properties are called superclasses (in Python, we call them also --
+ base classes).
+
+ >>> A.__bases__ # Does A have any superclasses?
+ () # No.
+ >>> B.__bases__ # Does B have any superclasses?
+ (,) # Yes. It has one superclass.
+ >>> B.__bases__[0] == A # Is it really the class A?
+ 1 # Yes, it is.
+
+--------
+
+ Congratulations on getting this far! This was the hard part.
+ Now, let's continue with the easy one.
+
+--------
+
+2. Meta-classes
+
+ You have to admit, that an anonymous group of Python wizards are
+ not satisfied with the property packaging facilities presented above.
+ They say, that the Real-World bugs them with problems that cannot be
+ modelled successfully with classes. Or, that the way classes are
+ implemented in Python and the way classes and instances behave at
+ runtime isn't always appropriate for reproducing the Real-World's
+ behavior in a way that satisfies them.
+
+ Hence, what they want is the following:
+
+ a) leave objects as they are (instances of classes)
+ b) leave classes as they are (property packages and object creators)
+
+ BUT, at the same time:
+
+ c) consider classes as being instances of mysterious objects.
+ d) label mysterious objects "meta-classes".
+
+ Easy, eh?
+
+ You may ask: "Why on earth do they want to do that?".
+ They answer: "Poor soul... Go and see how cruel the Real-World is!".
+ You - fuzzy: "OK, will do!"
+
+ And here we go for another round of what I said in section 1 -- Classes.
+
+ However, be warned! The features we're going to talk about aren't fully
+ implemented yet, because the Real-World don't let wizards to evaluate
+ precisely how cruel it is, so the features are still highly-experimental.
+
+ a) Meta-class definition
+
+ A meta-class is meant to define the common properties of a set of
+ classes. A meta-class is a "package" of properties. The assembly
+ of properties in a meta-class package is sometimes called a meta-class
+ structure (which isn't always appropriate).
+
+ In Python, a meta-class definition would have looked like this:
+
+ >>> metaclass M:
+ attr1 = "Hello" # an attribute of M
+ def method1(self, *args): pass # method1 of M
+ def method2(self, *args): pass # method2 of M
+ >>>
+
+ So far, we defined the structure of the meta-class M. The meta-class
+ M is of type . We cannot check this by asking Python, but
+ if we could, it would have answered:
+
+ >>> M # What is M?
+
+
+ b) Meta-class instantiation
+
+ Creating an object with the properties defined in the meta-class M is
+ called instantiation of the meta-class M. After an instantiation of M,
+ we obtain a new object, called an class, but now it is called also
+ a meta-instance, which has the properties packaged in the meta-class M.
+
+ In Python, instantiating a meta-class would have looked like this:
+
+ >>> A = M() # 'A' is the 1st instance of M
+ >>> A # What is 'A'?
+
+
+ >>> B = M() # 'B' is another instance of M
+ >>> B # What is 'B'?
+
+
+ The metaclass-instances, A and B, are of type and they both
+ have the same properties. Note, that A and B are different objects.
+ (their adresses differ). This is a bit hard to see, but if it was
+ possible to ask Python, it would have answered:
+
+ >>> A == B # Is A the same class as B?
+ 0 # No.
+
+ Class objects have one more special property, indicating the meta-class
+ they are an instance of. This property is named __metaclass__.
+
+ >>> A.__metaclass__ # What is the meta-class of A?
+ # A is an instance of M
+ >>> A.__metaclass__ # What is the meta-class of B?
+ # B is an instance of M
+ >>> A.__metaclass__ == B.__metaclass__ # Is it the same meta-class M?
+ 1 # Yes.
+
+ c) Meta-class inheritance (meta-class composition and specialization)
+
+ Meta-classes can be defined in terms of other existing meta-classes
+ (and only meta-classes!). Thus, we can compose property packages and
+ create new ones. We reuse the property set defined in a meta-class by
+ defining a new meta-class, which "inherits" from the former.
+ In other words, a meta-class N which inherits from the meta-class M,
+ inherits the properties defined in M, or, N inherits the structure of M.
+
+ In the same time, at the definition of the new meta-class N, we can
+ enrich the inherited set of properties by adding new ones and/or modify
+ some of the inherited properties.
+
+ >>> metaclass N(M): # N inherits M's properties
+ attr2 = "World" # additional attr2
+ def method2(self, arg1): pass # method2 is redefined
+ def method3(self, *args): pass # additional method3
+
+ >>> N # What is N?
+
+ >>> N == M # Is N the same meta-class as M?
+ 0 # No.
+
+ Meta-classes define one special property, indicating whether a
+ meta-class inherits the properties of another meta-class. This property
+ is called __metabases__ and it contains a list (a tuple) of the
+ meta-classes the new meta-class inherits from. The meta-classes from
+ which a meta-class is inheriting the properties are called
+ super-meta-classes (in Python, we call them also -- super meta-bases).
+
+ >>> M.__metabases__ # Does M have any supermetaclasses?
+ () # No.
+ >>> N.__metabases__ # Does N have any supermetaclasses?
+ (,) # Yes. It has a supermetaclass.
+ >>> N.__metabases__[0] == M # Is it really the meta-class M?
+ 1 # Yes, it is.
+
+--------
+
+ Triple congratulations on getting this far!
+ Now you know everything about meta-classes and the Real-World!
+
+
+
+--
+ Vladimir MARANGOZOV | Vladimir.Marangozov@inrialpes.fr
+http://sirac.inrialpes.fr/~marangoz | tel:(+33-4)76615277 fax:76615252
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/newmetaclasses/Eiffel.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/newmetaclasses/Eiffel.py
new file mode 100644
index 0000000000..f3a412b4c2
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/newmetaclasses/Eiffel.py
@@ -0,0 +1,141 @@
+"""Support Eiffel-style preconditions and postconditions."""
+
+from types import FunctionType as function
+
+class EiffelBaseMetaClass(type):
+
+ def __new__(meta, name, bases, dict):
+ meta.convert_methods(dict)
+ return super(EiffelBaseMetaClass, meta).__new__(meta, name, bases,
+ dict)
+
+ @classmethod
+ def convert_methods(cls, dict):
+ """Replace functions in dict with EiffelMethod wrappers.
+
+ The dict is modified in place.
+
+ If a method ends in _pre or _post, it is removed from the dict
+ regardless of whether there is a corresponding method.
+ """
+ # find methods with pre or post conditions
+ methods = []
+ for k, v in dict.iteritems():
+ if k.endswith('_pre') or k.endswith('_post'):
+ assert isinstance(v, function)
+ elif isinstance(v, function):
+ methods.append(k)
+ for m in methods:
+ pre = dict.get("%s_pre" % m)
+ post = dict.get("%s_post" % m)
+ if pre or post:
+ dict[k] = cls.make_eiffel_method(dict[m], pre, post)
+
+class EiffelMetaClass1(EiffelBaseMetaClass):
+ # an implementation of the "eiffel" meta class that uses nested functions
+
+ @staticmethod
+ def make_eiffel_method(func, pre, post):
+ def method(self, *args, **kwargs):
+ if pre:
+ pre(self, *args, **kwargs)
+ x = func(self, *args, **kwargs)
+ if post:
+ post(self, x, *args, **kwargs)
+ return x
+
+ if func.__doc__:
+ method.__doc__ = func.__doc__
+
+ return method
+
+class EiffelMethodWrapper:
+
+ def __init__(self, inst, descr):
+ self._inst = inst
+ self._descr = descr
+
+ def __call__(self, *args, **kwargs):
+ return self._descr.callmethod(self._inst, args, kwargs)
+
+class EiffelDescriptor(object):
+
+ def __init__(self, func, pre, post):
+ self._func = func
+ self._pre = pre
+ self._post = post
+
+ self.__name__ = func.__name__
+ self.__doc__ = func.__doc__
+
+ def __get__(self, obj, cls):
+ return EiffelMethodWrapper(obj, self)
+
+ def callmethod(self, inst, args, kwargs):
+ if self._pre:
+ self._pre(inst, *args, **kwargs)
+ x = self._func(inst, *args, **kwargs)
+ if self._post:
+ self._post(inst, x, *args, **kwargs)
+ return x
+
+class EiffelMetaClass2(EiffelBaseMetaClass):
+ # an implementation of the "eiffel" meta class that uses descriptors
+
+ make_eiffel_method = EiffelDescriptor
+
+def _test(metaclass):
+ class Eiffel:
+ __metaclass__ = metaclass
+
+ class Test(Eiffel):
+
+ def m(self, arg):
+ """Make it a little larger"""
+ return arg + 1
+
+ def m2(self, arg):
+ """Make it a little larger"""
+ return arg + 1
+
+ def m2_pre(self, arg):
+ assert arg > 0
+
+ def m2_post(self, result, arg):
+ assert result > arg
+
+ class Sub(Test):
+ def m2(self, arg):
+ return arg**2
+ def m2_post(self, Result, arg):
+ super(Sub, self).m2_post(Result, arg)
+ assert Result < 100
+
+ t = Test()
+ t.m(1)
+ t.m2(1)
+ try:
+ t.m2(0)
+ except AssertionError:
+ pass
+ else:
+ assert False
+
+ s = Sub()
+ try:
+ s.m2(1)
+ except AssertionError:
+ pass # result == arg
+ else:
+ assert False
+ try:
+ s.m2(10)
+ except AssertionError:
+ pass # result == 100
+ else:
+ assert False
+ s.m2(5)
+
+if __name__ == "__main__":
+ _test(EiffelMetaClass1)
+ _test(EiffelMetaClass2)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/newmetaclasses/Enum.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/newmetaclasses/Enum.py
new file mode 100644
index 0000000000..a080e8d98c
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/newmetaclasses/Enum.py
@@ -0,0 +1,177 @@
+"""Enumeration metaclass."""
+
+class EnumMetaclass(type):
+ """Metaclass for enumeration.
+
+ To define your own enumeration, do something like
+
+ class Color(Enum):
+ red = 1
+ green = 2
+ blue = 3
+
+ Now, Color.red, Color.green and Color.blue behave totally
+ different: they are enumerated values, not integers.
+
+ Enumerations cannot be instantiated; however they can be
+ subclassed.
+ """
+
+ def __init__(cls, name, bases, dict):
+ super(EnumMetaclass, cls).__init__(name, bases, dict)
+ cls._members = []
+ for attr in dict.keys():
+ if not (attr.startswith('__') and attr.endswith('__')):
+ enumval = EnumInstance(name, attr, dict[attr])
+ setattr(cls, attr, enumval)
+ cls._members.append(attr)
+
+ def __getattr__(cls, name):
+ if name == "__members__":
+ return cls._members
+ raise AttributeError, name
+
+ def __repr__(cls):
+ s1 = s2 = ""
+ enumbases = [base.__name__ for base in cls.__bases__
+ if isinstance(base, EnumMetaclass) and not base is Enum]
+ if enumbases:
+ s1 = "(%s)" % ", ".join(enumbases)
+ enumvalues = ["%s: %d" % (val, getattr(cls, val))
+ for val in cls._members]
+ if enumvalues:
+ s2 = ": {%s}" % ", ".join(enumvalues)
+ return "%s%s%s" % (cls.__name__, s1, s2)
+
+class FullEnumMetaclass(EnumMetaclass):
+ """Metaclass for full enumerations.
+
+ A full enumeration displays all the values defined in base classes.
+ """
+
+ def __init__(cls, name, bases, dict):
+ super(FullEnumMetaclass, cls).__init__(name, bases, dict)
+ for obj in cls.__mro__:
+ if isinstance(obj, EnumMetaclass):
+ for attr in obj._members:
+ # XXX inefficient
+ if not attr in cls._members:
+ cls._members.append(attr)
+
+class EnumInstance(int):
+ """Class to represent an enumeration value.
+
+ EnumInstance('Color', 'red', 12) prints as 'Color.red' and behaves
+ like the integer 12 when compared, but doesn't support arithmetic.
+
+ XXX Should it record the actual enumeration rather than just its
+ name?
+ """
+
+ def __new__(cls, classname, enumname, value):
+ return int.__new__(cls, value)
+
+ def __init__(self, classname, enumname, value):
+ self.__classname = classname
+ self.__enumname = enumname
+
+ def __repr__(self):
+ return "EnumInstance(%s, %s, %d)" % (self.__classname, self.__enumname,
+ self)
+
+ def __str__(self):
+ return "%s.%s" % (self.__classname, self.__enumname)
+
+class Enum:
+ __metaclass__ = EnumMetaclass
+
+class FullEnum:
+ __metaclass__ = FullEnumMetaclass
+
+def _test():
+
+ class Color(Enum):
+ red = 1
+ green = 2
+ blue = 3
+
+ print Color.red
+
+ print repr(Color.red)
+ print Color.red == Color.red
+ print Color.red == Color.blue
+ print Color.red == 1
+ print Color.red == 2
+
+ class ExtendedColor(Color):
+ white = 0
+ orange = 4
+ yellow = 5
+ purple = 6
+ black = 7
+
+ print ExtendedColor.orange
+ print ExtendedColor.red
+
+ print Color.red == ExtendedColor.red
+
+ class OtherColor(Enum):
+ white = 4
+ blue = 5
+
+ class MergedColor(Color, OtherColor):
+ pass
+
+ print MergedColor.red
+ print MergedColor.white
+
+ print Color
+ print ExtendedColor
+ print OtherColor
+ print MergedColor
+
+def _test2():
+
+ class Color(FullEnum):
+ red = 1
+ green = 2
+ blue = 3
+
+ print Color.red
+
+ print repr(Color.red)
+ print Color.red == Color.red
+ print Color.red == Color.blue
+ print Color.red == 1
+ print Color.red == 2
+
+ class ExtendedColor(Color):
+ white = 0
+ orange = 4
+ yellow = 5
+ purple = 6
+ black = 7
+
+ print ExtendedColor.orange
+ print ExtendedColor.red
+
+ print Color.red == ExtendedColor.red
+
+ class OtherColor(FullEnum):
+ white = 4
+ blue = 5
+
+ class MergedColor(Color, OtherColor):
+ pass
+
+ print MergedColor.red
+ print MergedColor.white
+
+ print Color
+ print ExtendedColor
+ print OtherColor
+ print MergedColor
+
+if __name__ == '__main__':
+ _test()
+ _test2()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/FILES b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/FILES
new file mode 100644
index 0000000000..1df6c3d26d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/FILES
@@ -0,0 +1,6 @@
+Demo/parser
+Doc/libparser.tex
+Lib/AST.py
+Lib/symbol.py
+Lib/token.py
+Modules/parsermodule.c
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/README b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/README
new file mode 100644
index 0000000000..fa5bd31351
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/README
@@ -0,0 +1,32 @@
+These files are from the large example of using the `parser' module. Refer
+to the Python Library Reference for more information.
+
+It also contains examples for the AST parser.
+
+Files:
+------
+
+ FILES -- list of files associated with the parser module.
+
+ README -- this file.
+
+ docstring.py -- sample source file containing only a module docstring.
+
+ example.py -- module that uses the `parser' module to extract
+ information from the parse tree of Python source
+ code.
+
+ simple.py -- sample source containing a "short form" definition.
+
+ source.py -- sample source code used to demonstrate ability to
+ handle nested constructs easily using the functions
+ and classes in example.py.
+
+ test_parser.py program to put the parser module through its paces.
+
+ test_unparse.py tests for the unparse module
+
+ unparse.py AST (2.7) based example to recreate source code
+ from an AST.
+
+Enjoy!
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/docstring.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/docstring.py
new file mode 100644
index 0000000000..81efa02cb7
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/docstring.py
@@ -0,0 +1,2 @@
+"""Some documentation.
+"""
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/example.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/example.py
new file mode 100644
index 0000000000..346f973d16
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/example.py
@@ -0,0 +1,190 @@
+"""Simple code to extract class & function docstrings from a module.
+
+This code is used as an example in the library reference manual in the
+section on using the parser module. Refer to the manual for a thorough
+discussion of the operation of this code.
+"""
+
+import os
+import parser
+import symbol
+import token
+import types
+
+from types import ListType, TupleType
+
+
+def get_docs(fileName):
+ """Retrieve information from the parse tree of a source file.
+
+ fileName
+ Name of the file to read Python source code from.
+ """
+ source = open(fileName).read()
+ basename = os.path.basename(os.path.splitext(fileName)[0])
+ ast = parser.suite(source)
+ return ModuleInfo(ast.totuple(), basename)
+
+
+class SuiteInfoBase:
+ _docstring = ''
+ _name = ''
+
+ def __init__(self, tree = None):
+ self._class_info = {}
+ self._function_info = {}
+ if tree:
+ self._extract_info(tree)
+
+ def _extract_info(self, tree):
+ # extract docstring
+ if len(tree) == 2:
+ found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1])
+ else:
+ found, vars = match(DOCSTRING_STMT_PATTERN, tree[3])
+ if found:
+ self._docstring = eval(vars['docstring'])
+ # discover inner definitions
+ for node in tree[1:]:
+ found, vars = match(COMPOUND_STMT_PATTERN, node)
+ if found:
+ cstmt = vars['compound']
+ if cstmt[0] == symbol.funcdef:
+ name = cstmt[2][1]
+ self._function_info[name] = FunctionInfo(cstmt)
+ elif cstmt[0] == symbol.classdef:
+ name = cstmt[2][1]
+ self._class_info[name] = ClassInfo(cstmt)
+
+ def get_docstring(self):
+ return self._docstring
+
+ def get_name(self):
+ return self._name
+
+ def get_class_names(self):
+ return self._class_info.keys()
+
+ def get_class_info(self, name):
+ return self._class_info[name]
+
+ def __getitem__(self, name):
+ try:
+ return self._class_info[name]
+ except KeyError:
+ return self._function_info[name]
+
+
+class SuiteFuncInfo:
+ # Mixin class providing access to function names and info.
+
+ def get_function_names(self):
+ return self._function_info.keys()
+
+ def get_function_info(self, name):
+ return self._function_info[name]
+
+
+class FunctionInfo(SuiteInfoBase, SuiteFuncInfo):
+ def __init__(self, tree = None):
+ self._name = tree[2][1]
+ SuiteInfoBase.__init__(self, tree and tree[-1] or None)
+
+
+class ClassInfo(SuiteInfoBase):
+ def __init__(self, tree = None):
+ self._name = tree[2][1]
+ SuiteInfoBase.__init__(self, tree and tree[-1] or None)
+
+ def get_method_names(self):
+ return self._function_info.keys()
+
+ def get_method_info(self, name):
+ return self._function_info[name]
+
+
+class ModuleInfo(SuiteInfoBase, SuiteFuncInfo):
+ def __init__(self, tree = None, name = ""):
+ self._name = name
+ SuiteInfoBase.__init__(self, tree)
+ if tree:
+ found, vars = match(DOCSTRING_STMT_PATTERN, tree[1])
+ if found:
+ self._docstring = vars["docstring"]
+
+
+def match(pattern, data, vars=None):
+ """Match `data' to `pattern', with variable extraction.
+
+ pattern
+ Pattern to match against, possibly containing variables.
+
+ data
+ Data to be checked and against which variables are extracted.
+
+ vars
+ Dictionary of variables which have already been found. If not
+ provided, an empty dictionary is created.
+
+ The `pattern' value may contain variables of the form ['varname'] which
+ are allowed to match anything. The value that is matched is returned as
+ part of a dictionary which maps 'varname' to the matched value. 'varname'
+ is not required to be a string object, but using strings makes patterns
+ and the code which uses them more readable.
+
+ This function returns two values: a boolean indicating whether a match
+ was found and a dictionary mapping variable names to their associated
+ values.
+ """
+ if vars is None:
+ vars = {}
+ if type(pattern) is ListType: # 'variables' are ['varname']
+ vars[pattern[0]] = data
+ return 1, vars
+ if type(pattern) is not TupleType:
+ return (pattern == data), vars
+ if len(data) != len(pattern):
+ return 0, vars
+ for pattern, data in map(None, pattern, data):
+ same, vars = match(pattern, data, vars)
+ if not same:
+ break
+ return same, vars
+
+
+# This pattern identifies compound statements, allowing them to be readily
+# differentiated from simple statements.
+#
+COMPOUND_STMT_PATTERN = (
+ symbol.stmt,
+ (symbol.compound_stmt, ['compound'])
+ )
+
+
+# This pattern will match a 'stmt' node which *might* represent a docstring;
+# docstrings require that the statement which provides the docstring be the
+# first statement in the class or function, which this pattern does not check.
+#
+DOCSTRING_STMT_PATTERN = (
+ symbol.stmt,
+ (symbol.simple_stmt,
+ (symbol.small_stmt,
+ (symbol.expr_stmt,
+ (symbol.testlist,
+ (symbol.test,
+ (symbol.and_test,
+ (symbol.not_test,
+ (symbol.comparison,
+ (symbol.expr,
+ (symbol.xor_expr,
+ (symbol.and_expr,
+ (symbol.shift_expr,
+ (symbol.arith_expr,
+ (symbol.term,
+ (symbol.factor,
+ (symbol.power,
+ (symbol.atom,
+ (token.STRING, ['docstring'])
+ )))))))))))))))),
+ (token.NEWLINE, '')
+ ))
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/simple.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/simple.py
new file mode 100644
index 0000000000..75ab0e7d5d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/simple.py
@@ -0,0 +1 @@
+def f(): "maybe a docstring"
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/source.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/source.py
new file mode 100644
index 0000000000..e5b6bec0b9
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/source.py
@@ -0,0 +1,27 @@
+"""Exmaple file to be parsed for the parsermodule example.
+
+The classes and functions in this module exist only to exhibit the ability
+of the handling information extraction from nested definitions using parse
+trees. They shouldn't interest you otherwise!
+"""
+
+class Simple:
+ "This class does very little."
+
+ def method(self):
+ "This method does almost nothing."
+ return 1
+
+ class Nested:
+ "This is a nested class."
+
+ def nested_method(self):
+ "Method of Nested class."
+ def nested_function():
+ "Function in method of Nested class."
+ pass
+ return nested_function
+
+def function():
+ "This function lives at the module level."
+ return 0
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/test_parser.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/test_parser.py
new file mode 100644
index 0000000000..f3f48b89b6
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/test_parser.py
@@ -0,0 +1,48 @@
+#! /usr/bin/env python
+# (Force the script to use the latest build.)
+#
+# test_parser.py
+
+import parser, traceback
+
+_numFailed = 0
+
+def testChunk(t, fileName):
+ global _numFailed
+ print '----', fileName,
+ try:
+ st = parser.suite(t)
+ tup = parser.st2tuple(st)
+ # this discards the first ST; a huge memory savings when running
+ # against a large source file like Tkinter.py.
+ st = None
+ new = parser.tuple2st(tup)
+ except parser.ParserError, err:
+ print
+ print 'parser module raised exception on input file', fileName + ':'
+ traceback.print_exc()
+ _numFailed = _numFailed + 1
+ else:
+ if tup != parser.st2tuple(new):
+ print
+ print 'parser module failed on input file', fileName
+ _numFailed = _numFailed + 1
+ else:
+ print 'o.k.'
+
+def testFile(fileName):
+ t = open(fileName).read()
+ testChunk(t, fileName)
+
+def test():
+ import sys
+ args = sys.argv[1:]
+ if not args:
+ import glob
+ args = glob.glob("*.py")
+ args.sort()
+ map(testFile, args)
+ sys.exit(_numFailed != 0)
+
+if __name__ == '__main__':
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/test_unparse.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/test_unparse.py
new file mode 100644
index 0000000000..eee1c7ab4c
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/test_unparse.py
@@ -0,0 +1,213 @@
+import unittest
+from test import test_support
+import cStringIO
+import sys
+import os
+import tokenize
+import ast
+import unparse
+
+def read_pyfile(filename):
+ """Read and return the contents of a Python source file (as a
+ string), taking into account the file encoding."""
+ with open(filename, "r") as pyfile:
+ source = pyfile.read()
+ return source
+
+for_else = """\
+def f():
+ for x in range(10):
+ break
+ else:
+ y = 2
+ z = 3
+"""
+
+while_else = """\
+def g():
+ while True:
+ break
+ else:
+ y = 2
+ z = 3
+"""
+
+relative_import = """\
+from . import fred
+from .. import barney
+from .australia import shrimp as prawns
+"""
+
+class_decorator = """\
+@f1(arg)
+@f2
+class Foo: pass
+"""
+
+elif1 = """\
+if cond1:
+ suite1
+elif cond2:
+ suite2
+else:
+ suite3
+"""
+
+elif2 = """\
+if cond1:
+ suite1
+elif cond2:
+ suite2
+"""
+
+try_except_finally = """\
+try:
+ suite1
+except ex1:
+ suite2
+except ex2:
+ suite3
+else:
+ suite4
+finally:
+ suite5
+"""
+
+class ASTTestCase(unittest.TestCase):
+ def assertASTEqual(self, ast1, ast2):
+ dump1 = ast.dump(ast1)
+ dump2 = ast.dump(ast2)
+ self.assertEqual(ast.dump(ast1), ast.dump(ast2))
+
+ def check_roundtrip(self, code1, filename="internal"):
+ ast1 = compile(code1, filename, "exec", ast.PyCF_ONLY_AST)
+ unparse_buffer = cStringIO.StringIO()
+ unparse.Unparser(ast1, unparse_buffer)
+ code2 = unparse_buffer.getvalue()
+ ast2 = compile(code2, filename, "exec", ast.PyCF_ONLY_AST)
+ self.assertASTEqual(ast1, ast2)
+
+class UnparseTestCase(ASTTestCase):
+ # Tests for specific bugs found in earlier versions of unparse
+
+ def test_del_statement(self):
+ self.check_roundtrip("del x, y, z")
+
+ def test_shifts(self):
+ self.check_roundtrip("45 << 2")
+ self.check_roundtrip("13 >> 7")
+
+ def test_for_else(self):
+ self.check_roundtrip(for_else)
+
+ def test_while_else(self):
+ self.check_roundtrip(while_else)
+
+ def test_unary_parens(self):
+ self.check_roundtrip("(-1)**7")
+ self.check_roundtrip("(-1.)**8")
+ self.check_roundtrip("(-1j)**6")
+ self.check_roundtrip("not True or False")
+ self.check_roundtrip("True or not False")
+
+ def test_integer_parens(self):
+ self.check_roundtrip("3 .__abs__()")
+
+ def test_huge_float(self):
+ self.check_roundtrip("1e1000")
+ self.check_roundtrip("-1e1000")
+ self.check_roundtrip("1e1000j")
+ self.check_roundtrip("-1e1000j")
+
+ def test_min_int(self):
+ self.check_roundtrip(str(-sys.maxint-1))
+ self.check_roundtrip("-(%s)" % (sys.maxint + 1))
+
+ def test_imaginary_literals(self):
+ self.check_roundtrip("7j")
+ self.check_roundtrip("-7j")
+ self.check_roundtrip("-(7j)")
+ self.check_roundtrip("0j")
+ self.check_roundtrip("-0j")
+ self.check_roundtrip("-(0j)")
+
+ def test_negative_zero(self):
+ self.check_roundtrip("-0")
+ self.check_roundtrip("-(0)")
+ self.check_roundtrip("-0b0")
+ self.check_roundtrip("-(0b0)")
+ self.check_roundtrip("-0o0")
+ self.check_roundtrip("-(0o0)")
+ self.check_roundtrip("-0x0")
+ self.check_roundtrip("-(0x0)")
+
+ def test_lambda_parentheses(self):
+ self.check_roundtrip("(lambda: int)()")
+
+ def test_chained_comparisons(self):
+ self.check_roundtrip("1 < 4 <= 5")
+ self.check_roundtrip("a is b is c is not d")
+
+ def test_function_arguments(self):
+ self.check_roundtrip("def f(): pass")
+ self.check_roundtrip("def f(a): pass")
+ self.check_roundtrip("def f(b = 2): pass")
+ self.check_roundtrip("def f(a, b): pass")
+ self.check_roundtrip("def f(a, b = 2): pass")
+ self.check_roundtrip("def f(a = 5, b = 2): pass")
+ self.check_roundtrip("def f(*args, **kwargs): pass")
+
+ def test_relative_import(self):
+ self.check_roundtrip(relative_import)
+
+ def test_bytes(self):
+ self.check_roundtrip("b'123'")
+
+ def test_set_literal(self):
+ self.check_roundtrip("{'a', 'b', 'c'}")
+
+ def test_set_comprehension(self):
+ self.check_roundtrip("{x for x in range(5)}")
+
+ def test_dict_comprehension(self):
+ self.check_roundtrip("{x: x*x for x in range(10)}")
+
+ def test_class_decorators(self):
+ self.check_roundtrip(class_decorator)
+
+ def test_elifs(self):
+ self.check_roundtrip(elif1)
+ self.check_roundtrip(elif2)
+
+ def test_try_except_finally(self):
+ self.check_roundtrip(try_except_finally)
+
+class DirectoryTestCase(ASTTestCase):
+ """Test roundtrip behaviour on all files in Lib and Lib/test."""
+
+ # test directories, relative to the root of the distribution
+ test_directories = 'Lib', os.path.join('Lib', 'test')
+
+ def test_files(self):
+ # get names of files to test
+ dist_dir = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
+
+ names = []
+ for d in self.test_directories:
+ test_dir = os.path.join(dist_dir, d)
+ for n in os.listdir(test_dir):
+ if n.endswith('.py') and not n.startswith('bad'):
+ names.append(os.path.join(test_dir, n))
+
+ for filename in names:
+ if test_support.verbose:
+ print('Testing %s' % filename)
+ source = read_pyfile(filename)
+ self.check_roundtrip(source)
+
+
+def test_main():
+ test_support.run_unittest(UnparseTestCase, DirectoryTestCase)
+
+if __name__ == '__main__':
+ test_main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/unparse.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/unparse.py
new file mode 100644
index 0000000000..b42d979a5e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/unparse.py
@@ -0,0 +1,606 @@
+"Usage: unparse.py "
+import sys
+import ast
+import cStringIO
+import os
+
+# Large float and imaginary literals get turned into infinities in the AST.
+# We unparse those infinities to INFSTR.
+INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)
+
+def interleave(inter, f, seq):
+ """Call f on each item in seq, calling inter() in between.
+ """
+ seq = iter(seq)
+ try:
+ f(next(seq))
+ except StopIteration:
+ pass
+ else:
+ for x in seq:
+ inter()
+ f(x)
+
+class Unparser:
+ """Methods in this class recursively traverse an AST and
+ output source code for the abstract syntax; original formatting
+ is disregarded. """
+
+ def __init__(self, tree, file = sys.stdout):
+ """Unparser(tree, file=sys.stdout) -> None.
+ Print the source for tree to file."""
+ self.f = file
+ self.future_imports = []
+ self._indent = 0
+ self.dispatch(tree)
+ self.f.write("")
+ self.f.flush()
+
+ def fill(self, text = ""):
+ "Indent a piece of text, according to the current indentation level"
+ self.f.write("\n"+" "*self._indent + text)
+
+ def write(self, text):
+ "Append a piece of text to the current line."
+ self.f.write(text)
+
+ def enter(self):
+ "Print ':', and increase the indentation."
+ self.write(":")
+ self._indent += 1
+
+ def leave(self):
+ "Decrease the indentation level."
+ self._indent -= 1
+
+ def dispatch(self, tree):
+ "Dispatcher function, dispatching tree type T to method _T."
+ if isinstance(tree, list):
+ for t in tree:
+ self.dispatch(t)
+ return
+ meth = getattr(self, "_"+tree.__class__.__name__)
+ meth(tree)
+
+
+ ############### Unparsing methods ######################
+ # There should be one method per concrete grammar type #
+ # Constructors should be grouped by sum type. Ideally, #
+ # this would follow the order in the grammar, but #
+ # currently doesn't. #
+ ########################################################
+
+ def _Module(self, tree):
+ for stmt in tree.body:
+ self.dispatch(stmt)
+
+ # stmt
+ def _Expr(self, tree):
+ self.fill()
+ self.dispatch(tree.value)
+
+ def _Import(self, t):
+ self.fill("import ")
+ interleave(lambda: self.write(", "), self.dispatch, t.names)
+
+ def _ImportFrom(self, t):
+ # A from __future__ import may affect unparsing, so record it.
+ if t.module and t.module == '__future__':
+ self.future_imports.extend(n.name for n in t.names)
+
+ self.fill("from ")
+ self.write("." * t.level)
+ if t.module:
+ self.write(t.module)
+ self.write(" import ")
+ interleave(lambda: self.write(", "), self.dispatch, t.names)
+
+ def _Assign(self, t):
+ self.fill()
+ for target in t.targets:
+ self.dispatch(target)
+ self.write(" = ")
+ self.dispatch(t.value)
+
+ def _AugAssign(self, t):
+ self.fill()
+ self.dispatch(t.target)
+ self.write(" "+self.binop[t.op.__class__.__name__]+"= ")
+ self.dispatch(t.value)
+
+ def _Return(self, t):
+ self.fill("return")
+ if t.value:
+ self.write(" ")
+ self.dispatch(t.value)
+
+ def _Pass(self, t):
+ self.fill("pass")
+
+ def _Break(self, t):
+ self.fill("break")
+
+ def _Continue(self, t):
+ self.fill("continue")
+
+ def _Delete(self, t):
+ self.fill("del ")
+ interleave(lambda: self.write(", "), self.dispatch, t.targets)
+
+ def _Assert(self, t):
+ self.fill("assert ")
+ self.dispatch(t.test)
+ if t.msg:
+ self.write(", ")
+ self.dispatch(t.msg)
+
+ def _Exec(self, t):
+ self.fill("exec ")
+ self.dispatch(t.body)
+ if t.globals:
+ self.write(" in ")
+ self.dispatch(t.globals)
+ if t.locals:
+ self.write(", ")
+ self.dispatch(t.locals)
+
+ def _Print(self, t):
+ self.fill("print ")
+ do_comma = False
+ if t.dest:
+ self.write(">>")
+ self.dispatch(t.dest)
+ do_comma = True
+ for e in t.values:
+ if do_comma:self.write(", ")
+ else:do_comma=True
+ self.dispatch(e)
+ if not t.nl:
+ self.write(",")
+
+ def _Global(self, t):
+ self.fill("global ")
+ interleave(lambda: self.write(", "), self.write, t.names)
+
+ def _Yield(self, t):
+ self.write("(")
+ self.write("yield")
+ if t.value:
+ self.write(" ")
+ self.dispatch(t.value)
+ self.write(")")
+
+ def _Raise(self, t):
+ self.fill('raise ')
+ if t.type:
+ self.dispatch(t.type)
+ if t.inst:
+ self.write(", ")
+ self.dispatch(t.inst)
+ if t.tback:
+ self.write(", ")
+ self.dispatch(t.tback)
+
+ def _TryExcept(self, t):
+ self.fill("try")
+ self.enter()
+ self.dispatch(t.body)
+ self.leave()
+
+ for ex in t.handlers:
+ self.dispatch(ex)
+ if t.orelse:
+ self.fill("else")
+ self.enter()
+ self.dispatch(t.orelse)
+ self.leave()
+
+ def _TryFinally(self, t):
+ if len(t.body) == 1 and isinstance(t.body[0], ast.TryExcept):
+ # try-except-finally
+ self.dispatch(t.body)
+ else:
+ self.fill("try")
+ self.enter()
+ self.dispatch(t.body)
+ self.leave()
+
+ self.fill("finally")
+ self.enter()
+ self.dispatch(t.finalbody)
+ self.leave()
+
+ def _ExceptHandler(self, t):
+ self.fill("except")
+ if t.type:
+ self.write(" ")
+ self.dispatch(t.type)
+ if t.name:
+ self.write(" as ")
+ self.dispatch(t.name)
+ self.enter()
+ self.dispatch(t.body)
+ self.leave()
+
+ def _ClassDef(self, t):
+ self.write("\n")
+ for deco in t.decorator_list:
+ self.fill("@")
+ self.dispatch(deco)
+ self.fill("class "+t.name)
+ if t.bases:
+ self.write("(")
+ for a in t.bases:
+ self.dispatch(a)
+ self.write(", ")
+ self.write(")")
+ self.enter()
+ self.dispatch(t.body)
+ self.leave()
+
+ def _FunctionDef(self, t):
+ self.write("\n")
+ for deco in t.decorator_list:
+ self.fill("@")
+ self.dispatch(deco)
+ self.fill("def "+t.name + "(")
+ self.dispatch(t.args)
+ self.write(")")
+ self.enter()
+ self.dispatch(t.body)
+ self.leave()
+
+ def _For(self, t):
+ self.fill("for ")
+ self.dispatch(t.target)
+ self.write(" in ")
+ self.dispatch(t.iter)
+ self.enter()
+ self.dispatch(t.body)
+ self.leave()
+ if t.orelse:
+ self.fill("else")
+ self.enter()
+ self.dispatch(t.orelse)
+ self.leave()
+
+ def _If(self, t):
+ self.fill("if ")
+ self.dispatch(t.test)
+ self.enter()
+ self.dispatch(t.body)
+ self.leave()
+ # collapse nested ifs into equivalent elifs.
+ while (t.orelse and len(t.orelse) == 1 and
+ isinstance(t.orelse[0], ast.If)):
+ t = t.orelse[0]
+ self.fill("elif ")
+ self.dispatch(t.test)
+ self.enter()
+ self.dispatch(t.body)
+ self.leave()
+ # final else
+ if t.orelse:
+ self.fill("else")
+ self.enter()
+ self.dispatch(t.orelse)
+ self.leave()
+
+ def _While(self, t):
+ self.fill("while ")
+ self.dispatch(t.test)
+ self.enter()
+ self.dispatch(t.body)
+ self.leave()
+ if t.orelse:
+ self.fill("else")
+ self.enter()
+ self.dispatch(t.orelse)
+ self.leave()
+
+ def _With(self, t):
+ self.fill("with ")
+ self.dispatch(t.context_expr)
+ if t.optional_vars:
+ self.write(" as ")
+ self.dispatch(t.optional_vars)
+ self.enter()
+ self.dispatch(t.body)
+ self.leave()
+
+ # expr
+ def _Str(self, tree):
+ # if from __future__ import unicode_literals is in effect,
+ # then we want to output string literals using a 'b' prefix
+ # and unicode literals with no prefix.
+ if "unicode_literals" not in self.future_imports:
+ self.write(repr(tree.s))
+ elif isinstance(tree.s, str):
+ self.write("b" + repr(tree.s))
+ elif isinstance(tree.s, unicode):
+ self.write(repr(tree.s).lstrip("u"))
+ else:
+ assert False, "shouldn't get here"
+
+ def _Name(self, t):
+ self.write(t.id)
+
+ def _Repr(self, t):
+ self.write("`")
+ self.dispatch(t.value)
+ self.write("`")
+
+ def _Num(self, t):
+ repr_n = repr(t.n)
+ # Parenthesize negative numbers, to avoid turning (-1)**2 into -1**2.
+ if repr_n.startswith("-"):
+ self.write("(")
+ # Substitute overflowing decimal literal for AST infinities.
+ self.write(repr_n.replace("inf", INFSTR))
+ if repr_n.startswith("-"):
+ self.write(")")
+
+ def _List(self, t):
+ self.write("[")
+ interleave(lambda: self.write(", "), self.dispatch, t.elts)
+ self.write("]")
+
+ def _ListComp(self, t):
+ self.write("[")
+ self.dispatch(t.elt)
+ for gen in t.generators:
+ self.dispatch(gen)
+ self.write("]")
+
+ def _GeneratorExp(self, t):
+ self.write("(")
+ self.dispatch(t.elt)
+ for gen in t.generators:
+ self.dispatch(gen)
+ self.write(")")
+
+ def _SetComp(self, t):
+ self.write("{")
+ self.dispatch(t.elt)
+ for gen in t.generators:
+ self.dispatch(gen)
+ self.write("}")
+
+ def _DictComp(self, t):
+ self.write("{")
+ self.dispatch(t.key)
+ self.write(": ")
+ self.dispatch(t.value)
+ for gen in t.generators:
+ self.dispatch(gen)
+ self.write("}")
+
+ def _comprehension(self, t):
+ self.write(" for ")
+ self.dispatch(t.target)
+ self.write(" in ")
+ self.dispatch(t.iter)
+ for if_clause in t.ifs:
+ self.write(" if ")
+ self.dispatch(if_clause)
+
+ def _IfExp(self, t):
+ self.write("(")
+ self.dispatch(t.body)
+ self.write(" if ")
+ self.dispatch(t.test)
+ self.write(" else ")
+ self.dispatch(t.orelse)
+ self.write(")")
+
+ def _Set(self, t):
+ assert(t.elts) # should be at least one element
+ self.write("{")
+ interleave(lambda: self.write(", "), self.dispatch, t.elts)
+ self.write("}")
+
+ def _Dict(self, t):
+ self.write("{")
+ def write_pair(pair):
+ (k, v) = pair
+ self.dispatch(k)
+ self.write(": ")
+ self.dispatch(v)
+ interleave(lambda: self.write(", "), write_pair, zip(t.keys, t.values))
+ self.write("}")
+
+ def _Tuple(self, t):
+ self.write("(")
+ if len(t.elts) == 1:
+ (elt,) = t.elts
+ self.dispatch(elt)
+ self.write(",")
+ else:
+ interleave(lambda: self.write(", "), self.dispatch, t.elts)
+ self.write(")")
+
+ unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"}
+ def _UnaryOp(self, t):
+ self.write("(")
+ self.write(self.unop[t.op.__class__.__name__])
+ self.write(" ")
+ # If we're applying unary minus to a number, parenthesize the number.
+ # This is necessary: -2147483648 is different from -(2147483648) on
+ # a 32-bit machine (the first is an int, the second a long), and
+ # -7j is different from -(7j). (The first has real part 0.0, the second
+ # has real part -0.0.)
+ if isinstance(t.op, ast.USub) and isinstance(t.operand, ast.Num):
+ self.write("(")
+ self.dispatch(t.operand)
+ self.write(")")
+ else:
+ self.dispatch(t.operand)
+ self.write(")")
+
+ binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%",
+ "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&",
+ "FloorDiv":"//", "Pow": "**"}
+ def _BinOp(self, t):
+ self.write("(")
+ self.dispatch(t.left)
+ self.write(" " + self.binop[t.op.__class__.__name__] + " ")
+ self.dispatch(t.right)
+ self.write(")")
+
+ cmpops = {"Eq":"==", "NotEq":"!=", "Lt":"<", "LtE":"<=", "Gt":">", "GtE":">=",
+ "Is":"is", "IsNot":"is not", "In":"in", "NotIn":"not in"}
+ def _Compare(self, t):
+ self.write("(")
+ self.dispatch(t.left)
+ for o, e in zip(t.ops, t.comparators):
+ self.write(" " + self.cmpops[o.__class__.__name__] + " ")
+ self.dispatch(e)
+ self.write(")")
+
+ boolops = {ast.And: 'and', ast.Or: 'or'}
+ def _BoolOp(self, t):
+ self.write("(")
+ s = " %s " % self.boolops[t.op.__class__]
+ interleave(lambda: self.write(s), self.dispatch, t.values)
+ self.write(")")
+
+ def _Attribute(self,t):
+ self.dispatch(t.value)
+ # Special case: 3.__abs__() is a syntax error, so if t.value
+ # is an integer literal then we need to either parenthesize
+ # it or add an extra space to get 3 .__abs__().
+ if isinstance(t.value, ast.Num) and isinstance(t.value.n, int):
+ self.write(" ")
+ self.write(".")
+ self.write(t.attr)
+
+ def _Call(self, t):
+ self.dispatch(t.func)
+ self.write("(")
+ comma = False
+ for e in t.args:
+ if comma: self.write(", ")
+ else: comma = True
+ self.dispatch(e)
+ for e in t.keywords:
+ if comma: self.write(", ")
+ else: comma = True
+ self.dispatch(e)
+ if t.starargs:
+ if comma: self.write(", ")
+ else: comma = True
+ self.write("*")
+ self.dispatch(t.starargs)
+ if t.kwargs:
+ if comma: self.write(", ")
+ else: comma = True
+ self.write("**")
+ self.dispatch(t.kwargs)
+ self.write(")")
+
+ def _Subscript(self, t):
+ self.dispatch(t.value)
+ self.write("[")
+ self.dispatch(t.slice)
+ self.write("]")
+
+ # slice
+ def _Ellipsis(self, t):
+ self.write("...")
+
+ def _Index(self, t):
+ self.dispatch(t.value)
+
+ def _Slice(self, t):
+ if t.lower:
+ self.dispatch(t.lower)
+ self.write(":")
+ if t.upper:
+ self.dispatch(t.upper)
+ if t.step:
+ self.write(":")
+ self.dispatch(t.step)
+
+ def _ExtSlice(self, t):
+ interleave(lambda: self.write(', '), self.dispatch, t.dims)
+
+ # others
+ def _arguments(self, t):
+ first = True
+ # normal arguments
+ defaults = [None] * (len(t.args) - len(t.defaults)) + t.defaults
+ for a,d in zip(t.args, defaults):
+ if first:first = False
+ else: self.write(", ")
+ self.dispatch(a),
+ if d:
+ self.write("=")
+ self.dispatch(d)
+
+ # varargs
+ if t.vararg:
+ if first:first = False
+ else: self.write(", ")
+ self.write("*")
+ self.write(t.vararg)
+
+ # kwargs
+ if t.kwarg:
+ if first:first = False
+ else: self.write(", ")
+ self.write("**"+t.kwarg)
+
+ def _keyword(self, t):
+ self.write(t.arg)
+ self.write("=")
+ self.dispatch(t.value)
+
+ def _Lambda(self, t):
+ self.write("(")
+ self.write("lambda ")
+ self.dispatch(t.args)
+ self.write(": ")
+ self.dispatch(t.body)
+ self.write(")")
+
+ def _alias(self, t):
+ self.write(t.name)
+ if t.asname:
+ self.write(" as "+t.asname)
+
+def roundtrip(filename, output=sys.stdout):
+ with open(filename, "r") as pyfile:
+ source = pyfile.read()
+ tree = compile(source, filename, "exec", ast.PyCF_ONLY_AST)
+ Unparser(tree, output)
+
+
+
+def testdir(a):
+ try:
+ names = [n for n in os.listdir(a) if n.endswith('.py')]
+ except OSError:
+ sys.stderr.write("Directory not readable: %s" % a)
+ else:
+ for n in names:
+ fullname = os.path.join(a, n)
+ if os.path.isfile(fullname):
+ output = cStringIO.StringIO()
+ print 'Testing %s' % fullname
+ try:
+ roundtrip(fullname, output)
+ except Exception as e:
+ print ' Failed to compile, exception is %s' % repr(e)
+ elif os.path.isdir(fullname):
+ testdir(fullname)
+
+def main(args):
+ if args[0] == '--testdir':
+ for a in args[1:]:
+ testdir(a)
+ else:
+ for a in args:
+ roundtrip(a)
+
+if __name__=='__main__':
+ main(sys.argv[1:])
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/FSProxy.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/FSProxy.py
new file mode 100644
index 0000000000..58354e1e31
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/FSProxy.py
@@ -0,0 +1,301 @@
+"""File System Proxy.
+
+Provide an OS-neutral view on a file system, locally or remotely.
+The functionality is geared towards implementing some sort of
+rdist-like utility between a Mac and a UNIX system.
+
+The module defines three classes:
+
+FSProxyLocal -- used for local access
+FSProxyServer -- used on the server side of remote access
+FSProxyClient -- used on the client side of remote access
+
+The remote classes are instantiated with an IP address and an optional
+verbosity flag.
+"""
+
+import server
+import client
+import md5
+import os
+import fnmatch
+from stat import *
+import time
+import fnmatch
+
+maxnamelen = 255
+
+skipnames = (os.curdir, os.pardir)
+
+
+class FSProxyLocal:
+
+ def __init__(self):
+ self._dirstack = []
+ self._ignore = ['*.pyc'] + self._readignore()
+
+ def _close(self):
+ while self._dirstack:
+ self.back()
+
+ def _readignore(self):
+ file = self._hide('ignore')
+ try:
+ f = open(file)
+ except IOError:
+ file = self._hide('synctree.ignorefiles')
+ try:
+ f = open(file)
+ except IOError:
+ return []
+ ignore = []
+ while 1:
+ line = f.readline()
+ if not line: break
+ if line[-1] == '\n': line = line[:-1]
+ ignore.append(line)
+ f.close()
+ return ignore
+
+ def _hidden(self, name):
+ return name[0] == '.'
+
+ def _hide(self, name):
+ return '.%s' % name
+
+ def visible(self, name):
+ if len(name) > maxnamelen: return 0
+ if name[-1] == '~': return 0
+ if name in skipnames: return 0
+ if self._hidden(name): return 0
+ head, tail = os.path.split(name)
+ if head or not tail: return 0
+ if os.path.islink(name): return 0
+ if '\0' in open(name, 'rb').read(512): return 0
+ for ign in self._ignore:
+ if fnmatch.fnmatch(name, ign): return 0
+ return 1
+
+ def check(self, name):
+ if not self.visible(name):
+ raise os.error, "protected name %s" % repr(name)
+
+ def checkfile(self, name):
+ self.check(name)
+ if not os.path.isfile(name):
+ raise os.error, "not a plain file %s" % repr(name)
+
+ def pwd(self):
+ return os.getcwd()
+
+ def cd(self, name):
+ self.check(name)
+ save = os.getcwd(), self._ignore
+ os.chdir(name)
+ self._dirstack.append(save)
+ self._ignore = self._ignore + self._readignore()
+
+ def back(self):
+ if not self._dirstack:
+ raise os.error, "empty directory stack"
+ dir, ignore = self._dirstack[-1]
+ os.chdir(dir)
+ del self._dirstack[-1]
+ self._ignore = ignore
+
+ def _filter(self, files, pat = None):
+ if pat:
+ def keep(name, pat = pat):
+ return fnmatch.fnmatch(name, pat)
+ files = filter(keep, files)
+ files = filter(self.visible, files)
+ files.sort()
+ return files
+
+ def list(self, pat = None):
+ files = os.listdir(os.curdir)
+ return self._filter(files, pat)
+
+ def listfiles(self, pat = None):
+ files = os.listdir(os.curdir)
+ files = filter(os.path.isfile, files)
+ return self._filter(files, pat)
+
+ def listsubdirs(self, pat = None):
+ files = os.listdir(os.curdir)
+ files = filter(os.path.isdir, files)
+ return self._filter(files, pat)
+
+ def exists(self, name):
+ return self.visible(name) and os.path.exists(name)
+
+ def isdir(self, name):
+ return self.visible(name) and os.path.isdir(name)
+
+ def islink(self, name):
+ return self.visible(name) and os.path.islink(name)
+
+ def isfile(self, name):
+ return self.visible(name) and os.path.isfile(name)
+
+ def sum(self, name):
+ self.checkfile(name)
+ BUFFERSIZE = 1024*8
+ f = open(name)
+ sum = md5.new()
+ while 1:
+ buffer = f.read(BUFFERSIZE)
+ if not buffer:
+ break
+ sum.update(buffer)
+ return sum.digest()
+
+ def size(self, name):
+ self.checkfile(name)
+ return os.stat(name)[ST_SIZE]
+
+ def mtime(self, name):
+ self.checkfile(name)
+ return time.localtime(os.stat(name)[ST_MTIME])
+
+ def stat(self, name):
+ self.checkfile(name)
+ size = os.stat(name)[ST_SIZE]
+ mtime = time.localtime(os.stat(name)[ST_MTIME])
+ return size, mtime
+
+ def info(self, name):
+ sum = self.sum(name)
+ size = os.stat(name)[ST_SIZE]
+ mtime = time.localtime(os.stat(name)[ST_MTIME])
+ return sum, size, mtime
+
+ def _list(self, function, list):
+ if list is None:
+ list = self.listfiles()
+ res = []
+ for name in list:
+ try:
+ res.append((name, function(name)))
+ except (os.error, IOError):
+ res.append((name, None))
+ return res
+
+ def sumlist(self, list = None):
+ return self._list(self.sum, list)
+
+ def statlist(self, list = None):
+ return self._list(self.stat, list)
+
+ def mtimelist(self, list = None):
+ return self._list(self.mtime, list)
+
+ def sizelist(self, list = None):
+ return self._list(self.size, list)
+
+ def infolist(self, list = None):
+ return self._list(self.info, list)
+
+ def _dict(self, function, list):
+ if list is None:
+ list = self.listfiles()
+ dict = {}
+ for name in list:
+ try:
+ dict[name] = function(name)
+ except (os.error, IOError):
+ pass
+ return dict
+
+ def sumdict(self, list = None):
+ return self.dict(self.sum, list)
+
+ def sizedict(self, list = None):
+ return self.dict(self.size, list)
+
+ def mtimedict(self, list = None):
+ return self.dict(self.mtime, list)
+
+ def statdict(self, list = None):
+ return self.dict(self.stat, list)
+
+ def infodict(self, list = None):
+ return self._dict(self.info, list)
+
+ def read(self, name, offset = 0, length = -1):
+ self.checkfile(name)
+ f = open(name)
+ f.seek(offset)
+ if length == 0:
+ data = ''
+ elif length < 0:
+ data = f.read()
+ else:
+ data = f.read(length)
+ f.close()
+ return data
+
+ def create(self, name):
+ self.check(name)
+ if os.path.exists(name):
+ self.checkfile(name)
+ bname = name + '~'
+ try:
+ os.unlink(bname)
+ except os.error:
+ pass
+ os.rename(name, bname)
+ f = open(name, 'w')
+ f.close()
+
+ def write(self, name, data, offset = 0):
+ self.checkfile(name)
+ f = open(name, 'r+')
+ f.seek(offset)
+ f.write(data)
+ f.close()
+
+ def mkdir(self, name):
+ self.check(name)
+ os.mkdir(name, 0777)
+
+ def rmdir(self, name):
+ self.check(name)
+ os.rmdir(name)
+
+
+class FSProxyServer(FSProxyLocal, server.Server):
+
+ def __init__(self, address, verbose = server.VERBOSE):
+ FSProxyLocal.__init__(self)
+ server.Server.__init__(self, address, verbose)
+
+ def _close(self):
+ server.Server._close(self)
+ FSProxyLocal._close(self)
+
+ def _serve(self):
+ server.Server._serve(self)
+ # Retreat into start directory
+ while self._dirstack: self.back()
+
+
+class FSProxyClient(client.Client):
+
+ def __init__(self, address, verbose = client.VERBOSE):
+ client.Client.__init__(self, address, verbose)
+
+
+def test():
+ import string
+ import sys
+ if sys.argv[1:]:
+ port = string.atoi(sys.argv[1])
+ else:
+ port = 4127
+ proxy = FSProxyServer(('', port))
+ proxy._serverloop()
+
+
+if __name__ == '__main__':
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/RCSProxy.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/RCSProxy.py
new file mode 100644
index 0000000000..b4b0d92b7e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/RCSProxy.py
@@ -0,0 +1,198 @@
+#! /usr/bin/env python
+
+"""RCS Proxy.
+
+Provide a simplified interface on RCS files, locally or remotely.
+The functionality is geared towards implementing some sort of
+remote CVS like utility. It is modeled after the similar module
+FSProxy.
+
+The module defines two classes:
+
+RCSProxyLocal -- used for local access
+RCSProxyServer -- used on the server side of remote access
+
+The corresponding client class, RCSProxyClient, is defined in module
+rcsclient.
+
+The remote classes are instantiated with an IP address and an optional
+verbosity flag.
+"""
+
+import server
+import md5
+import os
+import fnmatch
+import string
+import tempfile
+import rcslib
+
+
+class DirSupport:
+
+ def __init__(self):
+ self._dirstack = []
+
+ def __del__(self):
+ self._close()
+
+ def _close(self):
+ while self._dirstack:
+ self.back()
+
+ def pwd(self):
+ return os.getcwd()
+
+ def cd(self, name):
+ save = os.getcwd()
+ os.chdir(name)
+ self._dirstack.append(save)
+
+ def back(self):
+ if not self._dirstack:
+ raise os.error, "empty directory stack"
+ dir = self._dirstack[-1]
+ os.chdir(dir)
+ del self._dirstack[-1]
+
+ def listsubdirs(self, pat = None):
+ files = os.listdir(os.curdir)
+ files = filter(os.path.isdir, files)
+ return self._filter(files, pat)
+
+ def isdir(self, name):
+ return os.path.isdir(name)
+
+ def mkdir(self, name):
+ os.mkdir(name, 0777)
+
+ def rmdir(self, name):
+ os.rmdir(name)
+
+
+class RCSProxyLocal(rcslib.RCS, DirSupport):
+
+ def __init__(self):
+ rcslib.RCS.__init__(self)
+ DirSupport.__init__(self)
+
+ def __del__(self):
+ DirSupport.__del__(self)
+ rcslib.RCS.__del__(self)
+
+ def sumlist(self, list = None):
+ return self._list(self.sum, list)
+
+ def sumdict(self, list = None):
+ return self._dict(self.sum, list)
+
+ def sum(self, name_rev):
+ f = self._open(name_rev)
+ BUFFERSIZE = 1024*8
+ sum = md5.new()
+ while 1:
+ buffer = f.read(BUFFERSIZE)
+ if not buffer:
+ break
+ sum.update(buffer)
+ self._closepipe(f)
+ return sum.digest()
+
+ def get(self, name_rev):
+ f = self._open(name_rev)
+ data = f.read()
+ self._closepipe(f)
+ return data
+
+ def put(self, name_rev, data, message=None):
+ name, rev = self._unmangle(name_rev)
+ f = open(name, 'w')
+ f.write(data)
+ f.close()
+ self.checkin(name_rev, message)
+ self._remove(name)
+
+ def _list(self, function, list = None):
+ """INTERNAL: apply FUNCTION to all files in LIST.
+
+ Return a list of the results.
+
+ The list defaults to all files in the directory if None.
+
+ """
+ if list is None:
+ list = self.listfiles()
+ res = []
+ for name in list:
+ try:
+ res.append((name, function(name)))
+ except (os.error, IOError):
+ res.append((name, None))
+ return res
+
+ def _dict(self, function, list = None):
+ """INTERNAL: apply FUNCTION to all files in LIST.
+
+ Return a dictionary mapping files to results.
+
+ The list defaults to all files in the directory if None.
+
+ """
+ if list is None:
+ list = self.listfiles()
+ dict = {}
+ for name in list:
+ try:
+ dict[name] = function(name)
+ except (os.error, IOError):
+ pass
+ return dict
+
+
+class RCSProxyServer(RCSProxyLocal, server.SecureServer):
+
+ def __init__(self, address, verbose = server.VERBOSE):
+ RCSProxyLocal.__init__(self)
+ server.SecureServer.__init__(self, address, verbose)
+
+ def _close(self):
+ server.SecureServer._close(self)
+ RCSProxyLocal._close(self)
+
+ def _serve(self):
+ server.SecureServer._serve(self)
+ # Retreat into start directory
+ while self._dirstack: self.back()
+
+
+def test_server():
+ import string
+ import sys
+ if sys.argv[1:]:
+ port = string.atoi(sys.argv[1])
+ else:
+ port = 4127
+ proxy = RCSProxyServer(('', port))
+ proxy._serverloop()
+
+
+def test():
+ import sys
+ if not sys.argv[1:] or sys.argv[1] and sys.argv[1][0] in '0123456789':
+ test_server()
+ sys.exit(0)
+ proxy = RCSProxyLocal()
+ what = sys.argv[1]
+ if hasattr(proxy, what):
+ attr = getattr(proxy, what)
+ if callable(attr):
+ print apply(attr, tuple(sys.argv[2:]))
+ else:
+ print repr(attr)
+ else:
+ print "%s: no such attribute" % what
+ sys.exit(2)
+
+
+if __name__ == '__main__':
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/README b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/README
new file mode 100644
index 0000000000..c8137e9a84
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/README
@@ -0,0 +1,121 @@
+Filesystem, RCS and CVS client and server classes
+=================================================
+
+*** See the security warning at the end of this file! ***
+
+This directory contains various modules and classes that support
+remote file system operations.
+
+CVS stuff
+---------
+
+rcvs Script to put in your bin directory
+rcvs.py Remote CVS client command line interface
+
+cvslib.py CVS admin files classes (used by rrcs)
+cvslock.py CVS locking algorithms
+
+RCS stuff
+---------
+
+rrcs Script to put in your bin directory
+rrcs.py Remote RCS client command line interface
+
+rcsclient.py Return an RCSProxyClient instance
+ (has reasonable default server/port/directory)
+
+RCSProxy.py RCS proxy and server classes (on top of rcslib.py)
+
+rcslib.py Local-only RCS base class (affects stdout &
+ local work files)
+
+FSProxy stuff
+-------------
+
+sumtree.py Old demo for FSProxy
+cmptree.py First FSProxy client (used to sync from the Mac)
+FSProxy.py Filesystem interface classes
+
+Generic client/server stuff
+---------------------------
+
+client.py Client class
+server.py Server class
+
+security.py Security mix-in class (not very secure I think)
+
+Other generic stuff
+-------------------
+
+cmdfw.py CommandFrameWork class
+ (used by rcvs, should be used by rrcs as well)
+
+
+Client/Server operation
+-----------------------
+
+The Client and Server classes implement a simple-minded RPC protocol,
+using Python's pickle module to transfer arguments, return values and
+exceptions with the most generality. The Server class is instantiated
+with a port number on which it should listen for requests; the Client
+class is instantiated with a host name and a port number where it
+should connect to. Once a client is connected, a TCP connection is
+maintained between client and server.
+
+The Server class currently handles only one connection at a time;
+however it could be rewritten to allow various modes of operations,
+using multiple threads or processes or the select() system call as
+desired to serve multiple clients simultaneously (when using select(),
+still handling one request at a time). This would not require
+rewriting of the Client class. It may also be possible to adapt the
+code to use UDP instead of TCP, but then both classes will have to be
+rewritten (and unless extensive acknowlegements and request serial
+numbers are used, the server should handle duplicate requests, so its
+semantics should be idempotent -- shrudder).
+
+Even though the FSProxy and RCSProxy modules define client classes,
+the client class is fully generic -- what methods it supports is
+determined entirely by the server. The server class, however, must be
+derived from. This is generally done as follows:
+
+ from server import Server
+ from client import Client
+
+ # Define a class that performs the operations locally
+ class MyClassLocal:
+ def __init__(self): ...
+ def _close(self): ...
+
+ # Derive a server class using multiple inheritance
+ class MyClassServer(MyClassLocal, Server):
+ def __init__(self, address):
+ # Must initialize MyClassLocal as well as Server
+ MyClassLocal.__init__(self)
+ Server.__init__(self, address)
+ def _close(self):
+ Server._close()
+ MyClassLocal._close()
+
+ # A dummy client class
+ class MyClassClient(Client): pass
+
+Note that because MyClassLocal isn't used in the definition of
+MyClassClient, it would actually be better to place it in a separate
+module so the definition of MyClassLocal isn't executed when we only
+instantiate a client.
+
+The modules client and server should probably be renamed to Client and
+Server in order to match the class names.
+
+
+*** Security warning: this version requires that you have a file
+$HOME/.python_keyfile at the server and client side containing two
+comma- separated numbers. The security system at the moment makes no
+guarantees of actuallng being secure -- however it requires that the
+key file exists and contains the same numbers at both ends for this to
+work. (You can specify an alternative keyfile in $PYTHON_KEYFILE).
+Have a look at the Security class in security.py for details;
+basically, if the key file contains (x, y), then the security server
+class chooses a random number z (the challenge) in the range
+10..100000 and the client must be able to produce pow(z, x, y)
+(i.e. z**x mod y).
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/client.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/client.py
new file mode 100644
index 0000000000..41a5bcc2c8
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/client.py
@@ -0,0 +1,157 @@
+"""RPC Client module."""
+
+import sys
+import socket
+import pickle
+import __builtin__
+import os
+
+
+# Default verbosity (0 = silent, 1 = print connections, 2 = print requests too)
+VERBOSE = 1
+
+
+class Client:
+
+ """RPC Client class. No need to derive a class -- it's fully generic."""
+
+ def __init__(self, address, verbose = VERBOSE):
+ self._pre_init(address, verbose)
+ self._post_init()
+
+ def _pre_init(self, address, verbose = VERBOSE):
+ if type(address) == type(0):
+ address = ('', address)
+ self._address = address
+ self._verbose = verbose
+ if self._verbose: print "Connecting to %s ..." % repr(address)
+ self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self._socket.connect(address)
+ if self._verbose: print "Connected."
+ self._lastid = 0 # Last id for which a reply has been received
+ self._nextid = 1 # Id of next request
+ self._replies = {} # Unprocessed replies
+ self._rf = self._socket.makefile('r')
+ self._wf = self._socket.makefile('w')
+
+ def _post_init(self):
+ self._methods = self._call('.methods')
+
+ def __del__(self):
+ self._close()
+
+ def _close(self):
+ if self._rf: self._rf.close()
+ self._rf = None
+ if self._wf: self._wf.close()
+ self._wf = None
+ if self._socket: self._socket.close()
+ self._socket = None
+
+ def __getattr__(self, name):
+ if name in self._methods:
+ method = _stub(self, name)
+ setattr(self, name, method) # XXX circular reference
+ return method
+ raise AttributeError, name
+
+ def _setverbose(self, verbose):
+ self._verbose = verbose
+
+ def _call(self, name, *args):
+ return self._vcall(name, args)
+
+ def _vcall(self, name, args):
+ return self._recv(self._vsend(name, args))
+
+ def _send(self, name, *args):
+ return self._vsend(name, args)
+
+ def _send_noreply(self, name, *args):
+ return self._vsend(name, args, 0)
+
+ def _vsend_noreply(self, name, args):
+ return self._vsend(name, args, 0)
+
+ def _vsend(self, name, args, wantreply = 1):
+ id = self._nextid
+ self._nextid = id+1
+ if not wantreply: id = -id
+ request = (name, args, id)
+ if self._verbose > 1: print "sending request: %s" % repr(request)
+ wp = pickle.Pickler(self._wf)
+ wp.dump(request)
+ return id
+
+ def _recv(self, id):
+ exception, value, rid = self._vrecv(id)
+ if rid != id:
+ raise RuntimeError, "request/reply id mismatch: %d/%d" % (id, rid)
+ if exception is None:
+ return value
+ x = exception
+ if hasattr(__builtin__, exception):
+ x = getattr(__builtin__, exception)
+ elif exception in ('posix.error', 'mac.error'):
+ x = os.error
+ if x == exception:
+ exception = x
+ raise exception, value
+
+ def _vrecv(self, id):
+ self._flush()
+ if self._replies.has_key(id):
+ if self._verbose > 1: print "retrieving previous reply, id = %d" % id
+ reply = self._replies[id]
+ del self._replies[id]
+ return reply
+ aid = abs(id)
+ while 1:
+ if self._verbose > 1: print "waiting for reply, id = %d" % id
+ rp = pickle.Unpickler(self._rf)
+ reply = rp.load()
+ del rp
+ if self._verbose > 1: print "got reply: %s" % repr(reply)
+ rid = reply[2]
+ arid = abs(rid)
+ if arid == aid:
+ if self._verbose > 1: print "got it"
+ return reply
+ self._replies[rid] = reply
+ if arid > aid:
+ if self._verbose > 1: print "got higher id, assume all ok"
+ return (None, None, id)
+
+ def _flush(self):
+ self._wf.flush()
+
+
+from security import Security
+
+
+class SecureClient(Client, Security):
+
+ def __init__(self, *args):
+ import string
+ apply(self._pre_init, args)
+ Security.__init__(self)
+ self._wf.flush()
+ line = self._rf.readline()
+ challenge = string.atoi(string.strip(line))
+ response = self._encode_challenge(challenge)
+ line = repr(long(response))
+ if line[-1] in 'Ll': line = line[:-1]
+ self._wf.write(line + '\n')
+ self._wf.flush()
+ self._post_init()
+
+class _stub:
+
+ """Helper class for Client -- each instance serves as a method of the client."""
+
+ def __init__(self, client, name):
+ self._client = client
+ self._name = name
+
+ def __call__(self, *args):
+ return self._client._vcall(self._name, args)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cmdfw.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cmdfw.py
new file mode 100644
index 0000000000..96cc257db1
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cmdfw.py
@@ -0,0 +1,144 @@
+"Framework for command line interfaces like CVS. See class CmdFrameWork."
+
+
+class CommandFrameWork:
+
+ """Framework class for command line interfaces like CVS.
+
+ The general command line structure is
+
+ command [flags] subcommand [subflags] [argument] ...
+
+ There's a class variable GlobalFlags which specifies the
+ global flags options. Subcommands are defined by defining
+ methods named do_. Flags for the subcommand are
+ defined by defining class or instance variables named
+ flags_. If there's no command, method default()
+ is called. The __doc__ strings for the do_ methods are used
+ for the usage message, printed after the general usage message
+ which is the class variable UsageMessage. The class variable
+ PostUsageMessage is printed after all the do_ methods' __doc__
+ strings. The method's return value can be a suggested exit
+ status. [XXX Need to rewrite this to clarify it.]
+
+ Common usage is to derive a class, instantiate it, and then call its
+ run() method; by default this takes its arguments from sys.argv[1:].
+ """
+
+ UsageMessage = \
+ "usage: (name)s [flags] subcommand [subflags] [argument] ..."
+
+ PostUsageMessage = None
+
+ GlobalFlags = ''
+
+ def __init__(self):
+ """Constructor, present for completeness."""
+ pass
+
+ def run(self, args = None):
+ """Process flags, subcommand and options, then run it."""
+ import getopt, sys
+ if args is None: args = sys.argv[1:]
+ try:
+ opts, args = getopt.getopt(args, self.GlobalFlags)
+ except getopt.error, msg:
+ return self.usage(msg)
+ self.options(opts)
+ if not args:
+ self.ready()
+ return self.default()
+ else:
+ cmd = args[0]
+ mname = 'do_' + cmd
+ fname = 'flags_' + cmd
+ try:
+ method = getattr(self, mname)
+ except AttributeError:
+ return self.usage("command %r unknown" % (cmd,))
+ try:
+ flags = getattr(self, fname)
+ except AttributeError:
+ flags = ''
+ try:
+ opts, args = getopt.getopt(args[1:], flags)
+ except getopt.error, msg:
+ return self.usage(
+ "subcommand %s: " % cmd + str(msg))
+ self.ready()
+ return method(opts, args)
+
+ def options(self, opts):
+ """Process the options retrieved by getopt.
+ Override this if you have any options."""
+ if opts:
+ print "-"*40
+ print "Options:"
+ for o, a in opts:
+ print 'option', o, 'value', repr(a)
+ print "-"*40
+
+ def ready(self):
+ """Called just before calling the subcommand."""
+ pass
+
+ def usage(self, msg = None):
+ """Print usage message. Return suitable exit code (2)."""
+ if msg: print msg
+ print self.UsageMessage % {'name': self.__class__.__name__}
+ docstrings = {}
+ c = self.__class__
+ while 1:
+ for name in dir(c):
+ if name[:3] == 'do_':
+ if docstrings.has_key(name):
+ continue
+ try:
+ doc = getattr(c, name).__doc__
+ except:
+ doc = None
+ if doc:
+ docstrings[name] = doc
+ if not c.__bases__:
+ break
+ c = c.__bases__[0]
+ if docstrings:
+ print "where subcommand can be:"
+ names = docstrings.keys()
+ names.sort()
+ for name in names:
+ print docstrings[name]
+ if self.PostUsageMessage:
+ print self.PostUsageMessage
+ return 2
+
+ def default(self):
+ """Default method, called when no subcommand is given.
+ You should always override this."""
+ print "Nobody expects the Spanish Inquisition!"
+
+
+def test():
+ """Test script -- called when this module is run as a script."""
+ import sys
+ class Hello(CommandFrameWork):
+ def do_hello(self, opts, args):
+ "hello -- print 'hello world', needs no arguments"
+ print "Hello, world"
+ x = Hello()
+ tests = [
+ [],
+ ['hello'],
+ ['spam'],
+ ['-x'],
+ ['hello', '-x'],
+ None,
+ ]
+ for t in tests:
+ print '-'*10, t, '-'*10
+ sts = x.run(t)
+ print "Exit status:", repr(sts)
+
+
+if __name__ == '__main__':
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cmptree.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cmptree.py
new file mode 100644
index 0000000000..2f8a8a83b9
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cmptree.py
@@ -0,0 +1,208 @@
+"""Compare local and remote dictionaries and transfer differing files -- like rdist."""
+
+import sys
+from repr import repr
+import FSProxy
+import time
+import os
+
+def main():
+ pwd = os.getcwd()
+ s = raw_input("chdir [%s] " % pwd)
+ if s:
+ os.chdir(s)
+ pwd = os.getcwd()
+ host = ask("host", 'voorn.cwi.nl')
+ port = 4127
+ verbose = 1
+ mode = ''
+ print """\
+Mode should be a string of characters, indicating what to do with differences.
+r - read different files to local file system
+w - write different files to remote file system
+c - create new files, either remote or local
+d - delete disappearing files, either remote or local
+"""
+ s = raw_input("mode [%s] " % mode)
+ if s: mode = s
+ address = (host, port)
+ t1 = time.time()
+ local = FSProxy.FSProxyLocal()
+ remote = FSProxy.FSProxyClient(address, verbose)
+ compare(local, remote, mode)
+ remote._close()
+ local._close()
+ t2 = time.time()
+ dt = t2-t1
+ mins, secs = divmod(dt, 60)
+ print mins, "minutes and", round(secs), "seconds"
+ raw_input("[Return to exit] ")
+
+def ask(prompt, default):
+ s = raw_input("%s [%s] " % (prompt, default))
+ return s or default
+
+def askint(prompt, default):
+ s = raw_input("%s [%s] " % (prompt, str(default)))
+ if s: return string.atoi(s)
+ return default
+
+def compare(local, remote, mode):
+ print
+ print "PWD =", repr(os.getcwd())
+ sums_id = remote._send('sumlist')
+ subdirs_id = remote._send('listsubdirs')
+ remote._flush()
+ print "calculating local sums ..."
+ lsumdict = {}
+ for name, info in local.sumlist():
+ lsumdict[name] = info
+ print "getting remote sums ..."
+ sums = remote._recv(sums_id)
+ print "got", len(sums)
+ rsumdict = {}
+ for name, rsum in sums:
+ rsumdict[name] = rsum
+ if not lsumdict.has_key(name):
+ print repr(name), "only remote"
+ if 'r' in mode and 'c' in mode:
+ recvfile(local, remote, name)
+ else:
+ lsum = lsumdict[name]
+ if lsum != rsum:
+ print repr(name),
+ rmtime = remote.mtime(name)
+ lmtime = local.mtime(name)
+ if rmtime > lmtime:
+ print "remote newer",
+ if 'r' in mode:
+ recvfile(local, remote, name)
+ elif lmtime > rmtime:
+ print "local newer",
+ if 'w' in mode:
+ sendfile(local, remote, name)
+ else:
+ print "same mtime but different sum?!?!",
+ print
+ for name in lsumdict.keys():
+ if not rsumdict.keys():
+ print repr(name), "only locally",
+ fl()
+ if 'w' in mode and 'c' in mode:
+ sendfile(local, remote, name)
+ elif 'r' in mode and 'd' in mode:
+ os.unlink(name)
+ print "removed."
+ print
+ print "gettin subdirs ..."
+ subdirs = remote._recv(subdirs_id)
+ common = []
+ for name in subdirs:
+ if local.isdir(name):
+ print "Common subdirectory", repr(name)
+ common.append(name)
+ else:
+ print "Remote subdirectory", repr(name), "not found locally"
+ if 'r' in mode and 'c' in mode:
+ pr = "Create local subdirectory %s? [y] " % \
+ repr(name)
+ if 'y' in mode:
+ ok = 'y'
+ else:
+ ok = ask(pr, "y")
+ if ok[:1] in ('y', 'Y'):
+ local.mkdir(name)
+ print "Subdirectory %s made" % \
+ repr(name)
+ common.append(name)
+ lsubdirs = local.listsubdirs()
+ for name in lsubdirs:
+ if name not in subdirs:
+ print "Local subdirectory", repr(name), "not found remotely"
+ for name in common:
+ print "Entering subdirectory", repr(name)
+ local.cd(name)
+ remote.cd(name)
+ compare(local, remote, mode)
+ remote.back()
+ local.back()
+
+def sendfile(local, remote, name):
+ try:
+ remote.create(name)
+ except (IOError, os.error), msg:
+ print "cannot create:", msg
+ return
+
+ print "sending ...",
+ fl()
+
+ data = open(name).read()
+
+ t1 = time.time()
+
+ remote._send_noreply('write', name, data)
+ remote._flush()
+
+ t2 = time.time()
+
+ dt = t2-t1
+ print len(data), "bytes in", round(dt), "seconds",
+ if dt:
+ print "i.e.", round(len(data)/dt), "bytes/sec",
+ print
+
+def recvfile(local, remote, name):
+ ok = 0
+ try:
+ rv = recvfile_real(local, remote, name)
+ ok = 1
+ return rv
+ finally:
+ if not ok:
+ print "*** recvfile of %r failed, deleting" % (name,)
+ local.delete(name)
+
+def recvfile_real(local, remote, name):
+ try:
+ local.create(name)
+ except (IOError, os.error), msg:
+ print "cannot create:", msg
+ return
+
+ print "receiving ...",
+ fl()
+
+ f = open(name, 'w')
+ t1 = time.time()
+
+ length = 4*1024
+ offset = 0
+ id = remote._send('read', name, offset, length)
+ remote._flush()
+ while 1:
+ newoffset = offset + length
+ newid = remote._send('read', name, newoffset, length)
+ data = remote._recv(id)
+ id = newid
+ if not data: break
+ f.seek(offset)
+ f.write(data)
+ offset = newoffset
+ size = f.tell()
+
+ t2 = time.time()
+ f.close()
+
+ dt = t2-t1
+ print size, "bytes in", round(dt), "seconds",
+ if dt:
+ print "i.e.", size//dt, "bytes/sec",
+ print
+ remote._recv(id) # ignored
+
+def fl():
+ sys.stdout.flush()
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cvslib.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cvslib.py
new file mode 100644
index 0000000000..41c5979baf
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cvslib.py
@@ -0,0 +1,364 @@
+"""Utilities for CVS administration."""
+
+import string
+import os
+import time
+import md5
+import fnmatch
+
+if not hasattr(time, 'timezone'):
+ time.timezone = 0
+
+class File:
+
+ """Represent a file's status.
+
+ Instance variables:
+
+ file -- the filename (no slashes), None if uninitialized
+ lseen -- true if the data for the local file is up to date
+ eseen -- true if the data from the CVS/Entries entry is up to date
+ (this implies that the entry must be written back)
+ rseen -- true if the data for the remote file is up to date
+ proxy -- RCSProxy instance used to contact the server, or None
+
+ Note that lseen and rseen don't necessary mean that a local
+ or remote file *exists* -- they indicate that we've checked it.
+ However, eseen means that this instance corresponds to an
+ entry in the CVS/Entries file.
+
+ If lseen is true:
+
+ lsum -- checksum of the local file, None if no local file
+ lctime -- ctime of the local file, None if no local file
+ lmtime -- mtime of the local file, None if no local file
+
+ If eseen is true:
+
+ erev -- revision, None if this is a no revision (not '0')
+ enew -- true if this is an uncommitted added file
+ edeleted -- true if this is an uncommitted removed file
+ ectime -- ctime of last local file corresponding to erev
+ emtime -- mtime of last local file corresponding to erev
+ extra -- 5th string from CVS/Entries file
+
+ If rseen is true:
+
+ rrev -- revision of head, None if non-existent
+ rsum -- checksum of that revision, Non if non-existent
+
+ If eseen and rseen are both true:
+
+ esum -- checksum of revision erev, None if no revision
+
+ Note
+ """
+
+ def __init__(self, file = None):
+ if file and '/' in file:
+ raise ValueError, "no slash allowed in file"
+ self.file = file
+ self.lseen = self.eseen = self.rseen = 0
+ self.proxy = None
+
+ def __cmp__(self, other):
+ return cmp(self.file, other.file)
+
+ def getlocal(self):
+ try:
+ self.lmtime, self.lctime = os.stat(self.file)[-2:]
+ except os.error:
+ self.lmtime = self.lctime = self.lsum = None
+ else:
+ self.lsum = md5.new(open(self.file).read()).digest()
+ self.lseen = 1
+
+ def getentry(self, line):
+ words = string.splitfields(line, '/')
+ if self.file and words[1] != self.file:
+ raise ValueError, "file name mismatch"
+ self.file = words[1]
+ self.erev = words[2]
+ self.edeleted = 0
+ self.enew = 0
+ self.ectime = self.emtime = None
+ if self.erev[:1] == '-':
+ self.edeleted = 1
+ self.erev = self.erev[1:]
+ if self.erev == '0':
+ self.erev = None
+ self.enew = 1
+ else:
+ dates = words[3]
+ self.ectime = unctime(dates[:24])
+ self.emtime = unctime(dates[25:])
+ self.extra = words[4]
+ if self.rseen:
+ self.getesum()
+ self.eseen = 1
+
+ def getremote(self, proxy = None):
+ if proxy:
+ self.proxy = proxy
+ try:
+ self.rrev = self.proxy.head(self.file)
+ except (os.error, IOError):
+ self.rrev = None
+ if self.rrev:
+ self.rsum = self.proxy.sum(self.file)
+ else:
+ self.rsum = None
+ if self.eseen:
+ self.getesum()
+ self.rseen = 1
+
+ def getesum(self):
+ if self.erev == self.rrev:
+ self.esum = self.rsum
+ elif self.erev:
+ name = (self.file, self.erev)
+ self.esum = self.proxy.sum(name)
+ else:
+ self.esum = None
+
+ def putentry(self):
+ """Return a line suitable for inclusion in CVS/Entries.
+
+ The returned line is terminated by a newline.
+ If no entry should be written for this file,
+ return "".
+ """
+ if not self.eseen:
+ return ""
+
+ rev = self.erev or '0'
+ if self.edeleted:
+ rev = '-' + rev
+ if self.enew:
+ dates = 'Initial ' + self.file
+ else:
+ dates = gmctime(self.ectime) + ' ' + \
+ gmctime(self.emtime)
+ return "/%s/%s/%s/%s/\n" % (
+ self.file,
+ rev,
+ dates,
+ self.extra)
+
+ def report(self):
+ print '-'*50
+ def r(key, repr=repr, self=self):
+ try:
+ value = repr(getattr(self, key))
+ except AttributeError:
+ value = "?"
+ print "%-15s:" % key, value
+ r("file")
+ if self.lseen:
+ r("lsum", hexify)
+ r("lctime", gmctime)
+ r("lmtime", gmctime)
+ if self.eseen:
+ r("erev")
+ r("enew")
+ r("edeleted")
+ r("ectime", gmctime)
+ r("emtime", gmctime)
+ if self.rseen:
+ r("rrev")
+ r("rsum", hexify)
+ if self.eseen:
+ r("esum", hexify)
+
+
+class CVS:
+
+ """Represent the contents of a CVS admin file (and more).
+
+ Class variables:
+
+ FileClass -- the class to be instantiated for entries
+ (this should be derived from class File above)
+ IgnoreList -- shell patterns for local files to be ignored
+
+ Instance variables:
+
+ entries -- a dictionary containing File instances keyed by
+ their file name
+ proxy -- an RCSProxy instance, or None
+ """
+
+ FileClass = File
+
+ IgnoreList = ['.*', '@*', ',*', '*~', '*.o', '*.a', '*.so', '*.pyc']
+
+ def __init__(self):
+ self.entries = {}
+ self.proxy = None
+
+ def setproxy(self, proxy):
+ if proxy is self.proxy:
+ return
+ self.proxy = proxy
+ for e in self.entries.values():
+ e.rseen = 0
+
+ def getentries(self):
+ """Read the contents of CVS/Entries"""
+ self.entries = {}
+ f = self.cvsopen("Entries")
+ while 1:
+ line = f.readline()
+ if not line: break
+ e = self.FileClass()
+ e.getentry(line)
+ self.entries[e.file] = e
+ f.close()
+
+ def putentries(self):
+ """Write CVS/Entries back"""
+ f = self.cvsopen("Entries", 'w')
+ for e in self.values():
+ f.write(e.putentry())
+ f.close()
+
+ def getlocalfiles(self):
+ list = self.entries.keys()
+ addlist = os.listdir(os.curdir)
+ for name in addlist:
+ if name in list:
+ continue
+ if not self.ignored(name):
+ list.append(name)
+ list.sort()
+ for file in list:
+ try:
+ e = self.entries[file]
+ except KeyError:
+ e = self.entries[file] = self.FileClass(file)
+ e.getlocal()
+
+ def getremotefiles(self, proxy = None):
+ if proxy:
+ self.proxy = proxy
+ if not self.proxy:
+ raise RuntimeError, "no RCS proxy"
+ addlist = self.proxy.listfiles()
+ for file in addlist:
+ try:
+ e = self.entries[file]
+ except KeyError:
+ e = self.entries[file] = self.FileClass(file)
+ e.getremote(self.proxy)
+
+ def report(self):
+ for e in self.values():
+ e.report()
+ print '-'*50
+
+ def keys(self):
+ keys = self.entries.keys()
+ keys.sort()
+ return keys
+
+ def values(self):
+ def value(key, self=self):
+ return self.entries[key]
+ return map(value, self.keys())
+
+ def items(self):
+ def item(key, self=self):
+ return (key, self.entries[key])
+ return map(item, self.keys())
+
+ def cvsexists(self, file):
+ file = os.path.join("CVS", file)
+ return os.path.exists(file)
+
+ def cvsopen(self, file, mode = 'r'):
+ file = os.path.join("CVS", file)
+ if 'r' not in mode:
+ self.backup(file)
+ return open(file, mode)
+
+ def backup(self, file):
+ if os.path.isfile(file):
+ bfile = file + '~'
+ try: os.unlink(bfile)
+ except os.error: pass
+ os.rename(file, bfile)
+
+ def ignored(self, file):
+ if os.path.isdir(file): return True
+ for pat in self.IgnoreList:
+ if fnmatch.fnmatch(file, pat): return True
+ return False
+
+
+# hexify and unhexify are useful to print MD5 checksums in hex format
+
+hexify_format = '%02x' * 16
+def hexify(sum):
+ "Return a hex representation of a 16-byte string (e.g. an MD5 digest)"
+ if sum is None:
+ return "None"
+ return hexify_format % tuple(map(ord, sum))
+
+def unhexify(hexsum):
+ "Return the original from a hexified string"
+ if hexsum == "None":
+ return None
+ sum = ''
+ for i in range(0, len(hexsum), 2):
+ sum = sum + chr(string.atoi(hexsum[i:i+2], 16))
+ return sum
+
+
+unctime_monthmap = {}
+def unctime(date):
+ if date == "None": return None
+ if not unctime_monthmap:
+ months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
+ i = 0
+ for m in months:
+ i = i+1
+ unctime_monthmap[m] = i
+ words = string.split(date) # Day Mon DD HH:MM:SS YEAR
+ year = string.atoi(words[4])
+ month = unctime_monthmap[words[1]]
+ day = string.atoi(words[2])
+ [hh, mm, ss] = map(string.atoi, string.splitfields(words[3], ':'))
+ ss = ss - time.timezone
+ return time.mktime((year, month, day, hh, mm, ss, 0, 0, 0))
+
+def gmctime(t):
+ if t is None: return "None"
+ return time.asctime(time.gmtime(t))
+
+def test_unctime():
+ now = int(time.time())
+ t = time.gmtime(now)
+ at = time.asctime(t)
+ print 'GMT', now, at
+ print 'timezone', time.timezone
+ print 'local', time.ctime(now)
+ u = unctime(at)
+ print 'unctime()', u
+ gu = time.gmtime(u)
+ print '->', gu
+ print time.asctime(gu)
+
+def test():
+ x = CVS()
+ x.getentries()
+ x.getlocalfiles()
+## x.report()
+ import rcsclient
+ proxy = rcsclient.openrcsclient()
+ x.getremotefiles(proxy)
+ x.report()
+
+
+if __name__ == "__main__":
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cvslock.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cvslock.py
new file mode 100644
index 0000000000..95f5c58c05
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cvslock.py
@@ -0,0 +1,280 @@
+"""CVS locking algorithm.
+
+CVS locking strategy
+====================
+
+As reverse engineered from the CVS 1.3 sources (file lock.c):
+
+- Locking is done on a per repository basis (but a process can hold
+write locks for multiple directories); all lock files are placed in
+the repository and have names beginning with "#cvs.".
+
+- Before even attempting to lock, a file "#cvs.tfl." is created
+(and removed again), to test that we can write the repository. [The
+algorithm can still be fooled (1) if the repository's mode is changed
+while attempting to lock; (2) if this file exists and is writable but
+the directory is not.]
+
+- While creating the actual read/write lock files (which may exist for
+a long time), a "meta-lock" is held. The meta-lock is a directory
+named "#cvs.lock" in the repository. The meta-lock is also held while
+a write lock is held.
+
+- To set a read lock:
+
+ - acquire the meta-lock
+ - create the file "#cvs.rfl."
+ - release the meta-lock
+
+- To set a write lock:
+
+ - acquire the meta-lock
+ - check that there are no files called "#cvs.rfl.*"
+ - if there are, release the meta-lock, sleep, try again
+ - create the file "#cvs.wfl."
+
+- To release a write lock:
+
+ - remove the file "#cvs.wfl."
+ - rmdir the meta-lock
+
+- To release a read lock:
+
+ - remove the file "#cvs.rfl."
+
+
+Additional notes
+----------------
+
+- A process should read-lock at most one repository at a time.
+
+- A process may write-lock as many repositories as it wishes (to avoid
+deadlocks, I presume it should always lock them top-down in the
+directory hierarchy).
+
+- A process should make sure it removes all its lock files and
+directories when it crashes.
+
+- Limitation: one user id should not be committing files into the same
+repository at the same time.
+
+
+Turn this into Python code
+--------------------------
+
+rl = ReadLock(repository, waittime)
+
+wl = WriteLock(repository, waittime)
+
+list = MultipleWriteLock([repository1, repository2, ...], waittime)
+
+"""
+
+
+import os
+import time
+import stat
+import pwd
+
+
+# Default wait time
+DELAY = 10
+
+
+# XXX This should be the same on all Unix versions
+EEXIST = 17
+
+
+# Files used for locking (must match cvs.h in the CVS sources)
+CVSLCK = "#cvs.lck"
+CVSRFL = "#cvs.rfl."
+CVSWFL = "#cvs.wfl."
+
+
+class Error:
+
+ def __init__(self, msg):
+ self.msg = msg
+
+ def __repr__(self):
+ return repr(self.msg)
+
+ def __str__(self):
+ return str(self.msg)
+
+
+class Locked(Error):
+ pass
+
+
+class Lock:
+
+ def __init__(self, repository = ".", delay = DELAY):
+ self.repository = repository
+ self.delay = delay
+ self.lockdir = None
+ self.lockfile = None
+ pid = repr(os.getpid())
+ self.cvslck = self.join(CVSLCK)
+ self.cvsrfl = self.join(CVSRFL + pid)
+ self.cvswfl = self.join(CVSWFL + pid)
+
+ def __del__(self):
+ print "__del__"
+ self.unlock()
+
+ def setlockdir(self):
+ while 1:
+ try:
+ self.lockdir = self.cvslck
+ os.mkdir(self.cvslck, 0777)
+ return
+ except os.error, msg:
+ self.lockdir = None
+ if msg[0] == EEXIST:
+ try:
+ st = os.stat(self.cvslck)
+ except os.error:
+ continue
+ self.sleep(st)
+ continue
+ raise Error("failed to lock %s: %s" % (
+ self.repository, msg))
+
+ def unlock(self):
+ self.unlockfile()
+ self.unlockdir()
+
+ def unlockfile(self):
+ if self.lockfile:
+ print "unlink", self.lockfile
+ try:
+ os.unlink(self.lockfile)
+ except os.error:
+ pass
+ self.lockfile = None
+
+ def unlockdir(self):
+ if self.lockdir:
+ print "rmdir", self.lockdir
+ try:
+ os.rmdir(self.lockdir)
+ except os.error:
+ pass
+ self.lockdir = None
+
+ def sleep(self, st):
+ sleep(st, self.repository, self.delay)
+
+ def join(self, name):
+ return os.path.join(self.repository, name)
+
+
+def sleep(st, repository, delay):
+ if delay <= 0:
+ raise Locked(st)
+ uid = st[stat.ST_UID]
+ try:
+ pwent = pwd.getpwuid(uid)
+ user = pwent[0]
+ except KeyError:
+ user = "uid %d" % uid
+ print "[%s]" % time.ctime(time.time())[11:19],
+ print "Waiting for %s's lock in" % user, repository
+ time.sleep(delay)
+
+
+class ReadLock(Lock):
+
+ def __init__(self, repository, delay = DELAY):
+ Lock.__init__(self, repository, delay)
+ ok = 0
+ try:
+ self.setlockdir()
+ self.lockfile = self.cvsrfl
+ fp = open(self.lockfile, 'w')
+ fp.close()
+ ok = 1
+ finally:
+ if not ok:
+ self.unlockfile()
+ self.unlockdir()
+
+
+class WriteLock(Lock):
+
+ def __init__(self, repository, delay = DELAY):
+ Lock.__init__(self, repository, delay)
+ self.setlockdir()
+ while 1:
+ uid = self.readers_exist()
+ if not uid:
+ break
+ self.unlockdir()
+ self.sleep(uid)
+ self.lockfile = self.cvswfl
+ fp = open(self.lockfile, 'w')
+ fp.close()
+
+ def readers_exist(self):
+ n = len(CVSRFL)
+ for name in os.listdir(self.repository):
+ if name[:n] == CVSRFL:
+ try:
+ st = os.stat(self.join(name))
+ except os.error:
+ continue
+ return st
+ return None
+
+
+def MultipleWriteLock(repositories, delay = DELAY):
+ while 1:
+ locks = []
+ for r in repositories:
+ try:
+ locks.append(WriteLock(r, 0))
+ except Locked, instance:
+ del locks
+ break
+ else:
+ break
+ sleep(instance.msg, r, delay)
+ return list
+
+
+def test():
+ import sys
+ if sys.argv[1:]:
+ repository = sys.argv[1]
+ else:
+ repository = "."
+ rl = None
+ wl = None
+ try:
+ print "attempting write lock ..."
+ wl = WriteLock(repository)
+ print "got it."
+ wl.unlock()
+ print "attempting read lock ..."
+ rl = ReadLock(repository)
+ print "got it."
+ rl.unlock()
+ finally:
+ print [1]
+ sys.exc_traceback = None
+ print [2]
+ if rl:
+ rl.unlock()
+ print [3]
+ if wl:
+ wl.unlock()
+ print [4]
+ rl = None
+ print [5]
+ wl = None
+ print [6]
+
+
+if __name__ == '__main__':
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/mac.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/mac.py
new file mode 100644
index 0000000000..43a904e480
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/mac.py
@@ -0,0 +1,19 @@
+import sys
+import string
+import rcvs
+
+def main():
+ while 1:
+ try:
+ line = raw_input('$ ')
+ except EOFError:
+ break
+ words = string.split(line)
+ if not words:
+ continue
+ if words[0] != 'rcvs':
+ words.insert(0, 'rcvs')
+ sys.argv = words
+ rcvs.main()
+
+main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/makechangelog.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/makechangelog.py
new file mode 100644
index 0000000000..2f5519f473
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/makechangelog.py
@@ -0,0 +1,109 @@
+#! /usr/bin/env python
+
+"""Turn a pile of RCS log output into ChangeLog file entries.
+
+"""
+
+import sys
+import string
+import re
+import getopt
+import time
+
+def main():
+ args = sys.argv[1:]
+ opts, args = getopt.getopt(args, 'p:')
+ prefix = ''
+ for o, a in opts:
+ if p == '-p': prefix = a
+
+ f = sys.stdin
+ allrevs = []
+ while 1:
+ file = getnextfile(f)
+ if not file: break
+ revs = []
+ while 1:
+ rev = getnextrev(f, file)
+ if not rev:
+ break
+ revs.append(rev)
+ if revs:
+ allrevs[len(allrevs):] = revs
+ allrevs.sort()
+ allrevs.reverse()
+ for rev in allrevs:
+ formatrev(rev, prefix)
+
+parsedateprog = re.compile(
+ '^date: ([0-9]+)/([0-9]+)/([0-9]+) ' +
+ '([0-9]+):([0-9]+):([0-9]+); author: ([^ ;]+)')
+
+authormap = {
+ 'guido': 'Guido van Rossum ',
+ 'jack': 'Jack Jansen ',
+ 'sjoerd': 'Sjoerd Mullender ',
+ }
+
+def formatrev(rev, prefix):
+ dateline, file, revline, log = rev
+ if parsedateprog.match(dateline) >= 0:
+ fields = parsedateprog.group(1, 2, 3, 4, 5, 6)
+ author = parsedateprog.group(7)
+ if authormap.has_key(author): author = authormap[author]
+ tfields = map(string.atoi, fields) + [0, 0, 0]
+ tfields[5] = tfields[5] - time.timezone
+ t = time.mktime(tuple(tfields))
+ print time.ctime(t), '', author
+ words = string.split(log)
+ words[:0] = ['*', prefix + file + ':']
+ maxcol = 72-8
+ col = maxcol
+ for word in words:
+ if col > 0 and col + len(word) >= maxcol:
+ print
+ print '\t' + word,
+ col = -1
+ else:
+ print word,
+ col = col + 1 + len(word)
+ print
+ print
+
+startprog = re.compile("^Working file: (.*)$")
+
+def getnextfile(f):
+ while 1:
+ line = f.readline()
+ if not line: return None
+ if startprog.match(line) >= 0:
+ file = startprog.group(1)
+ # Skip until first revision
+ while 1:
+ line = f.readline()
+ if not line: return None
+ if line[:10] == '='*10: return None
+ if line[:10] == '-'*10: break
+## print "Skipped", line,
+ return file
+## else:
+## print "Ignored", line,
+
+def getnextrev(f, file):
+ # This is called when we are positioned just after a '---' separator
+ revline = f.readline()
+ dateline = f.readline()
+ log = ''
+ while 1:
+ line = f.readline()
+ if not line: break
+ if line[:10] == '='*10:
+ # Ignore the *last* log entry for each file since it
+ # is the revision since which we are logging.
+ return None
+ if line[:10] == '-'*10: break
+ log = log + line
+ return dateline, file, revline, log
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcsbump b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcsbump
new file mode 100644
index 0000000000..775de717e3
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcsbump
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+# -*- python -*-
+#
+# guido's version, from rcsbump,v 1.2 1995/06/22 21:27:27 bwarsaw Exp
+#
+# Python script for bumping up an RCS major revision number.
+
+import sys
+import re
+import rcslib
+import string
+
+WITHLOCK = 1
+majorrev_re = re.compile('^[0-9]+')
+
+dir = rcslib.RCS()
+
+if sys.argv[1:]:
+ files = sys.argv[1:]
+else:
+ files = dir.listfiles()
+
+for file in files:
+ # get the major revnumber of the file
+ headbranch = dir.info(file)['head']
+ majorrev_re.match(headbranch)
+ majorrev = string.atoi(majorrev_re.group(0)) + 1
+
+ if not dir.islocked(file):
+ dir.checkout(file, WITHLOCK)
+
+ msg = "Bumping major revision number (to %d)" % majorrev
+ dir.checkin((file, "%s.0" % majorrev), msg, "-f")
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcsclient.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcsclient.py
new file mode 100644
index 0000000000..dfa94368a6
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcsclient.py
@@ -0,0 +1,71 @@
+"""Customize this file to change the default client etc.
+
+(In general, it is probably be better to make local operation the
+default and to require something like an RCSSERVER environment
+variable to enable remote operation.)
+
+"""
+
+import string
+import os
+
+# These defaults don't belong here -- they should be taken from the
+# environment or from a hidden file in the current directory
+
+HOST = 'voorn.cwi.nl'
+PORT = 4127
+VERBOSE = 1
+LOCAL = 0
+
+import client
+
+
+class RCSProxyClient(client.SecureClient):
+
+ def __init__(self, address, verbose = client.VERBOSE):
+ client.SecureClient.__init__(self, address, verbose)
+
+
+def openrcsclient(opts = []):
+ "open an RCSProxy client based on a list of options returned by getopt"
+ import RCSProxy
+ host = HOST
+ port = PORT
+ verbose = VERBOSE
+ local = LOCAL
+ directory = None
+ for o, a in opts:
+ if o == '-h':
+ host = a
+ if ':' in host:
+ i = string.find(host, ':')
+ host, p = host[:i], host[i+1:]
+ if p:
+ port = string.atoi(p)
+ if o == '-p':
+ port = string.atoi(a)
+ if o == '-d':
+ directory = a
+ if o == '-v':
+ verbose = verbose + 1
+ if o == '-q':
+ verbose = 0
+ if o == '-L':
+ local = 1
+ if local:
+ import RCSProxy
+ x = RCSProxy.RCSProxyLocal()
+ else:
+ address = (host, port)
+ x = RCSProxyClient(address, verbose)
+ if not directory:
+ try:
+ directory = open(os.path.join("CVS", "Repository")).readline()
+ except IOError:
+ pass
+ else:
+ if directory[-1] == '\n':
+ directory = directory[:-1]
+ if directory:
+ x.cd(directory)
+ return x
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcslib.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcslib.py
new file mode 100644
index 0000000000..7d6ce9f3ff
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcslib.py
@@ -0,0 +1,334 @@
+"""RCS interface module.
+
+Defines the class RCS, which represents a directory with rcs version
+files and (possibly) corresponding work files.
+
+"""
+
+
+import fnmatch
+import os
+import re
+import string
+import tempfile
+
+
+class RCS:
+
+ """RCS interface class (local filesystem version).
+
+ An instance of this class represents a directory with rcs version
+ files and (possible) corresponding work files.
+
+ Methods provide access to most rcs operations such as
+ checkin/checkout, access to the rcs metadata (revisions, logs,
+ branches etc.) as well as some filesystem operations such as
+ listing all rcs version files.
+
+ XXX BUGS / PROBLEMS
+
+ - The instance always represents the current directory so it's not
+ very useful to have more than one instance around simultaneously
+
+ """
+
+ # Characters allowed in work file names
+ okchars = string.ascii_letters + string.digits + '-_=+'
+
+ def __init__(self):
+ """Constructor."""
+ pass
+
+ def __del__(self):
+ """Destructor."""
+ pass
+
+ # --- Informational methods about a single file/revision ---
+
+ def log(self, name_rev, otherflags = ''):
+ """Return the full log text for NAME_REV as a string.
+
+ Optional OTHERFLAGS are passed to rlog.
+
+ """
+ f = self._open(name_rev, 'rlog ' + otherflags)
+ data = f.read()
+ status = self._closepipe(f)
+ if status:
+ data = data + "%s: %s" % status
+ elif data[-1] == '\n':
+ data = data[:-1]
+ return data
+
+ def head(self, name_rev):
+ """Return the head revision for NAME_REV"""
+ dict = self.info(name_rev)
+ return dict['head']
+
+ def info(self, name_rev):
+ """Return a dictionary of info (from rlog -h) for NAME_REV
+
+ The dictionary's keys are the keywords that rlog prints
+ (e.g. 'head' and its values are the corresponding data
+ (e.g. '1.3').
+
+ XXX symbolic names and locks are not returned
+
+ """
+ f = self._open(name_rev, 'rlog -h')
+ dict = {}
+ while 1:
+ line = f.readline()
+ if not line: break
+ if line[0] == '\t':
+ # XXX could be a lock or symbolic name
+ # Anything else?
+ continue
+ i = string.find(line, ':')
+ if i > 0:
+ key, value = line[:i], string.strip(line[i+1:])
+ dict[key] = value
+ status = self._closepipe(f)
+ if status:
+ raise IOError, status
+ return dict
+
+ # --- Methods that change files ---
+
+ def lock(self, name_rev):
+ """Set an rcs lock on NAME_REV."""
+ name, rev = self.checkfile(name_rev)
+ cmd = "rcs -l%s %s" % (rev, name)
+ return self._system(cmd)
+
+ def unlock(self, name_rev):
+ """Clear an rcs lock on NAME_REV."""
+ name, rev = self.checkfile(name_rev)
+ cmd = "rcs -u%s %s" % (rev, name)
+ return self._system(cmd)
+
+ def checkout(self, name_rev, withlock=0, otherflags=""):
+ """Check out NAME_REV to its work file.
+
+ If optional WITHLOCK is set, check out locked, else unlocked.
+
+ The optional OTHERFLAGS is passed to co without
+ interpretation.
+
+ Any output from co goes to directly to stdout.
+
+ """
+ name, rev = self.checkfile(name_rev)
+ if withlock: lockflag = "-l"
+ else: lockflag = "-u"
+ cmd = 'co %s%s %s %s' % (lockflag, rev, otherflags, name)
+ return self._system(cmd)
+
+ def checkin(self, name_rev, message=None, otherflags=""):
+ """Check in NAME_REV from its work file.
+
+ The optional MESSAGE argument becomes the checkin message
+ (default "" if None); or the file description if this is
+ a new file.
+
+ The optional OTHERFLAGS argument is passed to ci without
+ interpretation.
+
+ Any output from ci goes to directly to stdout.
+
+ """
+ name, rev = self._unmangle(name_rev)
+ new = not self.isvalid(name)
+ if not message: message = ""
+ if message and message[-1] != '\n':
+ message = message + '\n'
+ lockflag = "-u"
+ if new:
+ f = tempfile.NamedTemporaryFile()
+ f.write(message)
+ f.flush()
+ cmd = 'ci %s%s -t%s %s %s' % \
+ (lockflag, rev, f.name, otherflags, name)
+ else:
+ message = re.sub(r'([\"$`])', r'\\\1', message)
+ cmd = 'ci %s%s -m"%s" %s %s' % \
+ (lockflag, rev, message, otherflags, name)
+ return self._system(cmd)
+
+ # --- Exported support methods ---
+
+ def listfiles(self, pat = None):
+ """Return a list of all version files matching optional PATTERN."""
+ files = os.listdir(os.curdir)
+ files = filter(self._isrcs, files)
+ if os.path.isdir('RCS'):
+ files2 = os.listdir('RCS')
+ files2 = filter(self._isrcs, files2)
+ files = files + files2
+ files = map(self.realname, files)
+ return self._filter(files, pat)
+
+ def isvalid(self, name):
+ """Test whether NAME has a version file associated."""
+ namev = self.rcsname(name)
+ return (os.path.isfile(namev) or
+ os.path.isfile(os.path.join('RCS', namev)))
+
+ def rcsname(self, name):
+ """Return the pathname of the version file for NAME.
+
+ The argument can be a work file name or a version file name.
+ If the version file does not exist, the name of the version
+ file that would be created by "ci" is returned.
+
+ """
+ if self._isrcs(name): namev = name
+ else: namev = name + ',v'
+ if os.path.isfile(namev): return namev
+ namev = os.path.join('RCS', os.path.basename(namev))
+ if os.path.isfile(namev): return namev
+ if os.path.isdir('RCS'):
+ return os.path.join('RCS', namev)
+ else:
+ return namev
+
+ def realname(self, namev):
+ """Return the pathname of the work file for NAME.
+
+ The argument can be a work file name or a version file name.
+ If the work file does not exist, the name of the work file
+ that would be created by "co" is returned.
+
+ """
+ if self._isrcs(namev): name = namev[:-2]
+ else: name = namev
+ if os.path.isfile(name): return name
+ name = os.path.basename(name)
+ return name
+
+ def islocked(self, name_rev):
+ """Test whether FILE (which must have a version file) is locked.
+
+ XXX This does not tell you which revision number is locked and
+ ignores any revision you may pass in (by virtue of using rlog
+ -L -R).
+
+ """
+ f = self._open(name_rev, 'rlog -L -R')
+ line = f.readline()
+ status = self._closepipe(f)
+ if status:
+ raise IOError, status
+ if not line: return None
+ if line[-1] == '\n':
+ line = line[:-1]
+ return self.realname(name_rev) == self.realname(line)
+
+ def checkfile(self, name_rev):
+ """Normalize NAME_REV into a (NAME, REV) tuple.
+
+ Raise an exception if there is no corresponding version file.
+
+ """
+ name, rev = self._unmangle(name_rev)
+ if not self.isvalid(name):
+ raise os.error, 'not an rcs file %r' % (name,)
+ return name, rev
+
+ # --- Internal methods ---
+
+ def _open(self, name_rev, cmd = 'co -p', rflag = '-r'):
+ """INTERNAL: open a read pipe to NAME_REV using optional COMMAND.
+
+ Optional FLAG is used to indicate the revision (default -r).
+
+ Default COMMAND is "co -p".
+
+ Return a file object connected by a pipe to the command's
+ output.
+
+ """
+ name, rev = self.checkfile(name_rev)
+ namev = self.rcsname(name)
+ if rev:
+ cmd = cmd + ' ' + rflag + rev
+ return os.popen("%s %r" % (cmd, namev))
+
+ def _unmangle(self, name_rev):
+ """INTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple.
+
+ Raise an exception if NAME contains invalid characters.
+
+ A NAME_REV argument is either NAME string (implying REV='') or
+ a tuple of the form (NAME, REV).
+
+ """
+ if type(name_rev) == type(''):
+ name_rev = name, rev = name_rev, ''
+ else:
+ name, rev = name_rev
+ for c in rev:
+ if c not in self.okchars:
+ raise ValueError, "bad char in rev"
+ return name_rev
+
+ def _closepipe(self, f):
+ """INTERNAL: Close PIPE and print its exit status if nonzero."""
+ sts = f.close()
+ if not sts: return None
+ detail, reason = divmod(sts, 256)
+ if reason == 0: return 'exit', detail # Exit status
+ signal = reason&0x7F
+ if signal == 0x7F:
+ code = 'stopped'
+ signal = detail
+ else:
+ code = 'killed'
+ if reason&0x80:
+ code = code + '(coredump)'
+ return code, signal
+
+ def _system(self, cmd):
+ """INTERNAL: run COMMAND in a subshell.
+
+ Standard input for the command is taken from /dev/null.
+
+ Raise IOError when the exit status is not zero.
+
+ Return whatever the calling method should return; normally
+ None.
+
+ A derived class may override this method and redefine it to
+ capture stdout/stderr of the command and return it.
+
+ """
+ cmd = cmd + " > ")
+ sys.stderr.flush()
+ line = sys.stdin.readline()
+ if not line or line == '.\n': break
+ message = message + line
+ return message
+
+def remove(fn):
+ try:
+ os.unlink(fn)
+ except os.error:
+ pass
+
+commands = {
+ 'ci': ('', checkin),
+ 'put': ('', checkin),
+ 'co': ('', checkout),
+ 'get': ('', checkout),
+ 'info': ('', info),
+ 'head': ('', head),
+ 'list': ('', list),
+ 'lock': ('', lock),
+ 'unlock': ('', unlock),
+ 'log': ('bhLRtd:l:r:s:w:V:', log),
+ 'diff': ('c', diff),
+ }
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/security.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/security.py
new file mode 100644
index 0000000000..051ace8f3e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/security.py
@@ -0,0 +1,33 @@
+class Security:
+
+ def __init__(self):
+ import os
+ env = os.environ
+ if env.has_key('PYTHON_KEYFILE'):
+ keyfile = env['PYTHON_KEYFILE']
+ else:
+ keyfile = '.python_keyfile'
+ if env.has_key('HOME'):
+ keyfile = os.path.join(env['HOME'], keyfile)
+ if not os.path.exists(keyfile):
+ import sys
+ for dir in sys.path:
+ kf = os.path.join(dir, keyfile)
+ if os.path.exists(kf):
+ keyfile = kf
+ break
+ try:
+ self._key = eval(open(keyfile).readline())
+ except IOError:
+ raise IOError, "python keyfile %s: cannot open" % keyfile
+
+ def _generate_challenge(self):
+ import random
+ return random.randint(100, 100000)
+
+ def _compare_challenge_response(self, challenge, response):
+ return self._encode_challenge(challenge) == response
+
+ def _encode_challenge(self, challenge):
+ p, m = self._key
+ return pow(long(challenge), p, m)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/server.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/server.py
new file mode 100644
index 0000000000..c7a4491eb3
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/server.py
@@ -0,0 +1,145 @@
+"""RPC Server module."""
+
+import sys
+import socket
+import pickle
+from fnmatch import fnmatch
+from repr import repr
+
+
+# Default verbosity (0 = silent, 1 = print connections, 2 = print requests too)
+VERBOSE = 1
+
+
+class Server:
+
+ """RPC Server class. Derive a class to implement a particular service."""
+
+ def __init__(self, address, verbose = VERBOSE):
+ if type(address) == type(0):
+ address = ('', address)
+ self._address = address
+ self._verbose = verbose
+ self._socket = None
+ self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self._socket.bind(address)
+ self._socket.listen(1)
+ self._listening = 1
+
+ def _setverbose(self, verbose):
+ self._verbose = verbose
+
+ def __del__(self):
+ self._close()
+
+ def _close(self):
+ self._listening = 0
+ if self._socket:
+ self._socket.close()
+ self._socket = None
+
+ def _serverloop(self):
+ while self._listening:
+ self._serve()
+
+ def _serve(self):
+ if self._verbose: print "Wait for connection ..."
+ conn, address = self._socket.accept()
+ if self._verbose: print "Accepted connection from %s" % repr(address)
+ if not self._verify(conn, address):
+ print "*** Connection from %s refused" % repr(address)
+ conn.close()
+ return
+ rf = conn.makefile('r')
+ wf = conn.makefile('w')
+ ok = 1
+ while ok:
+ wf.flush()
+ if self._verbose > 1: print "Wait for next request ..."
+ ok = self._dorequest(rf, wf)
+
+ _valid = ['192.16.201.*', '192.16.197.*', '132.151.1.*', '129.6.64.*']
+
+ def _verify(self, conn, address):
+ host, port = address
+ for pat in self._valid:
+ if fnmatch(host, pat): return 1
+ return 0
+
+ def _dorequest(self, rf, wf):
+ rp = pickle.Unpickler(rf)
+ try:
+ request = rp.load()
+ except EOFError:
+ return 0
+ if self._verbose > 1: print "Got request: %s" % repr(request)
+ try:
+ methodname, args, id = request
+ if '.' in methodname:
+ reply = (None, self._special(methodname, args), id)
+ elif methodname[0] == '_':
+ raise NameError, "illegal method name %s" % repr(methodname)
+ else:
+ method = getattr(self, methodname)
+ reply = (None, apply(method, args), id)
+ except:
+ reply = (sys.exc_type, sys.exc_value, id)
+ if id < 0 and reply[:2] == (None, None):
+ if self._verbose > 1: print "Suppress reply"
+ return 1
+ if self._verbose > 1: print "Send reply: %s" % repr(reply)
+ wp = pickle.Pickler(wf)
+ wp.dump(reply)
+ return 1
+
+ def _special(self, methodname, args):
+ if methodname == '.methods':
+ if not hasattr(self, '_methods'):
+ self._methods = tuple(self._listmethods())
+ return self._methods
+ raise NameError, "unrecognized special method name %s" % repr(methodname)
+
+ def _listmethods(self, cl=None):
+ if not cl: cl = self.__class__
+ names = cl.__dict__.keys()
+ names = filter(lambda x: x[0] != '_', names)
+ names.sort()
+ for base in cl.__bases__:
+ basenames = self._listmethods(base)
+ basenames = filter(lambda x, names=names: x not in names, basenames)
+ names[len(names):] = basenames
+ return names
+
+
+from security import Security
+
+
+class SecureServer(Server, Security):
+
+ def __init__(self, *args):
+ apply(Server.__init__, (self,) + args)
+ Security.__init__(self)
+
+ def _verify(self, conn, address):
+ import string
+ challenge = self._generate_challenge()
+ conn.send("%d\n" % challenge)
+ response = ""
+ while "\n" not in response and len(response) < 100:
+ data = conn.recv(100)
+ if not data:
+ break
+ response = response + data
+ try:
+ response = string.atol(string.strip(response))
+ except string.atol_error:
+ if self._verbose > 0:
+ print "Invalid response syntax", repr(response)
+ return 0
+ if not self._compare_challenge_response(challenge, response):
+ if self._verbose > 0:
+ print "Invalid response value", repr(response)
+ return 0
+ if self._verbose > 1:
+ print "Response matches challenge. Go ahead!"
+ return 1
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/sumtree.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/sumtree.py
new file mode 100644
index 0000000000..3c82282461
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/sumtree.py
@@ -0,0 +1,24 @@
+import time
+import FSProxy
+
+def main():
+ t1 = time.time()
+ #proxy = FSProxy.FSProxyClient(('voorn.cwi.nl', 4127))
+ proxy = FSProxy.FSProxyLocal()
+ sumtree(proxy)
+ proxy._close()
+ t2 = time.time()
+ print t2-t1, "seconds"
+ raw_input("[Return to exit] ")
+
+def sumtree(proxy):
+ print "PWD =", proxy.pwd()
+ files = proxy.listfiles()
+ proxy.infolist(files)
+ subdirs = proxy.listsubdirs()
+ for name in subdirs:
+ proxy.cd(name)
+ sumtree(proxy)
+ proxy.back()
+
+main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/README b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/README
new file mode 100644
index 0000000000..6550e67c59
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/README
@@ -0,0 +1,22 @@
+This directory contains a collection of executable Python scripts.
+
+See also the Tools/scripts directory!
+
+beer.py Print the classic 'bottles of beer' list
+eqfix.py Fix .py files to use the correct equality test operator
+fact.py Factorize numbers
+find-uname.py Search for Unicode characters using regexps
+from.py Summarize mailbox
+lpwatch.py Watch BSD line printer queues
+makedir.py Like mkdir -p
+markov.py Markov chain simulation of words or characters
+mboxconvert.py Convert MH or MMDF mailboxes to unix mailbox format
+morse.py Produce morse code (audible or on AIFF file)
+newslist.py List all newsgroups on a NNTP server as HTML pages
+pi.py Print all digits of pi -- given enough time and memory
+pp.py Emulate some Perl command line options
+primes.py Print prime numbers
+queens.py Dijkstra's solution to Wirth's "N Queens problem"
+script.py Equivalent to BSD script(1) -- by Steen Lumholt
+unbirthday.py Print unbirthday count
+update.py Update a bunch of files according to a script.
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/beer.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/beer.py
new file mode 100644
index 0000000000..f1ff58b50e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/beer.py
@@ -0,0 +1,20 @@
+#! /usr/bin/env python
+
+# By GvR, demystified after a version by Fredrik Lundh.
+
+import sys
+
+n = 100
+if sys.argv[1:]:
+ n = int(sys.argv[1])
+
+def bottle(n):
+ if n == 0: return "no more bottles of beer"
+ if n == 1: return "one bottle of beer"
+ return str(n) + " bottles of beer"
+
+for i in range(n, 0, -1):
+ print bottle(i), "on the wall,"
+ print bottle(i) + "."
+ print "Take one down, pass it around,"
+ print bottle(i-1), "on the wall."
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/eqfix.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/eqfix.py
new file mode 100644
index 0000000000..fc903c57cb
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/eqfix.py
@@ -0,0 +1,198 @@
+#! /usr/bin/env python
+
+# Fix Python source files to use the new equality test operator, i.e.,
+# if x = y: ...
+# is changed to
+# if x == y: ...
+# The script correctly tokenizes the Python program to reliably
+# distinguish between assignments and equality tests.
+#
+# Command line arguments are files or directories to be processed.
+# Directories are searched recursively for files whose name looks
+# like a python module.
+# Symbolic links are always ignored (except as explicit directory
+# arguments). Of course, the original file is kept as a back-up
+# (with a "~" attached to its name).
+# It complains about binaries (files containing null bytes)
+# and about files that are ostensibly not Python files: if the first
+# line starts with '#!' and does not contain the string 'python'.
+#
+# Changes made are reported to stdout in a diff-like format.
+#
+# Undoubtedly you can do this using find and sed or perl, but this is
+# a nice example of Python code that recurses down a directory tree
+# and uses regular expressions. Also note several subtleties like
+# preserving the file's mode and avoiding to even write a temp file
+# when no changes are needed for a file.
+#
+# NB: by changing only the function fixline() you can turn this
+# into a program for a different change to Python programs...
+
+import sys
+import re
+import os
+from stat import *
+import string
+
+err = sys.stderr.write
+dbg = err
+rep = sys.stdout.write
+
+def main():
+ bad = 0
+ if not sys.argv[1:]: # No arguments
+ err('usage: ' + sys.argv[0] + ' file-or-directory ...\n')
+ sys.exit(2)
+ for arg in sys.argv[1:]:
+ if os.path.isdir(arg):
+ if recursedown(arg): bad = 1
+ elif os.path.islink(arg):
+ err(arg + ': will not process symbolic links\n')
+ bad = 1
+ else:
+ if fix(arg): bad = 1
+ sys.exit(bad)
+
+ispythonprog = re.compile('^[a-zA-Z0-9_]+\.py$')
+def ispython(name):
+ return ispythonprog.match(name) >= 0
+
+def recursedown(dirname):
+ dbg('recursedown(%r)\n' % (dirname,))
+ bad = 0
+ try:
+ names = os.listdir(dirname)
+ except os.error, msg:
+ err('%s: cannot list directory: %r\n' % (dirname, msg))
+ return 1
+ names.sort()
+ subdirs = []
+ for name in names:
+ if name in (os.curdir, os.pardir): continue
+ fullname = os.path.join(dirname, name)
+ if os.path.islink(fullname): pass
+ elif os.path.isdir(fullname):
+ subdirs.append(fullname)
+ elif ispython(name):
+ if fix(fullname): bad = 1
+ for fullname in subdirs:
+ if recursedown(fullname): bad = 1
+ return bad
+
+def fix(filename):
+## dbg('fix(%r)\n' % (dirname,))
+ try:
+ f = open(filename, 'r')
+ except IOError, msg:
+ err('%s: cannot open: %r\n' % (filename, msg))
+ return 1
+ head, tail = os.path.split(filename)
+ tempname = os.path.join(head, '@' + tail)
+ g = None
+ # If we find a match, we rewind the file and start over but
+ # now copy everything to a temp file.
+ lineno = 0
+ while 1:
+ line = f.readline()
+ if not line: break
+ lineno = lineno + 1
+ if g is None and '\0' in line:
+ # Check for binary files
+ err(filename + ': contains null bytes; not fixed\n')
+ f.close()
+ return 1
+ if lineno == 1 and g is None and line[:2] == '#!':
+ # Check for non-Python scripts
+ words = string.split(line[2:])
+ if words and re.search('[pP]ython', words[0]) < 0:
+ msg = filename + ': ' + words[0]
+ msg = msg + ' script; not fixed\n'
+ err(msg)
+ f.close()
+ return 1
+ while line[-2:] == '\\\n':
+ nextline = f.readline()
+ if not nextline: break
+ line = line + nextline
+ lineno = lineno + 1
+ newline = fixline(line)
+ if newline != line:
+ if g is None:
+ try:
+ g = open(tempname, 'w')
+ except IOError, msg:
+ f.close()
+ err('%s: cannot create: %r\n' % (tempname, msg))
+ return 1
+ f.seek(0)
+ lineno = 0
+ rep(filename + ':\n')
+ continue # restart from the beginning
+ rep(repr(lineno) + '\n')
+ rep('< ' + line)
+ rep('> ' + newline)
+ if g is not None:
+ g.write(newline)
+
+ # End of file
+ f.close()
+ if not g: return 0 # No changes
+
+ # Finishing touch -- move files
+
+ # First copy the file's mode to the temp file
+ try:
+ statbuf = os.stat(filename)
+ os.chmod(tempname, statbuf[ST_MODE] & 07777)
+ except os.error, msg:
+ err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
+ # Then make a backup of the original file as filename~
+ try:
+ os.rename(filename, filename + '~')
+ except os.error, msg:
+ err('%s: warning: backup failed (%r)\n' % (filename, msg))
+ # Now move the temp file to the original file
+ try:
+ os.rename(tempname, filename)
+ except os.error, msg:
+ err('%s: rename failed (%r)\n' % (filename, msg))
+ return 1
+ # Return succes
+ return 0
+
+
+from tokenize import tokenprog
+
+match = {'if':':', 'elif':':', 'while':':', 'return':'\n', \
+ '(':')', '[':']', '{':'}', '`':'`'}
+
+def fixline(line):
+ # Quick check for easy case
+ if '=' not in line: return line
+
+ i, n = 0, len(line)
+ stack = []
+ while i < n:
+ j = tokenprog.match(line, i)
+ if j < 0:
+ # A bad token; forget about the rest of this line
+ print '(Syntax error:)'
+ print line,
+ return line
+ a, b = tokenprog.regs[3] # Location of the token proper
+ token = line[a:b]
+ i = i+j
+ if stack and token == stack[-1]:
+ del stack[-1]
+ elif match.has_key(token):
+ stack.append(match[token])
+ elif token == '=' and stack:
+ line = line[:a] + '==' + line[b:]
+ i, n = a + len('=='), len(line)
+ elif token == '==' and not stack:
+ print '(Warning: \'==\' at top level:)'
+ print line,
+ return line
+
+if __name__ == "__main__":
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/fact.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/fact.py
new file mode 100644
index 0000000000..2068c85bdc
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/fact.py
@@ -0,0 +1,49 @@
+#! /usr/bin/env python
+
+# Factorize numbers.
+# The algorithm is not efficient, but easy to understand.
+# If there are large factors, it will take forever to find them,
+# because we try all odd numbers between 3 and sqrt(n)...
+
+import sys
+from math import sqrt
+
+def fact(n):
+ if n < 1:
+ raise ValueError('fact() argument should be >= 1')
+ if n == 1:
+ return [] # special case
+ res = []
+ # Treat even factors special, so we can use i += 2 later
+ while n % 2 == 0:
+ res.append(2)
+ n //= 2
+ # Try odd numbers up to sqrt(n)
+ limit = sqrt(n+1)
+ i = 3
+ while i <= limit:
+ if n % i == 0:
+ res.append(i)
+ n //= i
+ limit = sqrt(n+1)
+ else:
+ i += 2
+ if n != 1:
+ res.append(n)
+ return res
+
+def main():
+ if len(sys.argv) > 1:
+ source = sys.argv[1:]
+ else:
+ source = iter(raw_input, '')
+ for arg in source:
+ try:
+ n = int(arg)
+ except ValueError:
+ print arg, 'is not an integer'
+ else:
+ print n, fact(n)
+
+if __name__ == "__main__":
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/find-uname.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/find-uname.py
new file mode 100644
index 0000000000..1213643694
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/find-uname.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+
+"""
+For each argument on the command line, look for it in the set of all Unicode
+names. Arguments are treated as case-insensitive regular expressions, e.g.:
+
+ % find-uname 'small letter a$' 'horizontal line'
+ *** small letter a$ matches ***
+ LATIN SMALL LETTER A (97)
+ COMBINING LATIN SMALL LETTER A (867)
+ CYRILLIC SMALL LETTER A (1072)
+ PARENTHESIZED LATIN SMALL LETTER A (9372)
+ CIRCLED LATIN SMALL LETTER A (9424)
+ FULLWIDTH LATIN SMALL LETTER A (65345)
+ *** horizontal line matches ***
+ HORIZONTAL LINE EXTENSION (9135)
+"""
+
+import unicodedata
+import sys
+import re
+
+def main(args):
+ unicode_names = []
+ for ix in range(sys.maxunicode+1):
+ try:
+ unicode_names.append((ix, unicodedata.name(unichr(ix))))
+ except ValueError: # no name for the character
+ pass
+ for arg in args:
+ pat = re.compile(arg, re.I)
+ matches = [(y,x) for (x,y) in unicode_names
+ if pat.search(y) is not None]
+ if matches:
+ print "***", arg, "matches", "***"
+ for match in matches:
+ print "%s (%d)" % match
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/from.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/from.py
new file mode 100644
index 0000000000..c7fcb9f0ea
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/from.py
@@ -0,0 +1,35 @@
+#! /usr/bin/env python
+
+# Print From and Subject of messages in $MAIL.
+# Extension to multiple mailboxes and other bells & whistles are left
+# as exercises for the reader.
+
+import sys, os
+
+# Open mailbox file. Exits with exception when this fails.
+
+try:
+ mailbox = os.environ['MAIL']
+except (AttributeError, KeyError):
+ sys.stderr.write('No environment variable $MAIL\n')
+ sys.exit(2)
+
+try:
+ mail = open(mailbox)
+except IOError:
+ sys.exit('Cannot open mailbox file: ' + mailbox)
+
+while 1:
+ line = mail.readline()
+ if not line:
+ break # EOF
+ if line.startswith('From '):
+ # Start of message found
+ print line[:-1],
+ while 1:
+ line = mail.readline()
+ if not line or line == '\n':
+ break
+ if line.startswith('Subject: '):
+ print repr(line[9:-1]),
+ print
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/lpwatch.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/lpwatch.py
new file mode 100644
index 0000000000..61e937fd2a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/lpwatch.py
@@ -0,0 +1,102 @@
+#! /usr/bin/env python
+
+# Watch line printer queue(s).
+# Intended for BSD 4.3 lpq.
+
+import os
+import sys
+import time
+
+DEF_PRINTER = 'psc'
+DEF_DELAY = 10
+
+def main():
+ delay = DEF_DELAY # XXX Use getopt() later
+ try:
+ thisuser = os.environ['LOGNAME']
+ except:
+ thisuser = os.environ['USER']
+ printers = sys.argv[1:]
+ if printers:
+ # Strip '-P' from printer names just in case
+ # the user specified it...
+ for i, name in enumerate(printers):
+ if name[:2] == '-P':
+ printers[i] = name[2:]
+ else:
+ if os.environ.has_key('PRINTER'):
+ printers = [os.environ['PRINTER']]
+ else:
+ printers = [DEF_PRINTER]
+
+ clearhome = os.popen('clear', 'r').read()
+
+ while True:
+ text = clearhome
+ for name in printers:
+ text += makestatus(name, thisuser) + '\n'
+ print text
+ time.sleep(delay)
+
+def makestatus(name, thisuser):
+ pipe = os.popen('lpq -P' + name + ' 2>&1', 'r')
+ lines = []
+ users = {}
+ aheadbytes = 0
+ aheadjobs = 0
+ userseen = False
+ totalbytes = 0
+ totaljobs = 0
+ for line in pipe:
+ fields = line.split()
+ n = len(fields)
+ if len(fields) >= 6 and fields[n-1] == 'bytes':
+ rank, user, job = fields[0:3]
+ files = fields[3:-2]
+ bytes = int(fields[n-2])
+ if user == thisuser:
+ userseen = True
+ elif not userseen:
+ aheadbytes += bytes
+ aheadjobs += 1
+ totalbytes += bytes
+ totaljobs += 1
+ ujobs, ubytes = users.get(user, (0, 0))
+ ujobs += 1
+ ubytes += bytes
+ users[user] = ujobs, ubytes
+ else:
+ if fields and fields[0] != 'Rank':
+ line = line.strip()
+ if line == 'no entries':
+ line = name + ': idle'
+ elif line[-22:] == ' is ready and printing':
+ line = name
+ lines.append(line)
+
+ if totaljobs:
+ line = '%d K' % ((totalbytes+1023) // 1024)
+ if totaljobs != len(users):
+ line += ' (%d jobs)' % totaljobs
+ if len(users) == 1:
+ line += ' for %s' % (users.keys()[0],)
+ else:
+ line += ' for %d users' % len(users)
+ if userseen:
+ if aheadjobs == 0:
+ line += ' (%s first)' % thisuser
+ else:
+ line += ' (%d K before %s)' % (
+ (aheadbytes+1023) // 1024, thisuser)
+ lines.append(line)
+
+ sts = pipe.close()
+ if sts:
+ lines.append('lpq exit status %r' % (sts,))
+ return ': '.join(lines)
+
+if __name__ == "__main__":
+ try:
+ main()
+ except KeyboardInterrupt:
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/makedir.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/makedir.py
new file mode 100644
index 0000000000..294502f3ad
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/makedir.py
@@ -0,0 +1,21 @@
+#! /usr/bin/env python
+
+# Like mkdir, but also make intermediate directories if necessary.
+# It is not an error if the given directory already exists (as long
+# as it is a directory).
+# Errors are not treated specially -- you just get a Python exception.
+
+import sys, os
+
+def main():
+ for p in sys.argv[1:]:
+ makedirs(p)
+
+def makedirs(p):
+ if p and not os.path.isdir(p):
+ head, tail = os.path.split(p)
+ makedirs(head)
+ os.mkdir(p, 0777)
+
+if __name__ == "__main__":
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/markov.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/markov.py
new file mode 100644
index 0000000000..993c3f6ecd
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/markov.py
@@ -0,0 +1,121 @@
+#! /usr/bin/env python
+
+class Markov:
+ def __init__(self, histsize, choice):
+ self.histsize = histsize
+ self.choice = choice
+ self.trans = {}
+
+ def add(self, state, next):
+ self.trans.setdefault(state, []).append(next)
+
+ def put(self, seq):
+ n = self.histsize
+ add = self.add
+ add(None, seq[:0])
+ for i in range(len(seq)):
+ add(seq[max(0, i-n):i], seq[i:i+1])
+ add(seq[len(seq)-n:], None)
+
+ def get(self):
+ choice = self.choice
+ trans = self.trans
+ n = self.histsize
+ seq = choice(trans[None])
+ while True:
+ subseq = seq[max(0, len(seq)-n):]
+ options = trans[subseq]
+ next = choice(options)
+ if not next:
+ break
+ seq += next
+ return seq
+
+
+def test():
+ import sys, random, getopt
+ args = sys.argv[1:]
+ try:
+ opts, args = getopt.getopt(args, '0123456789cdwq')
+ except getopt.error:
+ print 'Usage: %s [-#] [-cddqw] [file] ...' % sys.argv[0]
+ print 'Options:'
+ print '-#: 1-digit history size (default 2)'
+ print '-c: characters (default)'
+ print '-w: words'
+ print '-d: more debugging output'
+ print '-q: no debugging output'
+ print 'Input files (default stdin) are split in paragraphs'
+ print 'separated blank lines and each paragraph is split'
+ print 'in words by whitespace, then reconcatenated with'
+ print 'exactly one space separating words.'
+ print 'Output consists of paragraphs separated by blank'
+ print 'lines, where lines are no longer than 72 characters.'
+ sys.exit(2)
+ histsize = 2
+ do_words = False
+ debug = 1
+ for o, a in opts:
+ if '-0' <= o <= '-9': histsize = int(o[1:])
+ if o == '-c': do_words = False
+ if o == '-d': debug += 1
+ if o == '-q': debug = 0
+ if o == '-w': do_words = True
+ if not args:
+ args = ['-']
+
+ m = Markov(histsize, random.choice)
+ try:
+ for filename in args:
+ if filename == '-':
+ f = sys.stdin
+ if f.isatty():
+ print 'Sorry, need stdin from file'
+ continue
+ else:
+ f = open(filename, 'r')
+ if debug: print 'processing', filename, '...'
+ text = f.read()
+ f.close()
+ paralist = text.split('\n\n')
+ for para in paralist:
+ if debug > 1: print 'feeding ...'
+ words = para.split()
+ if words:
+ if do_words:
+ data = tuple(words)
+ else:
+ data = ' '.join(words)
+ m.put(data)
+ except KeyboardInterrupt:
+ print 'Interrupted -- continue with data read so far'
+ if not m.trans:
+ print 'No valid input files'
+ return
+ if debug: print 'done.'
+
+ if debug > 1:
+ for key in m.trans.keys():
+ if key is None or len(key) < histsize:
+ print repr(key), m.trans[key]
+ if histsize == 0: print repr(''), m.trans['']
+ print
+ while True:
+ data = m.get()
+ if do_words:
+ words = data
+ else:
+ words = data.split()
+ n = 0
+ limit = 72
+ for w in words:
+ if n + len(w) > limit:
+ print
+ n = 0
+ print w,
+ n += len(w) + 1
+ print
+ print
+
+if __name__ == "__main__":
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/mboxconvert.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/mboxconvert.py
new file mode 100644
index 0000000000..41d59d62a4
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/mboxconvert.py
@@ -0,0 +1,124 @@
+#! /usr/bin/env python
+
+# Convert MH directories (1 message per file) or MMDF mailboxes (4x^A
+# delimited) to unix mailbox (From ... delimited) on stdout.
+# If -f is given, files contain one message per file (e.g. MH messages)
+
+import rfc822
+import sys
+import time
+import os
+import stat
+import getopt
+import re
+
+def main():
+ dofile = mmdf
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], 'f')
+ except getopt.error, msg:
+ sys.stderr.write('%s\n' % msg)
+ sys.exit(2)
+ for o, a in opts:
+ if o == '-f':
+ dofile = message
+ if not args:
+ args = ['-']
+ sts = 0
+ for arg in args:
+ if arg == '-' or arg == '':
+ sts = dofile(sys.stdin) or sts
+ elif os.path.isdir(arg):
+ sts = mh(arg) or sts
+ elif os.path.isfile(arg):
+ try:
+ f = open(arg)
+ except IOError, msg:
+ sys.stderr.write('%s: %s\n' % (arg, msg))
+ sts = 1
+ continue
+ sts = dofile(f) or sts
+ f.close()
+ else:
+ sys.stderr.write('%s: not found\n' % arg)
+ sts = 1
+ if sts:
+ sys.exit(sts)
+
+numeric = re.compile('[1-9][0-9]*')
+
+def mh(dir):
+ sts = 0
+ msgs = os.listdir(dir)
+ for msg in msgs:
+ if numeric.match(msg) != len(msg):
+ continue
+ fn = os.path.join(dir, msg)
+ try:
+ f = open(fn)
+ except IOError, msg:
+ sys.stderr.write('%s: %s\n' % (fn, msg))
+ sts = 1
+ continue
+ sts = message(f) or sts
+ return sts
+
+def mmdf(f):
+ sts = 0
+ while 1:
+ line = f.readline()
+ if not line:
+ break
+ if line == '\1\1\1\1\n':
+ sts = message(f, line) or sts
+ else:
+ sys.stderr.write(
+ 'Bad line in MMFD mailbox: %r\n' % (line,))
+ return sts
+
+counter = 0 # for generating unique Message-ID headers
+
+def message(f, delimiter = ''):
+ sts = 0
+ # Parse RFC822 header
+ m = rfc822.Message(f)
+ # Write unix header line
+ fullname, email = m.getaddr('From')
+ tt = m.getdate('Date')
+ if tt:
+ t = time.mktime(tt)
+ else:
+ sys.stderr.write(
+ 'Unparseable date: %r\n' % (m.getheader('Date'),))
+ t = os.fstat(f.fileno())[stat.ST_MTIME]
+ print 'From', email, time.ctime(t)
+ # Copy RFC822 header
+ for line in m.headers:
+ print line,
+ # Invent Message-ID header if none is present
+ if not m.has_key('message-id'):
+ global counter
+ counter = counter + 1
+ msgid = "<%s.%d>" % (hex(t), counter)
+ sys.stderr.write("Adding Message-ID %s (From %s)\n" %
+ (msgid, email))
+ print "Message-ID:", msgid
+ print
+ # Copy body
+ while 1:
+ line = f.readline()
+ if line == delimiter:
+ break
+ if not line:
+ sys.stderr.write('Unexpected EOF in message\n')
+ sts = 1
+ break
+ if line[:5] == 'From ':
+ line = '>' + line
+ print line,
+ # Print trailing newline
+ print
+ return sts
+
+if __name__ == "__main__":
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/morse.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/morse.py
new file mode 100644
index 0000000000..138a186711
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/morse.py
@@ -0,0 +1,138 @@
+#! /usr/bin/env python
+
+# DAH should be three DOTs.
+# Space between DOTs and DAHs should be one DOT.
+# Space between two letters should be one DAH.
+# Space between two words should be DOT DAH DAH.
+
+import sys, math, audiodev
+
+DOT = 30
+DAH = 3 * DOT
+OCTAVE = 2 # 1 == 441 Hz, 2 == 882 Hz, ...
+
+morsetab = {
+ 'A': '.-', 'a': '.-',
+ 'B': '-...', 'b': '-...',
+ 'C': '-.-.', 'c': '-.-.',
+ 'D': '-..', 'd': '-..',
+ 'E': '.', 'e': '.',
+ 'F': '..-.', 'f': '..-.',
+ 'G': '--.', 'g': '--.',
+ 'H': '....', 'h': '....',
+ 'I': '..', 'i': '..',
+ 'J': '.---', 'j': '.---',
+ 'K': '-.-', 'k': '-.-',
+ 'L': '.-..', 'l': '.-..',
+ 'M': '--', 'm': '--',
+ 'N': '-.', 'n': '-.',
+ 'O': '---', 'o': '---',
+ 'P': '.--.', 'p': '.--.',
+ 'Q': '--.-', 'q': '--.-',
+ 'R': '.-.', 'r': '.-.',
+ 'S': '...', 's': '...',
+ 'T': '-', 't': '-',
+ 'U': '..-', 'u': '..-',
+ 'V': '...-', 'v': '...-',
+ 'W': '.--', 'w': '.--',
+ 'X': '-..-', 'x': '-..-',
+ 'Y': '-.--', 'y': '-.--',
+ 'Z': '--..', 'z': '--..',
+ '0': '-----', ',': '--..--',
+ '1': '.----', '.': '.-.-.-',
+ '2': '..---', '?': '..--..',
+ '3': '...--', ';': '-.-.-.',
+ '4': '....-', ':': '---...',
+ '5': '.....', "'": '.----.',
+ '6': '-....', '-': '-....-',
+ '7': '--...', '/': '-..-.',
+ '8': '---..', '(': '-.--.-',
+ '9': '----.', ')': '-.--.-',
+ ' ': ' ', '_': '..--.-',
+}
+
+nowave = '\0' * 200
+
+# If we play at 44.1 kHz (which we do), then if we produce one sine
+# wave in 100 samples, we get a tone of 441 Hz. If we produce two
+# sine waves in these 100 samples, we get a tone of 882 Hz. 882 Hz
+# appears to be a nice one for playing morse code.
+def mkwave(octave):
+ sinewave = ''
+ for i in range(100):
+ val = int(math.sin(math.pi * i * octave / 50.0) * 30000)
+ sinewave += chr((val >> 8) & 255) + chr(val & 255)
+ return sinewave
+
+defaultwave = mkwave(OCTAVE)
+
+def main():
+ import getopt
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], 'o:p:')
+ except getopt.error:
+ sys.stderr.write('Usage ' + sys.argv[0] +
+ ' [ -o outfile ] [ -p octave ] [ words ] ...\n')
+ sys.exit(1)
+ dev = None
+ wave = defaultwave
+ for o, a in opts:
+ if o == '-o':
+ import aifc
+ dev = aifc.open(a, 'w')
+ dev.setframerate(44100)
+ dev.setsampwidth(2)
+ dev.setnchannels(1)
+ if o == '-p':
+ wave = mkwave(int(a))
+ if not dev:
+ import audiodev
+ dev = audiodev.AudioDev()
+ dev.setoutrate(44100)
+ dev.setsampwidth(2)
+ dev.setnchannels(1)
+ dev.close = dev.stop
+ dev.writeframesraw = dev.writeframes
+ if args:
+ source = [' '.join(args)]
+ else:
+ source = iter(sys.stdin.readline, '')
+ for line in source:
+ mline = morse(line)
+ play(mline, dev, wave)
+ if hasattr(dev, 'wait'):
+ dev.wait()
+ dev.close()
+
+# Convert a string to morse code with \001 between the characters in
+# the string.
+def morse(line):
+ res = ''
+ for c in line:
+ try:
+ res += morsetab[c] + '\001'
+ except KeyError:
+ pass
+ return res
+
+# Play a line of morse code.
+def play(line, dev, wave):
+ for c in line:
+ if c == '.':
+ sine(dev, DOT, wave)
+ elif c == '-':
+ sine(dev, DAH, wave)
+ else: # space
+ pause(dev, DAH + DOT)
+ pause(dev, DOT)
+
+def sine(dev, length, wave):
+ for i in range(length):
+ dev.writeframesraw(wave)
+
+def pause(dev, length):
+ for i in range(length):
+ dev.writeframesraw(nowave)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/newslist.doc b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/newslist.doc
new file mode 100644
index 0000000000..d02e96f0a7
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/newslist.doc
@@ -0,0 +1,59 @@
+ NEWSLIST
+ ========
+ A program to assist HTTP browsing of newsgroups
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+WWW browsers such as NCSA Mosaic allow the user to read newsgroup
+articles by specifying the group name in a URL eg 'news:comp.answers'.
+
+To browse through many groups, though, (and there are several thousand
+of them) you really need a page or pages containing links to all the
+groups. There are some good ones out there, for example,
+
+ http://info.cern.ch/hypertext/DataSources/News/Groups/Overview.html
+
+is the standard one at CERN, but it only shows the groups available there,
+which may be rather different from those available on your machine.
+
+Newslist is a program which creates a hierarchy of pages for you based
+on the groups available from YOUR server. It is written in python - a
+splendid interpreted object-oriented language which I suggest you get
+right now from the directory /pub/python at ftp.cwi.nl, if you haven't
+already got it.
+
+You should be able to see some sample output by looking at:
+ http://pelican.cl.cam.ac.uk/newspage/root.html
+
+Descriptions of newsgroups can be added from a file with one group
+per line. eg:
+
+ alt.foo Articles about foo
+ comp.bar Programming in 'bar' and related languages
+
+A suitable list detailing most groups can be found at ftp.uu.net in
+/uunet-info/newsgroups.gz.
+
+Make sure you read the information at the beginning of the program source and
+configure the variables before running.
+
+In addition to python, you need:
+
+ An NNTP-based news feed.
+ A directory in which to put the pages.
+
+The programming is not very beautiful, but it works! It comes with no
+warranty, express or implied, but with the hope that some others may
+find it useful.
+
+Comments, improvements & suggestions welcomed.
+Quentin Stafford-Fraser
+
+ ----------------------------------------------------------------------
+ Quentin Stafford-Fraser
+ http://pelican.cl.cam.ac.uk/people/qs101/me.html
+
+ Cambridge University Computer Lab Rank Xerox Cambridge EuroPARC
+ qs101@cl.cam.ac.uk fraser@europarc.xerox.com
+ Tel: +44 223 334411 Tel: +44 223 341521
+ Fax: +44 223 334679 Fax: +44 223 341510
+ ----------------------------------------------------------------------
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/newslist.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/newslist.py
new file mode 100644
index 0000000000..54625203b0
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/newslist.py
@@ -0,0 +1,362 @@
+#! /usr/bin/env python
+#######################################################################
+# Newslist $Revision$
+#
+# Syntax:
+# newslist [ -a ]
+#
+# This is a program to create a directory full of HTML pages
+# which between them contain links to all the newsgroups available
+# on your server.
+#
+# The -a option causes a complete list of all groups to be read from
+# the server rather than just the ones which have appeared since last
+# execution. This recreates the local list from scratch. Use this on
+# the first invocation of the program, and from time to time thereafter.
+# When new groups are first created they may appear on your server as
+# empty groups. By default, empty groups are ignored by the -a option.
+# However, these new groups will not be created again, and so will not
+# appear in the server's list of 'new groups' at a later date. Hence it
+# won't appear until you do a '-a' after some articles have appeared.
+#
+# I should really keep a list of ignored empty groups and re-check them
+# for articles on every run, but I haven't got around to it yet.
+#
+# This assumes an NNTP news feed.
+#
+# Feel free to copy, distribute and modify this code for
+# non-commercial use. If you make any useful modifications, let me
+# know!
+#
+# (c) Quentin Stafford-Fraser 1994
+# fraser@europarc.xerox.com qs101@cl.cam.ac.uk
+# #
+#######################################################################
+import sys, nntplib, marshal, time, os
+
+#######################################################################
+# Check these variables before running! #
+
+# Top directory.
+# Filenames which don't start with / are taken as being relative to this.
+topdir = os.path.expanduser('~/newspage')
+
+# The name of your NNTP host
+# eg.
+# newshost = 'nntp-serv.cl.cam.ac.uk'
+# or use following to get the name from the NNTPSERVER environment
+# variable:
+# newshost = os.environ['NNTPSERVER']
+newshost = 'news.example.com'
+
+# The filename for a local cache of the newsgroup list
+treefile = 'grouptree'
+
+# The filename for descriptions of newsgroups
+# I found a suitable one at ftp.uu.net in /uunet-info/newgroups.gz
+# You can set this to '' if you don't wish to use one.
+descfile = 'newsgroups'
+
+# The directory in which HTML pages should be created
+# eg.
+# pagedir = '/usr/local/lib/html/newspage'
+# pagedir = 'pages'
+pagedir = topdir
+
+# The html prefix which will refer to this directory
+# eg.
+# httppref = '/newspage/',
+# or leave blank for relative links between pages: (Recommended)
+# httppref = ''
+httppref = ''
+
+# The name of the 'root' news page in this directory.
+# A .html suffix will be added.
+rootpage = 'root'
+
+# Set skipempty to 0 if you wish to see links to empty groups as well.
+# Only affects the -a option.
+skipempty = 1
+
+# pagelinkicon can contain html to put an icon after links to
+# further pages. This helps to make important links stand out.
+# Set to '' if not wanted, or '...' is quite a good one.
+pagelinkicon = '... '
+
+# ---------------------------------------------------------------------
+# Less important personal preferences:
+
+# Sublistsize controls the maximum number of items the will appear as
+# an indented sub-list before the whole thing is moved onto a different
+# page. The smaller this is, the more pages you will have, but the
+# shorter each will be.
+sublistsize = 4
+
+# That should be all. #
+#######################################################################
+
+for dir in os.curdir, os.environ['HOME']:
+ rcfile = os.path.join(dir, '.newslistrc.py')
+ if os.path.exists(rcfile):
+ print rcfile
+ execfile(rcfile)
+ break
+
+from nntplib import NNTP
+from stat import *
+
+rcsrev = '$Revision$'
+rcsrev = ' '.join(filter(lambda s: '$' not in s, rcsrev.split()))
+desc = {}
+
+# Make (possibly) relative filenames into absolute ones
+treefile = os.path.join(topdir,treefile)
+descfile = os.path.join(topdir,descfile)
+page = os.path.join(topdir,pagedir)
+
+# First the bits for creating trees ---------------------------
+
+# Addtotree creates/augments a tree from a list of group names
+def addtotree(tree, groups):
+ print 'Updating tree...'
+ for i in groups:
+ parts = i.split('.')
+ makeleaf(tree, parts)
+
+# Makeleaf makes a leaf and the branch leading to it if necessary
+def makeleaf(tree,path):
+ j = path[0]
+ l = len(path)
+
+ if j not in tree:
+ tree[j] = {}
+ if l == 1:
+ tree[j]['.'] = '.'
+ if l > 1:
+ makeleaf(tree[j],path[1:])
+
+# Then the bits for outputting trees as pages ----------------
+
+# Createpage creates an HTML file named .html containing links
+# to those groups beginning with .
+
+def createpage(root, tree, p):
+ filename = os.path.join(pagedir, root+'.html')
+ if root == rootpage:
+ detail = ''
+ else:
+ detail = ' under ' + root
+ with open(filename, 'w') as f:
+ # f.write('Content-Type: text/html\n')
+ f.write('\n\n')
+ f.write('Newsgroups available%s\n' % detail)
+ f.write('\n\n')
+ f.write('
')
+ f.write("This page automatically created by 'newslist' v. %s." %
+ rcsrev)
+ f.write(time.ctime(time.time()) + '\n')
+ f.write('\n\n')
+
+# Printtree prints the groups as a bulleted list. Groups with
+# more than subgroups will be put on a separate page.
+# Other sets of subgroups are just indented.
+
+def printtree(f, tree, indent, p):
+ l = len(tree)
+
+ if l > sublistsize and indent > 0:
+ # Create a new page and a link to it
+ f.write('
%s %s\n' %
+ (self._link, self._title, self._descr))
+
+ self._title = None
+ self._link = None
+ self._descr = ""
+
+ if name == "rss":
+ self._out.write(bottom)
+
+ def characters(self, content):
+ self._text = self._text + content
+
+# --- Main program
+
+if __name__ == '__main__':
+ parser = make_parser()
+ parser.setContentHandler(RSSHandler())
+ parser.parse(sys.argv[1])
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/zlib/minigzip.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/zlib/minigzip.py
new file mode 100644
index 0000000000..9b08b53881
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/zlib/minigzip.py
@@ -0,0 +1,133 @@
+#!/usr/bin/env python
+# Demo program for zlib; it compresses or decompresses files, but *doesn't*
+# delete the original. This doesn't support all of gzip's options.
+#
+# The 'gzip' module in the standard library provides a more complete
+# implementation of gzip-format files.
+
+import zlib, sys, os
+
+FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
+
+def write32(output, value):
+ output.write(chr(value & 255)) ; value=value // 256
+ output.write(chr(value & 255)) ; value=value // 256
+ output.write(chr(value & 255)) ; value=value // 256
+ output.write(chr(value & 255))
+
+def read32(input):
+ v = ord(input.read(1))
+ v += (ord(input.read(1)) << 8 )
+ v += (ord(input.read(1)) << 16)
+ v += (ord(input.read(1)) << 24)
+ return v
+
+def compress (filename, input, output):
+ output.write('\037\213\010') # Write the header, ...
+ output.write(chr(FNAME)) # ... flag byte ...
+
+ statval = os.stat(filename) # ... modification time ...
+ mtime = statval[8]
+ write32(output, mtime)
+ output.write('\002') # ... slowest compression alg. ...
+ output.write('\377') # ... OS (=unknown) ...
+ output.write(filename+'\000') # ... original filename ...
+
+ crcval = zlib.crc32("")
+ compobj = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS,
+ zlib.DEF_MEM_LEVEL, 0)
+ while True:
+ data = input.read(1024)
+ if data == "":
+ break
+ crcval = zlib.crc32(data, crcval)
+ output.write(compobj.compress(data))
+ output.write(compobj.flush())
+ write32(output, crcval) # ... the CRC ...
+ write32(output, statval[6]) # and the file size.
+
+def decompress (input, output):
+ magic = input.read(2)
+ if magic != '\037\213':
+ print 'Not a gzipped file'
+ sys.exit(0)
+ if ord(input.read(1)) != 8:
+ print 'Unknown compression method'
+ sys.exit(0)
+ flag = ord(input.read(1))
+ input.read(4+1+1) # Discard modification time,
+ # extra flags, and OS byte.
+ if flag & FEXTRA:
+ # Read & discard the extra field, if present
+ xlen = ord(input.read(1))
+ xlen += 256*ord(input.read(1))
+ input.read(xlen)
+ if flag & FNAME:
+ # Read and discard a null-terminated string containing the filename
+ while True:
+ s = input.read(1)
+ if s == '\0': break
+ if flag & FCOMMENT:
+ # Read and discard a null-terminated string containing a comment
+ while True:
+ s=input.read(1)
+ if s=='\0': break
+ if flag & FHCRC:
+ input.read(2) # Read & discard the 16-bit header CRC
+
+ decompobj = zlib.decompressobj(-zlib.MAX_WBITS)
+ crcval = zlib.crc32("")
+ length = 0
+ while True:
+ data=input.read(1024)
+ if data == "":
+ break
+ decompdata = decompobj.decompress(data)
+ output.write(decompdata)
+ length += len(decompdata)
+ crcval = zlib.crc32(decompdata, crcval)
+
+ decompdata = decompobj.flush()
+ output.write(decompdata)
+ length += len(decompdata)
+ crcval = zlib.crc32(decompdata, crcval)
+
+ # We've read to the end of the file, so we have to rewind in order
+ # to reread the 8 bytes containing the CRC and the file size. The
+ # decompressor is smart and knows when to stop, so feeding it
+ # extra data is harmless.
+ input.seek(-8, 2)
+ crc32 = read32(input)
+ isize = read32(input)
+ if crc32 != crcval:
+ print 'CRC check failed.'
+ if isize != length:
+ print 'Incorrect length of data produced'
+
+def main():
+ if len(sys.argv)!=2:
+ print 'Usage: minigzip.py '
+ print ' The file will be compressed or decompressed.'
+ sys.exit(0)
+
+ filename = sys.argv[1]
+ if filename.endswith('.gz'):
+ compressing = False
+ outputname = filename[:-3]
+ else:
+ compressing = True
+ outputname = filename + '.gz'
+
+ input = open(filename, 'rb')
+ output = open(outputname, 'wb')
+
+ if compressing:
+ compress(filename, input, output)
+ else:
+ decompress(input, output)
+
+ input.close()
+ output.close()
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/zlib/zlibdemo.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/zlib/zlibdemo.py
new file mode 100644
index 0000000000..7562874a8d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Demo/zlib/zlibdemo.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python
+
+# Takes an optional filename, defaulting to this file itself.
+# Reads the file and compresses the content using level 1 and level 9
+# compression, printing a summary of the results.
+
+import zlib, sys
+
+def main():
+ if len(sys.argv) > 1:
+ filename = sys.argv[1]
+ else:
+ filename = sys.argv[0]
+ print 'Reading', filename
+
+ f = open(filename, 'rb') # Get the data to compress
+ s = f.read()
+ f.close()
+
+ # First, we'll compress the string in one step
+ comptext = zlib.compress(s, 1)
+ decomp = zlib.decompress(comptext)
+
+ print '1-step compression: (level 1)'
+ print ' Original:', len(s), 'Compressed:', len(comptext),
+ print 'Uncompressed:', len(decomp)
+
+ # Now, let's compress the string in stages; set chunk to work in smaller steps
+
+ chunk = 256
+ compressor = zlib.compressobj(9)
+ decompressor = zlib.decompressobj()
+ comptext = decomp = ''
+ for i in range(0, len(s), chunk):
+ comptext = comptext+compressor.compress(s[i:i+chunk])
+ # Don't forget to call flush()!!
+ comptext = comptext + compressor.flush()
+
+ for i in range(0, len(comptext), chunk):
+ decomp = decomp + decompressor.decompress(comptext[i:i+chunk])
+ decomp=decomp+decompressor.flush()
+
+ print 'Progressive compression (level 9):'
+ print ' Original:', len(s), 'Compressed:', len(comptext),
+ print 'Uncompressed:', len(decomp)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Grammar/Grammar b/AppPkg/Applications/Python/Python-2.7.2/Grammar/Grammar
new file mode 100644
index 0000000000..a321787a48
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Grammar/Grammar
@@ -0,0 +1,142 @@
+# Grammar for Python
+
+# Note: Changing the grammar specified in this file will most likely
+# require corresponding changes in the parser module
+# (../Modules/parsermodule.c). If you can't make the changes to
+# that module yourself, please co-ordinate the required changes
+# with someone who can; ask around on python-dev for help. Fred
+# Drake will probably be listening there.
+
+# NOTE WELL: You should also follow all the steps listed in PEP 306,
+# "How to Change Python's Grammar"
+
+# Start symbols for the grammar:
+# single_input is a single interactive statement;
+# file_input is a module or sequence of commands read from an input file;
+# eval_input is the input for the eval() and input() functions.
+# NB: compound_stmt in single_input is followed by extra NEWLINE!
+single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
+file_input: (NEWLINE | stmt)* ENDMARKER
+eval_input: testlist NEWLINE* ENDMARKER
+
+decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
+decorators: decorator+
+decorated: decorators (classdef | funcdef)
+funcdef: 'def' NAME parameters ':' suite
+parameters: '(' [varargslist] ')'
+varargslist: ((fpdef ['=' test] ',')*
+ ('*' NAME [',' '**' NAME] | '**' NAME) |
+ fpdef ['=' test] (',' fpdef ['=' test])* [','])
+fpdef: NAME | '(' fplist ')'
+fplist: fpdef (',' fpdef)* [',']
+
+stmt: simple_stmt | compound_stmt
+simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
+small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
+ import_stmt | global_stmt | exec_stmt | assert_stmt)
+expr_stmt: testlist (augassign (yield_expr|testlist) |
+ ('=' (yield_expr|testlist))*)
+augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
+ '<<=' | '>>=' | '**=' | '//=')
+# For normal assignments, additional restrictions enforced by the interpreter
+print_stmt: 'print' ( [ test (',' test)* [','] ] |
+ '>>' test [ (',' test)+ [','] ] )
+del_stmt: 'del' exprlist
+pass_stmt: 'pass'
+flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
+break_stmt: 'break'
+continue_stmt: 'continue'
+return_stmt: 'return' [testlist]
+yield_stmt: yield_expr
+raise_stmt: 'raise' [test [',' test [',' test]]]
+import_stmt: import_name | import_from
+import_name: 'import' dotted_as_names
+import_from: ('from' ('.'* dotted_name | '.'+)
+ 'import' ('*' | '(' import_as_names ')' | import_as_names))
+import_as_name: NAME ['as' NAME]
+dotted_as_name: dotted_name ['as' NAME]
+import_as_names: import_as_name (',' import_as_name)* [',']
+dotted_as_names: dotted_as_name (',' dotted_as_name)*
+dotted_name: NAME ('.' NAME)*
+global_stmt: 'global' NAME (',' NAME)*
+exec_stmt: 'exec' expr ['in' test [',' test]]
+assert_stmt: 'assert' test [',' test]
+
+compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated
+if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
+while_stmt: 'while' test ':' suite ['else' ':' suite]
+for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
+try_stmt: ('try' ':' suite
+ ((except_clause ':' suite)+
+ ['else' ':' suite]
+ ['finally' ':' suite] |
+ 'finally' ':' suite))
+with_stmt: 'with' with_item (',' with_item)* ':' suite
+with_item: test ['as' expr]
+# NB compile.c makes sure that the default except clause is last
+except_clause: 'except' [test [('as' | ',') test]]
+suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
+
+# Backward compatibility cruft to support:
+# [ x for x in lambda: True, lambda: False if x() ]
+# even while also allowing:
+# lambda x: 5 if x else 2
+# (But not a mix of the two)
+testlist_safe: old_test [(',' old_test)+ [',']]
+old_test: or_test | old_lambdef
+old_lambdef: 'lambda' [varargslist] ':' old_test
+
+test: or_test ['if' or_test 'else' test] | lambdef
+or_test: and_test ('or' and_test)*
+and_test: not_test ('and' not_test)*
+not_test: 'not' not_test | comparison
+comparison: expr (comp_op expr)*
+comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
+expr: xor_expr ('|' xor_expr)*
+xor_expr: and_expr ('^' and_expr)*
+and_expr: shift_expr ('&' shift_expr)*
+shift_expr: arith_expr (('<<'|'>>') arith_expr)*
+arith_expr: term (('+'|'-') term)*
+term: factor (('*'|'/'|'%'|'//') factor)*
+factor: ('+'|'-'|'~') factor | power
+power: atom trailer* ['**' factor]
+atom: ('(' [yield_expr|testlist_comp] ')' |
+ '[' [listmaker] ']' |
+ '{' [dictorsetmaker] '}' |
+ '`' testlist1 '`' |
+ NAME | NUMBER | STRING+)
+listmaker: test ( list_for | (',' test)* [','] )
+testlist_comp: test ( comp_for | (',' test)* [','] )
+lambdef: 'lambda' [varargslist] ':' test
+trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
+subscriptlist: subscript (',' subscript)* [',']
+subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop]
+sliceop: ':' [test]
+exprlist: expr (',' expr)* [',']
+testlist: test (',' test)* [',']
+dictorsetmaker: ( (test ':' test (comp_for | (',' test ':' test)* [','])) |
+ (test (comp_for | (',' test)* [','])) )
+
+classdef: 'class' NAME ['(' [testlist] ')'] ':' suite
+
+arglist: (argument ',')* (argument [',']
+ |'*' test (',' argument)* [',' '**' test]
+ |'**' test)
+# The reason that keywords are test nodes instead of NAME is that using NAME
+# results in an ambiguity. ast.c makes sure it's a NAME.
+argument: test [comp_for] | test '=' test
+
+list_iter: list_for | list_if
+list_for: 'for' exprlist 'in' testlist_safe [list_iter]
+list_if: 'if' old_test [list_iter]
+
+comp_iter: comp_for | comp_if
+comp_for: 'for' exprlist 'in' or_test [comp_iter]
+comp_if: 'if' old_test [comp_iter]
+
+testlist1: test (',' test)*
+
+# not used in grammar, but may appear in "node" passed from Parser to Compiler
+encoding_decl: NAME
+
+yield_expr: 'yield' [testlist]
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/Python-ast.h b/AppPkg/Applications/Python/Python-2.7.2/Include/Python-ast.h
new file mode 100644
index 0000000000..d794c3273f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/Python-ast.h
@@ -0,0 +1,535 @@
+/* File automatically generated by Parser/asdl_c.py. */
+
+#include "asdl.h"
+
+typedef struct _mod *mod_ty;
+
+typedef struct _stmt *stmt_ty;
+
+typedef struct _expr *expr_ty;
+
+typedef enum _expr_context { Load=1, Store=2, Del=3, AugLoad=4, AugStore=5,
+ Param=6 } expr_context_ty;
+
+typedef struct _slice *slice_ty;
+
+typedef enum _boolop { And=1, Or=2 } boolop_ty;
+
+typedef enum _operator { Add=1, Sub=2, Mult=3, Div=4, Mod=5, Pow=6, LShift=7,
+ RShift=8, BitOr=9, BitXor=10, BitAnd=11, FloorDiv=12 }
+ operator_ty;
+
+typedef enum _unaryop { Invert=1, Not=2, UAdd=3, USub=4 } unaryop_ty;
+
+typedef enum _cmpop { Eq=1, NotEq=2, Lt=3, LtE=4, Gt=5, GtE=6, Is=7, IsNot=8,
+ In=9, NotIn=10 } cmpop_ty;
+
+typedef struct _comprehension *comprehension_ty;
+
+typedef struct _excepthandler *excepthandler_ty;
+
+typedef struct _arguments *arguments_ty;
+
+typedef struct _keyword *keyword_ty;
+
+typedef struct _alias *alias_ty;
+
+
+enum _mod_kind {Module_kind=1, Interactive_kind=2, Expression_kind=3,
+ Suite_kind=4};
+struct _mod {
+ enum _mod_kind kind;
+ union {
+ struct {
+ asdl_seq *body;
+ } Module;
+
+ struct {
+ asdl_seq *body;
+ } Interactive;
+
+ struct {
+ expr_ty body;
+ } Expression;
+
+ struct {
+ asdl_seq *body;
+ } Suite;
+
+ } v;
+};
+
+enum _stmt_kind {FunctionDef_kind=1, ClassDef_kind=2, Return_kind=3,
+ Delete_kind=4, Assign_kind=5, AugAssign_kind=6, Print_kind=7,
+ For_kind=8, While_kind=9, If_kind=10, With_kind=11,
+ Raise_kind=12, TryExcept_kind=13, TryFinally_kind=14,
+ Assert_kind=15, Import_kind=16, ImportFrom_kind=17,
+ Exec_kind=18, Global_kind=19, Expr_kind=20, Pass_kind=21,
+ Break_kind=22, Continue_kind=23};
+struct _stmt {
+ enum _stmt_kind kind;
+ union {
+ struct {
+ identifier name;
+ arguments_ty args;
+ asdl_seq *body;
+ asdl_seq *decorator_list;
+ } FunctionDef;
+
+ struct {
+ identifier name;
+ asdl_seq *bases;
+ asdl_seq *body;
+ asdl_seq *decorator_list;
+ } ClassDef;
+
+ struct {
+ expr_ty value;
+ } Return;
+
+ struct {
+ asdl_seq *targets;
+ } Delete;
+
+ struct {
+ asdl_seq *targets;
+ expr_ty value;
+ } Assign;
+
+ struct {
+ expr_ty target;
+ operator_ty op;
+ expr_ty value;
+ } AugAssign;
+
+ struct {
+ expr_ty dest;
+ asdl_seq *values;
+ bool nl;
+ } Print;
+
+ struct {
+ expr_ty target;
+ expr_ty iter;
+ asdl_seq *body;
+ asdl_seq *orelse;
+ } For;
+
+ struct {
+ expr_ty test;
+ asdl_seq *body;
+ asdl_seq *orelse;
+ } While;
+
+ struct {
+ expr_ty test;
+ asdl_seq *body;
+ asdl_seq *orelse;
+ } If;
+
+ struct {
+ expr_ty context_expr;
+ expr_ty optional_vars;
+ asdl_seq *body;
+ } With;
+
+ struct {
+ expr_ty type;
+ expr_ty inst;
+ expr_ty tback;
+ } Raise;
+
+ struct {
+ asdl_seq *body;
+ asdl_seq *handlers;
+ asdl_seq *orelse;
+ } TryExcept;
+
+ struct {
+ asdl_seq *body;
+ asdl_seq *finalbody;
+ } TryFinally;
+
+ struct {
+ expr_ty test;
+ expr_ty msg;
+ } Assert;
+
+ struct {
+ asdl_seq *names;
+ } Import;
+
+ struct {
+ identifier module;
+ asdl_seq *names;
+ int level;
+ } ImportFrom;
+
+ struct {
+ expr_ty body;
+ expr_ty globals;
+ expr_ty locals;
+ } Exec;
+
+ struct {
+ asdl_seq *names;
+ } Global;
+
+ struct {
+ expr_ty value;
+ } Expr;
+
+ } v;
+ int lineno;
+ int col_offset;
+};
+
+enum _expr_kind {BoolOp_kind=1, BinOp_kind=2, UnaryOp_kind=3, Lambda_kind=4,
+ IfExp_kind=5, Dict_kind=6, Set_kind=7, ListComp_kind=8,
+ SetComp_kind=9, DictComp_kind=10, GeneratorExp_kind=11,
+ Yield_kind=12, Compare_kind=13, Call_kind=14, Repr_kind=15,
+ Num_kind=16, Str_kind=17, Attribute_kind=18,
+ Subscript_kind=19, Name_kind=20, List_kind=21, Tuple_kind=22};
+struct _expr {
+ enum _expr_kind kind;
+ union {
+ struct {
+ boolop_ty op;
+ asdl_seq *values;
+ } BoolOp;
+
+ struct {
+ expr_ty left;
+ operator_ty op;
+ expr_ty right;
+ } BinOp;
+
+ struct {
+ unaryop_ty op;
+ expr_ty operand;
+ } UnaryOp;
+
+ struct {
+ arguments_ty args;
+ expr_ty body;
+ } Lambda;
+
+ struct {
+ expr_ty test;
+ expr_ty body;
+ expr_ty orelse;
+ } IfExp;
+
+ struct {
+ asdl_seq *keys;
+ asdl_seq *values;
+ } Dict;
+
+ struct {
+ asdl_seq *elts;
+ } Set;
+
+ struct {
+ expr_ty elt;
+ asdl_seq *generators;
+ } ListComp;
+
+ struct {
+ expr_ty elt;
+ asdl_seq *generators;
+ } SetComp;
+
+ struct {
+ expr_ty key;
+ expr_ty value;
+ asdl_seq *generators;
+ } DictComp;
+
+ struct {
+ expr_ty elt;
+ asdl_seq *generators;
+ } GeneratorExp;
+
+ struct {
+ expr_ty value;
+ } Yield;
+
+ struct {
+ expr_ty left;
+ asdl_int_seq *ops;
+ asdl_seq *comparators;
+ } Compare;
+
+ struct {
+ expr_ty func;
+ asdl_seq *args;
+ asdl_seq *keywords;
+ expr_ty starargs;
+ expr_ty kwargs;
+ } Call;
+
+ struct {
+ expr_ty value;
+ } Repr;
+
+ struct {
+ object n;
+ } Num;
+
+ struct {
+ string s;
+ } Str;
+
+ struct {
+ expr_ty value;
+ identifier attr;
+ expr_context_ty ctx;
+ } Attribute;
+
+ struct {
+ expr_ty value;
+ slice_ty slice;
+ expr_context_ty ctx;
+ } Subscript;
+
+ struct {
+ identifier id;
+ expr_context_ty ctx;
+ } Name;
+
+ struct {
+ asdl_seq *elts;
+ expr_context_ty ctx;
+ } List;
+
+ struct {
+ asdl_seq *elts;
+ expr_context_ty ctx;
+ } Tuple;
+
+ } v;
+ int lineno;
+ int col_offset;
+};
+
+enum _slice_kind {Ellipsis_kind=1, Slice_kind=2, ExtSlice_kind=3, Index_kind=4};
+struct _slice {
+ enum _slice_kind kind;
+ union {
+ struct {
+ expr_ty lower;
+ expr_ty upper;
+ expr_ty step;
+ } Slice;
+
+ struct {
+ asdl_seq *dims;
+ } ExtSlice;
+
+ struct {
+ expr_ty value;
+ } Index;
+
+ } v;
+};
+
+struct _comprehension {
+ expr_ty target;
+ expr_ty iter;
+ asdl_seq *ifs;
+};
+
+enum _excepthandler_kind {ExceptHandler_kind=1};
+struct _excepthandler {
+ enum _excepthandler_kind kind;
+ union {
+ struct {
+ expr_ty type;
+ expr_ty name;
+ asdl_seq *body;
+ } ExceptHandler;
+
+ } v;
+ int lineno;
+ int col_offset;
+};
+
+struct _arguments {
+ asdl_seq *args;
+ identifier vararg;
+ identifier kwarg;
+ asdl_seq *defaults;
+};
+
+struct _keyword {
+ identifier arg;
+ expr_ty value;
+};
+
+struct _alias {
+ identifier name;
+ identifier asname;
+};
+
+
+#define Module(a0, a1) _Py_Module(a0, a1)
+mod_ty _Py_Module(asdl_seq * body, PyArena *arena);
+#define Interactive(a0, a1) _Py_Interactive(a0, a1)
+mod_ty _Py_Interactive(asdl_seq * body, PyArena *arena);
+#define Expression(a0, a1) _Py_Expression(a0, a1)
+mod_ty _Py_Expression(expr_ty body, PyArena *arena);
+#define Suite(a0, a1) _Py_Suite(a0, a1)
+mod_ty _Py_Suite(asdl_seq * body, PyArena *arena);
+#define FunctionDef(a0, a1, a2, a3, a4, a5, a6) _Py_FunctionDef(a0, a1, a2, a3, a4, a5, a6)
+stmt_ty _Py_FunctionDef(identifier name, arguments_ty args, asdl_seq * body,
+ asdl_seq * decorator_list, int lineno, int col_offset,
+ PyArena *arena);
+#define ClassDef(a0, a1, a2, a3, a4, a5, a6) _Py_ClassDef(a0, a1, a2, a3, a4, a5, a6)
+stmt_ty _Py_ClassDef(identifier name, asdl_seq * bases, asdl_seq * body,
+ asdl_seq * decorator_list, int lineno, int col_offset,
+ PyArena *arena);
+#define Return(a0, a1, a2, a3) _Py_Return(a0, a1, a2, a3)
+stmt_ty _Py_Return(expr_ty value, int lineno, int col_offset, PyArena *arena);
+#define Delete(a0, a1, a2, a3) _Py_Delete(a0, a1, a2, a3)
+stmt_ty _Py_Delete(asdl_seq * targets, int lineno, int col_offset, PyArena
+ *arena);
+#define Assign(a0, a1, a2, a3, a4) _Py_Assign(a0, a1, a2, a3, a4)
+stmt_ty _Py_Assign(asdl_seq * targets, expr_ty value, int lineno, int
+ col_offset, PyArena *arena);
+#define AugAssign(a0, a1, a2, a3, a4, a5) _Py_AugAssign(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_AugAssign(expr_ty target, operator_ty op, expr_ty value, int
+ lineno, int col_offset, PyArena *arena);
+#define Print(a0, a1, a2, a3, a4, a5) _Py_Print(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_Print(expr_ty dest, asdl_seq * values, bool nl, int lineno, int
+ col_offset, PyArena *arena);
+#define For(a0, a1, a2, a3, a4, a5, a6) _Py_For(a0, a1, a2, a3, a4, a5, a6)
+stmt_ty _Py_For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq *
+ orelse, int lineno, int col_offset, PyArena *arena);
+#define While(a0, a1, a2, a3, a4, a5) _Py_While(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_While(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno,
+ int col_offset, PyArena *arena);
+#define If(a0, a1, a2, a3, a4, a5) _Py_If(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_If(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno,
+ int col_offset, PyArena *arena);
+#define With(a0, a1, a2, a3, a4, a5) _Py_With(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_With(expr_ty context_expr, expr_ty optional_vars, asdl_seq * body,
+ int lineno, int col_offset, PyArena *arena);
+#define Raise(a0, a1, a2, a3, a4, a5) _Py_Raise(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_Raise(expr_ty type, expr_ty inst, expr_ty tback, int lineno, int
+ col_offset, PyArena *arena);
+#define TryExcept(a0, a1, a2, a3, a4, a5) _Py_TryExcept(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_TryExcept(asdl_seq * body, asdl_seq * handlers, asdl_seq * orelse,
+ int lineno, int col_offset, PyArena *arena);
+#define TryFinally(a0, a1, a2, a3, a4) _Py_TryFinally(a0, a1, a2, a3, a4)
+stmt_ty _Py_TryFinally(asdl_seq * body, asdl_seq * finalbody, int lineno, int
+ col_offset, PyArena *arena);
+#define Assert(a0, a1, a2, a3, a4) _Py_Assert(a0, a1, a2, a3, a4)
+stmt_ty _Py_Assert(expr_ty test, expr_ty msg, int lineno, int col_offset,
+ PyArena *arena);
+#define Import(a0, a1, a2, a3) _Py_Import(a0, a1, a2, a3)
+stmt_ty _Py_Import(asdl_seq * names, int lineno, int col_offset, PyArena
+ *arena);
+#define ImportFrom(a0, a1, a2, a3, a4, a5) _Py_ImportFrom(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_ImportFrom(identifier module, asdl_seq * names, int level, int
+ lineno, int col_offset, PyArena *arena);
+#define Exec(a0, a1, a2, a3, a4, a5) _Py_Exec(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_Exec(expr_ty body, expr_ty globals, expr_ty locals, int lineno, int
+ col_offset, PyArena *arena);
+#define Global(a0, a1, a2, a3) _Py_Global(a0, a1, a2, a3)
+stmt_ty _Py_Global(asdl_seq * names, int lineno, int col_offset, PyArena
+ *arena);
+#define Expr(a0, a1, a2, a3) _Py_Expr(a0, a1, a2, a3)
+stmt_ty _Py_Expr(expr_ty value, int lineno, int col_offset, PyArena *arena);
+#define Pass(a0, a1, a2) _Py_Pass(a0, a1, a2)
+stmt_ty _Py_Pass(int lineno, int col_offset, PyArena *arena);
+#define Break(a0, a1, a2) _Py_Break(a0, a1, a2)
+stmt_ty _Py_Break(int lineno, int col_offset, PyArena *arena);
+#define Continue(a0, a1, a2) _Py_Continue(a0, a1, a2)
+stmt_ty _Py_Continue(int lineno, int col_offset, PyArena *arena);
+#define BoolOp(a0, a1, a2, a3, a4) _Py_BoolOp(a0, a1, a2, a3, a4)
+expr_ty _Py_BoolOp(boolop_ty op, asdl_seq * values, int lineno, int col_offset,
+ PyArena *arena);
+#define BinOp(a0, a1, a2, a3, a4, a5) _Py_BinOp(a0, a1, a2, a3, a4, a5)
+expr_ty _Py_BinOp(expr_ty left, operator_ty op, expr_ty right, int lineno, int
+ col_offset, PyArena *arena);
+#define UnaryOp(a0, a1, a2, a3, a4) _Py_UnaryOp(a0, a1, a2, a3, a4)
+expr_ty _Py_UnaryOp(unaryop_ty op, expr_ty operand, int lineno, int col_offset,
+ PyArena *arena);
+#define Lambda(a0, a1, a2, a3, a4) _Py_Lambda(a0, a1, a2, a3, a4)
+expr_ty _Py_Lambda(arguments_ty args, expr_ty body, int lineno, int col_offset,
+ PyArena *arena);
+#define IfExp(a0, a1, a2, a3, a4, a5) _Py_IfExp(a0, a1, a2, a3, a4, a5)
+expr_ty _Py_IfExp(expr_ty test, expr_ty body, expr_ty orelse, int lineno, int
+ col_offset, PyArena *arena);
+#define Dict(a0, a1, a2, a3, a4) _Py_Dict(a0, a1, a2, a3, a4)
+expr_ty _Py_Dict(asdl_seq * keys, asdl_seq * values, int lineno, int
+ col_offset, PyArena *arena);
+#define Set(a0, a1, a2, a3) _Py_Set(a0, a1, a2, a3)
+expr_ty _Py_Set(asdl_seq * elts, int lineno, int col_offset, PyArena *arena);
+#define ListComp(a0, a1, a2, a3, a4) _Py_ListComp(a0, a1, a2, a3, a4)
+expr_ty _Py_ListComp(expr_ty elt, asdl_seq * generators, int lineno, int
+ col_offset, PyArena *arena);
+#define SetComp(a0, a1, a2, a3, a4) _Py_SetComp(a0, a1, a2, a3, a4)
+expr_ty _Py_SetComp(expr_ty elt, asdl_seq * generators, int lineno, int
+ col_offset, PyArena *arena);
+#define DictComp(a0, a1, a2, a3, a4, a5) _Py_DictComp(a0, a1, a2, a3, a4, a5)
+expr_ty _Py_DictComp(expr_ty key, expr_ty value, asdl_seq * generators, int
+ lineno, int col_offset, PyArena *arena);
+#define GeneratorExp(a0, a1, a2, a3, a4) _Py_GeneratorExp(a0, a1, a2, a3, a4)
+expr_ty _Py_GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int
+ col_offset, PyArena *arena);
+#define Yield(a0, a1, a2, a3) _Py_Yield(a0, a1, a2, a3)
+expr_ty _Py_Yield(expr_ty value, int lineno, int col_offset, PyArena *arena);
+#define Compare(a0, a1, a2, a3, a4, a5) _Py_Compare(a0, a1, a2, a3, a4, a5)
+expr_ty _Py_Compare(expr_ty left, asdl_int_seq * ops, asdl_seq * comparators,
+ int lineno, int col_offset, PyArena *arena);
+#define Call(a0, a1, a2, a3, a4, a5, a6, a7) _Py_Call(a0, a1, a2, a3, a4, a5, a6, a7)
+expr_ty _Py_Call(expr_ty func, asdl_seq * args, asdl_seq * keywords, expr_ty
+ starargs, expr_ty kwargs, int lineno, int col_offset, PyArena
+ *arena);
+#define Repr(a0, a1, a2, a3) _Py_Repr(a0, a1, a2, a3)
+expr_ty _Py_Repr(expr_ty value, int lineno, int col_offset, PyArena *arena);
+#define Num(a0, a1, a2, a3) _Py_Num(a0, a1, a2, a3)
+expr_ty _Py_Num(object n, int lineno, int col_offset, PyArena *arena);
+#define Str(a0, a1, a2, a3) _Py_Str(a0, a1, a2, a3)
+expr_ty _Py_Str(string s, int lineno, int col_offset, PyArena *arena);
+#define Attribute(a0, a1, a2, a3, a4, a5) _Py_Attribute(a0, a1, a2, a3, a4, a5)
+expr_ty _Py_Attribute(expr_ty value, identifier attr, expr_context_ty ctx, int
+ lineno, int col_offset, PyArena *arena);
+#define Subscript(a0, a1, a2, a3, a4, a5) _Py_Subscript(a0, a1, a2, a3, a4, a5)
+expr_ty _Py_Subscript(expr_ty value, slice_ty slice, expr_context_ty ctx, int
+ lineno, int col_offset, PyArena *arena);
+#define Name(a0, a1, a2, a3, a4) _Py_Name(a0, a1, a2, a3, a4)
+expr_ty _Py_Name(identifier id, expr_context_ty ctx, int lineno, int
+ col_offset, PyArena *arena);
+#define List(a0, a1, a2, a3, a4) _Py_List(a0, a1, a2, a3, a4)
+expr_ty _Py_List(asdl_seq * elts, expr_context_ty ctx, int lineno, int
+ col_offset, PyArena *arena);
+#define Tuple(a0, a1, a2, a3, a4) _Py_Tuple(a0, a1, a2, a3, a4)
+expr_ty _Py_Tuple(asdl_seq * elts, expr_context_ty ctx, int lineno, int
+ col_offset, PyArena *arena);
+#define Ellipsis(a0) _Py_Ellipsis(a0)
+slice_ty _Py_Ellipsis(PyArena *arena);
+#define Slice(a0, a1, a2, a3) _Py_Slice(a0, a1, a2, a3)
+slice_ty _Py_Slice(expr_ty lower, expr_ty upper, expr_ty step, PyArena *arena);
+#define ExtSlice(a0, a1) _Py_ExtSlice(a0, a1)
+slice_ty _Py_ExtSlice(asdl_seq * dims, PyArena *arena);
+#define Index(a0, a1) _Py_Index(a0, a1)
+slice_ty _Py_Index(expr_ty value, PyArena *arena);
+#define comprehension(a0, a1, a2, a3) _Py_comprehension(a0, a1, a2, a3)
+comprehension_ty _Py_comprehension(expr_ty target, expr_ty iter, asdl_seq *
+ ifs, PyArena *arena);
+#define ExceptHandler(a0, a1, a2, a3, a4, a5) _Py_ExceptHandler(a0, a1, a2, a3, a4, a5)
+excepthandler_ty _Py_ExceptHandler(expr_ty type, expr_ty name, asdl_seq * body,
+ int lineno, int col_offset, PyArena *arena);
+#define arguments(a0, a1, a2, a3, a4) _Py_arguments(a0, a1, a2, a3, a4)
+arguments_ty _Py_arguments(asdl_seq * args, identifier vararg, identifier
+ kwarg, asdl_seq * defaults, PyArena *arena);
+#define keyword(a0, a1, a2) _Py_keyword(a0, a1, a2)
+keyword_ty _Py_keyword(identifier arg, expr_ty value, PyArena *arena);
+#define alias(a0, a1, a2) _Py_alias(a0, a1, a2)
+alias_ty _Py_alias(identifier name, identifier asname, PyArena *arena);
+
+PyObject* PyAST_mod2obj(mod_ty t);
+mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode);
+int PyAST_Check(PyObject* obj);
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/Python.h b/AppPkg/Applications/Python/Python-2.7.2/Include/Python.h
new file mode 100644
index 0000000000..5abad474c2
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/Python.h
@@ -0,0 +1,178 @@
+#ifndef Py_PYTHON_H
+#define Py_PYTHON_H
+/* Since this is a "meta-include" file, no #ifdef __cplusplus / extern "C" { */
+
+/* Include nearly all Python header files */
+
+#include "patchlevel.h"
+#include "pyconfig.h"
+#include "pymacconfig.h"
+
+/* Cyclic gc is always enabled, starting with release 2.3a1. Supply the
+ * old symbol for the benefit of extension modules written before then
+ * that may be conditionalizing on it. The core doesn't use it anymore.
+ */
+#ifndef WITH_CYCLE_GC
+#define WITH_CYCLE_GC 1
+#endif
+
+#include
+
+#ifndef UCHAR_MAX
+#error "Something's broken. UCHAR_MAX should be defined in limits.h."
+#endif
+
+#if UCHAR_MAX != 255
+#error "Python's source code assumes C's unsigned char is an 8-bit type."
+#endif
+
+#if defined(__sgi) && defined(WITH_THREAD) && !defined(_SGI_MP_SOURCE)
+#define _SGI_MP_SOURCE
+#endif
+
+#include
+#ifndef NULL
+# error "Python.h requires that stdio.h define NULL."
+#endif
+
+#include
+#ifdef HAVE_ERRNO_H
+#include
+#endif
+#include
+#ifdef HAVE_UNISTD_H
+#include
+#endif
+
+/* For size_t? */
+#ifdef HAVE_STDDEF_H
+#include
+#endif
+
+/* CAUTION: Build setups should ensure that NDEBUG is defined on the
+ * compiler command line when building Python in release mode; else
+ * assert() calls won't be removed.
+ */
+#include
+
+#include "pyport.h"
+
+/* pyconfig.h or pyport.h may or may not define DL_IMPORT */
+#ifndef DL_IMPORT /* declarations for DLL import/export */
+#define DL_IMPORT(RTYPE) RTYPE
+#endif
+#ifndef DL_EXPORT /* declarations for DLL import/export */
+#define DL_EXPORT(RTYPE) RTYPE
+#endif
+
+/* Debug-mode build with pymalloc implies PYMALLOC_DEBUG.
+ * PYMALLOC_DEBUG is in error if pymalloc is not in use.
+ */
+#if defined(Py_DEBUG) && defined(WITH_PYMALLOC) && !defined(PYMALLOC_DEBUG)
+#define PYMALLOC_DEBUG
+#endif
+#if defined(PYMALLOC_DEBUG) && !defined(WITH_PYMALLOC)
+#error "PYMALLOC_DEBUG requires WITH_PYMALLOC"
+#endif
+#include "pymath.h"
+#include "pymem.h"
+
+#include "object.h"
+#include "objimpl.h"
+
+#include "pydebug.h"
+
+#include "unicodeobject.h"
+#include "intobject.h"
+#include "boolobject.h"
+#include "longobject.h"
+#include "floatobject.h"
+#ifndef WITHOUT_COMPLEX
+#include "complexobject.h"
+#endif
+#include "rangeobject.h"
+#include "stringobject.h"
+#include "memoryobject.h"
+#include "bufferobject.h"
+#include "bytesobject.h"
+#include "bytearrayobject.h"
+#include "tupleobject.h"
+#include "listobject.h"
+#include "dictobject.h"
+#include "enumobject.h"
+#include "setobject.h"
+#include "methodobject.h"
+#include "moduleobject.h"
+#include "funcobject.h"
+#include "classobject.h"
+#include "fileobject.h"
+#include "cobject.h"
+#include "pycapsule.h"
+#include "traceback.h"
+#include "sliceobject.h"
+#include "cellobject.h"
+#include "iterobject.h"
+#include "genobject.h"
+#include "descrobject.h"
+#include "warnings.h"
+#include "weakrefobject.h"
+
+#include "codecs.h"
+#include "pyerrors.h"
+
+#include "pystate.h"
+
+#include "pyarena.h"
+#include "modsupport.h"
+#include "pythonrun.h"
+#include "ceval.h"
+#include "sysmodule.h"
+#include "intrcheck.h"
+#include "import.h"
+
+#include "abstract.h"
+
+#include "compile.h"
+#include "eval.h"
+
+#include "pyctype.h"
+#include "pystrtod.h"
+#include "pystrcmp.h"
+#include "dtoa.h"
+
+/* _Py_Mangle is defined in compile.c */
+PyAPI_FUNC(PyObject*) _Py_Mangle(PyObject *p, PyObject *name);
+
+/* PyArg_GetInt is deprecated and should not be used, use PyArg_Parse(). */
+#define PyArg_GetInt(v, a) PyArg_Parse((v), "i", (a))
+
+/* PyArg_NoArgs should not be necessary.
+ Set ml_flags in the PyMethodDef to METH_NOARGS. */
+#define PyArg_NoArgs(v) PyArg_Parse(v, "")
+
+/* Argument must be a char or an int in [-128, 127] or [0, 255]. */
+#define Py_CHARMASK(c) ((unsigned char)((c) & 0xff))
+
+#include "pyfpe.h"
+
+/* These definitions must match corresponding definitions in graminit.h.
+ There's code in compile.c that checks that they are the same. */
+#define Py_single_input 256
+#define Py_file_input 257
+#define Py_eval_input 258
+
+#ifdef HAVE_PTH
+/* GNU pth user-space thread support */
+#include
+#endif
+
+/* Define macros for inline documentation. */
+#define PyDoc_VAR(name) static char name[]
+#define PyDoc_STRVAR(name,str) PyDoc_VAR(name) = PyDoc_STR(str)
+#ifdef WITH_DOC_STRINGS
+#define PyDoc_STR(str) str
+#else
+#define PyDoc_STR(str) ""
+#endif
+
+#endif /* !Py_PYTHON_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/abstract.h b/AppPkg/Applications/Python/Python-2.7.2/Include/abstract.h
new file mode 100644
index 0000000000..241fd44872
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/abstract.h
@@ -0,0 +1,1396 @@
+#ifndef Py_ABSTRACTOBJECT_H
+#define Py_ABSTRACTOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef PY_SSIZE_T_CLEAN
+#define PyObject_CallFunction _PyObject_CallFunction_SizeT
+#define PyObject_CallMethod _PyObject_CallMethod_SizeT
+#endif
+
+/* Abstract Object Interface (many thanks to Jim Fulton) */
+
+/*
+ PROPOSAL: A Generic Python Object Interface for Python C Modules
+
+Problem
+
+ Python modules written in C that must access Python objects must do
+ so through routines whose interfaces are described by a set of
+ include files. Unfortunately, these routines vary according to the
+ object accessed. To use these routines, the C programmer must check
+ the type of the object being used and must call a routine based on
+ the object type. For example, to access an element of a sequence,
+ the programmer must determine whether the sequence is a list or a
+ tuple:
+
+ if(is_tupleobject(o))
+ e=gettupleitem(o,i)
+ else if(is_listitem(o))
+ e=getlistitem(o,i)
+
+ If the programmer wants to get an item from another type of object
+ that provides sequence behavior, there is no clear way to do it
+ correctly.
+
+ The persistent programmer may peruse object.h and find that the
+ _typeobject structure provides a means of invoking up to (currently
+ about) 41 special operators. So, for example, a routine can get an
+ item from any object that provides sequence behavior. However, to
+ use this mechanism, the programmer must make their code dependent on
+ the current Python implementation.
+
+ Also, certain semantics, especially memory management semantics, may
+ differ by the type of object being used. Unfortunately, these
+ semantics are not clearly described in the current include files.
+ An abstract interface providing more consistent semantics is needed.
+
+Proposal
+
+ I propose the creation of a standard interface (with an associated
+ library of routines and/or macros) for generically obtaining the
+ services of Python objects. This proposal can be viewed as one
+ components of a Python C interface consisting of several components.
+
+ From the viewpoint of C access to Python services, we have (as
+ suggested by Guido in off-line discussions):
+
+ - "Very high level layer": two or three functions that let you exec or
+ eval arbitrary Python code given as a string in a module whose name is
+ given, passing C values in and getting C values out using
+ mkvalue/getargs style format strings. This does not require the user
+ to declare any variables of type "PyObject *". This should be enough
+ to write a simple application that gets Python code from the user,
+ execs it, and returns the output or errors. (Error handling must also
+ be part of this API.)
+
+ - "Abstract objects layer": which is the subject of this proposal.
+ It has many functions operating on objects, and lest you do many
+ things from C that you can also write in Python, without going
+ through the Python parser.
+
+ - "Concrete objects layer": This is the public type-dependent
+ interface provided by the standard built-in types, such as floats,
+ strings, and lists. This interface exists and is currently
+ documented by the collection of include files provided with the
+ Python distributions.
+
+ From the point of view of Python accessing services provided by C
+ modules:
+
+ - "Python module interface": this interface consist of the basic
+ routines used to define modules and their members. Most of the
+ current extensions-writing guide deals with this interface.
+
+ - "Built-in object interface": this is the interface that a new
+ built-in type must provide and the mechanisms and rules that a
+ developer of a new built-in type must use and follow.
+
+ This proposal is a "first-cut" that is intended to spur
+ discussion. See especially the lists of notes.
+
+ The Python C object interface will provide four protocols: object,
+ numeric, sequence, and mapping. Each protocol consists of a
+ collection of related operations. If an operation that is not
+ provided by a particular type is invoked, then a standard exception,
+ NotImplementedError is raised with a operation name as an argument.
+ In addition, for convenience this interface defines a set of
+ constructors for building objects of built-in types. This is needed
+ so new objects can be returned from C functions that otherwise treat
+ objects generically.
+
+Memory Management
+
+ For all of the functions described in this proposal, if a function
+ retains a reference to a Python object passed as an argument, then the
+ function will increase the reference count of the object. It is
+ unnecessary for the caller to increase the reference count of an
+ argument in anticipation of the object's retention.
+
+ All Python objects returned from functions should be treated as new
+ objects. Functions that return objects assume that the caller will
+ retain a reference and the reference count of the object has already
+ been incremented to account for this fact. A caller that does not
+ retain a reference to an object that is returned from a function
+ must decrement the reference count of the object (using
+ DECREF(object)) to prevent memory leaks.
+
+ Note that the behavior mentioned here is different from the current
+ behavior for some objects (e.g. lists and tuples) when certain
+ type-specific routines are called directly (e.g. setlistitem). The
+ proposed abstraction layer will provide a consistent memory
+ management interface, correcting for inconsistent behavior for some
+ built-in types.
+
+Protocols
+
+xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
+
+/* Object Protocol: */
+
+ /* Implemented elsewhere:
+
+ int PyObject_Print(PyObject *o, FILE *fp, int flags);
+
+ Print an object, o, on file, fp. Returns -1 on
+ error. The flags argument is used to enable certain printing
+ options. The only option currently supported is Py_Print_RAW.
+
+ (What should be said about Py_Print_RAW?)
+
+ */
+
+ /* Implemented elsewhere:
+
+ int PyObject_HasAttrString(PyObject *o, char *attr_name);
+
+ Returns 1 if o has the attribute attr_name, and 0 otherwise.
+ This is equivalent to the Python expression:
+ hasattr(o,attr_name).
+
+ This function always succeeds.
+
+ */
+
+ /* Implemented elsewhere:
+
+ PyObject* PyObject_GetAttrString(PyObject *o, char *attr_name);
+
+ Retrieve an attributed named attr_name form object o.
+ Returns the attribute value on success, or NULL on failure.
+ This is the equivalent of the Python expression: o.attr_name.
+
+ */
+
+ /* Implemented elsewhere:
+
+ int PyObject_HasAttr(PyObject *o, PyObject *attr_name);
+
+ Returns 1 if o has the attribute attr_name, and 0 otherwise.
+ This is equivalent to the Python expression:
+ hasattr(o,attr_name).
+
+ This function always succeeds.
+
+ */
+
+ /* Implemented elsewhere:
+
+ PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name);
+
+ Retrieve an attributed named attr_name form object o.
+ Returns the attribute value on success, or NULL on failure.
+ This is the equivalent of the Python expression: o.attr_name.
+
+ */
+
+
+ /* Implemented elsewhere:
+
+ int PyObject_SetAttrString(PyObject *o, char *attr_name, PyObject *v);
+
+ Set the value of the attribute named attr_name, for object o,
+ to the value, v. Returns -1 on failure. This is
+ the equivalent of the Python statement: o.attr_name=v.
+
+ */
+
+ /* Implemented elsewhere:
+
+ int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v);
+
+ Set the value of the attribute named attr_name, for object o,
+ to the value, v. Returns -1 on failure. This is
+ the equivalent of the Python statement: o.attr_name=v.
+
+ */
+
+ /* implemented as a macro:
+
+ int PyObject_DelAttrString(PyObject *o, char *attr_name);
+
+ Delete attribute named attr_name, for object o. Returns
+ -1 on failure. This is the equivalent of the Python
+ statement: del o.attr_name.
+
+ */
+#define PyObject_DelAttrString(O,A) PyObject_SetAttrString((O),(A),NULL)
+
+ /* implemented as a macro:
+
+ int PyObject_DelAttr(PyObject *o, PyObject *attr_name);
+
+ Delete attribute named attr_name, for object o. Returns -1
+ on failure. This is the equivalent of the Python
+ statement: del o.attr_name.
+
+ */
+#define PyObject_DelAttr(O,A) PyObject_SetAttr((O),(A),NULL)
+
+ PyAPI_FUNC(int) PyObject_Cmp(PyObject *o1, PyObject *o2, int *result);
+
+ /*
+ Compare the values of o1 and o2 using a routine provided by
+ o1, if one exists, otherwise with a routine provided by o2.
+ The result of the comparison is returned in result. Returns
+ -1 on failure. This is the equivalent of the Python
+ statement: result=cmp(o1,o2).
+
+ */
+
+ /* Implemented elsewhere:
+
+ int PyObject_Compare(PyObject *o1, PyObject *o2);
+
+ Compare the values of o1 and o2 using a routine provided by
+ o1, if one exists, otherwise with a routine provided by o2.
+ Returns the result of the comparison on success. On error,
+ the value returned is undefined. This is equivalent to the
+ Python expression: cmp(o1,o2).
+
+ */
+
+ /* Implemented elsewhere:
+
+ PyObject *PyObject_Repr(PyObject *o);
+
+ Compute the string representation of object, o. Returns the
+ string representation on success, NULL on failure. This is
+ the equivalent of the Python expression: repr(o).
+
+ Called by the repr() built-in function and by reverse quotes.
+
+ */
+
+ /* Implemented elsewhere:
+
+ PyObject *PyObject_Str(PyObject *o);
+
+ Compute the string representation of object, o. Returns the
+ string representation on success, NULL on failure. This is
+ the equivalent of the Python expression: str(o).)
+
+ Called by the str() built-in function and by the print
+ statement.
+
+ */
+
+ /* Implemented elsewhere:
+
+ PyObject *PyObject_Unicode(PyObject *o);
+
+ Compute the unicode representation of object, o. Returns the
+ unicode representation on success, NULL on failure. This is
+ the equivalent of the Python expression: unistr(o).)
+
+ Called by the unistr() built-in function.
+
+ */
+
+ /* Declared elsewhere
+
+ PyAPI_FUNC(int) PyCallable_Check(PyObject *o);
+
+ Determine if the object, o, is callable. Return 1 if the
+ object is callable and 0 otherwise.
+
+ This function always succeeds.
+
+ */
+
+
+
+ PyAPI_FUNC(PyObject *) PyObject_Call(PyObject *callable_object,
+ PyObject *args, PyObject *kw);
+
+ /*
+ Call a callable Python object, callable_object, with
+ arguments and keywords arguments. The 'args' argument can not be
+ NULL, but the 'kw' argument can be NULL.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyObject_CallObject(PyObject *callable_object,
+ PyObject *args);
+
+ /*
+ Call a callable Python object, callable_object, with
+ arguments given by the tuple, args. If no arguments are
+ needed, then args may be NULL. Returns the result of the
+ call on success, or NULL on failure. This is the equivalent
+ of the Python expression: apply(o,args).
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyObject_CallFunction(PyObject *callable_object,
+ char *format, ...);
+
+ /*
+ Call a callable Python object, callable_object, with a
+ variable number of C arguments. The C arguments are described
+ using a mkvalue-style format string. The format may be NULL,
+ indicating that no arguments are provided. Returns the
+ result of the call on success, or NULL on failure. This is
+ the equivalent of the Python expression: apply(o,args).
+
+ */
+
+
+ PyAPI_FUNC(PyObject *) PyObject_CallMethod(PyObject *o, char *m,
+ char *format, ...);
+
+ /*
+ Call the method named m of object o with a variable number of
+ C arguments. The C arguments are described by a mkvalue
+ format string. The format may be NULL, indicating that no
+ arguments are provided. Returns the result of the call on
+ success, or NULL on failure. This is the equivalent of the
+ Python expression: o.method(args).
+ */
+
+ PyAPI_FUNC(PyObject *) _PyObject_CallFunction_SizeT(PyObject *callable,
+ char *format, ...);
+ PyAPI_FUNC(PyObject *) _PyObject_CallMethod_SizeT(PyObject *o,
+ char *name,
+ char *format, ...);
+
+ PyAPI_FUNC(PyObject *) PyObject_CallFunctionObjArgs(PyObject *callable,
+ ...);
+
+ /*
+ Call a callable Python object, callable_object, with a
+ variable number of C arguments. The C arguments are provided
+ as PyObject * values, terminated by a NULL. Returns the
+ result of the call on success, or NULL on failure. This is
+ the equivalent of the Python expression: apply(o,args).
+ */
+
+
+ PyAPI_FUNC(PyObject *) PyObject_CallMethodObjArgs(PyObject *o,
+ PyObject *m, ...);
+
+ /*
+ Call the method named m of object o with a variable number of
+ C arguments. The C arguments are provided as PyObject *
+ values, terminated by NULL. Returns the result of the call
+ on success, or NULL on failure. This is the equivalent of
+ the Python expression: o.method(args).
+ */
+
+
+ /* Implemented elsewhere:
+
+ long PyObject_Hash(PyObject *o);
+
+ Compute and return the hash, hash_value, of an object, o. On
+ failure, return -1. This is the equivalent of the Python
+ expression: hash(o).
+
+ */
+
+
+ /* Implemented elsewhere:
+
+ int PyObject_IsTrue(PyObject *o);
+
+ Returns 1 if the object, o, is considered to be true, 0 if o is
+ considered to be false and -1 on failure. This is equivalent to the
+ Python expression: not not o
+
+ */
+
+ /* Implemented elsewhere:
+
+ int PyObject_Not(PyObject *o);
+
+ Returns 0 if the object, o, is considered to be true, 1 if o is
+ considered to be false and -1 on failure. This is equivalent to the
+ Python expression: not o
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyObject_Type(PyObject *o);
+
+ /*
+ On success, returns a type object corresponding to the object
+ type of object o. On failure, returns NULL. This is
+ equivalent to the Python expression: type(o).
+ */
+
+ PyAPI_FUNC(Py_ssize_t) PyObject_Size(PyObject *o);
+
+ /*
+ Return the size of object o. If the object, o, provides
+ both sequence and mapping protocols, the sequence size is
+ returned. On error, -1 is returned. This is the equivalent
+ to the Python expression: len(o).
+
+ */
+
+ /* For DLL compatibility */
+#undef PyObject_Length
+ PyAPI_FUNC(Py_ssize_t) PyObject_Length(PyObject *o);
+#define PyObject_Length PyObject_Size
+
+ PyAPI_FUNC(Py_ssize_t) _PyObject_LengthHint(PyObject *o, Py_ssize_t);
+
+ /*
+ Guess the size of object o using len(o) or o.__length_hint__().
+ If neither of those return a non-negative value, then return the
+ default value. If one of the calls fails, this function returns -1.
+ */
+
+ PyAPI_FUNC(PyObject *) PyObject_GetItem(PyObject *o, PyObject *key);
+
+ /*
+ Return element of o corresponding to the object, key, or NULL
+ on failure. This is the equivalent of the Python expression:
+ o[key].
+
+ */
+
+ PyAPI_FUNC(int) PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v);
+
+ /*
+ Map the object, key, to the value, v. Returns
+ -1 on failure. This is the equivalent of the Python
+ statement: o[key]=v.
+ */
+
+ PyAPI_FUNC(int) PyObject_DelItemString(PyObject *o, char *key);
+
+ /*
+ Remove the mapping for object, key, from the object *o.
+ Returns -1 on failure. This is equivalent to
+ the Python statement: del o[key].
+ */
+
+ PyAPI_FUNC(int) PyObject_DelItem(PyObject *o, PyObject *key);
+
+ /*
+ Delete the mapping for key from *o. Returns -1 on failure.
+ This is the equivalent of the Python statement: del o[key].
+ */
+
+ PyAPI_FUNC(int) PyObject_AsCharBuffer(PyObject *obj,
+ const char **buffer,
+ Py_ssize_t *buffer_len);
+
+ /*
+ Takes an arbitrary object which must support the (character,
+ single segment) buffer interface and returns a pointer to a
+ read-only memory location useable as character based input
+ for subsequent processing.
+
+ 0 is returned on success. buffer and buffer_len are only
+ set in case no error occurs. Otherwise, -1 is returned and
+ an exception set.
+
+ */
+
+ PyAPI_FUNC(int) PyObject_CheckReadBuffer(PyObject *obj);
+
+ /*
+ Checks whether an arbitrary object supports the (character,
+ single segment) buffer interface. Returns 1 on success, 0
+ on failure.
+
+ */
+
+ PyAPI_FUNC(int) PyObject_AsReadBuffer(PyObject *obj,
+ const void **buffer,
+ Py_ssize_t *buffer_len);
+
+ /*
+ Same as PyObject_AsCharBuffer() except that this API expects
+ (readable, single segment) buffer interface and returns a
+ pointer to a read-only memory location which can contain
+ arbitrary data.
+
+ 0 is returned on success. buffer and buffer_len are only
+ set in case no error occurs. Otherwise, -1 is returned and
+ an exception set.
+
+ */
+
+ PyAPI_FUNC(int) PyObject_AsWriteBuffer(PyObject *obj,
+ void **buffer,
+ Py_ssize_t *buffer_len);
+
+ /*
+ Takes an arbitrary object which must support the (writeable,
+ single segment) buffer interface and returns a pointer to a
+ writeable memory location in buffer of size buffer_len.
+
+ 0 is returned on success. buffer and buffer_len are only
+ set in case no error occurs. Otherwise, -1 is returned and
+ an exception set.
+
+ */
+
+ /* new buffer API */
+
+#define PyObject_CheckBuffer(obj) \
+ (((obj)->ob_type->tp_as_buffer != NULL) && \
+ (PyType_HasFeature((obj)->ob_type, Py_TPFLAGS_HAVE_NEWBUFFER)) && \
+ ((obj)->ob_type->tp_as_buffer->bf_getbuffer != NULL))
+
+ /* Return 1 if the getbuffer function is available, otherwise
+ return 0 */
+
+ PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view,
+ int flags);
+
+ /* This is a C-API version of the getbuffer function call. It checks
+ to make sure object has the required function pointer and issues the
+ call. Returns -1 and raises an error on failure and returns 0 on
+ success
+ */
+
+
+ PyAPI_FUNC(void *) PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices);
+
+ /* Get the memory area pointed to by the indices for the buffer given.
+ Note that view->ndim is the assumed size of indices
+ */
+
+ PyAPI_FUNC(int) PyBuffer_SizeFromFormat(const char *);
+
+ /* Return the implied itemsize of the data-format area from a
+ struct-style description */
+
+
+
+ PyAPI_FUNC(int) PyBuffer_ToContiguous(void *buf, Py_buffer *view,
+ Py_ssize_t len, char fort);
+
+ PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf,
+ Py_ssize_t len, char fort);
+
+
+ /* Copy len bytes of data from the contiguous chunk of memory
+ pointed to by buf into the buffer exported by obj. Return
+ 0 on success and return -1 and raise a PyBuffer_Error on
+ error (i.e. the object does not have a buffer interface or
+ it is not working).
+
+ If fort is 'F' and the object is multi-dimensional,
+ then the data will be copied into the array in
+ Fortran-style (first dimension varies the fastest). If
+ fort is 'C', then the data will be copied into the array
+ in C-style (last dimension varies the fastest). If fort
+ is 'A', then it does not matter and the copy will be made
+ in whatever way is more efficient.
+
+ */
+
+ PyAPI_FUNC(int) PyObject_CopyData(PyObject *dest, PyObject *src);
+
+ /* Copy the data from the src buffer to the buffer of destination
+ */
+
+ PyAPI_FUNC(int) PyBuffer_IsContiguous(Py_buffer *view, char fort);
+
+
+ PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims,
+ Py_ssize_t *shape,
+ Py_ssize_t *strides,
+ int itemsize,
+ char fort);
+
+ /* Fill the strides array with byte-strides of a contiguous
+ (Fortran-style if fort is 'F' or C-style otherwise)
+ array of the given shape with the given number of bytes
+ per element.
+ */
+
+ PyAPI_FUNC(int) PyBuffer_FillInfo(Py_buffer *view, PyObject *o, void *buf,
+ Py_ssize_t len, int readonly,
+ int flags);
+
+ /* Fills in a buffer-info structure correctly for an exporter
+ that can only share a contiguous chunk of memory of
+ "unsigned bytes" of the given length. Returns 0 on success
+ and -1 (with raising an error) on error.
+ */
+
+ PyAPI_FUNC(void) PyBuffer_Release(Py_buffer *view);
+
+ /* Releases a Py_buffer obtained from getbuffer ParseTuple's s*.
+ */
+
+ PyAPI_FUNC(PyObject *) PyObject_Format(PyObject* obj,
+ PyObject *format_spec);
+ /*
+ Takes an arbitrary object and returns the result of
+ calling obj.__format__(format_spec).
+ */
+
+/* Iterators */
+
+ PyAPI_FUNC(PyObject *) PyObject_GetIter(PyObject *);
+ /* Takes an object and returns an iterator for it.
+ This is typically a new iterator but if the argument
+ is an iterator, this returns itself. */
+
+#define PyIter_Check(obj) \
+ (PyType_HasFeature((obj)->ob_type, Py_TPFLAGS_HAVE_ITER) && \
+ (obj)->ob_type->tp_iternext != NULL && \
+ (obj)->ob_type->tp_iternext != &_PyObject_NextNotImplemented)
+
+ PyAPI_FUNC(PyObject *) PyIter_Next(PyObject *);
+ /* Takes an iterator object and calls its tp_iternext slot,
+ returning the next value. If the iterator is exhausted,
+ this returns NULL without setting an exception.
+ NULL with an exception means an error occurred. */
+
+/* Number Protocol:*/
+
+ PyAPI_FUNC(int) PyNumber_Check(PyObject *o);
+
+ /*
+ Returns 1 if the object, o, provides numeric protocols, and
+ false otherwise.
+
+ This function always succeeds.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Add(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of adding o1 and o2, or null on failure.
+ This is the equivalent of the Python expression: o1+o2.
+
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Subtract(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of subtracting o2 from o1, or null on
+ failure. This is the equivalent of the Python expression:
+ o1-o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Multiply(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of multiplying o1 and o2, or null on
+ failure. This is the equivalent of the Python expression:
+ o1*o2.
+
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Divide(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of dividing o1 by o2, or null on failure.
+ This is the equivalent of the Python expression: o1/o2.
+
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_FloorDivide(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of dividing o1 by o2 giving an integral result,
+ or null on failure.
+ This is the equivalent of the Python expression: o1//o2.
+
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_TrueDivide(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of dividing o1 by o2 giving a float result,
+ or null on failure.
+ This is the equivalent of the Python expression: o1/o2.
+
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Remainder(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the remainder of dividing o1 by o2, or null on
+ failure. This is the equivalent of the Python expression:
+ o1%o2.
+
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Divmod(PyObject *o1, PyObject *o2);
+
+ /*
+ See the built-in function divmod. Returns NULL on failure.
+ This is the equivalent of the Python expression:
+ divmod(o1,o2).
+
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Power(PyObject *o1, PyObject *o2,
+ PyObject *o3);
+
+ /*
+ See the built-in function pow. Returns NULL on failure.
+ This is the equivalent of the Python expression:
+ pow(o1,o2,o3), where o3 is optional.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Negative(PyObject *o);
+
+ /*
+ Returns the negation of o on success, or null on failure.
+ This is the equivalent of the Python expression: -o.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Positive(PyObject *o);
+
+ /*
+ Returns the (what?) of o on success, or NULL on failure.
+ This is the equivalent of the Python expression: +o.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Absolute(PyObject *o);
+
+ /*
+ Returns the absolute value of o, or null on failure. This is
+ the equivalent of the Python expression: abs(o).
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Invert(PyObject *o);
+
+ /*
+ Returns the bitwise negation of o on success, or NULL on
+ failure. This is the equivalent of the Python expression:
+ ~o.
+
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Lshift(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of left shifting o1 by o2 on success, or
+ NULL on failure. This is the equivalent of the Python
+ expression: o1 << o2.
+
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Rshift(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of right shifting o1 by o2 on success, or
+ NULL on failure. This is the equivalent of the Python
+ expression: o1 >> o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_And(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of bitwise and of o1 and o2 on success, or
+ NULL on failure. This is the equivalent of the Python
+ expression: o1&o2.
+
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Xor(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the bitwise exclusive or of o1 by o2 on success, or
+ NULL on failure. This is the equivalent of the Python
+ expression: o1^o2.
+
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Or(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of bitwise or on o1 and o2 on success, or
+ NULL on failure. This is the equivalent of the Python
+ expression: o1|o2.
+
+ */
+
+ /* Implemented elsewhere:
+
+ int PyNumber_Coerce(PyObject **p1, PyObject **p2);
+
+ This function takes the addresses of two variables of type
+ PyObject*.
+
+ If the objects pointed to by *p1 and *p2 have the same type,
+ increment their reference count and return 0 (success).
+ If the objects can be converted to a common numeric type,
+ replace *p1 and *p2 by their converted value (with 'new'
+ reference counts), and return 0.
+ If no conversion is possible, or if some other error occurs,
+ return -1 (failure) and don't increment the reference counts.
+ The call PyNumber_Coerce(&o1, &o2) is equivalent to the Python
+ statement o1, o2 = coerce(o1, o2).
+
+ */
+
+#define PyIndex_Check(obj) \
+ ((obj)->ob_type->tp_as_number != NULL && \
+ PyType_HasFeature((obj)->ob_type, Py_TPFLAGS_HAVE_INDEX) && \
+ (obj)->ob_type->tp_as_number->nb_index != NULL)
+
+ PyAPI_FUNC(PyObject *) PyNumber_Index(PyObject *o);
+
+ /*
+ Returns the object converted to a Python long or int
+ or NULL with an error raised on failure.
+ */
+
+ PyAPI_FUNC(Py_ssize_t) PyNumber_AsSsize_t(PyObject *o, PyObject *exc);
+
+ /*
+ Returns the Integral instance converted to an int. The
+ instance is expected to be int or long or have an __int__
+ method. Steals integral's reference. error_format will be
+ used to create the TypeError if integral isn't actually an
+ Integral instance. error_format should be a format string
+ that can accept a char* naming integral's type.
+ */
+
+ PyAPI_FUNC(PyObject *) _PyNumber_ConvertIntegralToInt(
+ PyObject *integral,
+ const char* error_format);
+
+ /*
+ Returns the object converted to Py_ssize_t by going through
+ PyNumber_Index first. If an overflow error occurs while
+ converting the int-or-long to Py_ssize_t, then the second argument
+ is the error-type to return. If it is NULL, then the overflow error
+ is cleared and the value is clipped.
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Int(PyObject *o);
+
+ /*
+ Returns the o converted to an integer object on success, or
+ NULL on failure. This is the equivalent of the Python
+ expression: int(o).
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Long(PyObject *o);
+
+ /*
+ Returns the o converted to a long integer object on success,
+ or NULL on failure. This is the equivalent of the Python
+ expression: long(o).
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_Float(PyObject *o);
+
+ /*
+ Returns the o converted to a float object on success, or NULL
+ on failure. This is the equivalent of the Python expression:
+ float(o).
+ */
+
+/* In-place variants of (some of) the above number protocol functions */
+
+ PyAPI_FUNC(PyObject *) PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of adding o2 to o1, possibly in-place, or null
+ on failure. This is the equivalent of the Python expression:
+ o1 += o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of subtracting o2 from o1, possibly in-place or
+ null on failure. This is the equivalent of the Python expression:
+ o1 -= o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of multiplying o1 by o2, possibly in-place, or
+ null on failure. This is the equivalent of the Python expression:
+ o1 *= o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_InPlaceDivide(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of dividing o1 by o2, possibly in-place, or null
+ on failure. This is the equivalent of the Python expression:
+ o1 /= o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_InPlaceFloorDivide(PyObject *o1,
+ PyObject *o2);
+
+ /*
+ Returns the result of dividing o1 by o2 giving an integral result,
+ possibly in-place, or null on failure.
+ This is the equivalent of the Python expression:
+ o1 /= o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_InPlaceTrueDivide(PyObject *o1,
+ PyObject *o2);
+
+ /*
+ Returns the result of dividing o1 by o2 giving a float result,
+ possibly in-place, or null on failure.
+ This is the equivalent of the Python expression:
+ o1 /= o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the remainder of dividing o1 by o2, possibly in-place, or
+ null on failure. This is the equivalent of the Python expression:
+ o1 %= o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_InPlacePower(PyObject *o1, PyObject *o2,
+ PyObject *o3);
+
+ /*
+ Returns the result of raising o1 to the power of o2, possibly
+ in-place, or null on failure. This is the equivalent of the Python
+ expression: o1 **= o2, or pow(o1, o2, o3) if o3 is present.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of left shifting o1 by o2, possibly in-place, or
+ null on failure. This is the equivalent of the Python expression:
+ o1 <<= o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of right shifting o1 by o2, possibly in-place or
+ null on failure. This is the equivalent of the Python expression:
+ o1 >>= o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of bitwise and of o1 and o2, possibly in-place,
+ or null on failure. This is the equivalent of the Python
+ expression: o1 &= o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_InPlaceXor(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the bitwise exclusive or of o1 by o2, possibly in-place, or
+ null on failure. This is the equivalent of the Python expression:
+ o1 ^= o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PyNumber_InPlaceOr(PyObject *o1, PyObject *o2);
+
+ /*
+ Returns the result of bitwise or of o1 and o2, possibly in-place,
+ or null on failure. This is the equivalent of the Python
+ expression: o1 |= o2.
+
+ */
+
+
+ PyAPI_FUNC(PyObject *) PyNumber_ToBase(PyObject *n, int base);
+
+ /*
+ Returns the integer n converted to a string with a base, with a base
+ marker of 0b, 0o or 0x prefixed if applicable.
+ If n is not an int object, it is converted with PyNumber_Index first.
+ */
+
+
+/* Sequence protocol:*/
+
+ PyAPI_FUNC(int) PySequence_Check(PyObject *o);
+
+ /*
+ Return 1 if the object provides sequence protocol, and zero
+ otherwise.
+
+ This function always succeeds.
+
+ */
+
+ PyAPI_FUNC(Py_ssize_t) PySequence_Size(PyObject *o);
+
+ /*
+ Return the size of sequence object o, or -1 on failure.
+
+ */
+
+ /* For DLL compatibility */
+#undef PySequence_Length
+ PyAPI_FUNC(Py_ssize_t) PySequence_Length(PyObject *o);
+#define PySequence_Length PySequence_Size
+
+
+ PyAPI_FUNC(PyObject *) PySequence_Concat(PyObject *o1, PyObject *o2);
+
+ /*
+ Return the concatenation of o1 and o2 on success, and NULL on
+ failure. This is the equivalent of the Python
+ expression: o1+o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PySequence_Repeat(PyObject *o, Py_ssize_t count);
+
+ /*
+ Return the result of repeating sequence object o count times,
+ or NULL on failure. This is the equivalent of the Python
+ expression: o1*count.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PySequence_GetItem(PyObject *o, Py_ssize_t i);
+
+ /*
+ Return the ith element of o, or NULL on failure. This is the
+ equivalent of the Python expression: o[i].
+ */
+
+ PyAPI_FUNC(PyObject *) PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2);
+
+ /*
+ Return the slice of sequence object o between i1 and i2, or
+ NULL on failure. This is the equivalent of the Python
+ expression: o[i1:i2].
+
+ */
+
+ PyAPI_FUNC(int) PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v);
+
+ /*
+ Assign object v to the ith element of o. Returns
+ -1 on failure. This is the equivalent of the Python
+ statement: o[i]=v.
+
+ */
+
+ PyAPI_FUNC(int) PySequence_DelItem(PyObject *o, Py_ssize_t i);
+
+ /*
+ Delete the ith element of object v. Returns
+ -1 on failure. This is the equivalent of the Python
+ statement: del o[i].
+ */
+
+ PyAPI_FUNC(int) PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2,
+ PyObject *v);
+
+ /*
+ Assign the sequence object, v, to the slice in sequence
+ object, o, from i1 to i2. Returns -1 on failure. This is the
+ equivalent of the Python statement: o[i1:i2]=v.
+ */
+
+ PyAPI_FUNC(int) PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2);
+
+ /*
+ Delete the slice in sequence object, o, from i1 to i2.
+ Returns -1 on failure. This is the equivalent of the Python
+ statement: del o[i1:i2].
+ */
+
+ PyAPI_FUNC(PyObject *) PySequence_Tuple(PyObject *o);
+
+ /*
+ Returns the sequence, o, as a tuple on success, and NULL on failure.
+ This is equivalent to the Python expression: tuple(o)
+ */
+
+
+ PyAPI_FUNC(PyObject *) PySequence_List(PyObject *o);
+ /*
+ Returns the sequence, o, as a list on success, and NULL on failure.
+ This is equivalent to the Python expression: list(o)
+ */
+
+ PyAPI_FUNC(PyObject *) PySequence_Fast(PyObject *o, const char* m);
+ /*
+ Returns the sequence, o, as a tuple, unless it's already a
+ tuple or list. Use PySequence_Fast_GET_ITEM to access the
+ members of this list, and PySequence_Fast_GET_SIZE to get its length.
+
+ Returns NULL on failure. If the object does not support iteration,
+ raises a TypeError exception with m as the message text.
+ */
+
+#define PySequence_Fast_GET_SIZE(o) \
+ (PyList_Check(o) ? PyList_GET_SIZE(o) : PyTuple_GET_SIZE(o))
+ /*
+ Return the size of o, assuming that o was returned by
+ PySequence_Fast and is not NULL.
+ */
+
+#define PySequence_Fast_GET_ITEM(o, i)\
+ (PyList_Check(o) ? PyList_GET_ITEM(o, i) : PyTuple_GET_ITEM(o, i))
+ /*
+ Return the ith element of o, assuming that o was returned by
+ PySequence_Fast, and that i is within bounds.
+ */
+
+#define PySequence_ITEM(o, i)\
+ ( Py_TYPE(o)->tp_as_sequence->sq_item(o, i) )
+ /* Assume tp_as_sequence and sq_item exist and that i does not
+ need to be corrected for a negative index
+ */
+
+#define PySequence_Fast_ITEMS(sf) \
+ (PyList_Check(sf) ? ((PyListObject *)(sf))->ob_item \
+ : ((PyTupleObject *)(sf))->ob_item)
+ /* Return a pointer to the underlying item array for
+ an object retured by PySequence_Fast */
+
+ PyAPI_FUNC(Py_ssize_t) PySequence_Count(PyObject *o, PyObject *value);
+
+ /*
+ Return the number of occurrences on value on o, that is,
+ return the number of keys for which o[key]==value. On
+ failure, return -1. This is equivalent to the Python
+ expression: o.count(value).
+ */
+
+ PyAPI_FUNC(int) PySequence_Contains(PyObject *seq, PyObject *ob);
+ /*
+ Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
+ Use __contains__ if possible, else _PySequence_IterSearch().
+ */
+
+#define PY_ITERSEARCH_COUNT 1
+#define PY_ITERSEARCH_INDEX 2
+#define PY_ITERSEARCH_CONTAINS 3
+ PyAPI_FUNC(Py_ssize_t) _PySequence_IterSearch(PyObject *seq,
+ PyObject *obj, int operation);
+ /*
+ Iterate over seq. Result depends on the operation:
+ PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if
+ error.
+ PY_ITERSEARCH_INDEX: return 0-based index of first occurrence of
+ obj in seq; set ValueError and return -1 if none found;
+ also return -1 on error.
+ PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on
+ error.
+ */
+
+/* For DLL-level backwards compatibility */
+#undef PySequence_In
+ PyAPI_FUNC(int) PySequence_In(PyObject *o, PyObject *value);
+
+/* For source-level backwards compatibility */
+#define PySequence_In PySequence_Contains
+
+ /*
+ Determine if o contains value. If an item in o is equal to
+ X, return 1, otherwise return 0. On error, return -1. This
+ is equivalent to the Python expression: value in o.
+ */
+
+ PyAPI_FUNC(Py_ssize_t) PySequence_Index(PyObject *o, PyObject *value);
+
+ /*
+ Return the first index for which o[i]=value. On error,
+ return -1. This is equivalent to the Python
+ expression: o.index(value).
+ */
+
+/* In-place versions of some of the above Sequence functions. */
+
+ PyAPI_FUNC(PyObject *) PySequence_InPlaceConcat(PyObject *o1, PyObject *o2);
+
+ /*
+ Append o2 to o1, in-place when possible. Return the resulting
+ object, which could be o1, or NULL on failure. This is the
+ equivalent of the Python expression: o1 += o2.
+
+ */
+
+ PyAPI_FUNC(PyObject *) PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count);
+
+ /*
+ Repeat o1 by count, in-place when possible. Return the resulting
+ object, which could be o1, or NULL on failure. This is the
+ equivalent of the Python expression: o1 *= count.
+
+ */
+
+/* Mapping protocol:*/
+
+ PyAPI_FUNC(int) PyMapping_Check(PyObject *o);
+
+ /*
+ Return 1 if the object provides mapping protocol, and zero
+ otherwise.
+
+ This function always succeeds.
+ */
+
+ PyAPI_FUNC(Py_ssize_t) PyMapping_Size(PyObject *o);
+
+ /*
+ Returns the number of keys in object o on success, and -1 on
+ failure. For objects that do not provide sequence protocol,
+ this is equivalent to the Python expression: len(o).
+ */
+
+ /* For DLL compatibility */
+#undef PyMapping_Length
+ PyAPI_FUNC(Py_ssize_t) PyMapping_Length(PyObject *o);
+#define PyMapping_Length PyMapping_Size
+
+
+ /* implemented as a macro:
+
+ int PyMapping_DelItemString(PyObject *o, char *key);
+
+ Remove the mapping for object, key, from the object *o.
+ Returns -1 on failure. This is equivalent to
+ the Python statement: del o[key].
+ */
+#define PyMapping_DelItemString(O,K) PyObject_DelItemString((O),(K))
+
+ /* implemented as a macro:
+
+ int PyMapping_DelItem(PyObject *o, PyObject *key);
+
+ Remove the mapping for object, key, from the object *o.
+ Returns -1 on failure. This is equivalent to
+ the Python statement: del o[key].
+ */
+#define PyMapping_DelItem(O,K) PyObject_DelItem((O),(K))
+
+ PyAPI_FUNC(int) PyMapping_HasKeyString(PyObject *o, char *key);
+
+ /*
+ On success, return 1 if the mapping object has the key, key,
+ and 0 otherwise. This is equivalent to the Python expression:
+ o.has_key(key).
+
+ This function always succeeds.
+ */
+
+ PyAPI_FUNC(int) PyMapping_HasKey(PyObject *o, PyObject *key);
+
+ /*
+ Return 1 if the mapping object has the key, key,
+ and 0 otherwise. This is equivalent to the Python expression:
+ o.has_key(key).
+
+ This function always succeeds.
+
+ */
+
+ /* Implemented as macro:
+
+ PyObject *PyMapping_Keys(PyObject *o);
+
+ On success, return a list of the keys in object o. On
+ failure, return NULL. This is equivalent to the Python
+ expression: o.keys().
+ */
+#define PyMapping_Keys(O) PyObject_CallMethod(O,"keys",NULL)
+
+ /* Implemented as macro:
+
+ PyObject *PyMapping_Values(PyObject *o);
+
+ On success, return a list of the values in object o. On
+ failure, return NULL. This is equivalent to the Python
+ expression: o.values().
+ */
+#define PyMapping_Values(O) PyObject_CallMethod(O,"values",NULL)
+
+ /* Implemented as macro:
+
+ PyObject *PyMapping_Items(PyObject *o);
+
+ On success, return a list of the items in object o, where
+ each item is a tuple containing a key-value pair. On
+ failure, return NULL. This is equivalent to the Python
+ expression: o.items().
+
+ */
+#define PyMapping_Items(O) PyObject_CallMethod(O,"items",NULL)
+
+ PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o, char *key);
+
+ /*
+ Return element of o corresponding to the object, key, or NULL
+ on failure. This is the equivalent of the Python expression:
+ o[key].
+ */
+
+ PyAPI_FUNC(int) PyMapping_SetItemString(PyObject *o, char *key,
+ PyObject *value);
+
+ /*
+ Map the object, key, to the value, v. Returns
+ -1 on failure. This is the equivalent of the Python
+ statement: o[key]=v.
+ */
+
+
+PyAPI_FUNC(int) PyObject_IsInstance(PyObject *object, PyObject *typeorclass);
+ /* isinstance(object, typeorclass) */
+
+PyAPI_FUNC(int) PyObject_IsSubclass(PyObject *object, PyObject *typeorclass);
+ /* issubclass(object, typeorclass) */
+
+
+PyAPI_FUNC(int) _PyObject_RealIsInstance(PyObject *inst, PyObject *cls);
+
+PyAPI_FUNC(int) _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls);
+
+
+/* For internal use by buffer API functions */
+PyAPI_FUNC(void) _Py_add_one_to_index_F(int nd, Py_ssize_t *index,
+ const Py_ssize_t *shape);
+PyAPI_FUNC(void) _Py_add_one_to_index_C(int nd, Py_ssize_t *index,
+ const Py_ssize_t *shape);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* Py_ABSTRACTOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/asdl.h b/AppPkg/Applications/Python/Python-2.7.2/Include/asdl.h
new file mode 100644
index 0000000000..d72b2f81ea
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/asdl.h
@@ -0,0 +1,45 @@
+#ifndef Py_ASDL_H
+#define Py_ASDL_H
+
+typedef PyObject * identifier;
+typedef PyObject * string;
+typedef PyObject * object;
+
+#ifndef __cplusplus
+typedef enum {false, true} bool;
+#endif
+
+/* It would be nice if the code generated by asdl_c.py was completely
+ independent of Python, but it is a goal the requires too much work
+ at this stage. So, for example, I'll represent identifiers as
+ interned Python strings.
+*/
+
+/* XXX A sequence should be typed so that its use can be typechecked. */
+
+typedef struct {
+ int size;
+ void *elements[1];
+} asdl_seq;
+
+typedef struct {
+ int size;
+ int elements[1];
+} asdl_int_seq;
+
+asdl_seq *asdl_seq_new(int size, PyArena *arena);
+asdl_int_seq *asdl_int_seq_new(int size, PyArena *arena);
+
+#define asdl_seq_GET(S, I) (S)->elements[(I)]
+#define asdl_seq_LEN(S) ((S) == NULL ? 0 : (S)->size)
+#ifdef Py_DEBUG
+#define asdl_seq_SET(S, I, V) { \
+ int _asdl_i = (I); \
+ assert((S) && _asdl_i < (S)->size); \
+ (S)->elements[_asdl_i] = (V); \
+}
+#else
+#define asdl_seq_SET(S, I, V) (S)->elements[I] = (V)
+#endif
+
+#endif /* !Py_ASDL_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/ast.h b/AppPkg/Applications/Python/Python-2.7.2/Include/ast.h
new file mode 100644
index 0000000000..77dbe5ffc6
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/ast.h
@@ -0,0 +1,13 @@
+#ifndef Py_AST_H
+#define Py_AST_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_FUNC(mod_ty) PyAST_FromNode(const node *, PyCompilerFlags *flags,
+ const char *, PyArena *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_AST_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/bitset.h b/AppPkg/Applications/Python/Python-2.7.2/Include/bitset.h
new file mode 100644
index 0000000000..028acdf042
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/bitset.h
@@ -0,0 +1,32 @@
+
+#ifndef Py_BITSET_H
+#define Py_BITSET_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Bitset interface */
+
+#define BYTE char
+
+typedef BYTE *bitset;
+
+bitset newbitset(int nbits);
+void delbitset(bitset bs);
+#define testbit(ss, ibit) (((ss)[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0)
+int addbit(bitset bs, int ibit); /* Returns 0 if already set */
+int samebitset(bitset bs1, bitset bs2, int nbits);
+void mergebitset(bitset bs1, bitset bs2, int nbits);
+
+#define BITSPERBYTE (8*sizeof(BYTE))
+#define NBYTES(nbits) (((nbits) + BITSPERBYTE - 1) / BITSPERBYTE)
+
+#define BIT2BYTE(ibit) ((ibit) / BITSPERBYTE)
+#define BIT2SHIFT(ibit) ((ibit) % BITSPERBYTE)
+#define BIT2MASK(ibit) (1 << BIT2SHIFT(ibit))
+#define BYTE2BIT(ibyte) ((ibyte) * BITSPERBYTE)
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_BITSET_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/boolobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/boolobject.h
new file mode 100644
index 0000000000..9dd0e43501
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/boolobject.h
@@ -0,0 +1,36 @@
+/* Boolean object interface */
+
+#ifndef Py_BOOLOBJECT_H
+#define Py_BOOLOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+typedef PyIntObject PyBoolObject;
+
+PyAPI_DATA(PyTypeObject) PyBool_Type;
+
+#define PyBool_Check(x) (Py_TYPE(x) == &PyBool_Type)
+
+/* Py_False and Py_True are the only two bools in existence.
+Don't forget to apply Py_INCREF() when returning either!!! */
+
+/* Don't use these directly */
+PyAPI_DATA(PyIntObject) _Py_ZeroStruct, _Py_TrueStruct;
+
+/* Use these macros */
+#define Py_False ((PyObject *) &_Py_ZeroStruct)
+#define Py_True ((PyObject *) &_Py_TrueStruct)
+
+/* Macros for returning Py_True or Py_False, respectively */
+#define Py_RETURN_TRUE return Py_INCREF(Py_True), Py_True
+#define Py_RETURN_FALSE return Py_INCREF(Py_False), Py_False
+
+/* Function to return a bool from a C long */
+PyAPI_FUNC(PyObject *) PyBool_FromLong(long);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_BOOLOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/bufferobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/bufferobject.h
new file mode 100644
index 0000000000..6c33a8b023
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/bufferobject.h
@@ -0,0 +1,33 @@
+
+/* Buffer object interface */
+
+/* Note: the object's structure is private */
+
+#ifndef Py_BUFFEROBJECT_H
+#define Py_BUFFEROBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+PyAPI_DATA(PyTypeObject) PyBuffer_Type;
+
+#define PyBuffer_Check(op) (Py_TYPE(op) == &PyBuffer_Type)
+
+#define Py_END_OF_BUFFER (-1)
+
+PyAPI_FUNC(PyObject *) PyBuffer_FromObject(PyObject *base,
+ Py_ssize_t offset, Py_ssize_t size);
+PyAPI_FUNC(PyObject *) PyBuffer_FromReadWriteObject(PyObject *base,
+ Py_ssize_t offset,
+ Py_ssize_t size);
+
+PyAPI_FUNC(PyObject *) PyBuffer_FromMemory(void *ptr, Py_ssize_t size);
+PyAPI_FUNC(PyObject *) PyBuffer_FromReadWriteMemory(void *ptr, Py_ssize_t size);
+
+PyAPI_FUNC(PyObject *) PyBuffer_New(Py_ssize_t size);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_BUFFEROBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/bytearrayobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/bytearrayobject.h
new file mode 100644
index 0000000000..6d5af4d87d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/bytearrayobject.h
@@ -0,0 +1,57 @@
+/* ByteArray object interface */
+
+#ifndef Py_BYTEARRAYOBJECT_H
+#define Py_BYTEARRAYOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include
+
+/* Type PyByteArrayObject represents a mutable array of bytes.
+ * The Python API is that of a sequence;
+ * the bytes are mapped to ints in [0, 256).
+ * Bytes are not characters; they may be used to encode characters.
+ * The only way to go between bytes and str/unicode is via encoding
+ * and decoding.
+ * For the convenience of C programmers, the bytes type is considered
+ * to contain a char pointer, not an unsigned char pointer.
+ */
+
+/* Object layout */
+typedef struct {
+ PyObject_VAR_HEAD
+ /* XXX(nnorwitz): should ob_exports be Py_ssize_t? */
+ int ob_exports; /* how many buffer exports */
+ Py_ssize_t ob_alloc; /* How many bytes allocated */
+ char *ob_bytes;
+} PyByteArrayObject;
+
+/* Type object */
+PyAPI_DATA(PyTypeObject) PyByteArray_Type;
+PyAPI_DATA(PyTypeObject) PyByteArrayIter_Type;
+
+/* Type check macros */
+#define PyByteArray_Check(self) PyObject_TypeCheck(self, &PyByteArray_Type)
+#define PyByteArray_CheckExact(self) (Py_TYPE(self) == &PyByteArray_Type)
+
+/* Direct API functions */
+PyAPI_FUNC(PyObject *) PyByteArray_FromObject(PyObject *);
+PyAPI_FUNC(PyObject *) PyByteArray_Concat(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyByteArray_FromStringAndSize(const char *, Py_ssize_t);
+PyAPI_FUNC(Py_ssize_t) PyByteArray_Size(PyObject *);
+PyAPI_FUNC(char *) PyByteArray_AsString(PyObject *);
+PyAPI_FUNC(int) PyByteArray_Resize(PyObject *, Py_ssize_t);
+
+/* Macros, trading safety for speed */
+#define PyByteArray_AS_STRING(self) \
+ (assert(PyByteArray_Check(self)), \
+ Py_SIZE(self) ? ((PyByteArrayObject *)(self))->ob_bytes : _PyByteArray_empty_string)
+#define PyByteArray_GET_SIZE(self) (assert(PyByteArray_Check(self)),Py_SIZE(self))
+
+PyAPI_DATA(char) _PyByteArray_empty_string[];
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_BYTEARRAYOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/bytes_methods.h b/AppPkg/Applications/Python/Python-2.7.2/Include/bytes_methods.h
new file mode 100644
index 0000000000..64ba0aa76c
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/bytes_methods.h
@@ -0,0 +1,75 @@
+#ifndef Py_BYTES_CTYPE_H
+#define Py_BYTES_CTYPE_H
+
+/*
+ * The internal implementation behind PyString (bytes) and PyBytes (buffer)
+ * methods of the given names, they operate on ASCII byte strings.
+ */
+extern PyObject* _Py_bytes_isspace(const char *cptr, Py_ssize_t len);
+extern PyObject* _Py_bytes_isalpha(const char *cptr, Py_ssize_t len);
+extern PyObject* _Py_bytes_isalnum(const char *cptr, Py_ssize_t len);
+extern PyObject* _Py_bytes_isdigit(const char *cptr, Py_ssize_t len);
+extern PyObject* _Py_bytes_islower(const char *cptr, Py_ssize_t len);
+extern PyObject* _Py_bytes_isupper(const char *cptr, Py_ssize_t len);
+extern PyObject* _Py_bytes_istitle(const char *cptr, Py_ssize_t len);
+
+/* These store their len sized answer in the given preallocated *result arg. */
+extern void _Py_bytes_lower(char *result, const char *cptr, Py_ssize_t len);
+extern void _Py_bytes_upper(char *result, const char *cptr, Py_ssize_t len);
+extern void _Py_bytes_title(char *result, char *s, Py_ssize_t len);
+extern void _Py_bytes_capitalize(char *result, char *s, Py_ssize_t len);
+extern void _Py_bytes_swapcase(char *result, char *s, Py_ssize_t len);
+
+/* Shared __doc__ strings. */
+extern const char _Py_isspace__doc__[];
+extern const char _Py_isalpha__doc__[];
+extern const char _Py_isalnum__doc__[];
+extern const char _Py_isdigit__doc__[];
+extern const char _Py_islower__doc__[];
+extern const char _Py_isupper__doc__[];
+extern const char _Py_istitle__doc__[];
+extern const char _Py_lower__doc__[];
+extern const char _Py_upper__doc__[];
+extern const char _Py_title__doc__[];
+extern const char _Py_capitalize__doc__[];
+extern const char _Py_swapcase__doc__[];
+
+/* These are left in for backward compatibility and will be removed
+ in 2.8/3.2 */
+#define ISLOWER(c) Py_ISLOWER(c)
+#define ISUPPER(c) Py_ISUPPER(c)
+#define ISALPHA(c) Py_ISALPHA(c)
+#define ISDIGIT(c) Py_ISDIGIT(c)
+#define ISXDIGIT(c) Py_ISXDIGIT(c)
+#define ISALNUM(c) Py_ISALNUM(c)
+#define ISSPACE(c) Py_ISSPACE(c)
+
+#undef islower
+#define islower(c) undefined_islower(c)
+#undef isupper
+#define isupper(c) undefined_isupper(c)
+#undef isalpha
+#define isalpha(c) undefined_isalpha(c)
+#undef isdigit
+#define isdigit(c) undefined_isdigit(c)
+#undef isxdigit
+#define isxdigit(c) undefined_isxdigit(c)
+#undef isalnum
+#define isalnum(c) undefined_isalnum(c)
+#undef isspace
+#define isspace(c) undefined_isspace(c)
+
+/* These are left in for backward compatibility and will be removed
+ in 2.8/3.2 */
+#define TOLOWER(c) Py_TOLOWER(c)
+#define TOUPPER(c) Py_TOUPPER(c)
+
+#undef tolower
+#define tolower(c) undefined_tolower(c)
+#undef toupper
+#define toupper(c) undefined_toupper(c)
+
+/* this is needed because some docs are shared from the .o, not static */
+#define PyDoc_STRVAR_shared(name,str) const char name[] = PyDoc_STR(str)
+
+#endif /* !Py_BYTES_CTYPE_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/bytesobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/bytesobject.h
new file mode 100644
index 0000000000..d60bdc0af0
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/bytesobject.h
@@ -0,0 +1,27 @@
+#define PyBytesObject PyStringObject
+#define PyBytes_Type PyString_Type
+
+#define PyBytes_Check PyString_Check
+#define PyBytes_CheckExact PyString_CheckExact
+#define PyBytes_CHECK_INTERNED PyString_CHECK_INTERNED
+#define PyBytes_AS_STRING PyString_AS_STRING
+#define PyBytes_GET_SIZE PyString_GET_SIZE
+#define Py_TPFLAGS_BYTES_SUBCLASS Py_TPFLAGS_STRING_SUBCLASS
+
+#define PyBytes_FromStringAndSize PyString_FromStringAndSize
+#define PyBytes_FromString PyString_FromString
+#define PyBytes_FromFormatV PyString_FromFormatV
+#define PyBytes_FromFormat PyString_FromFormat
+#define PyBytes_Size PyString_Size
+#define PyBytes_AsString PyString_AsString
+#define PyBytes_Repr PyString_Repr
+#define PyBytes_Concat PyString_Concat
+#define PyBytes_ConcatAndDel PyString_ConcatAndDel
+#define _PyBytes_Resize _PyString_Resize
+#define _PyBytes_Eq _PyString_Eq
+#define PyBytes_Format PyString_Format
+#define _PyBytes_FormatLong _PyString_FormatLong
+#define PyBytes_DecodeEscape PyString_DecodeEscape
+#define _PyBytes_Join _PyString_Join
+#define PyBytes_AsStringAndSize PyString_AsStringAndSize
+#define _PyBytes_InsertThousandsGrouping _PyString_InsertThousandsGrouping
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/cStringIO.h b/AppPkg/Applications/Python/Python-2.7.2/Include/cStringIO.h
new file mode 100644
index 0000000000..d8fdde416c
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/cStringIO.h
@@ -0,0 +1,73 @@
+#ifndef Py_CSTRINGIO_H
+#define Py_CSTRINGIO_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+/*
+
+ This header provides access to cStringIO objects from C.
+ Functions are provided for calling cStringIO objects and
+ macros are provided for testing whether you have cStringIO
+ objects.
+
+ Before calling any of the functions or macros, you must initialize
+ the routines with:
+
+ PycString_IMPORT
+
+ This would typically be done in your init function.
+
+*/
+
+#define PycStringIO_CAPSULE_NAME "cStringIO.cStringIO_CAPI"
+
+#define PycString_IMPORT \
+ PycStringIO = ((struct PycStringIO_CAPI*)PyCapsule_Import(\
+ PycStringIO_CAPSULE_NAME, 0))
+
+/* Basic functions to manipulate cStringIO objects from C */
+
+static struct PycStringIO_CAPI {
+
+ /* Read a string from an input object. If the last argument
+ is -1, the remainder will be read.
+ */
+ int(*cread)(PyObject *, char **, Py_ssize_t);
+
+ /* Read a line from an input object. Returns the length of the read
+ line as an int and a pointer inside the object buffer as char** (so
+ the caller doesn't have to provide its own buffer as destination).
+ */
+ int(*creadline)(PyObject *, char **);
+
+ /* Write a string to an output object*/
+ int(*cwrite)(PyObject *, const char *, Py_ssize_t);
+
+ /* Get the output object as a Python string (returns new reference). */
+ PyObject *(*cgetvalue)(PyObject *);
+
+ /* Create a new output object */
+ PyObject *(*NewOutput)(int);
+
+ /* Create an input object from a Python string
+ (copies the Python string reference).
+ */
+ PyObject *(*NewInput)(PyObject *);
+
+ /* The Python types for cStringIO input and output objects.
+ Note that you can do input on an output object.
+ */
+ PyTypeObject *InputType, *OutputType;
+
+} *PycStringIO;
+
+/* These can be used to test if you have one */
+#define PycStringIO_InputCheck(O) \
+ (Py_TYPE(O)==PycStringIO->InputType)
+#define PycStringIO_OutputCheck(O) \
+ (Py_TYPE(O)==PycStringIO->OutputType)
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_CSTRINGIO_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/cellobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/cellobject.h
new file mode 100644
index 0000000000..8d27f35ad4
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/cellobject.h
@@ -0,0 +1,28 @@
+/* Cell object interface */
+
+#ifndef Py_CELLOBJECT_H
+#define Py_CELLOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *ob_ref; /* Content of the cell or NULL when empty */
+} PyCellObject;
+
+PyAPI_DATA(PyTypeObject) PyCell_Type;
+
+#define PyCell_Check(op) (Py_TYPE(op) == &PyCell_Type)
+
+PyAPI_FUNC(PyObject *) PyCell_New(PyObject *);
+PyAPI_FUNC(PyObject *) PyCell_Get(PyObject *);
+PyAPI_FUNC(int) PyCell_Set(PyObject *, PyObject *);
+
+#define PyCell_GET(op) (((PyCellObject *)(op))->ob_ref)
+#define PyCell_SET(op, v) (((PyCellObject *)(op))->ob_ref = v)
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_TUPLEOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/ceval.h b/AppPkg/Applications/Python/Python-2.7.2/Include/ceval.h
new file mode 100644
index 0000000000..58b2dedf6d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/ceval.h
@@ -0,0 +1,153 @@
+#ifndef Py_CEVAL_H
+#define Py_CEVAL_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Interface to random parts in ceval.c */
+
+PyAPI_FUNC(PyObject *) PyEval_CallObjectWithKeywords(
+ PyObject *, PyObject *, PyObject *);
+
+/* Inline this */
+#define PyEval_CallObject(func,arg) \
+ PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
+
+PyAPI_FUNC(PyObject *) PyEval_CallFunction(PyObject *obj,
+ const char *format, ...);
+PyAPI_FUNC(PyObject *) PyEval_CallMethod(PyObject *obj,
+ const char *methodname,
+ const char *format, ...);
+
+PyAPI_FUNC(void) PyEval_SetProfile(Py_tracefunc, PyObject *);
+PyAPI_FUNC(void) PyEval_SetTrace(Py_tracefunc, PyObject *);
+
+struct _frame; /* Avoid including frameobject.h */
+
+PyAPI_FUNC(PyObject *) PyEval_GetBuiltins(void);
+PyAPI_FUNC(PyObject *) PyEval_GetGlobals(void);
+PyAPI_FUNC(PyObject *) PyEval_GetLocals(void);
+PyAPI_FUNC(struct _frame *) PyEval_GetFrame(void);
+PyAPI_FUNC(int) PyEval_GetRestricted(void);
+
+/* Look at the current frame's (if any) code's co_flags, and turn on
+ the corresponding compiler flags in cf->cf_flags. Return 1 if any
+ flag was set, else return 0. */
+PyAPI_FUNC(int) PyEval_MergeCompilerFlags(PyCompilerFlags *cf);
+
+PyAPI_FUNC(int) Py_FlushLine(void);
+
+PyAPI_FUNC(int) Py_AddPendingCall(int (*func)(void *), void *arg);
+PyAPI_FUNC(int) Py_MakePendingCalls(void);
+
+/* Protection against deeply nested recursive calls */
+PyAPI_FUNC(void) Py_SetRecursionLimit(int);
+PyAPI_FUNC(int) Py_GetRecursionLimit(void);
+
+#define Py_EnterRecursiveCall(where) \
+ (_Py_MakeRecCheck(PyThreadState_GET()->recursion_depth) && \
+ _Py_CheckRecursiveCall(where))
+#define Py_LeaveRecursiveCall() \
+ (--PyThreadState_GET()->recursion_depth)
+PyAPI_FUNC(int) _Py_CheckRecursiveCall(char *where);
+PyAPI_DATA(int) _Py_CheckRecursionLimit;
+#ifdef USE_STACKCHECK
+# define _Py_MakeRecCheck(x) (++(x) > --_Py_CheckRecursionLimit)
+#else
+# define _Py_MakeRecCheck(x) (++(x) > _Py_CheckRecursionLimit)
+#endif
+
+PyAPI_FUNC(const char *) PyEval_GetFuncName(PyObject *);
+PyAPI_FUNC(const char *) PyEval_GetFuncDesc(PyObject *);
+
+PyAPI_FUNC(PyObject *) PyEval_GetCallStats(PyObject *);
+PyAPI_FUNC(PyObject *) PyEval_EvalFrame(struct _frame *);
+PyAPI_FUNC(PyObject *) PyEval_EvalFrameEx(struct _frame *f, int exc);
+
+/* this used to be handled on a per-thread basis - now just two globals */
+PyAPI_DATA(volatile int) _Py_Ticker;
+PyAPI_DATA(int) _Py_CheckInterval;
+
+/* Interface for threads.
+
+ A module that plans to do a blocking system call (or something else
+ that lasts a long time and doesn't touch Python data) can allow other
+ threads to run as follows:
+
+ ...preparations here...
+ Py_BEGIN_ALLOW_THREADS
+ ...blocking system call here...
+ Py_END_ALLOW_THREADS
+ ...interpret result here...
+
+ The Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS pair expands to a
+ {}-surrounded block.
+ To leave the block in the middle (e.g., with return), you must insert
+ a line containing Py_BLOCK_THREADS before the return, e.g.
+
+ if (...premature_exit...) {
+ Py_BLOCK_THREADS
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+
+ An alternative is:
+
+ Py_BLOCK_THREADS
+ if (...premature_exit...) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ Py_UNBLOCK_THREADS
+
+ For convenience, that the value of 'errno' is restored across
+ Py_END_ALLOW_THREADS and Py_BLOCK_THREADS.
+
+ WARNING: NEVER NEST CALLS TO Py_BEGIN_ALLOW_THREADS AND
+ Py_END_ALLOW_THREADS!!!
+
+ The function PyEval_InitThreads() should be called only from
+ initthread() in "threadmodule.c".
+
+ Note that not yet all candidates have been converted to use this
+ mechanism!
+*/
+
+PyAPI_FUNC(PyThreadState *) PyEval_SaveThread(void);
+PyAPI_FUNC(void) PyEval_RestoreThread(PyThreadState *);
+
+#ifdef WITH_THREAD
+
+PyAPI_FUNC(int) PyEval_ThreadsInitialized(void);
+PyAPI_FUNC(void) PyEval_InitThreads(void);
+PyAPI_FUNC(void) PyEval_AcquireLock(void);
+PyAPI_FUNC(void) PyEval_ReleaseLock(void);
+PyAPI_FUNC(void) PyEval_AcquireThread(PyThreadState *tstate);
+PyAPI_FUNC(void) PyEval_ReleaseThread(PyThreadState *tstate);
+PyAPI_FUNC(void) PyEval_ReInitThreads(void);
+
+#define Py_BEGIN_ALLOW_THREADS { \
+ PyThreadState *_save; \
+ _save = PyEval_SaveThread();
+#define Py_BLOCK_THREADS PyEval_RestoreThread(_save);
+#define Py_UNBLOCK_THREADS _save = PyEval_SaveThread();
+#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \
+ }
+
+#else /* !WITH_THREAD */
+
+#define Py_BEGIN_ALLOW_THREADS {
+#define Py_BLOCK_THREADS
+#define Py_UNBLOCK_THREADS
+#define Py_END_ALLOW_THREADS }
+
+#endif /* !WITH_THREAD */
+
+PyAPI_FUNC(int) _PyEval_SliceIndex(PyObject *, Py_ssize_t *);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_CEVAL_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/classobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/classobject.h
new file mode 100644
index 0000000000..8e42e53edc
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/classobject.h
@@ -0,0 +1,83 @@
+
+/* Class object interface */
+
+/* Revealing some structures (not for general use) */
+
+#ifndef Py_CLASSOBJECT_H
+#define Py_CLASSOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *cl_bases; /* A tuple of class objects */
+ PyObject *cl_dict; /* A dictionary */
+ PyObject *cl_name; /* A string */
+ /* The following three are functions or NULL */
+ PyObject *cl_getattr;
+ PyObject *cl_setattr;
+ PyObject *cl_delattr;
+ PyObject *cl_weakreflist; /* List of weak references */
+} PyClassObject;
+
+typedef struct {
+ PyObject_HEAD
+ PyClassObject *in_class; /* The class object */
+ PyObject *in_dict; /* A dictionary */
+ PyObject *in_weakreflist; /* List of weak references */
+} PyInstanceObject;
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *im_func; /* The callable object implementing the method */
+ PyObject *im_self; /* The instance it is bound to, or NULL */
+ PyObject *im_class; /* The class that asked for the method */
+ PyObject *im_weakreflist; /* List of weak references */
+} PyMethodObject;
+
+PyAPI_DATA(PyTypeObject) PyClass_Type, PyInstance_Type, PyMethod_Type;
+
+#define PyClass_Check(op) ((op)->ob_type == &PyClass_Type)
+#define PyInstance_Check(op) ((op)->ob_type == &PyInstance_Type)
+#define PyMethod_Check(op) ((op)->ob_type == &PyMethod_Type)
+
+PyAPI_FUNC(PyObject *) PyClass_New(PyObject *, PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyInstance_New(PyObject *, PyObject *,
+ PyObject *);
+PyAPI_FUNC(PyObject *) PyInstance_NewRaw(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyMethod_New(PyObject *, PyObject *, PyObject *);
+
+PyAPI_FUNC(PyObject *) PyMethod_Function(PyObject *);
+PyAPI_FUNC(PyObject *) PyMethod_Self(PyObject *);
+PyAPI_FUNC(PyObject *) PyMethod_Class(PyObject *);
+
+/* Look up attribute with name (a string) on instance object pinst, using
+ * only the instance and base class dicts. If a descriptor is found in
+ * a class dict, the descriptor is returned without calling it.
+ * Returns NULL if nothing found, else a borrowed reference to the
+ * value associated with name in the dict in which name was found.
+ * The point of this routine is that it never calls arbitrary Python
+ * code, so is always "safe": all it does is dict lookups. The function
+ * can't fail, never sets an exception, and NULL is not an error (it just
+ * means "not found").
+ */
+PyAPI_FUNC(PyObject *) _PyInstance_Lookup(PyObject *pinst, PyObject *name);
+
+/* Macros for direct access to these values. Type checks are *not*
+ done, so use with care. */
+#define PyMethod_GET_FUNCTION(meth) \
+ (((PyMethodObject *)meth) -> im_func)
+#define PyMethod_GET_SELF(meth) \
+ (((PyMethodObject *)meth) -> im_self)
+#define PyMethod_GET_CLASS(meth) \
+ (((PyMethodObject *)meth) -> im_class)
+
+PyAPI_FUNC(int) PyClass_IsSubclass(PyObject *, PyObject *);
+
+PyAPI_FUNC(int) PyMethod_ClearFreeList(void);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_CLASSOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/cobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/cobject.h
new file mode 100644
index 0000000000..11a8b434ee
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/cobject.h
@@ -0,0 +1,89 @@
+/*
+ CObjects are marked Pending Deprecation as of Python 2.7.
+ The full schedule for 2.x is as follows:
+ - CObjects are marked Pending Deprecation in Python 2.7.
+ - CObjects will be marked Deprecated in Python 2.8
+ (if there is one).
+ - CObjects will be removed in Python 2.9 (if there is one).
+
+ Additionally, for the Python 3.x series:
+ - CObjects were marked Deprecated in Python 3.1.
+ - CObjects will be removed in Python 3.2.
+
+ You should switch all use of CObjects to capsules. Capsules
+ have a safer and more consistent API. For more information,
+ see Include/pycapsule.h, or read the "Capsules" topic in
+ the "Python/C API Reference Manual".
+
+ Python 2.7 no longer uses CObjects itself; all objects which
+ were formerly CObjects are now capsules. Note that this change
+ does not by itself break binary compatibility with extensions
+ built for previous versions of Python--PyCObject_AsVoidPtr()
+ has been changed to also understand capsules.
+
+*/
+
+/* original file header comment follows: */
+
+/* C objects to be exported from one extension module to another.
+
+ C objects are used for communication between extension modules.
+ They provide a way for an extension module to export a C interface
+ to other extension modules, so that extension modules can use the
+ Python import mechanism to link to one another.
+
+*/
+
+#ifndef Py_COBJECT_H
+#define Py_COBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_DATA(PyTypeObject) PyCObject_Type;
+
+#define PyCObject_Check(op) (Py_TYPE(op) == &PyCObject_Type)
+
+/* Create a PyCObject from a pointer to a C object and an optional
+ destructor function. If the second argument is non-null, then it
+ will be called with the first argument if and when the PyCObject is
+ destroyed.
+
+*/
+PyAPI_FUNC(PyObject *) PyCObject_FromVoidPtr(
+ void *cobj, void (*destruct)(void*));
+
+
+/* Create a PyCObject from a pointer to a C object, a description object,
+ and an optional destructor function. If the third argument is non-null,
+ then it will be called with the first and second arguments if and when
+ the PyCObject is destroyed.
+*/
+PyAPI_FUNC(PyObject *) PyCObject_FromVoidPtrAndDesc(
+ void *cobj, void *desc, void (*destruct)(void*,void*));
+
+/* Retrieve a pointer to a C object from a PyCObject. */
+PyAPI_FUNC(void *) PyCObject_AsVoidPtr(PyObject *);
+
+/* Retrieve a pointer to a description object from a PyCObject. */
+PyAPI_FUNC(void *) PyCObject_GetDesc(PyObject *);
+
+/* Import a pointer to a C object from a module using a PyCObject. */
+PyAPI_FUNC(void *) PyCObject_Import(char *module_name, char *cobject_name);
+
+/* Modify a C object. Fails (==0) if object has a destructor. */
+PyAPI_FUNC(int) PyCObject_SetVoidPtr(PyObject *self, void *cobj);
+
+
+typedef struct {
+ PyObject_HEAD
+ void *cobject;
+ void *desc;
+ void (*destructor)(void *);
+} PyCObject;
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_COBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/code.h b/AppPkg/Applications/Python/Python-2.7.2/Include/code.h
new file mode 100644
index 0000000000..40151595c6
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/code.h
@@ -0,0 +1,107 @@
+/* Definitions for bytecode */
+
+#ifndef Py_CODE_H
+#define Py_CODE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Bytecode object */
+typedef struct {
+ PyObject_HEAD
+ int co_argcount; /* #arguments, except *args */
+ int co_nlocals; /* #local variables */
+ int co_stacksize; /* #entries needed for evaluation stack */
+ int co_flags; /* CO_..., see below */
+ PyObject *co_code; /* instruction opcodes */
+ PyObject *co_consts; /* list (constants used) */
+ PyObject *co_names; /* list of strings (names used) */
+ PyObject *co_varnames; /* tuple of strings (local variable names) */
+ PyObject *co_freevars; /* tuple of strings (free variable names) */
+ PyObject *co_cellvars; /* tuple of strings (cell variable names) */
+ /* The rest doesn't count for hash/cmp */
+ PyObject *co_filename; /* string (where it was loaded from) */
+ PyObject *co_name; /* string (name, for reference) */
+ int co_firstlineno; /* first source line number */
+ PyObject *co_lnotab; /* string (encoding addr<->lineno mapping) See
+ Objects/lnotab_notes.txt for details. */
+ void *co_zombieframe; /* for optimization only (see frameobject.c) */
+ PyObject *co_weakreflist; /* to support weakrefs to code objects */
+} PyCodeObject;
+
+/* Masks for co_flags above */
+#define CO_OPTIMIZED 0x0001
+#define CO_NEWLOCALS 0x0002
+#define CO_VARARGS 0x0004
+#define CO_VARKEYWORDS 0x0008
+#define CO_NESTED 0x0010
+#define CO_GENERATOR 0x0020
+/* The CO_NOFREE flag is set if there are no free or cell variables.
+ This information is redundant, but it allows a single flag test
+ to determine whether there is any extra work to be done when the
+ call frame it setup.
+*/
+#define CO_NOFREE 0x0040
+
+#if 0
+/* This is no longer used. Stopped defining in 2.5, do not re-use. */
+#define CO_GENERATOR_ALLOWED 0x1000
+#endif
+#define CO_FUTURE_DIVISION 0x2000
+#define CO_FUTURE_ABSOLUTE_IMPORT 0x4000 /* do absolute imports by default */
+#define CO_FUTURE_WITH_STATEMENT 0x8000
+#define CO_FUTURE_PRINT_FUNCTION 0x10000
+#define CO_FUTURE_UNICODE_LITERALS 0x20000
+
+/* This should be defined if a future statement modifies the syntax.
+ For example, when a keyword is added.
+*/
+#if 1
+#define PY_PARSER_REQUIRES_FUTURE_KEYWORD
+#endif
+
+#define CO_MAXBLOCKS 20 /* Max static block nesting within a function */
+
+PyAPI_DATA(PyTypeObject) PyCode_Type;
+
+#define PyCode_Check(op) (Py_TYPE(op) == &PyCode_Type)
+#define PyCode_GetNumFree(op) (PyTuple_GET_SIZE((op)->co_freevars))
+
+/* Public interface */
+PyAPI_FUNC(PyCodeObject *) PyCode_New(
+ int, int, int, int, PyObject *, PyObject *, PyObject *, PyObject *,
+ PyObject *, PyObject *, PyObject *, PyObject *, int, PyObject *);
+ /* same as struct above */
+
+/* Creates a new empty code object with the specified source location. */
+PyAPI_FUNC(PyCodeObject *)
+PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno);
+
+/* Return the line number associated with the specified bytecode index
+ in this code object. If you just need the line number of a frame,
+ use PyFrame_GetLineNumber() instead. */
+PyAPI_FUNC(int) PyCode_Addr2Line(PyCodeObject *, int);
+
+/* for internal use only */
+#define _PyCode_GETCODEPTR(co, pp) \
+ ((*Py_TYPE((co)->co_code)->tp_as_buffer->bf_getreadbuffer) \
+ ((co)->co_code, 0, (void **)(pp)))
+
+typedef struct _addr_pair {
+ int ap_lower;
+ int ap_upper;
+} PyAddrPair;
+
+/* Update *bounds to describe the first and one-past-the-last instructions in the
+ same line as lasti. Return the number of that line.
+*/
+PyAPI_FUNC(int) _PyCode_CheckLineNumber(PyCodeObject* co,
+ int lasti, PyAddrPair *bounds);
+
+PyAPI_FUNC(PyObject*) PyCode_Optimize(PyObject *code, PyObject* consts,
+ PyObject *names, PyObject *lineno_obj);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_CODE_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/codecs.h b/AppPkg/Applications/Python/Python-2.7.2/Include/codecs.h
new file mode 100644
index 0000000000..79c19a8453
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/codecs.h
@@ -0,0 +1,167 @@
+#ifndef Py_CODECREGISTRY_H
+#define Py_CODECREGISTRY_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* ------------------------------------------------------------------------
+
+ Python Codec Registry and support functions
+
+
+Written by Marc-Andre Lemburg (mal@lemburg.com).
+
+Copyright (c) Corporation for National Research Initiatives.
+
+ ------------------------------------------------------------------------ */
+
+/* Register a new codec search function.
+
+ As side effect, this tries to load the encodings package, if not
+ yet done, to make sure that it is always first in the list of
+ search functions.
+
+ The search_function's refcount is incremented by this function. */
+
+PyAPI_FUNC(int) PyCodec_Register(
+ PyObject *search_function
+ );
+
+/* Codec register lookup API.
+
+ Looks up the given encoding and returns a CodecInfo object with
+ function attributes which implement the different aspects of
+ processing the encoding.
+
+ The encoding string is looked up converted to all lower-case
+ characters. This makes encodings looked up through this mechanism
+ effectively case-insensitive.
+
+ If no codec is found, a KeyError is set and NULL returned.
+
+ As side effect, this tries to load the encodings package, if not
+ yet done. This is part of the lazy load strategy for the encodings
+ package.
+
+ */
+
+PyAPI_FUNC(PyObject *) _PyCodec_Lookup(
+ const char *encoding
+ );
+
+/* Generic codec based encoding API.
+
+ object is passed through the encoder function found for the given
+ encoding using the error handling method defined by errors. errors
+ may be NULL to use the default method defined for the codec.
+
+ Raises a LookupError in case no encoder can be found.
+
+ */
+
+PyAPI_FUNC(PyObject *) PyCodec_Encode(
+ PyObject *object,
+ const char *encoding,
+ const char *errors
+ );
+
+/* Generic codec based decoding API.
+
+ object is passed through the decoder function found for the given
+ encoding using the error handling method defined by errors. errors
+ may be NULL to use the default method defined for the codec.
+
+ Raises a LookupError in case no encoder can be found.
+
+ */
+
+PyAPI_FUNC(PyObject *) PyCodec_Decode(
+ PyObject *object,
+ const char *encoding,
+ const char *errors
+ );
+
+/* --- Codec Lookup APIs --------------------------------------------------
+
+ All APIs return a codec object with incremented refcount and are
+ based on _PyCodec_Lookup(). The same comments w/r to the encoding
+ name also apply to these APIs.
+
+*/
+
+/* Get an encoder function for the given encoding. */
+
+PyAPI_FUNC(PyObject *) PyCodec_Encoder(
+ const char *encoding
+ );
+
+/* Get a decoder function for the given encoding. */
+
+PyAPI_FUNC(PyObject *) PyCodec_Decoder(
+ const char *encoding
+ );
+
+/* Get a IncrementalEncoder object for the given encoding. */
+
+PyAPI_FUNC(PyObject *) PyCodec_IncrementalEncoder(
+ const char *encoding,
+ const char *errors
+ );
+
+/* Get a IncrementalDecoder object function for the given encoding. */
+
+PyAPI_FUNC(PyObject *) PyCodec_IncrementalDecoder(
+ const char *encoding,
+ const char *errors
+ );
+
+/* Get a StreamReader factory function for the given encoding. */
+
+PyAPI_FUNC(PyObject *) PyCodec_StreamReader(
+ const char *encoding,
+ PyObject *stream,
+ const char *errors
+ );
+
+/* Get a StreamWriter factory function for the given encoding. */
+
+PyAPI_FUNC(PyObject *) PyCodec_StreamWriter(
+ const char *encoding,
+ PyObject *stream,
+ const char *errors
+ );
+
+/* Unicode encoding error handling callback registry API */
+
+/* Register the error handling callback function error under the given
+ name. This function will be called by the codec when it encounters
+ unencodable characters/undecodable bytes and doesn't know the
+ callback name, when name is specified as the error parameter
+ in the call to the encode/decode function.
+ Return 0 on success, -1 on error */
+PyAPI_FUNC(int) PyCodec_RegisterError(const char *name, PyObject *error);
+
+/* Lookup the error handling callback function registered under the given
+ name. As a special case NULL can be passed, in which case
+ the error handling callback for "strict" will be returned. */
+PyAPI_FUNC(PyObject *) PyCodec_LookupError(const char *name);
+
+/* raise exc as an exception */
+PyAPI_FUNC(PyObject *) PyCodec_StrictErrors(PyObject *exc);
+
+/* ignore the unicode error, skipping the faulty input */
+PyAPI_FUNC(PyObject *) PyCodec_IgnoreErrors(PyObject *exc);
+
+/* replace the unicode encode error with ? or U+FFFD */
+PyAPI_FUNC(PyObject *) PyCodec_ReplaceErrors(PyObject *exc);
+
+/* replace the unicode encode error with XML character references */
+PyAPI_FUNC(PyObject *) PyCodec_XMLCharRefReplaceErrors(PyObject *exc);
+
+/* replace the unicode encode error with backslash escapes (\x, \u and \U) */
+PyAPI_FUNC(PyObject *) PyCodec_BackslashReplaceErrors(PyObject *exc);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_CODECREGISTRY_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/compile.h b/AppPkg/Applications/Python/Python-2.7.2/Include/compile.h
new file mode 100644
index 0000000000..22cb75f073
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/compile.h
@@ -0,0 +1,40 @@
+
+#ifndef Py_COMPILE_H
+#define Py_COMPILE_H
+
+#include "code.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Public interface */
+struct _node; /* Declare the existence of this type */
+PyAPI_FUNC(PyCodeObject *) PyNode_Compile(struct _node *, const char *);
+
+/* Future feature support */
+
+typedef struct {
+ int ff_features; /* flags set by future statements */
+ int ff_lineno; /* line number of last future statement */
+} PyFutureFeatures;
+
+#define FUTURE_NESTED_SCOPES "nested_scopes"
+#define FUTURE_GENERATORS "generators"
+#define FUTURE_DIVISION "division"
+#define FUTURE_ABSOLUTE_IMPORT "absolute_import"
+#define FUTURE_WITH_STATEMENT "with_statement"
+#define FUTURE_PRINT_FUNCTION "print_function"
+#define FUTURE_UNICODE_LITERALS "unicode_literals"
+
+
+struct _mod; /* Declare the existence of this type */
+PyAPI_FUNC(PyCodeObject *) PyAST_Compile(struct _mod *, const char *,
+ PyCompilerFlags *, PyArena *);
+PyAPI_FUNC(PyFutureFeatures *) PyFuture_FromAST(struct _mod *, const char *);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_COMPILE_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/complexobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/complexobject.h
new file mode 100644
index 0000000000..747048a9ac
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/complexobject.h
@@ -0,0 +1,66 @@
+/* Complex number structure */
+
+#ifndef Py_COMPLEXOBJECT_H
+#define Py_COMPLEXOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ double real;
+ double imag;
+} Py_complex;
+
+/* Operations on complex numbers from complexmodule.c */
+
+#define c_sum _Py_c_sum
+#define c_diff _Py_c_diff
+#define c_neg _Py_c_neg
+#define c_prod _Py_c_prod
+#define c_quot _Py_c_quot
+#define c_pow _Py_c_pow
+#define c_abs _Py_c_abs
+
+PyAPI_FUNC(Py_complex) c_sum(Py_complex, Py_complex);
+PyAPI_FUNC(Py_complex) c_diff(Py_complex, Py_complex);
+PyAPI_FUNC(Py_complex) c_neg(Py_complex);
+PyAPI_FUNC(Py_complex) c_prod(Py_complex, Py_complex);
+PyAPI_FUNC(Py_complex) c_quot(Py_complex, Py_complex);
+PyAPI_FUNC(Py_complex) c_pow(Py_complex, Py_complex);
+PyAPI_FUNC(double) c_abs(Py_complex);
+
+
+/* Complex object interface */
+
+/*
+PyComplexObject represents a complex number with double-precision
+real and imaginary parts.
+*/
+
+typedef struct {
+ PyObject_HEAD
+ Py_complex cval;
+} PyComplexObject;
+
+PyAPI_DATA(PyTypeObject) PyComplex_Type;
+
+#define PyComplex_Check(op) PyObject_TypeCheck(op, &PyComplex_Type)
+#define PyComplex_CheckExact(op) (Py_TYPE(op) == &PyComplex_Type)
+
+PyAPI_FUNC(PyObject *) PyComplex_FromCComplex(Py_complex);
+PyAPI_FUNC(PyObject *) PyComplex_FromDoubles(double real, double imag);
+
+PyAPI_FUNC(double) PyComplex_RealAsDouble(PyObject *op);
+PyAPI_FUNC(double) PyComplex_ImagAsDouble(PyObject *op);
+PyAPI_FUNC(Py_complex) PyComplex_AsCComplex(PyObject *op);
+
+/* Format the object based on the format_spec, as defined in PEP 3101
+ (Advanced String Formatting). */
+PyAPI_FUNC(PyObject *) _PyComplex_FormatAdvanced(PyObject *obj,
+ char *format_spec,
+ Py_ssize_t format_spec_len);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_COMPLEXOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/datetime.h b/AppPkg/Applications/Python/Python-2.7.2/Include/datetime.h
new file mode 100644
index 0000000000..afd81415fc
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/datetime.h
@@ -0,0 +1,239 @@
+/* datetime.h
+ */
+
+#ifndef DATETIME_H
+#define DATETIME_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Fields are packed into successive bytes, each viewed as unsigned and
+ * big-endian, unless otherwise noted:
+ *
+ * byte offset
+ * 0 year 2 bytes, 1-9999
+ * 2 month 1 byte, 1-12
+ * 3 day 1 byte, 1-31
+ * 4 hour 1 byte, 0-23
+ * 5 minute 1 byte, 0-59
+ * 6 second 1 byte, 0-59
+ * 7 usecond 3 bytes, 0-999999
+ * 10
+ */
+
+/* # of bytes for year, month, and day. */
+#define _PyDateTime_DATE_DATASIZE 4
+
+/* # of bytes for hour, minute, second, and usecond. */
+#define _PyDateTime_TIME_DATASIZE 6
+
+/* # of bytes for year, month, day, hour, minute, second, and usecond. */
+#define _PyDateTime_DATETIME_DATASIZE 10
+
+
+typedef struct
+{
+ PyObject_HEAD
+ long hashcode; /* -1 when unknown */
+ int days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */
+ int seconds; /* 0 <= seconds < 24*3600 is invariant */
+ int microseconds; /* 0 <= microseconds < 1000000 is invariant */
+} PyDateTime_Delta;
+
+typedef struct
+{
+ PyObject_HEAD /* a pure abstract base clase */
+} PyDateTime_TZInfo;
+
+
+/* The datetime and time types have hashcodes, and an optional tzinfo member,
+ * present if and only if hastzinfo is true.
+ */
+#define _PyTZINFO_HEAD \
+ PyObject_HEAD \
+ long hashcode; \
+ char hastzinfo; /* boolean flag */
+
+/* No _PyDateTime_BaseTZInfo is allocated; it's just to have something
+ * convenient to cast to, when getting at the hastzinfo member of objects
+ * starting with _PyTZINFO_HEAD.
+ */
+typedef struct
+{
+ _PyTZINFO_HEAD
+} _PyDateTime_BaseTZInfo;
+
+/* All time objects are of PyDateTime_TimeType, but that can be allocated
+ * in two ways, with or without a tzinfo member. Without is the same as
+ * tzinfo == None, but consumes less memory. _PyDateTime_BaseTime is an
+ * internal struct used to allocate the right amount of space for the
+ * "without" case.
+ */
+#define _PyDateTime_TIMEHEAD \
+ _PyTZINFO_HEAD \
+ unsigned char data[_PyDateTime_TIME_DATASIZE];
+
+typedef struct
+{
+ _PyDateTime_TIMEHEAD
+} _PyDateTime_BaseTime; /* hastzinfo false */
+
+typedef struct
+{
+ _PyDateTime_TIMEHEAD
+ PyObject *tzinfo;
+} PyDateTime_Time; /* hastzinfo true */
+
+
+/* All datetime objects are of PyDateTime_DateTimeType, but that can be
+ * allocated in two ways too, just like for time objects above. In addition,
+ * the plain date type is a base class for datetime, so it must also have
+ * a hastzinfo member (although it's unused there).
+ */
+typedef struct
+{
+ _PyTZINFO_HEAD
+ unsigned char data[_PyDateTime_DATE_DATASIZE];
+} PyDateTime_Date;
+
+#define _PyDateTime_DATETIMEHEAD \
+ _PyTZINFO_HEAD \
+ unsigned char data[_PyDateTime_DATETIME_DATASIZE];
+
+typedef struct
+{
+ _PyDateTime_DATETIMEHEAD
+} _PyDateTime_BaseDateTime; /* hastzinfo false */
+
+typedef struct
+{
+ _PyDateTime_DATETIMEHEAD
+ PyObject *tzinfo;
+} PyDateTime_DateTime; /* hastzinfo true */
+
+
+/* Apply for date and datetime instances. */
+#define PyDateTime_GET_YEAR(o) ((((PyDateTime_Date*)o)->data[0] << 8) | \
+ ((PyDateTime_Date*)o)->data[1])
+#define PyDateTime_GET_MONTH(o) (((PyDateTime_Date*)o)->data[2])
+#define PyDateTime_GET_DAY(o) (((PyDateTime_Date*)o)->data[3])
+
+#define PyDateTime_DATE_GET_HOUR(o) (((PyDateTime_DateTime*)o)->data[4])
+#define PyDateTime_DATE_GET_MINUTE(o) (((PyDateTime_DateTime*)o)->data[5])
+#define PyDateTime_DATE_GET_SECOND(o) (((PyDateTime_DateTime*)o)->data[6])
+#define PyDateTime_DATE_GET_MICROSECOND(o) \
+ ((((PyDateTime_DateTime*)o)->data[7] << 16) | \
+ (((PyDateTime_DateTime*)o)->data[8] << 8) | \
+ ((PyDateTime_DateTime*)o)->data[9])
+
+/* Apply for time instances. */
+#define PyDateTime_TIME_GET_HOUR(o) (((PyDateTime_Time*)o)->data[0])
+#define PyDateTime_TIME_GET_MINUTE(o) (((PyDateTime_Time*)o)->data[1])
+#define PyDateTime_TIME_GET_SECOND(o) (((PyDateTime_Time*)o)->data[2])
+#define PyDateTime_TIME_GET_MICROSECOND(o) \
+ ((((PyDateTime_Time*)o)->data[3] << 16) | \
+ (((PyDateTime_Time*)o)->data[4] << 8) | \
+ ((PyDateTime_Time*)o)->data[5])
+
+
+/* Define structure for C API. */
+typedef struct {
+ /* type objects */
+ PyTypeObject *DateType;
+ PyTypeObject *DateTimeType;
+ PyTypeObject *TimeType;
+ PyTypeObject *DeltaType;
+ PyTypeObject *TZInfoType;
+
+ /* constructors */
+ PyObject *(*Date_FromDate)(int, int, int, PyTypeObject*);
+ PyObject *(*DateTime_FromDateAndTime)(int, int, int, int, int, int, int,
+ PyObject*, PyTypeObject*);
+ PyObject *(*Time_FromTime)(int, int, int, int, PyObject*, PyTypeObject*);
+ PyObject *(*Delta_FromDelta)(int, int, int, int, PyTypeObject*);
+
+ /* constructors for the DB API */
+ PyObject *(*DateTime_FromTimestamp)(PyObject*, PyObject*, PyObject*);
+ PyObject *(*Date_FromTimestamp)(PyObject*, PyObject*);
+
+} PyDateTime_CAPI;
+
+#define PyDateTime_CAPSULE_NAME "datetime.datetime_CAPI"
+
+
+/* "magic" constant used to partially protect against developer mistakes. */
+#define DATETIME_API_MAGIC 0x414548d5
+
+#ifdef Py_BUILD_CORE
+
+/* Macros for type checking when building the Python core. */
+#define PyDate_Check(op) PyObject_TypeCheck(op, &PyDateTime_DateType)
+#define PyDate_CheckExact(op) (Py_TYPE(op) == &PyDateTime_DateType)
+
+#define PyDateTime_Check(op) PyObject_TypeCheck(op, &PyDateTime_DateTimeType)
+#define PyDateTime_CheckExact(op) (Py_TYPE(op) == &PyDateTime_DateTimeType)
+
+#define PyTime_Check(op) PyObject_TypeCheck(op, &PyDateTime_TimeType)
+#define PyTime_CheckExact(op) (Py_TYPE(op) == &PyDateTime_TimeType)
+
+#define PyDelta_Check(op) PyObject_TypeCheck(op, &PyDateTime_DeltaType)
+#define PyDelta_CheckExact(op) (Py_TYPE(op) == &PyDateTime_DeltaType)
+
+#define PyTZInfo_Check(op) PyObject_TypeCheck(op, &PyDateTime_TZInfoType)
+#define PyTZInfo_CheckExact(op) (Py_TYPE(op) == &PyDateTime_TZInfoType)
+
+#else
+
+/* Define global variable for the C API and a macro for setting it. */
+static PyDateTime_CAPI *PyDateTimeAPI = NULL;
+
+#define PyDateTime_IMPORT \
+ PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0)
+
+/* Macros for type checking when not building the Python core. */
+#define PyDate_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateType)
+#define PyDate_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->DateType)
+
+#define PyDateTime_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateTimeType)
+#define PyDateTime_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->DateTimeType)
+
+#define PyTime_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->TimeType)
+#define PyTime_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->TimeType)
+
+#define PyDelta_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DeltaType)
+#define PyDelta_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->DeltaType)
+
+#define PyTZInfo_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->TZInfoType)
+#define PyTZInfo_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->TZInfoType)
+
+/* Macros for accessing constructors in a simplified fashion. */
+#define PyDate_FromDate(year, month, day) \
+ PyDateTimeAPI->Date_FromDate(year, month, day, PyDateTimeAPI->DateType)
+
+#define PyDateTime_FromDateAndTime(year, month, day, hour, min, sec, usec) \
+ PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, \
+ min, sec, usec, Py_None, PyDateTimeAPI->DateTimeType)
+
+#define PyTime_FromTime(hour, minute, second, usecond) \
+ PyDateTimeAPI->Time_FromTime(hour, minute, second, usecond, \
+ Py_None, PyDateTimeAPI->TimeType)
+
+#define PyDelta_FromDSU(days, seconds, useconds) \
+ PyDateTimeAPI->Delta_FromDelta(days, seconds, useconds, 1, \
+ PyDateTimeAPI->DeltaType)
+
+/* Macros supporting the DB API. */
+#define PyDateTime_FromTimestamp(args) \
+ PyDateTimeAPI->DateTime_FromTimestamp( \
+ (PyObject*) (PyDateTimeAPI->DateTimeType), args, NULL)
+
+#define PyDate_FromTimestamp(args) \
+ PyDateTimeAPI->Date_FromTimestamp( \
+ (PyObject*) (PyDateTimeAPI->DateType), args)
+
+#endif /* Py_BUILD_CORE */
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/descrobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/descrobject.h
new file mode 100644
index 0000000000..5a9c3e17e6
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/descrobject.h
@@ -0,0 +1,94 @@
+/* Descriptors */
+#ifndef Py_DESCROBJECT_H
+#define Py_DESCROBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef PyObject *(*getter)(PyObject *, void *);
+typedef int (*setter)(PyObject *, PyObject *, void *);
+
+typedef struct PyGetSetDef {
+ char *name;
+ getter get;
+ setter set;
+ char *doc;
+ void *closure;
+} PyGetSetDef;
+
+typedef PyObject *(*wrapperfunc)(PyObject *self, PyObject *args,
+ void *wrapped);
+
+typedef PyObject *(*wrapperfunc_kwds)(PyObject *self, PyObject *args,
+ void *wrapped, PyObject *kwds);
+
+struct wrapperbase {
+ char *name;
+ int offset;
+ void *function;
+ wrapperfunc wrapper;
+ char *doc;
+ int flags;
+ PyObject *name_strobj;
+};
+
+/* Flags for above struct */
+#define PyWrapperFlag_KEYWORDS 1 /* wrapper function takes keyword args */
+
+/* Various kinds of descriptor objects */
+
+#define PyDescr_COMMON \
+ PyObject_HEAD \
+ PyTypeObject *d_type; \
+ PyObject *d_name
+
+typedef struct {
+ PyDescr_COMMON;
+} PyDescrObject;
+
+typedef struct {
+ PyDescr_COMMON;
+ PyMethodDef *d_method;
+} PyMethodDescrObject;
+
+typedef struct {
+ PyDescr_COMMON;
+ struct PyMemberDef *d_member;
+} PyMemberDescrObject;
+
+typedef struct {
+ PyDescr_COMMON;
+ PyGetSetDef *d_getset;
+} PyGetSetDescrObject;
+
+typedef struct {
+ PyDescr_COMMON;
+ struct wrapperbase *d_base;
+ void *d_wrapped; /* This can be any function pointer */
+} PyWrapperDescrObject;
+
+PyAPI_DATA(PyTypeObject) PyWrapperDescr_Type;
+PyAPI_DATA(PyTypeObject) PyDictProxy_Type;
+PyAPI_DATA(PyTypeObject) PyGetSetDescr_Type;
+PyAPI_DATA(PyTypeObject) PyMemberDescr_Type;
+
+PyAPI_FUNC(PyObject *) PyDescr_NewMethod(PyTypeObject *, PyMethodDef *);
+PyAPI_FUNC(PyObject *) PyDescr_NewClassMethod(PyTypeObject *, PyMethodDef *);
+PyAPI_FUNC(PyObject *) PyDescr_NewMember(PyTypeObject *,
+ struct PyMemberDef *);
+PyAPI_FUNC(PyObject *) PyDescr_NewGetSet(PyTypeObject *,
+ struct PyGetSetDef *);
+PyAPI_FUNC(PyObject *) PyDescr_NewWrapper(PyTypeObject *,
+ struct wrapperbase *, void *);
+#define PyDescr_IsData(d) (Py_TYPE(d)->tp_descr_set != NULL)
+
+PyAPI_FUNC(PyObject *) PyDictProxy_New(PyObject *);
+PyAPI_FUNC(PyObject *) PyWrapper_New(PyObject *, PyObject *);
+
+
+PyAPI_DATA(PyTypeObject) PyProperty_Type;
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_DESCROBJECT_H */
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/dictobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/dictobject.h
new file mode 100644
index 0000000000..0f3ab17caa
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/dictobject.h
@@ -0,0 +1,156 @@
+#ifndef Py_DICTOBJECT_H
+#define Py_DICTOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Dictionary object type -- mapping from hashable object to object */
+
+/* The distribution includes a separate file, Objects/dictnotes.txt,
+ describing explorations into dictionary design and optimization.
+ It covers typical dictionary use patterns, the parameters for
+ tuning dictionaries, and several ideas for possible optimizations.
+*/
+
+/*
+There are three kinds of slots in the table:
+
+1. Unused. me_key == me_value == NULL
+ Does not hold an active (key, value) pair now and never did. Unused can
+ transition to Active upon key insertion. This is the only case in which
+ me_key is NULL, and is each slot's initial state.
+
+2. Active. me_key != NULL and me_key != dummy and me_value != NULL
+ Holds an active (key, value) pair. Active can transition to Dummy upon
+ key deletion. This is the only case in which me_value != NULL.
+
+3. Dummy. me_key == dummy and me_value == NULL
+ Previously held an active (key, value) pair, but that was deleted and an
+ active pair has not yet overwritten the slot. Dummy can transition to
+ Active upon key insertion. Dummy slots cannot be made Unused again
+ (cannot have me_key set to NULL), else the probe sequence in case of
+ collision would have no way to know they were once active.
+
+Note: .popitem() abuses the me_hash field of an Unused or Dummy slot to
+hold a search finger. The me_hash field of Unused or Dummy slots has no
+meaning otherwise.
+*/
+
+/* PyDict_MINSIZE is the minimum size of a dictionary. This many slots are
+ * allocated directly in the dict object (in the ma_smalltable member).
+ * It must be a power of 2, and at least 4. 8 allows dicts with no more
+ * than 5 active entries to live in ma_smalltable (and so avoid an
+ * additional malloc); instrumentation suggested this suffices for the
+ * majority of dicts (consisting mostly of usually-small instance dicts and
+ * usually-small dicts created to pass keyword arguments).
+ */
+#define PyDict_MINSIZE 8
+
+typedef struct {
+ /* Cached hash code of me_key. Note that hash codes are C longs.
+ * We have to use Py_ssize_t instead because dict_popitem() abuses
+ * me_hash to hold a search finger.
+ */
+ Py_ssize_t me_hash;
+ PyObject *me_key;
+ PyObject *me_value;
+} PyDictEntry;
+
+/*
+To ensure the lookup algorithm terminates, there must be at least one Unused
+slot (NULL key) in the table.
+The value ma_fill is the number of non-NULL keys (sum of Active and Dummy);
+ma_used is the number of non-NULL, non-dummy keys (== the number of non-NULL
+values == the number of Active items).
+To avoid slowing down lookups on a near-full table, we resize the table when
+it's two-thirds full.
+*/
+typedef struct _dictobject PyDictObject;
+struct _dictobject {
+ PyObject_HEAD
+ Py_ssize_t ma_fill; /* # Active + # Dummy */
+ Py_ssize_t ma_used; /* # Active */
+
+ /* The table contains ma_mask + 1 slots, and that's a power of 2.
+ * We store the mask instead of the size because the mask is more
+ * frequently needed.
+ */
+ Py_ssize_t ma_mask;
+
+ /* ma_table points to ma_smalltable for small tables, else to
+ * additional malloc'ed memory. ma_table is never NULL! This rule
+ * saves repeated runtime null-tests in the workhorse getitem and
+ * setitem calls.
+ */
+ PyDictEntry *ma_table;
+ PyDictEntry *(*ma_lookup)(PyDictObject *mp, PyObject *key, long hash);
+ PyDictEntry ma_smalltable[PyDict_MINSIZE];
+};
+
+PyAPI_DATA(PyTypeObject) PyDict_Type;
+PyAPI_DATA(PyTypeObject) PyDictIterKey_Type;
+PyAPI_DATA(PyTypeObject) PyDictIterValue_Type;
+PyAPI_DATA(PyTypeObject) PyDictIterItem_Type;
+PyAPI_DATA(PyTypeObject) PyDictKeys_Type;
+PyAPI_DATA(PyTypeObject) PyDictItems_Type;
+PyAPI_DATA(PyTypeObject) PyDictValues_Type;
+
+#define PyDict_Check(op) \
+ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_DICT_SUBCLASS)
+#define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type)
+#define PyDictKeys_Check(op) (Py_TYPE(op) == &PyDictKeys_Type)
+#define PyDictItems_Check(op) (Py_TYPE(op) == &PyDictItems_Type)
+#define PyDictValues_Check(op) (Py_TYPE(op) == &PyDictValues_Type)
+/* This excludes Values, since they are not sets. */
+# define PyDictViewSet_Check(op) \
+ (PyDictKeys_Check(op) || PyDictItems_Check(op))
+
+PyAPI_FUNC(PyObject *) PyDict_New(void);
+PyAPI_FUNC(PyObject *) PyDict_GetItem(PyObject *mp, PyObject *key);
+PyAPI_FUNC(int) PyDict_SetItem(PyObject *mp, PyObject *key, PyObject *item);
+PyAPI_FUNC(int) PyDict_DelItem(PyObject *mp, PyObject *key);
+PyAPI_FUNC(void) PyDict_Clear(PyObject *mp);
+PyAPI_FUNC(int) PyDict_Next(
+ PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value);
+PyAPI_FUNC(int) _PyDict_Next(
+ PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash);
+PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp);
+PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp);
+PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp);
+PyAPI_FUNC(Py_ssize_t) PyDict_Size(PyObject *mp);
+PyAPI_FUNC(PyObject *) PyDict_Copy(PyObject *mp);
+PyAPI_FUNC(int) PyDict_Contains(PyObject *mp, PyObject *key);
+PyAPI_FUNC(int) _PyDict_Contains(PyObject *mp, PyObject *key, long hash);
+PyAPI_FUNC(PyObject *) _PyDict_NewPresized(Py_ssize_t minused);
+PyAPI_FUNC(void) _PyDict_MaybeUntrack(PyObject *mp);
+
+/* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */
+PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other);
+
+/* PyDict_Merge updates/merges from a mapping object (an object that
+ supports PyMapping_Keys() and PyObject_GetItem()). If override is true,
+ the last occurrence of a key wins, else the first. The Python
+ dict.update(other) is equivalent to PyDict_Merge(dict, other, 1).
+*/
+PyAPI_FUNC(int) PyDict_Merge(PyObject *mp,
+ PyObject *other,
+ int override);
+
+/* PyDict_MergeFromSeq2 updates/merges from an iterable object producing
+ iterable objects of length 2. If override is true, the last occurrence
+ of a key wins, else the first. The Python dict constructor dict(seq2)
+ is equivalent to dict={}; PyDict_MergeFromSeq(dict, seq2, 1).
+*/
+PyAPI_FUNC(int) PyDict_MergeFromSeq2(PyObject *d,
+ PyObject *seq2,
+ int override);
+
+PyAPI_FUNC(PyObject *) PyDict_GetItemString(PyObject *dp, const char *key);
+PyAPI_FUNC(int) PyDict_SetItemString(PyObject *dp, const char *key, PyObject *item);
+PyAPI_FUNC(int) PyDict_DelItemString(PyObject *dp, const char *key);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_DICTOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/dtoa.h b/AppPkg/Applications/Python/Python-2.7.2/Include/dtoa.h
new file mode 100644
index 0000000000..c7e80bcf8a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/dtoa.h
@@ -0,0 +1,15 @@
+#ifndef PY_NO_SHORT_FLOAT_REPR
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_FUNC(double) _Py_dg_strtod(const char *str, char **ptr);
+PyAPI_FUNC(char *) _Py_dg_dtoa(double d, int mode, int ndigits,
+ int *decpt, int *sign, char **rve);
+PyAPI_FUNC(void) _Py_dg_freedtoa(char *s);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/enumobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/enumobject.h
new file mode 100644
index 0000000000..42dc2d27de
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/enumobject.h
@@ -0,0 +1,17 @@
+#ifndef Py_ENUMOBJECT_H
+#define Py_ENUMOBJECT_H
+
+/* Enumerate Object */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_DATA(PyTypeObject) PyEnum_Type;
+PyAPI_DATA(PyTypeObject) PyReversed_Type;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !Py_ENUMOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/errcode.h b/AppPkg/Applications/Python/Python-2.7.2/Include/errcode.h
new file mode 100644
index 0000000000..295295cd60
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/errcode.h
@@ -0,0 +1,36 @@
+#ifndef Py_ERRCODE_H
+#define Py_ERRCODE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Error codes passed around between file input, tokenizer, parser and
+ interpreter. This is necessary so we can turn them into Python
+ exceptions at a higher level. Note that some errors have a
+ slightly different meaning when passed from the tokenizer to the
+ parser than when passed from the parser to the interpreter; e.g.
+ the parser only returns E_EOF when it hits EOF immediately, and it
+ never returns E_OK. */
+
+#define E_OK 10 /* No error */
+#define E_EOF 11 /* End Of File */
+#define E_INTR 12 /* Interrupted */
+#define E_TOKEN 13 /* Bad token */
+#define E_SYNTAX 14 /* Syntax error */
+#define E_NOMEM 15 /* Ran out of memory */
+#define E_DONE 16 /* Parsing complete */
+#define E_ERROR 17 /* Execution error */
+#define E_TABSPACE 18 /* Inconsistent mixing of tabs and spaces */
+#define E_OVERFLOW 19 /* Node had too many children */
+#define E_TOODEEP 20 /* Too many indentation levels */
+#define E_DEDENT 21 /* No matching outer block for dedent */
+#define E_DECODE 22 /* Error in decoding into Unicode */
+#define E_EOFS 23 /* EOF in triple-quoted string */
+#define E_EOLS 24 /* EOL in single-quoted string */
+#define E_LINECONT 25 /* Unexpected characters after a line continuation */
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_ERRCODE_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/eval.h b/AppPkg/Applications/Python/Python-2.7.2/Include/eval.h
new file mode 100644
index 0000000000..fe1d47aebb
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/eval.h
@@ -0,0 +1,25 @@
+
+/* Interface to execute compiled code */
+
+#ifndef Py_EVAL_H
+#define Py_EVAL_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_FUNC(PyObject *) PyEval_EvalCode(PyCodeObject *, PyObject *, PyObject *);
+
+PyAPI_FUNC(PyObject *) PyEval_EvalCodeEx(PyCodeObject *co,
+ PyObject *globals,
+ PyObject *locals,
+ PyObject **args, int argc,
+ PyObject **kwds, int kwdc,
+ PyObject **defs, int defc,
+ PyObject *closure);
+
+PyAPI_FUNC(PyObject *) _PyEval_CallTracing(PyObject *func, PyObject *args);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_EVAL_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/fileobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/fileobject.h
new file mode 100644
index 0000000000..f1fdde2449
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/fileobject.h
@@ -0,0 +1,102 @@
+/** @file
+ File object interface.
+
+ Copyright (c) 2011, Intel Corporation. All rights reserved.
+ This program and the accompanying materials are licensed and made available under
+ the terms and conditions of the BSD License that accompanies this distribution.
+ The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+**/
+
+/* File object interface */
+
+#ifndef Py_FILEOBJECT_H
+#define Py_FILEOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ PyObject_HEAD
+ FILE *f_fp;
+ PyObject *f_name;
+ PyObject *f_mode;
+ int (*f_close)(FILE *);
+ int f_softspace; /* Flag used by 'print' command */
+ int f_binary; /* Flag which indicates whether the file is
+ open in binary (1) or text (0) mode */
+ char* f_buf; /* Allocated readahead buffer */
+ char* f_bufend; /* Points after last occupied position */
+ char* f_bufptr; /* Current buffer position */
+ char *f_setbuf; /* Buffer for setbuf(3) and setvbuf(3) */
+ int f_univ_newline; /* Handle any newline convention */
+ int f_newlinetypes; /* Types of newlines seen */
+ int f_skipnextlf; /* Skip next \n */
+ PyObject *f_encoding;
+ PyObject *f_errors;
+ PyObject *weakreflist; /* List of weak references */
+ int unlocked_count; /* Num. currently running sections of code
+ using f_fp with the GIL released. */
+ int readable;
+ int writable;
+} PyFileObject;
+
+PyAPI_DATA(PyTypeObject) PyFile_Type;
+
+#define PyFile_Check(op) PyObject_TypeCheck(op, &PyFile_Type)
+#define PyFile_CheckExact(op) (Py_TYPE(op) == &PyFile_Type)
+
+PyAPI_FUNC(PyObject *) PyFile_FromString(char *, char *);
+PyAPI_FUNC(void) PyFile_SetBufSize(PyObject *, int);
+PyAPI_FUNC(int) PyFile_SetEncoding(PyObject *, const char *);
+PyAPI_FUNC(int) PyFile_SetEncodingAndErrors(PyObject *, const char *, char *errors);
+PyAPI_FUNC(PyObject *) PyFile_FromFile(FILE *, char *, char *,
+ int (*)(FILE *));
+PyAPI_FUNC(FILE *) PyFile_AsFile(PyObject *);
+PyAPI_FUNC(void) PyFile_IncUseCount(PyFileObject *);
+PyAPI_FUNC(void) PyFile_DecUseCount(PyFileObject *);
+PyAPI_FUNC(PyObject *) PyFile_Name(PyObject *);
+PyAPI_FUNC(PyObject *) PyFile_GetLine(PyObject *, int);
+PyAPI_FUNC(int) PyFile_WriteObject(PyObject *, PyObject *, int);
+PyAPI_FUNC(int) PyFile_SoftSpace(PyObject *, int);
+PyAPI_FUNC(int) PyFile_WriteString(const char *, PyObject *);
+PyAPI_FUNC(int) PyObject_AsFileDescriptor(PyObject *);
+
+/* The default encoding used by the platform file system APIs
+ If non-NULL, this is different than the default encoding for strings
+*/
+PyAPI_DATA(const char *) Py_FileSystemDefaultEncoding;
+
+/* Routines to replace fread() and fgets() which accept any of \r, \n
+ or \r\n as line terminators.
+*/
+#define PY_STDIOTEXTMODE "b"
+char *Py_UniversalNewlineFgets(char *, int, FILE*, PyObject *);
+size_t Py_UniversalNewlineFread(char *, size_t, FILE *, PyObject *);
+
+/* A routine to do sanity checking on the file mode string. returns
+ non-zero on if an exception occurred
+*/
+int _PyFile_SanitizeMode(char *mode);
+
+//#if defined _MSC_VER && _MSC_VER >= 1400
+/* A routine to check if a file descriptor is valid on Windows. Returns 0
+ * and sets errno to EBADF if it isn't. This is to avoid Assertions
+ * from various functions in the Windows CRT beginning with
+ * Visual Studio 2005
+ */
+//int _PyVerify_fd(int fd);
+//#elif defined _MSC_VER && _MSC_VER >= 1200
+/* fdopen doesn't set errno EBADF and crashes for large fd on debug build */
+//#define _PyVerify_fd(fd) (_get_osfhandle(fd) >= 0)
+//#else
+#define _PyVerify_fd(A) (1) /* dummy */
+//#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_FILEOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/floatobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/floatobject.h
new file mode 100644
index 0000000000..92c69fe88f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/floatobject.h
@@ -0,0 +1,140 @@
+
+/* Float object interface */
+
+/*
+PyFloatObject represents a (double precision) floating point number.
+*/
+
+#ifndef Py_FLOATOBJECT_H
+#define Py_FLOATOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ PyObject_HEAD
+ double ob_fval;
+} PyFloatObject;
+
+PyAPI_DATA(PyTypeObject) PyFloat_Type;
+
+#define PyFloat_Check(op) PyObject_TypeCheck(op, &PyFloat_Type)
+#define PyFloat_CheckExact(op) (Py_TYPE(op) == &PyFloat_Type)
+
+/* The str() precision PyFloat_STR_PRECISION is chosen so that in most cases,
+ the rounding noise created by various operations is suppressed, while
+ giving plenty of precision for practical use. */
+
+#define PyFloat_STR_PRECISION 12
+
+#ifdef Py_NAN
+#define Py_RETURN_NAN return PyFloat_FromDouble(Py_NAN)
+#endif
+
+#define Py_RETURN_INF(sign) do \
+ if (copysign(1., sign) == 1.) { \
+ return PyFloat_FromDouble(Py_HUGE_VAL); \
+ } else { \
+ return PyFloat_FromDouble(-Py_HUGE_VAL); \
+ } while(0)
+
+PyAPI_FUNC(double) PyFloat_GetMax(void);
+PyAPI_FUNC(double) PyFloat_GetMin(void);
+PyAPI_FUNC(PyObject *) PyFloat_GetInfo(void);
+
+/* Return Python float from string PyObject. Second argument ignored on
+ input, and, if non-NULL, NULL is stored into *junk (this tried to serve a
+ purpose once but can't be made to work as intended). */
+PyAPI_FUNC(PyObject *) PyFloat_FromString(PyObject*, char** junk);
+
+/* Return Python float from C double. */
+PyAPI_FUNC(PyObject *) PyFloat_FromDouble(double);
+
+/* Extract C double from Python float. The macro version trades safety for
+ speed. */
+PyAPI_FUNC(double) PyFloat_AsDouble(PyObject *);
+#define PyFloat_AS_DOUBLE(op) (((PyFloatObject *)(op))->ob_fval)
+
+/* Write repr(v) into the char buffer argument, followed by null byte. The
+ buffer must be "big enough"; >= 100 is very safe.
+ PyFloat_AsReprString(buf, x) strives to print enough digits so that
+ PyFloat_FromString(buf) then reproduces x exactly. */
+PyAPI_FUNC(void) PyFloat_AsReprString(char*, PyFloatObject *v);
+
+/* Write str(v) into the char buffer argument, followed by null byte. The
+ buffer must be "big enough"; >= 100 is very safe. Note that it's
+ unusual to be able to get back the float you started with from
+ PyFloat_AsString's result -- use PyFloat_AsReprString() if you want to
+ preserve precision across conversions. */
+PyAPI_FUNC(void) PyFloat_AsString(char*, PyFloatObject *v);
+
+/* _PyFloat_{Pack,Unpack}{4,8}
+ *
+ * The struct and pickle (at least) modules need an efficient platform-
+ * independent way to store floating-point values as byte strings.
+ * The Pack routines produce a string from a C double, and the Unpack
+ * routines produce a C double from such a string. The suffix (4 or 8)
+ * specifies the number of bytes in the string.
+ *
+ * On platforms that appear to use (see _PyFloat_Init()) IEEE-754 formats
+ * these functions work by copying bits. On other platforms, the formats the
+ * 4- byte format is identical to the IEEE-754 single precision format, and
+ * the 8-byte format to the IEEE-754 double precision format, although the
+ * packing of INFs and NaNs (if such things exist on the platform) isn't
+ * handled correctly, and attempting to unpack a string containing an IEEE
+ * INF or NaN will raise an exception.
+ *
+ * On non-IEEE platforms with more precision, or larger dynamic range, than
+ * 754 supports, not all values can be packed; on non-IEEE platforms with less
+ * precision, or smaller dynamic range, not all values can be unpacked. What
+ * happens in such cases is partly accidental (alas).
+ */
+
+/* The pack routines write 4 or 8 bytes, starting at p. le is a bool
+ * argument, true if you want the string in little-endian format (exponent
+ * last, at p+3 or p+7), false if you want big-endian format (exponent
+ * first, at p).
+ * Return value: 0 if all is OK, -1 if error (and an exception is
+ * set, most likely OverflowError).
+ * There are two problems on non-IEEE platforms:
+ * 1): What this does is undefined if x is a NaN or infinity.
+ * 2): -0.0 and +0.0 produce the same string.
+ */
+PyAPI_FUNC(int) _PyFloat_Pack4(double x, unsigned char *p, int le);
+PyAPI_FUNC(int) _PyFloat_Pack8(double x, unsigned char *p, int le);
+
+/* Used to get the important decimal digits of a double */
+PyAPI_FUNC(int) _PyFloat_Digits(char *buf, double v, int *signum);
+PyAPI_FUNC(void) _PyFloat_DigitsInit(void);
+
+/* The unpack routines read 4 or 8 bytes, starting at p. le is a bool
+ * argument, true if the string is in little-endian format (exponent
+ * last, at p+3 or p+7), false if big-endian (exponent first, at p).
+ * Return value: The unpacked double. On error, this is -1.0 and
+ * PyErr_Occurred() is true (and an exception is set, most likely
+ * OverflowError). Note that on a non-IEEE platform this will refuse
+ * to unpack a string that represents a NaN or infinity.
+ */
+PyAPI_FUNC(double) _PyFloat_Unpack4(const unsigned char *p, int le);
+PyAPI_FUNC(double) _PyFloat_Unpack8(const unsigned char *p, int le);
+
+/* free list api */
+PyAPI_FUNC(int) PyFloat_ClearFreeList(void);
+
+/* Format the object based on the format_spec, as defined in PEP 3101
+ (Advanced String Formatting). */
+PyAPI_FUNC(PyObject *) _PyFloat_FormatAdvanced(PyObject *obj,
+ char *format_spec,
+ Py_ssize_t format_spec_len);
+
+/* Round a C double x to the closest multiple of 10**-ndigits. Returns a
+ Python float on success, or NULL (with an appropriate exception set) on
+ failure. Used in builtin_round in bltinmodule.c. */
+PyAPI_FUNC(PyObject *) _Py_double_round(double x, int ndigits);
+
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_FLOATOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/frameobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/frameobject.h
new file mode 100644
index 0000000000..2298ed315c
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/frameobject.h
@@ -0,0 +1,89 @@
+
+/* Frame object interface */
+
+#ifndef Py_FRAMEOBJECT_H
+#define Py_FRAMEOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ int b_type; /* what kind of block this is */
+ int b_handler; /* where to jump to find handler */
+ int b_level; /* value stack level to pop to */
+} PyTryBlock;
+
+typedef struct _frame {
+ PyObject_VAR_HEAD
+ struct _frame *f_back; /* previous frame, or NULL */
+ PyCodeObject *f_code; /* code segment */
+ PyObject *f_builtins; /* builtin symbol table (PyDictObject) */
+ PyObject *f_globals; /* global symbol table (PyDictObject) */
+ PyObject *f_locals; /* local symbol table (any mapping) */
+ PyObject **f_valuestack; /* points after the last local */
+ /* Next free slot in f_valuestack. Frame creation sets to f_valuestack.
+ Frame evaluation usually NULLs it, but a frame that yields sets it
+ to the current stack top. */
+ PyObject **f_stacktop;
+ PyObject *f_trace; /* Trace function */
+
+ /* If an exception is raised in this frame, the next three are used to
+ * record the exception info (if any) originally in the thread state. See
+ * comments before set_exc_info() -- it's not obvious.
+ * Invariant: if _type is NULL, then so are _value and _traceback.
+ * Desired invariant: all three are NULL, or all three are non-NULL. That
+ * one isn't currently true, but "should be".
+ */
+ PyObject *f_exc_type, *f_exc_value, *f_exc_traceback;
+
+ PyThreadState *f_tstate;
+ int f_lasti; /* Last instruction if called */
+ /* Call PyFrame_GetLineNumber() instead of reading this field
+ directly. As of 2.3 f_lineno is only valid when tracing is
+ active (i.e. when f_trace is set). At other times we use
+ PyCode_Addr2Line to calculate the line from the current
+ bytecode index. */
+ int f_lineno; /* Current line number */
+ int f_iblock; /* index in f_blockstack */
+ PyTryBlock f_blockstack[CO_MAXBLOCKS]; /* for try and loop blocks */
+ PyObject *f_localsplus[1]; /* locals+stack, dynamically sized */
+} PyFrameObject;
+
+
+/* Standard object interface */
+
+PyAPI_DATA(PyTypeObject) PyFrame_Type;
+
+#define PyFrame_Check(op) ((op)->ob_type == &PyFrame_Type)
+#define PyFrame_IsRestricted(f) \
+ ((f)->f_builtins != (f)->f_tstate->interp->builtins)
+
+PyAPI_FUNC(PyFrameObject *) PyFrame_New(PyThreadState *, PyCodeObject *,
+ PyObject *, PyObject *);
+
+
+/* The rest of the interface is specific for frame objects */
+
+/* Block management functions */
+
+PyAPI_FUNC(void) PyFrame_BlockSetup(PyFrameObject *, int, int, int);
+PyAPI_FUNC(PyTryBlock *) PyFrame_BlockPop(PyFrameObject *);
+
+/* Extend the value stack */
+
+PyAPI_FUNC(PyObject **) PyFrame_ExtendStack(PyFrameObject *, int, int);
+
+/* Conversions between "fast locals" and locals in dictionary */
+
+PyAPI_FUNC(void) PyFrame_LocalsToFast(PyFrameObject *, int);
+PyAPI_FUNC(void) PyFrame_FastToLocals(PyFrameObject *);
+
+PyAPI_FUNC(int) PyFrame_ClearFreeList(void);
+
+/* Return the line of code the frame is currently executing. */
+PyAPI_FUNC(int) PyFrame_GetLineNumber(PyFrameObject *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_FRAMEOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/funcobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/funcobject.h
new file mode 100644
index 0000000000..07c05ce3f8
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/funcobject.h
@@ -0,0 +1,76 @@
+
+/* Function object interface */
+
+#ifndef Py_FUNCOBJECT_H
+#define Py_FUNCOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Function objects and code objects should not be confused with each other:
+ *
+ * Function objects are created by the execution of the 'def' statement.
+ * They reference a code object in their func_code attribute, which is a
+ * purely syntactic object, i.e. nothing more than a compiled version of some
+ * source code lines. There is one code object per source code "fragment",
+ * but each code object can be referenced by zero or many function objects
+ * depending only on how many times the 'def' statement in the source was
+ * executed so far.
+ */
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *func_code; /* A code object */
+ PyObject *func_globals; /* A dictionary (other mappings won't do) */
+ PyObject *func_defaults; /* NULL or a tuple */
+ PyObject *func_closure; /* NULL or a tuple of cell objects */
+ PyObject *func_doc; /* The __doc__ attribute, can be anything */
+ PyObject *func_name; /* The __name__ attribute, a string object */
+ PyObject *func_dict; /* The __dict__ attribute, a dict or NULL */
+ PyObject *func_weakreflist; /* List of weak references */
+ PyObject *func_module; /* The __module__ attribute, can be anything */
+
+ /* Invariant:
+ * func_closure contains the bindings for func_code->co_freevars, so
+ * PyTuple_Size(func_closure) == PyCode_GetNumFree(func_code)
+ * (func_closure may be NULL if PyCode_GetNumFree(func_code) == 0).
+ */
+} PyFunctionObject;
+
+PyAPI_DATA(PyTypeObject) PyFunction_Type;
+
+#define PyFunction_Check(op) (Py_TYPE(op) == &PyFunction_Type)
+
+PyAPI_FUNC(PyObject *) PyFunction_New(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyFunction_GetCode(PyObject *);
+PyAPI_FUNC(PyObject *) PyFunction_GetGlobals(PyObject *);
+PyAPI_FUNC(PyObject *) PyFunction_GetModule(PyObject *);
+PyAPI_FUNC(PyObject *) PyFunction_GetDefaults(PyObject *);
+PyAPI_FUNC(int) PyFunction_SetDefaults(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyFunction_GetClosure(PyObject *);
+PyAPI_FUNC(int) PyFunction_SetClosure(PyObject *, PyObject *);
+
+/* Macros for direct access to these values. Type checks are *not*
+ done, so use with care. */
+#define PyFunction_GET_CODE(func) \
+ (((PyFunctionObject *)func) -> func_code)
+#define PyFunction_GET_GLOBALS(func) \
+ (((PyFunctionObject *)func) -> func_globals)
+#define PyFunction_GET_MODULE(func) \
+ (((PyFunctionObject *)func) -> func_module)
+#define PyFunction_GET_DEFAULTS(func) \
+ (((PyFunctionObject *)func) -> func_defaults)
+#define PyFunction_GET_CLOSURE(func) \
+ (((PyFunctionObject *)func) -> func_closure)
+
+/* The classmethod and staticmethod types lives here, too */
+PyAPI_DATA(PyTypeObject) PyClassMethod_Type;
+PyAPI_DATA(PyTypeObject) PyStaticMethod_Type;
+
+PyAPI_FUNC(PyObject *) PyClassMethod_New(PyObject *);
+PyAPI_FUNC(PyObject *) PyStaticMethod_New(PyObject *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_FUNCOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/genobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/genobject.h
new file mode 100644
index 0000000000..ab9680da0f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/genobject.h
@@ -0,0 +1,40 @@
+
+/* Generator object interface */
+
+#ifndef Py_GENOBJECT_H
+#define Py_GENOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct _frame; /* Avoid including frameobject.h */
+
+typedef struct {
+ PyObject_HEAD
+ /* The gi_ prefix is intended to remind of generator-iterator. */
+
+ /* Note: gi_frame can be NULL if the generator is "finished" */
+ struct _frame *gi_frame;
+
+ /* True if generator is being executed. */
+ int gi_running;
+
+ /* The code object backing the generator */
+ PyObject *gi_code;
+
+ /* List of weak reference. */
+ PyObject *gi_weakreflist;
+} PyGenObject;
+
+PyAPI_DATA(PyTypeObject) PyGen_Type;
+
+#define PyGen_Check(op) PyObject_TypeCheck(op, &PyGen_Type)
+#define PyGen_CheckExact(op) (Py_TYPE(op) == &PyGen_Type)
+
+PyAPI_FUNC(PyObject *) PyGen_New(struct _frame *);
+PyAPI_FUNC(int) PyGen_NeedsFinalizing(PyGenObject *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_GENOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/graminit.h b/AppPkg/Applications/Python/Python-2.7.2/Include/graminit.h
new file mode 100644
index 0000000000..b083e9d1f5
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/graminit.h
@@ -0,0 +1,87 @@
+/* Generated by Parser/pgen */
+
+#define single_input 256
+#define file_input 257
+#define eval_input 258
+#define decorator 259
+#define decorators 260
+#define decorated 261
+#define funcdef 262
+#define parameters 263
+#define varargslist 264
+#define fpdef 265
+#define fplist 266
+#define stmt 267
+#define simple_stmt 268
+#define small_stmt 269
+#define expr_stmt 270
+#define augassign 271
+#define print_stmt 272
+#define del_stmt 273
+#define pass_stmt 274
+#define flow_stmt 275
+#define break_stmt 276
+#define continue_stmt 277
+#define return_stmt 278
+#define yield_stmt 279
+#define raise_stmt 280
+#define import_stmt 281
+#define import_name 282
+#define import_from 283
+#define import_as_name 284
+#define dotted_as_name 285
+#define import_as_names 286
+#define dotted_as_names 287
+#define dotted_name 288
+#define global_stmt 289
+#define exec_stmt 290
+#define assert_stmt 291
+#define compound_stmt 292
+#define if_stmt 293
+#define while_stmt 294
+#define for_stmt 295
+#define try_stmt 296
+#define with_stmt 297
+#define with_item 298
+#define except_clause 299
+#define suite 300
+#define testlist_safe 301
+#define old_test 302
+#define old_lambdef 303
+#define test 304
+#define or_test 305
+#define and_test 306
+#define not_test 307
+#define comparison 308
+#define comp_op 309
+#define expr 310
+#define xor_expr 311
+#define and_expr 312
+#define shift_expr 313
+#define arith_expr 314
+#define term 315
+#define factor 316
+#define power 317
+#define atom 318
+#define listmaker 319
+#define testlist_comp 320
+#define lambdef 321
+#define trailer 322
+#define subscriptlist 323
+#define subscript 324
+#define sliceop 325
+#define exprlist 326
+#define testlist 327
+#define dictorsetmaker 328
+#define classdef 329
+#define arglist 330
+#define argument 331
+#define list_iter 332
+#define list_for 333
+#define list_if 334
+#define comp_iter 335
+#define comp_for 336
+#define comp_if 337
+#define testlist1 338
+#define encoding_decl 339
+#define yield_expr 340
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/grammar.h b/AppPkg/Applications/Python/Python-2.7.2/Include/grammar.h
new file mode 100644
index 0000000000..f82ee9c1dc
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/grammar.h
@@ -0,0 +1,93 @@
+
+/* Grammar interface */
+
+#ifndef Py_GRAMMAR_H
+#define Py_GRAMMAR_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "bitset.h" /* Sigh... */
+
+/* A label of an arc */
+
+typedef struct {
+ int lb_type;
+ char *lb_str;
+} label;
+
+#define EMPTY 0 /* Label number 0 is by definition the empty label */
+
+/* A list of labels */
+
+typedef struct {
+ int ll_nlabels;
+ label *ll_label;
+} labellist;
+
+/* An arc from one state to another */
+
+typedef struct {
+ short a_lbl; /* Label of this arc */
+ short a_arrow; /* State where this arc goes to */
+} arc;
+
+/* A state in a DFA */
+
+typedef struct {
+ int s_narcs;
+ arc *s_arc; /* Array of arcs */
+
+ /* Optional accelerators */
+ int s_lower; /* Lowest label index */
+ int s_upper; /* Highest label index */
+ int *s_accel; /* Accelerator */
+ int s_accept; /* Nonzero for accepting state */
+} state;
+
+/* A DFA */
+
+typedef struct {
+ int d_type; /* Non-terminal this represents */
+ char *d_name; /* For printing */
+ int d_initial; /* Initial state */
+ int d_nstates;
+ state *d_state; /* Array of states */
+ bitset d_first;
+} dfa;
+
+/* A grammar */
+
+typedef struct {
+ int g_ndfas;
+ dfa *g_dfa; /* Array of DFAs */
+ labellist g_ll;
+ int g_start; /* Start symbol of the grammar */
+ int g_accel; /* Set if accelerators present */
+} grammar;
+
+/* FUNCTIONS */
+
+grammar *newgrammar(int start);
+dfa *adddfa(grammar *g, int type, char *name);
+int addstate(dfa *d);
+void addarc(dfa *d, int from, int to, int lbl);
+dfa *PyGrammar_FindDFA(grammar *g, int type);
+
+int addlabel(labellist *ll, int type, char *str);
+int findlabel(labellist *ll, int type, char *str);
+char *PyGrammar_LabelRepr(label *lb);
+void translatelabels(grammar *g);
+
+void addfirstsets(grammar *g);
+
+void PyGrammar_AddAccelerators(grammar *g);
+void PyGrammar_RemoveAccelerators(grammar *);
+
+void printgrammar(grammar *g, FILE *fp);
+void printnonterminals(grammar *g, FILE *fp);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_GRAMMAR_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/import.h b/AppPkg/Applications/Python/Python-2.7.2/Include/import.h
new file mode 100644
index 0000000000..48475965ac
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/import.h
@@ -0,0 +1,71 @@
+
+/* Module definition and import interface */
+
+#ifndef Py_IMPORT_H
+#define Py_IMPORT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_FUNC(long) PyImport_GetMagicNumber(void);
+PyAPI_FUNC(PyObject *) PyImport_ExecCodeModule(char *name, PyObject *co);
+PyAPI_FUNC(PyObject *) PyImport_ExecCodeModuleEx(
+ char *name, PyObject *co, char *pathname);
+PyAPI_FUNC(PyObject *) PyImport_GetModuleDict(void);
+PyAPI_FUNC(PyObject *) PyImport_AddModule(const char *name);
+PyAPI_FUNC(PyObject *) PyImport_ImportModule(const char *name);
+PyAPI_FUNC(PyObject *) PyImport_ImportModuleNoBlock(const char *);
+PyAPI_FUNC(PyObject *) PyImport_ImportModuleLevel(char *name,
+ PyObject *globals, PyObject *locals, PyObject *fromlist, int level);
+
+#define PyImport_ImportModuleEx(n, g, l, f) \
+ PyImport_ImportModuleLevel(n, g, l, f, -1)
+
+PyAPI_FUNC(PyObject *) PyImport_GetImporter(PyObject *path);
+PyAPI_FUNC(PyObject *) PyImport_Import(PyObject *name);
+PyAPI_FUNC(PyObject *) PyImport_ReloadModule(PyObject *m);
+PyAPI_FUNC(void) PyImport_Cleanup(void);
+PyAPI_FUNC(int) PyImport_ImportFrozenModule(char *);
+
+#ifdef WITH_THREAD
+PyAPI_FUNC(void) _PyImport_AcquireLock(void);
+PyAPI_FUNC(int) _PyImport_ReleaseLock(void);
+#else
+#define _PyImport_AcquireLock()
+#define _PyImport_ReleaseLock() 1
+#endif
+
+PyAPI_FUNC(struct filedescr *) _PyImport_FindModule(
+ const char *, PyObject *, char *, size_t, FILE **, PyObject **);
+PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr *);
+PyAPI_FUNC(void) _PyImport_ReInitLock(void);
+
+PyAPI_FUNC(PyObject *)_PyImport_FindExtension(char *, char *);
+PyAPI_FUNC(PyObject *)_PyImport_FixupExtension(char *, char *);
+
+struct _inittab {
+ char *name;
+ void (*initfunc)(void);
+};
+
+PyAPI_DATA(PyTypeObject) PyNullImporter_Type;
+PyAPI_DATA(struct _inittab *) PyImport_Inittab;
+
+PyAPI_FUNC(int) PyImport_AppendInittab(const char *name, void (*initfunc)(void));
+PyAPI_FUNC(int) PyImport_ExtendInittab(struct _inittab *newtab);
+
+struct _frozen {
+ char *name;
+ unsigned char *code;
+ int size;
+};
+
+/* Embedding apps may change this pointer to point to their favorite
+ collection of frozen modules: */
+
+PyAPI_DATA(struct _frozen *) PyImport_FrozenModules;
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_IMPORT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/intobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/intobject.h
new file mode 100644
index 0000000000..dc08017fa6
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/intobject.h
@@ -0,0 +1,80 @@
+
+/* Integer object interface */
+
+/*
+PyIntObject represents a (long) integer. This is an immutable object;
+an integer cannot change its value after creation.
+
+There are functions to create new integer objects, to test an object
+for integer-ness, and to get the integer value. The latter functions
+returns -1 and sets errno to EBADF if the object is not an PyIntObject.
+None of the functions should be applied to nil objects.
+
+The type PyIntObject is (unfortunately) exposed here so we can declare
+_Py_TrueStruct and _Py_ZeroStruct in boolobject.h; don't use this.
+*/
+
+#ifndef Py_INTOBJECT_H
+#define Py_INTOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ PyObject_HEAD
+ long ob_ival;
+} PyIntObject;
+
+PyAPI_DATA(PyTypeObject) PyInt_Type;
+
+#define PyInt_Check(op) \
+ PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_INT_SUBCLASS)
+#define PyInt_CheckExact(op) ((op)->ob_type == &PyInt_Type)
+
+PyAPI_FUNC(PyObject *) PyInt_FromString(char*, char**, int);
+#ifdef Py_USING_UNICODE
+PyAPI_FUNC(PyObject *) PyInt_FromUnicode(Py_UNICODE*, Py_ssize_t, int);
+#endif
+PyAPI_FUNC(PyObject *) PyInt_FromLong(long);
+PyAPI_FUNC(PyObject *) PyInt_FromSize_t(size_t);
+PyAPI_FUNC(PyObject *) PyInt_FromSsize_t(Py_ssize_t);
+PyAPI_FUNC(long) PyInt_AsLong(PyObject *);
+PyAPI_FUNC(Py_ssize_t) PyInt_AsSsize_t(PyObject *);
+PyAPI_FUNC(unsigned long) PyInt_AsUnsignedLongMask(PyObject *);
+#ifdef HAVE_LONG_LONG
+PyAPI_FUNC(unsigned PY_LONG_LONG) PyInt_AsUnsignedLongLongMask(PyObject *);
+#endif
+
+PyAPI_FUNC(long) PyInt_GetMax(void);
+
+/* Macro, trading safety for speed */
+#define PyInt_AS_LONG(op) (((PyIntObject *)(op))->ob_ival)
+
+/* These aren't really part of the Int object, but they're handy; the protos
+ * are necessary for systems that need the magic of PyAPI_FUNC and that want
+ * to have stropmodule as a dynamically loaded module instead of building it
+ * into the main Python shared library/DLL. Guido thinks I'm weird for
+ * building it this way. :-) [cjh]
+ */
+PyAPI_FUNC(unsigned long) PyOS_strtoul(char *, char **, int);
+PyAPI_FUNC(long) PyOS_strtol(char *, char **, int);
+
+/* free list api */
+PyAPI_FUNC(int) PyInt_ClearFreeList(void);
+
+/* Convert an integer to the given base. Returns a string.
+ If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'.
+ If newstyle is zero, then use the pre-2.6 behavior of octal having
+ a leading "0" */
+PyAPI_FUNC(PyObject*) _PyInt_Format(PyIntObject* v, int base, int newstyle);
+
+/* Format the object based on the format_spec, as defined in PEP 3101
+ (Advanced String Formatting). */
+PyAPI_FUNC(PyObject *) _PyInt_FormatAdvanced(PyObject *obj,
+ char *format_spec,
+ Py_ssize_t format_spec_len);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/intrcheck.h b/AppPkg/Applications/Python/Python-2.7.2/Include/intrcheck.h
new file mode 100644
index 0000000000..11d759e42a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/intrcheck.h
@@ -0,0 +1,15 @@
+
+#ifndef Py_INTRCHECK_H
+#define Py_INTRCHECK_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_FUNC(int) PyOS_InterruptOccurred(void);
+PyAPI_FUNC(void) PyOS_InitInterrupts(void);
+PyAPI_FUNC(void) PyOS_AfterFork(void);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTRCHECK_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/iterobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/iterobject.h
new file mode 100644
index 0000000000..ac49cb6fbf
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/iterobject.h
@@ -0,0 +1,23 @@
+#ifndef Py_ITEROBJECT_H
+#define Py_ITEROBJECT_H
+/* Iterators (the basic kind, over a sequence) */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_DATA(PyTypeObject) PySeqIter_Type;
+
+#define PySeqIter_Check(op) (Py_TYPE(op) == &PySeqIter_Type)
+
+PyAPI_FUNC(PyObject *) PySeqIter_New(PyObject *);
+
+PyAPI_DATA(PyTypeObject) PyCallIter_Type;
+
+#define PyCallIter_Check(op) (Py_TYPE(op) == &PyCallIter_Type)
+
+PyAPI_FUNC(PyObject *) PyCallIter_New(PyObject *, PyObject *);
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_ITEROBJECT_H */
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/listobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/listobject.h
new file mode 100644
index 0000000000..04aca45f3a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/listobject.h
@@ -0,0 +1,68 @@
+
+/* List object interface */
+
+/*
+Another generally useful object type is an list of object pointers.
+This is a mutable type: the list items can be changed, and items can be
+added or removed. Out-of-range indices or non-list objects are ignored.
+
+*** WARNING *** PyList_SetItem does not increment the new item's reference
+count, but does decrement the reference count of the item it replaces,
+if not nil. It does *decrement* the reference count if it is *not*
+inserted in the list. Similarly, PyList_GetItem does not increment the
+returned item's reference count.
+*/
+
+#ifndef Py_LISTOBJECT_H
+#define Py_LISTOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ PyObject_VAR_HEAD
+ /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */
+ PyObject **ob_item;
+
+ /* ob_item contains space for 'allocated' elements. The number
+ * currently in use is ob_size.
+ * Invariants:
+ * 0 <= ob_size <= allocated
+ * len(list) == ob_size
+ * ob_item == NULL implies ob_size == allocated == 0
+ * list.sort() temporarily sets allocated to -1 to detect mutations.
+ *
+ * Items must normally not be NULL, except during construction when
+ * the list is not yet visible outside the function that builds it.
+ */
+ Py_ssize_t allocated;
+} PyListObject;
+
+PyAPI_DATA(PyTypeObject) PyList_Type;
+
+#define PyList_Check(op) \
+ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_LIST_SUBCLASS)
+#define PyList_CheckExact(op) (Py_TYPE(op) == &PyList_Type)
+
+PyAPI_FUNC(PyObject *) PyList_New(Py_ssize_t size);
+PyAPI_FUNC(Py_ssize_t) PyList_Size(PyObject *);
+PyAPI_FUNC(PyObject *) PyList_GetItem(PyObject *, Py_ssize_t);
+PyAPI_FUNC(int) PyList_SetItem(PyObject *, Py_ssize_t, PyObject *);
+PyAPI_FUNC(int) PyList_Insert(PyObject *, Py_ssize_t, PyObject *);
+PyAPI_FUNC(int) PyList_Append(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyList_GetSlice(PyObject *, Py_ssize_t, Py_ssize_t);
+PyAPI_FUNC(int) PyList_SetSlice(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
+PyAPI_FUNC(int) PyList_Sort(PyObject *);
+PyAPI_FUNC(int) PyList_Reverse(PyObject *);
+PyAPI_FUNC(PyObject *) PyList_AsTuple(PyObject *);
+PyAPI_FUNC(PyObject *) _PyList_Extend(PyListObject *, PyObject *);
+
+/* Macro, trading safety for speed */
+#define PyList_GET_ITEM(op, i) (((PyListObject *)(op))->ob_item[i])
+#define PyList_SET_ITEM(op, i, v) (((PyListObject *)(op))->ob_item[i] = (v))
+#define PyList_GET_SIZE(op) Py_SIZE(op)
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_LISTOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/longintrepr.h b/AppPkg/Applications/Python/Python-2.7.2/Include/longintrepr.h
new file mode 100644
index 0000000000..3d1cd25b89
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/longintrepr.h
@@ -0,0 +1,103 @@
+#ifndef Py_LONGINTREPR_H
+#define Py_LONGINTREPR_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* This is published for the benefit of "friend" marshal.c only. */
+
+/* Parameters of the long integer representation. There are two different
+ sets of parameters: one set for 30-bit digits, stored in an unsigned 32-bit
+ integer type, and one set for 15-bit digits with each digit stored in an
+ unsigned short. The value of PYLONG_BITS_IN_DIGIT, defined either at
+ configure time or in pyport.h, is used to decide which digit size to use.
+
+ Type 'digit' should be able to hold 2*PyLong_BASE-1, and type 'twodigits'
+ should be an unsigned integer type able to hold all integers up to
+ PyLong_BASE*PyLong_BASE-1. x_sub assumes that 'digit' is an unsigned type,
+ and that overflow is handled by taking the result modulo 2**N for some N >
+ PyLong_SHIFT. The majority of the code doesn't care about the precise
+ value of PyLong_SHIFT, but there are some notable exceptions:
+
+ - long_pow() requires that PyLong_SHIFT be divisible by 5
+
+ - PyLong_{As,From}ByteArray require that PyLong_SHIFT be at least 8
+
+ - long_hash() requires that PyLong_SHIFT is *strictly* less than the number
+ of bits in an unsigned long, as do the PyLong <-> long (or unsigned long)
+ conversion functions
+
+ - the long <-> size_t/Py_ssize_t conversion functions expect that
+ PyLong_SHIFT is strictly less than the number of bits in a size_t
+
+ - the marshal code currently expects that PyLong_SHIFT is a multiple of 15
+
+ The values 15 and 30 should fit all of the above requirements, on any
+ platform.
+*/
+
+#if PYLONG_BITS_IN_DIGIT == 30
+#if !(defined HAVE_UINT64_T && defined HAVE_UINT32_T && \
+ defined HAVE_INT64_T && defined HAVE_INT32_T)
+#error "30-bit long digits requested, but the necessary types are not available on this platform"
+#endif
+typedef PY_UINT32_T digit;
+typedef PY_INT32_T sdigit; /* signed variant of digit */
+typedef PY_UINT64_T twodigits;
+typedef PY_INT64_T stwodigits; /* signed variant of twodigits */
+#define PyLong_SHIFT 30
+#define _PyLong_DECIMAL_SHIFT 9 /* max(e such that 10**e fits in a digit) */
+#define _PyLong_DECIMAL_BASE ((digit)1000000000) /* 10 ** DECIMAL_SHIFT */
+#elif PYLONG_BITS_IN_DIGIT == 15
+typedef unsigned short digit;
+typedef short sdigit; /* signed variant of digit */
+typedef unsigned long twodigits;
+typedef long stwodigits; /* signed variant of twodigits */
+#define PyLong_SHIFT 15
+#define _PyLong_DECIMAL_SHIFT 4 /* max(e such that 10**e fits in a digit) */
+#define _PyLong_DECIMAL_BASE ((digit)10000) /* 10 ** DECIMAL_SHIFT */
+#else
+#error "PYLONG_BITS_IN_DIGIT should be 15 or 30"
+#endif
+#define PyLong_BASE ((digit)1 << PyLong_SHIFT)
+#define PyLong_MASK ((digit)(PyLong_BASE - 1))
+
+/* b/w compatibility with Python 2.5 */
+#define SHIFT PyLong_SHIFT
+#define BASE PyLong_BASE
+#define MASK PyLong_MASK
+
+#if PyLong_SHIFT % 5 != 0
+#error "longobject.c requires that PyLong_SHIFT be divisible by 5"
+#endif
+
+/* Long integer representation.
+ The absolute value of a number is equal to
+ SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
+ Negative numbers are represented with ob_size < 0;
+ zero is represented by ob_size == 0.
+ In a normalized number, ob_digit[abs(ob_size)-1] (the most significant
+ digit) is never zero. Also, in all cases, for all valid i,
+ 0 <= ob_digit[i] <= MASK.
+ The allocation function takes care of allocating extra memory
+ so that ob_digit[0] ... ob_digit[abs(ob_size)-1] are actually available.
+
+ CAUTION: Generic code manipulating subtypes of PyVarObject has to
+ aware that longs abuse ob_size's sign bit.
+*/
+
+struct _longobject {
+ PyObject_VAR_HEAD
+ digit ob_digit[1];
+};
+
+PyAPI_FUNC(PyLongObject *) _PyLong_New(Py_ssize_t);
+
+/* Return a copy of src. */
+PyAPI_FUNC(PyObject *) _PyLong_Copy(PyLongObject *src);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_LONGINTREPR_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/longobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/longobject.h
new file mode 100644
index 0000000000..ba5bf46464
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/longobject.h
@@ -0,0 +1,134 @@
+#ifndef Py_LONGOBJECT_H
+#define Py_LONGOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Long (arbitrary precision) integer object interface */
+
+typedef struct _longobject PyLongObject; /* Revealed in longintrepr.h */
+
+PyAPI_DATA(PyTypeObject) PyLong_Type;
+
+#define PyLong_Check(op) \
+ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_LONG_SUBCLASS)
+#define PyLong_CheckExact(op) (Py_TYPE(op) == &PyLong_Type)
+
+PyAPI_FUNC(PyObject *) PyLong_FromLong(long);
+PyAPI_FUNC(PyObject *) PyLong_FromUnsignedLong(unsigned long);
+PyAPI_FUNC(PyObject *) PyLong_FromDouble(double);
+PyAPI_FUNC(PyObject *) PyLong_FromSize_t(size_t);
+PyAPI_FUNC(PyObject *) PyLong_FromSsize_t(Py_ssize_t);
+PyAPI_FUNC(long) PyLong_AsLong(PyObject *);
+PyAPI_FUNC(long) PyLong_AsLongAndOverflow(PyObject *, int *);
+PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLong(PyObject *);
+PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLongMask(PyObject *);
+PyAPI_FUNC(Py_ssize_t) PyLong_AsSsize_t(PyObject *);
+PyAPI_FUNC(PyObject *) PyLong_GetInfo(void);
+
+/* For use by intobject.c only */
+#define _PyLong_AsSsize_t PyLong_AsSsize_t
+#define _PyLong_FromSize_t PyLong_FromSize_t
+#define _PyLong_FromSsize_t PyLong_FromSsize_t
+PyAPI_DATA(int) _PyLong_DigitValue[256];
+
+/* _PyLong_Frexp returns a double x and an exponent e such that the
+ true value is approximately equal to x * 2**e. e is >= 0. x is
+ 0.0 if and only if the input is 0 (in which case, e and x are both
+ zeroes); otherwise, 0.5 <= abs(x) < 1.0. On overflow, which is
+ possible if the number of bits doesn't fit into a Py_ssize_t, sets
+ OverflowError and returns -1.0 for x, 0 for e. */
+PyAPI_FUNC(double) _PyLong_Frexp(PyLongObject *a, Py_ssize_t *e);
+
+PyAPI_FUNC(double) PyLong_AsDouble(PyObject *);
+PyAPI_FUNC(PyObject *) PyLong_FromVoidPtr(void *);
+PyAPI_FUNC(void *) PyLong_AsVoidPtr(PyObject *);
+
+#ifdef HAVE_LONG_LONG
+PyAPI_FUNC(PyObject *) PyLong_FromLongLong(PY_LONG_LONG);
+PyAPI_FUNC(PyObject *) PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG);
+PyAPI_FUNC(PY_LONG_LONG) PyLong_AsLongLong(PyObject *);
+PyAPI_FUNC(unsigned PY_LONG_LONG) PyLong_AsUnsignedLongLong(PyObject *);
+PyAPI_FUNC(unsigned PY_LONG_LONG) PyLong_AsUnsignedLongLongMask(PyObject *);
+PyAPI_FUNC(PY_LONG_LONG) PyLong_AsLongLongAndOverflow(PyObject *, int *);
+#endif /* HAVE_LONG_LONG */
+
+PyAPI_FUNC(PyObject *) PyLong_FromString(char *, char **, int);
+#ifdef Py_USING_UNICODE
+PyAPI_FUNC(PyObject *) PyLong_FromUnicode(Py_UNICODE*, Py_ssize_t, int);
+#endif
+
+/* _PyLong_Sign. Return 0 if v is 0, -1 if v < 0, +1 if v > 0.
+ v must not be NULL, and must be a normalized long.
+ There are no error cases.
+*/
+PyAPI_FUNC(int) _PyLong_Sign(PyObject *v);
+
+
+/* _PyLong_NumBits. Return the number of bits needed to represent the
+ absolute value of a long. For example, this returns 1 for 1 and -1, 2
+ for 2 and -2, and 2 for 3 and -3. It returns 0 for 0.
+ v must not be NULL, and must be a normalized long.
+ (size_t)-1 is returned and OverflowError set if the true result doesn't
+ fit in a size_t.
+*/
+PyAPI_FUNC(size_t) _PyLong_NumBits(PyObject *v);
+
+/* _PyLong_FromByteArray: View the n unsigned bytes as a binary integer in
+ base 256, and return a Python long with the same numeric value.
+ If n is 0, the integer is 0. Else:
+ If little_endian is 1/true, bytes[n-1] is the MSB and bytes[0] the LSB;
+ else (little_endian is 0/false) bytes[0] is the MSB and bytes[n-1] the
+ LSB.
+ If is_signed is 0/false, view the bytes as a non-negative integer.
+ If is_signed is 1/true, view the bytes as a 2's-complement integer,
+ non-negative if bit 0x80 of the MSB is clear, negative if set.
+ Error returns:
+ + Return NULL with the appropriate exception set if there's not
+ enough memory to create the Python long.
+*/
+PyAPI_FUNC(PyObject *) _PyLong_FromByteArray(
+ const unsigned char* bytes, size_t n,
+ int little_endian, int is_signed);
+
+/* _PyLong_AsByteArray: Convert the least-significant 8*n bits of long
+ v to a base-256 integer, stored in array bytes. Normally return 0,
+ return -1 on error.
+ If little_endian is 1/true, store the MSB at bytes[n-1] and the LSB at
+ bytes[0]; else (little_endian is 0/false) store the MSB at bytes[0] and
+ the LSB at bytes[n-1].
+ If is_signed is 0/false, it's an error if v < 0; else (v >= 0) n bytes
+ are filled and there's nothing special about bit 0x80 of the MSB.
+ If is_signed is 1/true, bytes is filled with the 2's-complement
+ representation of v's value. Bit 0x80 of the MSB is the sign bit.
+ Error returns (-1):
+ + is_signed is 0 and v < 0. TypeError is set in this case, and bytes
+ isn't altered.
+ + n isn't big enough to hold the full mathematical value of v. For
+ example, if is_signed is 0 and there are more digits in the v than
+ fit in n; or if is_signed is 1, v < 0, and n is just 1 bit shy of
+ being large enough to hold a sign bit. OverflowError is set in this
+ case, but bytes holds the least-signficant n bytes of the true value.
+*/
+PyAPI_FUNC(int) _PyLong_AsByteArray(PyLongObject* v,
+ unsigned char* bytes, size_t n,
+ int little_endian, int is_signed);
+
+/* _PyLong_Format: Convert the long to a string object with given base,
+ appending a base prefix of 0[box] if base is 2, 8 or 16.
+ Add a trailing "L" if addL is non-zero.
+ If newstyle is zero, then use the pre-2.6 behavior of octal having
+ a leading "0", instead of the prefix "0o" */
+PyAPI_FUNC(PyObject *) _PyLong_Format(PyObject *aa, int base, int addL, int newstyle);
+
+/* Format the object based on the format_spec, as defined in PEP 3101
+ (Advanced String Formatting). */
+PyAPI_FUNC(PyObject *) _PyLong_FormatAdvanced(PyObject *obj,
+ char *format_spec,
+ Py_ssize_t format_spec_len);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_LONGOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/marshal.h b/AppPkg/Applications/Python/Python-2.7.2/Include/marshal.h
new file mode 100644
index 0000000000..43ac5385a7
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/marshal.h
@@ -0,0 +1,25 @@
+
+/* Interface for marshal.c */
+
+#ifndef Py_MARSHAL_H
+#define Py_MARSHAL_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define Py_MARSHAL_VERSION 2
+
+PyAPI_FUNC(void) PyMarshal_WriteLongToFile(long, FILE *, int);
+PyAPI_FUNC(void) PyMarshal_WriteObjectToFile(PyObject *, FILE *, int);
+PyAPI_FUNC(PyObject *) PyMarshal_WriteObjectToString(PyObject *, int);
+
+PyAPI_FUNC(long) PyMarshal_ReadLongFromFile(FILE *);
+PyAPI_FUNC(int) PyMarshal_ReadShortFromFile(FILE *);
+PyAPI_FUNC(PyObject *) PyMarshal_ReadObjectFromFile(FILE *);
+PyAPI_FUNC(PyObject *) PyMarshal_ReadLastObjectFromFile(FILE *);
+PyAPI_FUNC(PyObject *) PyMarshal_ReadObjectFromString(char *, Py_ssize_t);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_MARSHAL_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/memoryobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/memoryobject.h
new file mode 100644
index 0000000000..ca5064e985
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/memoryobject.h
@@ -0,0 +1,74 @@
+/* Memory view object. In Python this is available as "memoryview". */
+
+#ifndef Py_MEMORYOBJECT_H
+#define Py_MEMORYOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_DATA(PyTypeObject) PyMemoryView_Type;
+
+#define PyMemoryView_Check(op) (Py_TYPE(op) == &PyMemoryView_Type)
+
+/* Get a pointer to the underlying Py_buffer of a memoryview object. */
+#define PyMemoryView_GET_BUFFER(op) (&((PyMemoryViewObject *)(op))->view)
+/* Get a pointer to the PyObject from which originates a memoryview object. */
+#define PyMemoryView_GET_BASE(op) (((PyMemoryViewObject *)(op))->view.obj)
+
+
+PyAPI_FUNC(PyObject *) PyMemoryView_GetContiguous(PyObject *base,
+ int buffertype,
+ char fort);
+
+ /* Return a contiguous chunk of memory representing the buffer
+ from an object in a memory view object. If a copy is made then the
+ base object for the memory view will be a *new* bytes object.
+
+ Otherwise, the base-object will be the object itself and no
+ data-copying will be done.
+
+ The buffertype argument can be PyBUF_READ, PyBUF_WRITE,
+ PyBUF_SHADOW to determine whether the returned buffer
+ should be READONLY, WRITABLE, or set to update the
+ original buffer if a copy must be made. If buffertype is
+ PyBUF_WRITE and the buffer is not contiguous an error will
+ be raised. In this circumstance, the user can use
+ PyBUF_SHADOW to ensure that a a writable temporary
+ contiguous buffer is returned. The contents of this
+ contiguous buffer will be copied back into the original
+ object after the memoryview object is deleted as long as
+ the original object is writable and allows setting an
+ exclusive write lock. If this is not allowed by the
+ original object, then a BufferError is raised.
+
+ If the object is multi-dimensional and if fortran is 'F',
+ the first dimension of the underlying array will vary the
+ fastest in the buffer. If fortran is 'C', then the last
+ dimension will vary the fastest (C-style contiguous). If
+ fortran is 'A', then it does not matter and you will get
+ whatever the object decides is more efficient.
+
+ A new reference is returned that must be DECREF'd when finished.
+ */
+
+PyAPI_FUNC(PyObject *) PyMemoryView_FromObject(PyObject *base);
+
+PyAPI_FUNC(PyObject *) PyMemoryView_FromBuffer(Py_buffer *info);
+ /* create new if bufptr is NULL
+ will be a new bytesobject in base */
+
+
+/* The struct is declared here so that macros can work, but it shouldn't
+ be considered public. Don't access those fields directly, use the macros
+ and functions instead! */
+typedef struct {
+ PyObject_HEAD
+ PyObject *base;
+ Py_buffer view;
+} PyMemoryViewObject;
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_MEMORYOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/metagrammar.h b/AppPkg/Applications/Python/Python-2.7.2/Include/metagrammar.h
new file mode 100644
index 0000000000..1fb471a0f9
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/metagrammar.h
@@ -0,0 +1,18 @@
+#ifndef Py_METAGRAMMAR_H
+#define Py_METAGRAMMAR_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#define MSTART 256
+#define RULE 257
+#define RHS 258
+#define ALT 259
+#define ITEM 260
+#define ATOM 261
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_METAGRAMMAR_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/methodobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/methodobject.h
new file mode 100644
index 0000000000..8b2828853f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/methodobject.h
@@ -0,0 +1,93 @@
+
+/* Method object interface */
+
+#ifndef Py_METHODOBJECT_H
+#define Py_METHODOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* This is about the type 'builtin_function_or_method',
+ not Python methods in user-defined classes. See classobject.h
+ for the latter. */
+
+PyAPI_DATA(PyTypeObject) PyCFunction_Type;
+
+#define PyCFunction_Check(op) (Py_TYPE(op) == &PyCFunction_Type)
+
+typedef PyObject *(*PyCFunction)(PyObject *, PyObject *);
+typedef PyObject *(*PyCFunctionWithKeywords)(PyObject *, PyObject *,
+ PyObject *);
+typedef PyObject *(*PyNoArgsFunction)(PyObject *);
+
+PyAPI_FUNC(PyCFunction) PyCFunction_GetFunction(PyObject *);
+PyAPI_FUNC(PyObject *) PyCFunction_GetSelf(PyObject *);
+PyAPI_FUNC(int) PyCFunction_GetFlags(PyObject *);
+
+/* Macros for direct access to these values. Type checks are *not*
+ done, so use with care. */
+#define PyCFunction_GET_FUNCTION(func) \
+ (((PyCFunctionObject *)func) -> m_ml -> ml_meth)
+#define PyCFunction_GET_SELF(func) \
+ (((PyCFunctionObject *)func) -> m_self)
+#define PyCFunction_GET_FLAGS(func) \
+ (((PyCFunctionObject *)func) -> m_ml -> ml_flags)
+PyAPI_FUNC(PyObject *) PyCFunction_Call(PyObject *, PyObject *, PyObject *);
+
+struct PyMethodDef {
+ const char *ml_name; /* The name of the built-in function/method */
+ PyCFunction ml_meth; /* The C function that implements it */
+ int ml_flags; /* Combination of METH_xxx flags, which mostly
+ describe the args expected by the C func */
+ const char *ml_doc; /* The __doc__ attribute, or NULL */
+};
+typedef struct PyMethodDef PyMethodDef;
+
+PyAPI_FUNC(PyObject *) Py_FindMethod(PyMethodDef[], PyObject *, const char *);
+
+#define PyCFunction_New(ML, SELF) PyCFunction_NewEx((ML), (SELF), NULL)
+PyAPI_FUNC(PyObject *) PyCFunction_NewEx(PyMethodDef *, PyObject *,
+ PyObject *);
+
+/* Flag passed to newmethodobject */
+#define METH_OLDARGS 0x0000
+#define METH_VARARGS 0x0001
+#define METH_KEYWORDS 0x0002
+/* METH_NOARGS and METH_O must not be combined with the flags above. */
+#define METH_NOARGS 0x0004
+#define METH_O 0x0008
+
+/* METH_CLASS and METH_STATIC are a little different; these control
+ the construction of methods for a class. These cannot be used for
+ functions in modules. */
+#define METH_CLASS 0x0010
+#define METH_STATIC 0x0020
+
+/* METH_COEXIST allows a method to be entered eventhough a slot has
+ already filled the entry. When defined, the flag allows a separate
+ method, "__contains__" for example, to coexist with a defined
+ slot like sq_contains. */
+
+#define METH_COEXIST 0x0040
+
+typedef struct PyMethodChain {
+ PyMethodDef *methods; /* Methods of this type */
+ struct PyMethodChain *link; /* NULL or base type */
+} PyMethodChain;
+
+PyAPI_FUNC(PyObject *) Py_FindMethodInChain(PyMethodChain *, PyObject *,
+ const char *);
+
+typedef struct {
+ PyObject_HEAD
+ PyMethodDef *m_ml; /* Description of the C function to call */
+ PyObject *m_self; /* Passed as 'self' arg to the C func, can be NULL */
+ PyObject *m_module; /* The __module__ attribute, can be anything */
+} PyCFunctionObject;
+
+PyAPI_FUNC(int) PyCFunction_ClearFreeList(void);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_METHODOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/modsupport.h b/AppPkg/Applications/Python/Python-2.7.2/Include/modsupport.h
new file mode 100644
index 0000000000..8a8cf8d710
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/modsupport.h
@@ -0,0 +1,134 @@
+
+#ifndef Py_MODSUPPORT_H
+#define Py_MODSUPPORT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Module support interface */
+
+#include
+
+/* If PY_SSIZE_T_CLEAN is defined, each functions treats #-specifier
+ to mean Py_ssize_t */
+#ifdef PY_SSIZE_T_CLEAN
+#define PyArg_Parse _PyArg_Parse_SizeT
+#define PyArg_ParseTuple _PyArg_ParseTuple_SizeT
+#define PyArg_ParseTupleAndKeywords _PyArg_ParseTupleAndKeywords_SizeT
+#define PyArg_VaParse _PyArg_VaParse_SizeT
+#define PyArg_VaParseTupleAndKeywords _PyArg_VaParseTupleAndKeywords_SizeT
+#define Py_BuildValue _Py_BuildValue_SizeT
+#define Py_VaBuildValue _Py_VaBuildValue_SizeT
+#else
+PyAPI_FUNC(PyObject *) _Py_VaBuildValue_SizeT(const char *, va_list);
+#endif
+
+PyAPI_FUNC(int) PyArg_Parse(PyObject *, const char *, ...);
+PyAPI_FUNC(int) PyArg_ParseTuple(PyObject *, const char *, ...) Py_FORMAT_PARSETUPLE(PyArg_ParseTuple, 2, 3);
+PyAPI_FUNC(int) PyArg_ParseTupleAndKeywords(PyObject *, PyObject *,
+ const char *, char **, ...);
+PyAPI_FUNC(int) PyArg_UnpackTuple(PyObject *, const char *, Py_ssize_t, Py_ssize_t, ...);
+PyAPI_FUNC(PyObject *) Py_BuildValue(const char *, ...);
+PyAPI_FUNC(PyObject *) _Py_BuildValue_SizeT(const char *, ...);
+PyAPI_FUNC(int) _PyArg_NoKeywords(const char *funcname, PyObject *kw);
+
+PyAPI_FUNC(int) PyArg_VaParse(PyObject *, const char *, va_list);
+PyAPI_FUNC(int) PyArg_VaParseTupleAndKeywords(PyObject *, PyObject *,
+ const char *, char **, va_list);
+PyAPI_FUNC(PyObject *) Py_VaBuildValue(const char *, va_list);
+
+PyAPI_FUNC(int) PyModule_AddObject(PyObject *, const char *, PyObject *);
+PyAPI_FUNC(int) PyModule_AddIntConstant(PyObject *, const char *, long);
+PyAPI_FUNC(int) PyModule_AddStringConstant(PyObject *, const char *, const char *);
+#define PyModule_AddIntMacro(m, c) PyModule_AddIntConstant(m, #c, c)
+#define PyModule_AddStringMacro(m, c) PyModule_AddStringConstant(m, #c, c)
+
+#define PYTHON_API_VERSION 1013
+#define PYTHON_API_STRING "1013"
+/* The API version is maintained (independently from the Python version)
+ so we can detect mismatches between the interpreter and dynamically
+ loaded modules. These are diagnosed by an error message but
+ the module is still loaded (because the mismatch can only be tested
+ after loading the module). The error message is intended to
+ explain the core dump a few seconds later.
+
+ The symbol PYTHON_API_STRING defines the same value as a string
+ literal. *** PLEASE MAKE SURE THE DEFINITIONS MATCH. ***
+
+ Please add a line or two to the top of this log for each API
+ version change:
+
+ 22-Feb-2006 MvL 1013 PEP 353 - long indices for sequence lengths
+
+ 19-Aug-2002 GvR 1012 Changes to string object struct for
+ interning changes, saving 3 bytes.
+
+ 17-Jul-2001 GvR 1011 Descr-branch, just to be on the safe side
+
+ 25-Jan-2001 FLD 1010 Parameters added to PyCode_New() and
+ PyFrame_New(); Python 2.1a2
+
+ 14-Mar-2000 GvR 1009 Unicode API added
+
+ 3-Jan-1999 GvR 1007 Decided to change back! (Don't reuse 1008!)
+
+ 3-Dec-1998 GvR 1008 Python 1.5.2b1
+
+ 18-Jan-1997 GvR 1007 string interning and other speedups
+
+ 11-Oct-1996 GvR renamed Py_Ellipses to Py_Ellipsis :-(
+
+ 30-Jul-1996 GvR Slice and ellipses syntax added
+
+ 23-Jul-1996 GvR For 1.4 -- better safe than sorry this time :-)
+
+ 7-Nov-1995 GvR Keyword arguments (should've been done at 1.3 :-( )
+
+ 10-Jan-1995 GvR Renamed globals to new naming scheme
+
+ 9-Jan-1995 GvR Initial version (incompatible with older API)
+*/
+
+#ifdef MS_WINDOWS
+/* Special defines for Windows versions used to live here. Things
+ have changed, and the "Version" is now in a global string variable.
+ Reason for this is that this for easier branding of a "custom DLL"
+ without actually needing a recompile. */
+#endif /* MS_WINDOWS */
+
+#if SIZEOF_SIZE_T != SIZEOF_INT
+/* On a 64-bit system, rename the Py_InitModule4 so that 2.4
+ modules cannot get loaded into a 2.5 interpreter */
+#define Py_InitModule4 Py_InitModule4_64
+#endif
+
+#ifdef Py_TRACE_REFS
+ /* When we are tracing reference counts, rename Py_InitModule4 so
+ modules compiled with incompatible settings will generate a
+ link-time error. */
+ #if SIZEOF_SIZE_T != SIZEOF_INT
+ #undef Py_InitModule4
+ #define Py_InitModule4 Py_InitModule4TraceRefs_64
+ #else
+ #define Py_InitModule4 Py_InitModule4TraceRefs
+ #endif
+#endif
+
+PyAPI_FUNC(PyObject *) Py_InitModule4(const char *name, PyMethodDef *methods,
+ const char *doc, PyObject *self,
+ int apiver);
+
+#define Py_InitModule(name, methods) \
+ Py_InitModule4(name, methods, (char *)NULL, (PyObject *)NULL, \
+ PYTHON_API_VERSION)
+
+#define Py_InitModule3(name, methods, doc) \
+ Py_InitModule4(name, methods, doc, (PyObject *)NULL, \
+ PYTHON_API_VERSION)
+
+PyAPI_DATA(char *) _Py_PackageContext;
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_MODSUPPORT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/moduleobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/moduleobject.h
new file mode 100644
index 0000000000..ff16ad288a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/moduleobject.h
@@ -0,0 +1,24 @@
+
+/* Module object interface */
+
+#ifndef Py_MODULEOBJECT_H
+#define Py_MODULEOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_DATA(PyTypeObject) PyModule_Type;
+
+#define PyModule_Check(op) PyObject_TypeCheck(op, &PyModule_Type)
+#define PyModule_CheckExact(op) (Py_TYPE(op) == &PyModule_Type)
+
+PyAPI_FUNC(PyObject *) PyModule_New(const char *);
+PyAPI_FUNC(PyObject *) PyModule_GetDict(PyObject *);
+PyAPI_FUNC(char *) PyModule_GetName(PyObject *);
+PyAPI_FUNC(char *) PyModule_GetFilename(PyObject *);
+PyAPI_FUNC(void) _PyModule_Clear(PyObject *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_MODULEOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/node.h b/AppPkg/Applications/Python/Python-2.7.2/Include/node.h
new file mode 100644
index 0000000000..7bab3c790e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/node.h
@@ -0,0 +1,40 @@
+
+/* Parse tree node interface */
+
+#ifndef Py_NODE_H
+#define Py_NODE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct _node {
+ short n_type;
+ char *n_str;
+ int n_lineno;
+ int n_col_offset;
+ int n_nchildren;
+ struct _node *n_child;
+} node;
+
+PyAPI_FUNC(node *) PyNode_New(int type);
+PyAPI_FUNC(int) PyNode_AddChild(node *n, int type,
+ char *str, int lineno, int col_offset);
+PyAPI_FUNC(void) PyNode_Free(node *n);
+
+/* Node access functions */
+#define NCH(n) ((n)->n_nchildren)
+
+#define CHILD(n, i) (&(n)->n_child[i])
+#define RCHILD(n, i) (CHILD(n, NCH(n) + i))
+#define TYPE(n) ((n)->n_type)
+#define STR(n) ((n)->n_str)
+
+/* Assert that the type of a node is what we expect */
+#define REQ(n, type) assert(TYPE(n) == (type))
+
+PyAPI_FUNC(void) PyNode_ListTree(node *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_NODE_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/object.h b/AppPkg/Applications/Python/Python-2.7.2/Include/object.h
new file mode 100644
index 0000000000..27ba8b3fd7
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/object.h
@@ -0,0 +1,986 @@
+#ifndef Py_OBJECT_H
+#define Py_OBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Object and type object interface */
+
+/*
+Objects are structures allocated on the heap. Special rules apply to
+the use of objects to ensure they are properly garbage-collected.
+Objects are never allocated statically or on the stack; they must be
+accessed through special macros and functions only. (Type objects are
+exceptions to the first rule; the standard types are represented by
+statically initialized type objects, although work on type/class unification
+for Python 2.2 made it possible to have heap-allocated type objects too).
+
+An object has a 'reference count' that is increased or decreased when a
+pointer to the object is copied or deleted; when the reference count
+reaches zero there are no references to the object left and it can be
+removed from the heap.
+
+An object has a 'type' that determines what it represents and what kind
+of data it contains. An object's type is fixed when it is created.
+Types themselves are represented as objects; an object contains a
+pointer to the corresponding type object. The type itself has a type
+pointer pointing to the object representing the type 'type', which
+contains a pointer to itself!).
+
+Objects do not float around in memory; once allocated an object keeps
+the same size and address. Objects that must hold variable-size data
+can contain pointers to variable-size parts of the object. Not all
+objects of the same type have the same size; but the size cannot change
+after allocation. (These restrictions are made so a reference to an
+object can be simply a pointer -- moving an object would require
+updating all the pointers, and changing an object's size would require
+moving it if there was another object right next to it.)
+
+Objects are always accessed through pointers of the type 'PyObject *'.
+The type 'PyObject' is a structure that only contains the reference count
+and the type pointer. The actual memory allocated for an object
+contains other data that can only be accessed after casting the pointer
+to a pointer to a longer structure type. This longer type must start
+with the reference count and type fields; the macro PyObject_HEAD should be
+used for this (to accommodate for future changes). The implementation
+of a particular object type can cast the object pointer to the proper
+type and back.
+
+A standard interface exists for objects that contain an array of items
+whose size is determined when the object is allocated.
+*/
+
+/* Py_DEBUG implies Py_TRACE_REFS. */
+#if defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
+#define Py_TRACE_REFS
+#endif
+
+/* Py_TRACE_REFS implies Py_REF_DEBUG. */
+#if defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG)
+#define Py_REF_DEBUG
+#endif
+
+#ifdef Py_TRACE_REFS
+/* Define pointers to support a doubly-linked list of all live heap objects. */
+#define _PyObject_HEAD_EXTRA \
+ struct _object *_ob_next; \
+ struct _object *_ob_prev;
+
+#define _PyObject_EXTRA_INIT 0, 0,
+
+#else
+#define _PyObject_HEAD_EXTRA
+#define _PyObject_EXTRA_INIT
+#endif
+
+/* PyObject_HEAD defines the initial segment of every PyObject. */
+#define PyObject_HEAD \
+ _PyObject_HEAD_EXTRA \
+ Py_ssize_t ob_refcnt; \
+ struct _typeobject *ob_type;
+
+#define PyObject_HEAD_INIT(type) \
+ _PyObject_EXTRA_INIT \
+ 1, type,
+
+#define PyVarObject_HEAD_INIT(type, size) \
+ PyObject_HEAD_INIT(type) size,
+
+/* PyObject_VAR_HEAD defines the initial segment of all variable-size
+ * container objects. These end with a declaration of an array with 1
+ * element, but enough space is malloc'ed so that the array actually
+ * has room for ob_size elements. Note that ob_size is an element count,
+ * not necessarily a byte count.
+ */
+#define PyObject_VAR_HEAD \
+ PyObject_HEAD \
+ Py_ssize_t ob_size; /* Number of items in variable part */
+#define Py_INVALID_SIZE (Py_ssize_t)-1
+
+/* Nothing is actually declared to be a PyObject, but every pointer to
+ * a Python object can be cast to a PyObject*. This is inheritance built
+ * by hand. Similarly every pointer to a variable-size Python object can,
+ * in addition, be cast to PyVarObject*.
+ */
+typedef struct _object {
+ PyObject_HEAD
+} PyObject;
+
+typedef struct {
+ PyObject_VAR_HEAD
+} PyVarObject;
+
+#define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt)
+#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
+#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)
+
+/*
+Type objects contain a string containing the type name (to help somewhat
+in debugging), the allocation parameters (see PyObject_New() and
+PyObject_NewVar()),
+and methods for accessing objects of the type. Methods are optional, a
+nil pointer meaning that particular kind of access is not available for
+this type. The Py_DECREF() macro uses the tp_dealloc method without
+checking for a nil pointer; it should always be implemented except if
+the implementation can guarantee that the reference count will never
+reach zero (e.g., for statically allocated type objects).
+
+NB: the methods for certain type groups are now contained in separate
+method blocks.
+*/
+
+typedef PyObject * (*unaryfunc)(PyObject *);
+typedef PyObject * (*binaryfunc)(PyObject *, PyObject *);
+typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *);
+typedef int (*inquiry)(PyObject *);
+typedef Py_ssize_t (*lenfunc)(PyObject *);
+typedef int (*coercion)(PyObject **, PyObject **);
+typedef PyObject *(*intargfunc)(PyObject *, int) Py_DEPRECATED(2.5);
+typedef PyObject *(*intintargfunc)(PyObject *, int, int) Py_DEPRECATED(2.5);
+typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t);
+typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t);
+typedef int(*intobjargproc)(PyObject *, int, PyObject *);
+typedef int(*intintobjargproc)(PyObject *, int, int, PyObject *);
+typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *);
+typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
+typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *);
+
+
+
+/* int-based buffer interface */
+typedef int (*getreadbufferproc)(PyObject *, int, void **);
+typedef int (*getwritebufferproc)(PyObject *, int, void **);
+typedef int (*getsegcountproc)(PyObject *, int *);
+typedef int (*getcharbufferproc)(PyObject *, int, char **);
+/* ssize_t-based buffer interface */
+typedef Py_ssize_t (*readbufferproc)(PyObject *, Py_ssize_t, void **);
+typedef Py_ssize_t (*writebufferproc)(PyObject *, Py_ssize_t, void **);
+typedef Py_ssize_t (*segcountproc)(PyObject *, Py_ssize_t *);
+typedef Py_ssize_t (*charbufferproc)(PyObject *, Py_ssize_t, char **);
+
+
+/* Py3k buffer interface */
+typedef struct bufferinfo {
+ void *buf;
+ PyObject *obj; /* owned reference */
+ Py_ssize_t len;
+ Py_ssize_t itemsize; /* This is Py_ssize_t so it can be
+ pointed to by strides in simple case.*/
+ int readonly;
+ int ndim;
+ char *format;
+ Py_ssize_t *shape;
+ Py_ssize_t *strides;
+ Py_ssize_t *suboffsets;
+ Py_ssize_t smalltable[2]; /* static store for shape and strides of
+ mono-dimensional buffers. */
+ void *internal;
+} Py_buffer;
+
+typedef int (*getbufferproc)(PyObject *, Py_buffer *, int);
+typedef void (*releasebufferproc)(PyObject *, Py_buffer *);
+
+ /* Flags for getting buffers */
+#define PyBUF_SIMPLE 0
+#define PyBUF_WRITABLE 0x0001
+/* we used to include an E, backwards compatible alias */
+#define PyBUF_WRITEABLE PyBUF_WRITABLE
+#define PyBUF_FORMAT 0x0004
+#define PyBUF_ND 0x0008
+#define PyBUF_STRIDES (0x0010 | PyBUF_ND)
+#define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES)
+#define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES)
+#define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES)
+#define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES)
+
+#define PyBUF_CONTIG (PyBUF_ND | PyBUF_WRITABLE)
+#define PyBUF_CONTIG_RO (PyBUF_ND)
+
+#define PyBUF_STRIDED (PyBUF_STRIDES | PyBUF_WRITABLE)
+#define PyBUF_STRIDED_RO (PyBUF_STRIDES)
+
+#define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_WRITABLE | PyBUF_FORMAT)
+#define PyBUF_RECORDS_RO (PyBUF_STRIDES | PyBUF_FORMAT)
+
+#define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_WRITABLE | PyBUF_FORMAT)
+#define PyBUF_FULL_RO (PyBUF_INDIRECT | PyBUF_FORMAT)
+
+
+#define PyBUF_READ 0x100
+#define PyBUF_WRITE 0x200
+#define PyBUF_SHADOW 0x400
+/* end Py3k buffer interface */
+
+typedef int (*objobjproc)(PyObject *, PyObject *);
+typedef int (*visitproc)(PyObject *, void *);
+typedef int (*traverseproc)(PyObject *, visitproc, void *);
+
+typedef struct {
+ /* For numbers without flag bit Py_TPFLAGS_CHECKTYPES set, all
+ arguments are guaranteed to be of the object's type (modulo
+ coercion hacks -- i.e. if the type's coercion function
+ returns other types, then these are allowed as well). Numbers that
+ have the Py_TPFLAGS_CHECKTYPES flag bit set should check *both*
+ arguments for proper type and implement the necessary conversions
+ in the slot functions themselves. */
+
+ binaryfunc nb_add;
+ binaryfunc nb_subtract;
+ binaryfunc nb_multiply;
+ binaryfunc nb_divide;
+ binaryfunc nb_remainder;
+ binaryfunc nb_divmod;
+ ternaryfunc nb_power;
+ unaryfunc nb_negative;
+ unaryfunc nb_positive;
+ unaryfunc nb_absolute;
+ inquiry nb_nonzero;
+ unaryfunc nb_invert;
+ binaryfunc nb_lshift;
+ binaryfunc nb_rshift;
+ binaryfunc nb_and;
+ binaryfunc nb_xor;
+ binaryfunc nb_or;
+ coercion nb_coerce;
+ unaryfunc nb_int;
+ unaryfunc nb_long;
+ unaryfunc nb_float;
+ unaryfunc nb_oct;
+ unaryfunc nb_hex;
+ /* Added in release 2.0 */
+ binaryfunc nb_inplace_add;
+ binaryfunc nb_inplace_subtract;
+ binaryfunc nb_inplace_multiply;
+ binaryfunc nb_inplace_divide;
+ binaryfunc nb_inplace_remainder;
+ ternaryfunc nb_inplace_power;
+ binaryfunc nb_inplace_lshift;
+ binaryfunc nb_inplace_rshift;
+ binaryfunc nb_inplace_and;
+ binaryfunc nb_inplace_xor;
+ binaryfunc nb_inplace_or;
+
+ /* Added in release 2.2 */
+ /* The following require the Py_TPFLAGS_HAVE_CLASS flag */
+ binaryfunc nb_floor_divide;
+ binaryfunc nb_true_divide;
+ binaryfunc nb_inplace_floor_divide;
+ binaryfunc nb_inplace_true_divide;
+
+ /* Added in release 2.5 */
+ unaryfunc nb_index;
+} PyNumberMethods;
+
+typedef struct {
+ lenfunc sq_length;
+ binaryfunc sq_concat;
+ ssizeargfunc sq_repeat;
+ ssizeargfunc sq_item;
+ ssizessizeargfunc sq_slice;
+ ssizeobjargproc sq_ass_item;
+ ssizessizeobjargproc sq_ass_slice;
+ objobjproc sq_contains;
+ /* Added in release 2.0 */
+ binaryfunc sq_inplace_concat;
+ ssizeargfunc sq_inplace_repeat;
+} PySequenceMethods;
+
+typedef struct {
+ lenfunc mp_length;
+ binaryfunc mp_subscript;
+ objobjargproc mp_ass_subscript;
+} PyMappingMethods;
+
+typedef struct {
+ readbufferproc bf_getreadbuffer;
+ writebufferproc bf_getwritebuffer;
+ segcountproc bf_getsegcount;
+ charbufferproc bf_getcharbuffer;
+ getbufferproc bf_getbuffer;
+ releasebufferproc bf_releasebuffer;
+} PyBufferProcs;
+
+
+typedef void (*freefunc)(void *);
+typedef void (*destructor)(PyObject *);
+typedef int (*printfunc)(PyObject *, FILE *, int);
+typedef PyObject *(*getattrfunc)(PyObject *, char *);
+typedef PyObject *(*getattrofunc)(PyObject *, PyObject *);
+typedef int (*setattrfunc)(PyObject *, char *, PyObject *);
+typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *);
+typedef int (*cmpfunc)(PyObject *, PyObject *);
+typedef PyObject *(*reprfunc)(PyObject *);
+typedef long (*hashfunc)(PyObject *);
+typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int);
+typedef PyObject *(*getiterfunc) (PyObject *);
+typedef PyObject *(*iternextfunc) (PyObject *);
+typedef PyObject *(*descrgetfunc) (PyObject *, PyObject *, PyObject *);
+typedef int (*descrsetfunc) (PyObject *, PyObject *, PyObject *);
+typedef int (*initproc)(PyObject *, PyObject *, PyObject *);
+typedef PyObject *(*newfunc)(struct _typeobject *, PyObject *, PyObject *);
+typedef PyObject *(*allocfunc)(struct _typeobject *, Py_ssize_t);
+
+typedef struct _typeobject {
+ PyObject_VAR_HEAD
+ const char *tp_name; /* For printing, in format "." */
+ Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
+
+ /* Methods to implement standard operations */
+
+ destructor tp_dealloc;
+ printfunc tp_print;
+ getattrfunc tp_getattr;
+ setattrfunc tp_setattr;
+ cmpfunc tp_compare;
+ reprfunc tp_repr;
+
+ /* Method suites for standard classes */
+
+ PyNumberMethods *tp_as_number;
+ PySequenceMethods *tp_as_sequence;
+ PyMappingMethods *tp_as_mapping;
+
+ /* More standard operations (here for binary compatibility) */
+
+ hashfunc tp_hash;
+ ternaryfunc tp_call;
+ reprfunc tp_str;
+ getattrofunc tp_getattro;
+ setattrofunc tp_setattro;
+
+ /* Functions to access object as input/output buffer */
+ PyBufferProcs *tp_as_buffer;
+
+ /* Flags to define presence of optional/expanded features */
+ long tp_flags;
+
+ const char *tp_doc; /* Documentation string */
+
+ /* Assigned meaning in release 2.0 */
+ /* call function for all accessible objects */
+ traverseproc tp_traverse;
+
+ /* delete references to contained objects */
+ inquiry tp_clear;
+
+ /* Assigned meaning in release 2.1 */
+ /* rich comparisons */
+ richcmpfunc tp_richcompare;
+
+ /* weak reference enabler */
+ Py_ssize_t tp_weaklistoffset;
+
+ /* Added in release 2.2 */
+ /* Iterators */
+ getiterfunc tp_iter;
+ iternextfunc tp_iternext;
+
+ /* Attribute descriptor and subclassing stuff */
+ struct PyMethodDef *tp_methods;
+ struct PyMemberDef *tp_members;
+ struct PyGetSetDef *tp_getset;
+ struct _typeobject *tp_base;
+ PyObject *tp_dict;
+ descrgetfunc tp_descr_get;
+ descrsetfunc tp_descr_set;
+ Py_ssize_t tp_dictoffset;
+ initproc tp_init;
+ allocfunc tp_alloc;
+ newfunc tp_new;
+ freefunc tp_free; /* Low-level free-memory routine */
+ inquiry tp_is_gc; /* For PyObject_IS_GC */
+ PyObject *tp_bases;
+ PyObject *tp_mro; /* method resolution order */
+ PyObject *tp_cache;
+ PyObject *tp_subclasses;
+ PyObject *tp_weaklist;
+ destructor tp_del;
+
+ /* Type attribute cache version tag. Added in version 2.6 */
+ unsigned int tp_version_tag;
+
+#ifdef COUNT_ALLOCS
+ /* these must be last and never explicitly initialized */
+ Py_ssize_t tp_allocs;
+ Py_ssize_t tp_frees;
+ Py_ssize_t tp_maxalloc;
+ struct _typeobject *tp_prev;
+ struct _typeobject *tp_next;
+#endif
+} PyTypeObject;
+
+
+/* The *real* layout of a type object when allocated on the heap */
+typedef struct _heaptypeobject {
+ /* Note: there's a dependency on the order of these members
+ in slotptr() in typeobject.c . */
+ PyTypeObject ht_type;
+ PyNumberMethods as_number;
+ PyMappingMethods as_mapping;
+ PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
+ so that the mapping wins when both
+ the mapping and the sequence define
+ a given operator (e.g. __getitem__).
+ see add_operators() in typeobject.c . */
+ PyBufferProcs as_buffer;
+ PyObject *ht_name, *ht_slots;
+ /* here are optional user slots, followed by the members. */
+} PyHeapTypeObject;
+
+/* access macro to the members which are floating "behind" the object */
+#define PyHeapType_GET_MEMBERS(etype) \
+ ((PyMemberDef *)(((char *)etype) + Py_TYPE(etype)->tp_basicsize))
+
+
+/* Generic type check */
+PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);
+#define PyObject_TypeCheck(ob, tp) \
+ (Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp)))
+
+PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */
+PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */
+PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */
+
+#define PyType_Check(op) \
+ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS)
+#define PyType_CheckExact(op) (Py_TYPE(op) == &PyType_Type)
+
+PyAPI_FUNC(int) PyType_Ready(PyTypeObject *);
+PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t);
+PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *,
+ PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *);
+PyAPI_FUNC(PyObject *) _PyObject_LookupSpecial(PyObject *, char *, PyObject **);
+PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
+PyAPI_FUNC(void) PyType_Modified(PyTypeObject *);
+
+/* Generic operations on objects */
+PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int);
+PyAPI_FUNC(void) _PyObject_Dump(PyObject *);
+PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *);
+PyAPI_FUNC(PyObject *) _PyObject_Str(PyObject *);
+PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *);
+#define PyObject_Bytes PyObject_Str
+#ifdef Py_USING_UNICODE
+PyAPI_FUNC(PyObject *) PyObject_Unicode(PyObject *);
+#endif
+PyAPI_FUNC(int) PyObject_Compare(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int);
+PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int);
+PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *);
+PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *);
+PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *);
+PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *);
+PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *);
+PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject **) _PyObject_GetDictPtr(PyObject *);
+PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
+PyAPI_FUNC(PyObject *) _PyObject_NextNotImplemented(PyObject *);
+PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
+PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *,
+ PyObject *, PyObject *);
+PyAPI_FUNC(long) PyObject_Hash(PyObject *);
+PyAPI_FUNC(long) PyObject_HashNotImplemented(PyObject *);
+PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
+PyAPI_FUNC(int) PyObject_Not(PyObject *);
+PyAPI_FUNC(int) PyCallable_Check(PyObject *);
+PyAPI_FUNC(int) PyNumber_Coerce(PyObject **, PyObject **);
+PyAPI_FUNC(int) PyNumber_CoerceEx(PyObject **, PyObject **);
+
+PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *);
+
+/* A slot function whose address we need to compare */
+extern int _PyObject_SlotCompare(PyObject *, PyObject *);
+/* Same as PyObject_Generic{Get,Set}Attr, but passing the attributes
+ dict as the last parameter. */
+PyAPI_FUNC(PyObject *)
+_PyObject_GenericGetAttrWithDict(PyObject *, PyObject *, PyObject *);
+PyAPI_FUNC(int)
+_PyObject_GenericSetAttrWithDict(PyObject *, PyObject *,
+ PyObject *, PyObject *);
+
+
+/* PyObject_Dir(obj) acts like Python __builtin__.dir(obj), returning a
+ list of strings. PyObject_Dir(NULL) is like __builtin__.dir(),
+ returning the names of the current locals. In this case, if there are
+ no current locals, NULL is returned, and PyErr_Occurred() is false.
+*/
+PyAPI_FUNC(PyObject *) PyObject_Dir(PyObject *);
+
+
+/* Helpers for printing recursive container types */
+PyAPI_FUNC(int) Py_ReprEnter(PyObject *);
+PyAPI_FUNC(void) Py_ReprLeave(PyObject *);
+
+/* Helpers for hash functions */
+PyAPI_FUNC(long) _Py_HashDouble(double);
+PyAPI_FUNC(long) _Py_HashPointer(void*);
+
+/* Helper for passing objects to printf and the like */
+#define PyObject_REPR(obj) PyString_AS_STRING(PyObject_Repr(obj))
+
+/* Flag bits for printing: */
+#define Py_PRINT_RAW 1 /* No string quotes etc. */
+
+/*
+`Type flags (tp_flags)
+
+These flags are used to extend the type structure in a backwards-compatible
+fashion. Extensions can use the flags to indicate (and test) when a given
+type structure contains a new feature. The Python core will use these when
+introducing new functionality between major revisions (to avoid mid-version
+changes in the PYTHON_API_VERSION).
+
+Arbitration of the flag bit positions will need to be coordinated among
+all extension writers who publically release their extensions (this will
+be fewer than you might expect!)..
+
+Python 1.5.2 introduced the bf_getcharbuffer slot into PyBufferProcs.
+
+Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value.
+
+Code can use PyType_HasFeature(type_ob, flag_value) to test whether the
+given type object has a specified feature.
+
+NOTE: when building the core, Py_TPFLAGS_DEFAULT includes
+Py_TPFLAGS_HAVE_VERSION_TAG; outside the core, it doesn't. This is so
+that extensions that modify tp_dict of their own types directly don't
+break, since this was allowed in 2.5. In 3.0 they will have to
+manually remove this flag though!
+*/
+
+/* PyBufferProcs contains bf_getcharbuffer */
+#define Py_TPFLAGS_HAVE_GETCHARBUFFER (1L<<0)
+
+/* PySequenceMethods contains sq_contains */
+#define Py_TPFLAGS_HAVE_SEQUENCE_IN (1L<<1)
+
+/* This is here for backwards compatibility. Extensions that use the old GC
+ * API will still compile but the objects will not be tracked by the GC. */
+#define Py_TPFLAGS_GC 0 /* used to be (1L<<2) */
+
+/* PySequenceMethods and PyNumberMethods contain in-place operators */
+#define Py_TPFLAGS_HAVE_INPLACEOPS (1L<<3)
+
+/* PyNumberMethods do their own coercion */
+#define Py_TPFLAGS_CHECKTYPES (1L<<4)
+
+/* tp_richcompare is defined */
+#define Py_TPFLAGS_HAVE_RICHCOMPARE (1L<<5)
+
+/* Objects which are weakly referencable if their tp_weaklistoffset is >0 */
+#define Py_TPFLAGS_HAVE_WEAKREFS (1L<<6)
+
+/* tp_iter is defined */
+#define Py_TPFLAGS_HAVE_ITER (1L<<7)
+
+/* New members introduced by Python 2.2 exist */
+#define Py_TPFLAGS_HAVE_CLASS (1L<<8)
+
+/* Set if the type object is dynamically allocated */
+#define Py_TPFLAGS_HEAPTYPE (1L<<9)
+
+/* Set if the type allows subclassing */
+#define Py_TPFLAGS_BASETYPE (1L<<10)
+
+/* Set if the type is 'ready' -- fully initialized */
+#define Py_TPFLAGS_READY (1L<<12)
+
+/* Set while the type is being 'readied', to prevent recursive ready calls */
+#define Py_TPFLAGS_READYING (1L<<13)
+
+/* Objects support garbage collection (see objimp.h) */
+#define Py_TPFLAGS_HAVE_GC (1L<<14)
+
+/* These two bits are preserved for Stackless Python, next after this is 17 */
+#ifdef STACKLESS
+#define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3L<<15)
+#else
+#define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0
+#endif
+
+/* Objects support nb_index in PyNumberMethods */
+#define Py_TPFLAGS_HAVE_INDEX (1L<<17)
+
+/* Objects support type attribute cache */
+#define Py_TPFLAGS_HAVE_VERSION_TAG (1L<<18)
+#define Py_TPFLAGS_VALID_VERSION_TAG (1L<<19)
+
+/* Type is abstract and cannot be instantiated */
+#define Py_TPFLAGS_IS_ABSTRACT (1L<<20)
+
+/* Has the new buffer protocol */
+#define Py_TPFLAGS_HAVE_NEWBUFFER (1L<<21)
+
+/* These flags are used to determine if a type is a subclass. */
+#define Py_TPFLAGS_INT_SUBCLASS (1L<<23)
+#define Py_TPFLAGS_LONG_SUBCLASS (1L<<24)
+#define Py_TPFLAGS_LIST_SUBCLASS (1L<<25)
+#define Py_TPFLAGS_TUPLE_SUBCLASS (1L<<26)
+#define Py_TPFLAGS_STRING_SUBCLASS (1L<<27)
+#define Py_TPFLAGS_UNICODE_SUBCLASS (1L<<28)
+#define Py_TPFLAGS_DICT_SUBCLASS (1L<<29)
+#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1L<<30)
+#define Py_TPFLAGS_TYPE_SUBCLASS (1L<<31)
+
+#define Py_TPFLAGS_DEFAULT_EXTERNAL ( \
+ Py_TPFLAGS_HAVE_GETCHARBUFFER | \
+ Py_TPFLAGS_HAVE_SEQUENCE_IN | \
+ Py_TPFLAGS_HAVE_INPLACEOPS | \
+ Py_TPFLAGS_HAVE_RICHCOMPARE | \
+ Py_TPFLAGS_HAVE_WEAKREFS | \
+ Py_TPFLAGS_HAVE_ITER | \
+ Py_TPFLAGS_HAVE_CLASS | \
+ Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
+ Py_TPFLAGS_HAVE_INDEX | \
+ 0)
+#define Py_TPFLAGS_DEFAULT_CORE (Py_TPFLAGS_DEFAULT_EXTERNAL | \
+ Py_TPFLAGS_HAVE_VERSION_TAG)
+
+#ifdef Py_BUILD_CORE
+#define Py_TPFLAGS_DEFAULT Py_TPFLAGS_DEFAULT_CORE
+#else
+#define Py_TPFLAGS_DEFAULT Py_TPFLAGS_DEFAULT_EXTERNAL
+#endif
+
+#define PyType_HasFeature(t,f) (((t)->tp_flags & (f)) != 0)
+#define PyType_FastSubclass(t,f) PyType_HasFeature(t,f)
+
+
+/*
+The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement
+reference counts. Py_DECREF calls the object's deallocator function when
+the refcount falls to 0; for
+objects that don't contain references to other objects or heap memory
+this can be the standard function free(). Both macros can be used
+wherever a void expression is allowed. The argument must not be a
+NULL pointer. If it may be NULL, use Py_XINCREF/Py_XDECREF instead.
+The macro _Py_NewReference(op) initialize reference counts to 1, and
+in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional
+bookkeeping appropriate to the special build.
+
+We assume that the reference count field can never overflow; this can
+be proven when the size of the field is the same as the pointer size, so
+we ignore the possibility. Provided a C int is at least 32 bits (which
+is implicitly assumed in many parts of this code), that's enough for
+about 2**31 references to an object.
+
+XXX The following became out of date in Python 2.2, but I'm not sure
+XXX what the full truth is now. Certainly, heap-allocated type objects
+XXX can and should be deallocated.
+Type objects should never be deallocated; the type pointer in an object
+is not considered to be a reference to the type object, to save
+complications in the deallocation function. (This is actually a
+decision that's up to the implementer of each new type so if you want,
+you can count such references to the type object.)
+
+*** WARNING*** The Py_DECREF macro must have a side-effect-free argument
+since it may evaluate its argument multiple times. (The alternative
+would be to mace it a proper function or assign it to a global temporary
+variable first, both of which are slower; and in a multi-threaded
+environment the global variable trick is not safe.)
+*/
+
+/* First define a pile of simple helper macros, one set per special
+ * build symbol. These either expand to the obvious things, or to
+ * nothing at all when the special mode isn't in effect. The main
+ * macros can later be defined just once then, yet expand to different
+ * things depending on which special build options are and aren't in effect.
+ * Trust me : while painful, this is 20x easier to understand than,
+ * e.g, defining _Py_NewReference five different times in a maze of nested
+ * #ifdefs (we used to do that -- it was impenetrable).
+ */
+#ifdef Py_REF_DEBUG
+PyAPI_DATA(Py_ssize_t) _Py_RefTotal;
+PyAPI_FUNC(void) _Py_NegativeRefcount(const char *fname,
+ int lineno, PyObject *op);
+PyAPI_FUNC(PyObject *) _PyDict_Dummy(void);
+PyAPI_FUNC(PyObject *) _PySet_Dummy(void);
+PyAPI_FUNC(Py_ssize_t) _Py_GetRefTotal(void);
+#define _Py_INC_REFTOTAL _Py_RefTotal++
+#define _Py_DEC_REFTOTAL _Py_RefTotal--
+#define _Py_REF_DEBUG_COMMA ,
+#define _Py_CHECK_REFCNT(OP) \
+{ if (((PyObject*)OP)->ob_refcnt < 0) \
+ _Py_NegativeRefcount(__FILE__, __LINE__, \
+ (PyObject *)(OP)); \
+}
+#else
+#define _Py_INC_REFTOTAL
+#define _Py_DEC_REFTOTAL
+#define _Py_REF_DEBUG_COMMA
+#define _Py_CHECK_REFCNT(OP) /* a semicolon */;
+#endif /* Py_REF_DEBUG */
+
+#ifdef COUNT_ALLOCS
+PyAPI_FUNC(void) inc_count(PyTypeObject *);
+PyAPI_FUNC(void) dec_count(PyTypeObject *);
+#define _Py_INC_TPALLOCS(OP) inc_count(Py_TYPE(OP))
+#define _Py_INC_TPFREES(OP) dec_count(Py_TYPE(OP))
+#define _Py_DEC_TPFREES(OP) Py_TYPE(OP)->tp_frees--
+#define _Py_COUNT_ALLOCS_COMMA ,
+#else
+#define _Py_INC_TPALLOCS(OP)
+#define _Py_INC_TPFREES(OP)
+#define _Py_DEC_TPFREES(OP)
+#define _Py_COUNT_ALLOCS_COMMA
+#endif /* COUNT_ALLOCS */
+
+#ifdef Py_TRACE_REFS
+/* Py_TRACE_REFS is such major surgery that we call external routines. */
+PyAPI_FUNC(void) _Py_NewReference(PyObject *);
+PyAPI_FUNC(void) _Py_ForgetReference(PyObject *);
+PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
+PyAPI_FUNC(void) _Py_PrintReferences(FILE *);
+PyAPI_FUNC(void) _Py_PrintReferenceAddresses(FILE *);
+PyAPI_FUNC(void) _Py_AddToAllObjects(PyObject *, int force);
+
+#else
+/* Without Py_TRACE_REFS, there's little enough to do that we expand code
+ * inline.
+ */
+#define _Py_NewReference(op) ( \
+ _Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA \
+ _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \
+ Py_REFCNT(op) = 1)
+
+#define _Py_ForgetReference(op) _Py_INC_TPFREES(op)
+
+#define _Py_Dealloc(op) ( \
+ _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA \
+ (*Py_TYPE(op)->tp_dealloc)((PyObject *)(op)))
+#endif /* !Py_TRACE_REFS */
+
+#define Py_INCREF(op) ( \
+ _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \
+ ((PyObject*)(op))->ob_refcnt++)
+
+#define Py_DECREF(op) \
+ do { \
+ if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \
+ --((PyObject*)(op))->ob_refcnt != 0) \
+ _Py_CHECK_REFCNT(op) \
+ else \
+ _Py_Dealloc((PyObject *)(op)); \
+ } while (0)
+
+/* Safely decref `op` and set `op` to NULL, especially useful in tp_clear
+ * and tp_dealloc implementatons.
+ *
+ * Note that "the obvious" code can be deadly:
+ *
+ * Py_XDECREF(op);
+ * op = NULL;
+ *
+ * Typically, `op` is something like self->containee, and `self` is done
+ * using its `containee` member. In the code sequence above, suppose
+ * `containee` is non-NULL with a refcount of 1. Its refcount falls to
+ * 0 on the first line, which can trigger an arbitrary amount of code,
+ * possibly including finalizers (like __del__ methods or weakref callbacks)
+ * coded in Python, which in turn can release the GIL and allow other threads
+ * to run, etc. Such code may even invoke methods of `self` again, or cause
+ * cyclic gc to trigger, but-- oops! --self->containee still points to the
+ * object being torn down, and it may be in an insane state while being torn
+ * down. This has in fact been a rich historic source of miserable (rare &
+ * hard-to-diagnose) segfaulting (and other) bugs.
+ *
+ * The safe way is:
+ *
+ * Py_CLEAR(op);
+ *
+ * That arranges to set `op` to NULL _before_ decref'ing, so that any code
+ * triggered as a side-effect of `op` getting torn down no longer believes
+ * `op` points to a valid object.
+ *
+ * There are cases where it's safe to use the naive code, but they're brittle.
+ * For example, if `op` points to a Python integer, you know that destroying
+ * one of those can't cause problems -- but in part that relies on that
+ * Python integers aren't currently weakly referencable. Best practice is
+ * to use Py_CLEAR() even if you can't think of a reason for why you need to.
+ */
+#define Py_CLEAR(op) \
+ do { \
+ if (op) { \
+ PyObject *_py_tmp = (PyObject *)(op); \
+ (op) = NULL; \
+ Py_DECREF(_py_tmp); \
+ } \
+ } while (0)
+
+/* Macros to use in case the object pointer may be NULL: */
+#define Py_XINCREF(op) do { if ((op) == NULL) ; else Py_INCREF(op); } while (0)
+#define Py_XDECREF(op) do { if ((op) == NULL) ; else Py_DECREF(op); } while (0)
+
+/*
+These are provided as conveniences to Python runtime embedders, so that
+they can have object code that is not dependent on Python compilation flags.
+*/
+PyAPI_FUNC(void) Py_IncRef(PyObject *);
+PyAPI_FUNC(void) Py_DecRef(PyObject *);
+
+/*
+_Py_NoneStruct is an object of undefined type which can be used in contexts
+where NULL (nil) is not suitable (since NULL often means 'error').
+
+Don't forget to apply Py_INCREF() when returning this value!!!
+*/
+PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */
+#define Py_None (&_Py_NoneStruct)
+
+/* Macro for returning Py_None from a function */
+#define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
+
+/*
+Py_NotImplemented is a singleton used to signal that an operation is
+not implemented for a given type combination.
+*/
+PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */
+#define Py_NotImplemented (&_Py_NotImplementedStruct)
+
+/* Rich comparison opcodes */
+#define Py_LT 0
+#define Py_LE 1
+#define Py_EQ 2
+#define Py_NE 3
+#define Py_GT 4
+#define Py_GE 5
+
+/* Maps Py_LT to Py_GT, ..., Py_GE to Py_LE.
+ * Defined in object.c.
+ */
+PyAPI_DATA(int) _Py_SwappedOp[];
+
+/*
+Define staticforward and statichere for source compatibility with old
+C extensions.
+
+The staticforward define was needed to support certain broken C
+compilers (notably SCO ODT 3.0, perhaps early AIX as well) botched the
+static keyword when it was used with a forward declaration of a static
+initialized structure. Standard C allows the forward declaration with
+static, and we've decided to stop catering to broken C compilers.
+(In fact, we expect that the compilers are all fixed eight years later.)
+*/
+
+#define staticforward static
+#define statichere static
+
+
+/*
+More conventions
+================
+
+Argument Checking
+-----------------
+
+Functions that take objects as arguments normally don't check for nil
+arguments, but they do check the type of the argument, and return an
+error if the function doesn't apply to the type.
+
+Failure Modes
+-------------
+
+Functions may fail for a variety of reasons, including running out of
+memory. This is communicated to the caller in two ways: an error string
+is set (see errors.h), and the function result differs: functions that
+normally return a pointer return NULL for failure, functions returning
+an integer return -1 (which could be a legal return value too!), and
+other functions return 0 for success and -1 for failure.
+Callers should always check for errors before using the result. If
+an error was set, the caller must either explicitly clear it, or pass
+the error on to its caller.
+
+Reference Counts
+----------------
+
+It takes a while to get used to the proper usage of reference counts.
+
+Functions that create an object set the reference count to 1; such new
+objects must be stored somewhere or destroyed again with Py_DECREF().
+Some functions that 'store' objects, such as PyTuple_SetItem() and
+PyList_SetItem(),
+don't increment the reference count of the object, since the most
+frequent use is to store a fresh object. Functions that 'retrieve'
+objects, such as PyTuple_GetItem() and PyDict_GetItemString(), also
+don't increment
+the reference count, since most frequently the object is only looked at
+quickly. Thus, to retrieve an object and store it again, the caller
+must call Py_INCREF() explicitly.
+
+NOTE: functions that 'consume' a reference count, like
+PyList_SetItem(), consume the reference even if the object wasn't
+successfully stored, to simplify error handling.
+
+It seems attractive to make other functions that take an object as
+argument consume a reference count; however, this may quickly get
+confusing (even the current practice is already confusing). Consider
+it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at
+times.
+*/
+
+
+/* Trashcan mechanism, thanks to Christian Tismer.
+
+When deallocating a container object, it's possible to trigger an unbounded
+chain of deallocations, as each Py_DECREF in turn drops the refcount on "the
+next" object in the chain to 0. This can easily lead to stack faults, and
+especially in threads (which typically have less stack space to work with).
+
+A container object that participates in cyclic gc can avoid this by
+bracketing the body of its tp_dealloc function with a pair of macros:
+
+static void
+mytype_dealloc(mytype *p)
+{
+ ... declarations go here ...
+
+ PyObject_GC_UnTrack(p); // must untrack first
+ Py_TRASHCAN_SAFE_BEGIN(p)
+ ... The body of the deallocator goes here, including all calls ...
+ ... to Py_DECREF on contained objects. ...
+ Py_TRASHCAN_SAFE_END(p)
+}
+
+CAUTION: Never return from the middle of the body! If the body needs to
+"get out early", put a label immediately before the Py_TRASHCAN_SAFE_END
+call, and goto it. Else the call-depth counter (see below) will stay
+above 0 forever, and the trashcan will never get emptied.
+
+How it works: The BEGIN macro increments a call-depth counter. So long
+as this counter is small, the body of the deallocator is run directly without
+further ado. But if the counter gets large, it instead adds p to a list of
+objects to be deallocated later, skips the body of the deallocator, and
+resumes execution after the END macro. The tp_dealloc routine then returns
+without deallocating anything (and so unbounded call-stack depth is avoided).
+
+When the call stack finishes unwinding again, code generated by the END macro
+notices this, and calls another routine to deallocate all the objects that
+may have been added to the list of deferred deallocations. In effect, a
+chain of N deallocations is broken into N / PyTrash_UNWIND_LEVEL pieces,
+with the call stack never exceeding a depth of PyTrash_UNWIND_LEVEL.
+*/
+
+PyAPI_FUNC(void) _PyTrash_deposit_object(PyObject*);
+PyAPI_FUNC(void) _PyTrash_destroy_chain(void);
+PyAPI_DATA(int) _PyTrash_delete_nesting;
+PyAPI_DATA(PyObject *) _PyTrash_delete_later;
+
+#define PyTrash_UNWIND_LEVEL 50
+
+#define Py_TRASHCAN_SAFE_BEGIN(op) \
+ if (_PyTrash_delete_nesting < PyTrash_UNWIND_LEVEL) { \
+ ++_PyTrash_delete_nesting;
+ /* The body of the deallocator is here. */
+#define Py_TRASHCAN_SAFE_END(op) \
+ --_PyTrash_delete_nesting; \
+ if (_PyTrash_delete_later && _PyTrash_delete_nesting <= 0) \
+ _PyTrash_destroy_chain(); \
+ } \
+ else \
+ _PyTrash_deposit_object((PyObject*)op);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_OBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/objimpl.h b/AppPkg/Applications/Python/Python-2.7.2/Include/objimpl.h
new file mode 100644
index 0000000000..79d7e2de60
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/objimpl.h
@@ -0,0 +1,354 @@
+/* The PyObject_ memory family: high-level object memory interfaces.
+ See pymem.h for the low-level PyMem_ family.
+*/
+
+#ifndef Py_OBJIMPL_H
+#define Py_OBJIMPL_H
+
+#include "pymem.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* BEWARE:
+
+ Each interface exports both functions and macros. Extension modules should
+ use the functions, to ensure binary compatibility across Python versions.
+ Because the Python implementation is free to change internal details, and
+ the macros may (or may not) expose details for speed, if you do use the
+ macros you must recompile your extensions with each Python release.
+
+ Never mix calls to PyObject_ memory functions with calls to the platform
+ malloc/realloc/ calloc/free, or with calls to PyMem_.
+*/
+
+/*
+Functions and macros for modules that implement new object types.
+
+ - PyObject_New(type, typeobj) allocates memory for a new object of the given
+ type, and initializes part of it. 'type' must be the C structure type used
+ to represent the object, and 'typeobj' the address of the corresponding
+ type object. Reference count and type pointer are filled in; the rest of
+ the bytes of the object are *undefined*! The resulting expression type is
+ 'type *'. The size of the object is determined by the tp_basicsize field
+ of the type object.
+
+ - PyObject_NewVar(type, typeobj, n) is similar but allocates a variable-size
+ object with room for n items. In addition to the refcount and type pointer
+ fields, this also fills in the ob_size field.
+
+ - PyObject_Del(op) releases the memory allocated for an object. It does not
+ run a destructor -- it only frees the memory. PyObject_Free is identical.
+
+ - PyObject_Init(op, typeobj) and PyObject_InitVar(op, typeobj, n) don't
+ allocate memory. Instead of a 'type' parameter, they take a pointer to a
+ new object (allocated by an arbitrary allocator), and initialize its object
+ header fields.
+
+Note that objects created with PyObject_{New, NewVar} are allocated using the
+specialized Python allocator (implemented in obmalloc.c), if WITH_PYMALLOC is
+enabled. In addition, a special debugging allocator is used if PYMALLOC_DEBUG
+is also #defined.
+
+In case a specific form of memory management is needed (for example, if you
+must use the platform malloc heap(s), or shared memory, or C++ local storage or
+operator new), you must first allocate the object with your custom allocator,
+then pass its pointer to PyObject_{Init, InitVar} for filling in its Python-
+specific fields: reference count, type pointer, possibly others. You should
+be aware that Python no control over these objects because they don't
+cooperate with the Python memory manager. Such objects may not be eligible
+for automatic garbage collection and you have to make sure that they are
+released accordingly whenever their destructor gets called (cf. the specific
+form of memory management you're using).
+
+Unless you have specific memory management requirements, use
+PyObject_{New, NewVar, Del}.
+*/
+
+/*
+ * Raw object memory interface
+ * ===========================
+ */
+
+/* Functions to call the same malloc/realloc/free as used by Python's
+ object allocator. If WITH_PYMALLOC is enabled, these may differ from
+ the platform malloc/realloc/free. The Python object allocator is
+ designed for fast, cache-conscious allocation of many "small" objects,
+ and with low hidden memory overhead.
+
+ PyObject_Malloc(0) returns a unique non-NULL pointer if possible.
+
+ PyObject_Realloc(NULL, n) acts like PyObject_Malloc(n).
+ PyObject_Realloc(p != NULL, 0) does not return NULL, or free the memory
+ at p.
+
+ Returned pointers must be checked for NULL explicitly; no action is
+ performed on failure other than to return NULL (no warning it printed, no
+ exception is set, etc).
+
+ For allocating objects, use PyObject_{New, NewVar} instead whenever
+ possible. The PyObject_{Malloc, Realloc, Free} family is exposed
+ so that you can exploit Python's small-block allocator for non-object
+ uses. If you must use these routines to allocate object memory, make sure
+ the object gets initialized via PyObject_{Init, InitVar} after obtaining
+ the raw memory.
+*/
+PyAPI_FUNC(void *) PyObject_Malloc(size_t);
+PyAPI_FUNC(void *) PyObject_Realloc(void *, size_t);
+PyAPI_FUNC(void) PyObject_Free(void *);
+
+
+/* Macros */
+#ifdef WITH_PYMALLOC
+#ifdef PYMALLOC_DEBUG /* WITH_PYMALLOC && PYMALLOC_DEBUG */
+PyAPI_FUNC(void *) _PyObject_DebugMalloc(size_t nbytes);
+PyAPI_FUNC(void *) _PyObject_DebugRealloc(void *p, size_t nbytes);
+PyAPI_FUNC(void) _PyObject_DebugFree(void *p);
+PyAPI_FUNC(void) _PyObject_DebugDumpAddress(const void *p);
+PyAPI_FUNC(void) _PyObject_DebugCheckAddress(const void *p);
+PyAPI_FUNC(void) _PyObject_DebugMallocStats(void);
+PyAPI_FUNC(void *) _PyObject_DebugMallocApi(char api, size_t nbytes);
+PyAPI_FUNC(void *) _PyObject_DebugReallocApi(char api, void *p, size_t nbytes);
+PyAPI_FUNC(void) _PyObject_DebugFreeApi(char api, void *p);
+PyAPI_FUNC(void) _PyObject_DebugCheckAddressApi(char api, const void *p);
+PyAPI_FUNC(void *) _PyMem_DebugMalloc(size_t nbytes);
+PyAPI_FUNC(void *) _PyMem_DebugRealloc(void *p, size_t nbytes);
+PyAPI_FUNC(void) _PyMem_DebugFree(void *p);
+#define PyObject_MALLOC _PyObject_DebugMalloc
+#define PyObject_Malloc _PyObject_DebugMalloc
+#define PyObject_REALLOC _PyObject_DebugRealloc
+#define PyObject_Realloc _PyObject_DebugRealloc
+#define PyObject_FREE _PyObject_DebugFree
+#define PyObject_Free _PyObject_DebugFree
+
+#else /* WITH_PYMALLOC && ! PYMALLOC_DEBUG */
+#define PyObject_MALLOC PyObject_Malloc
+#define PyObject_REALLOC PyObject_Realloc
+#define PyObject_FREE PyObject_Free
+#endif
+
+#else /* ! WITH_PYMALLOC */
+#define PyObject_MALLOC PyMem_MALLOC
+#define PyObject_REALLOC PyMem_REALLOC
+#define PyObject_FREE PyMem_FREE
+
+#endif /* WITH_PYMALLOC */
+
+#define PyObject_Del PyObject_Free
+#define PyObject_DEL PyObject_FREE
+
+/* for source compatibility with 2.2 */
+#define _PyObject_Del PyObject_Free
+
+/*
+ * Generic object allocator interface
+ * ==================================
+ */
+
+/* Functions */
+PyAPI_FUNC(PyObject *) PyObject_Init(PyObject *, PyTypeObject *);
+PyAPI_FUNC(PyVarObject *) PyObject_InitVar(PyVarObject *,
+ PyTypeObject *, Py_ssize_t);
+PyAPI_FUNC(PyObject *) _PyObject_New(PyTypeObject *);
+PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t);
+
+#define PyObject_New(type, typeobj) \
+ ( (type *) _PyObject_New(typeobj) )
+#define PyObject_NewVar(type, typeobj, n) \
+ ( (type *) _PyObject_NewVar((typeobj), (n)) )
+
+/* Macros trading binary compatibility for speed. See also pymem.h.
+ Note that these macros expect non-NULL object pointers.*/
+#define PyObject_INIT(op, typeobj) \
+ ( Py_TYPE(op) = (typeobj), _Py_NewReference((PyObject *)(op)), (op) )
+#define PyObject_INIT_VAR(op, typeobj, size) \
+ ( Py_SIZE(op) = (size), PyObject_INIT((op), (typeobj)) )
+
+#define _PyObject_SIZE(typeobj) ( (typeobj)->tp_basicsize )
+
+/* _PyObject_VAR_SIZE returns the number of bytes (as size_t) allocated for a
+ vrbl-size object with nitems items, exclusive of gc overhead (if any). The
+ value is rounded up to the closest multiple of sizeof(void *), in order to
+ ensure that pointer fields at the end of the object are correctly aligned
+ for the platform (this is of special importance for subclasses of, e.g.,
+ str or long, so that pointers can be stored after the embedded data).
+
+ Note that there's no memory wastage in doing this, as malloc has to
+ return (at worst) pointer-aligned memory anyway.
+*/
+#if ((SIZEOF_VOID_P - 1) & SIZEOF_VOID_P) != 0
+# error "_PyObject_VAR_SIZE requires SIZEOF_VOID_P be a power of 2"
+#endif
+
+#define _PyObject_VAR_SIZE(typeobj, nitems) \
+ (size_t) \
+ ( ( (typeobj)->tp_basicsize + \
+ (nitems)*(typeobj)->tp_itemsize + \
+ (SIZEOF_VOID_P - 1) \
+ ) & ~(SIZEOF_VOID_P - 1) \
+ )
+
+#define PyObject_NEW(type, typeobj) \
+( (type *) PyObject_Init( \
+ (PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) )
+
+#define PyObject_NEW_VAR(type, typeobj, n) \
+( (type *) PyObject_InitVar( \
+ (PyVarObject *) PyObject_MALLOC(_PyObject_VAR_SIZE((typeobj),(n)) ),\
+ (typeobj), (n)) )
+
+/* This example code implements an object constructor with a custom
+ allocator, where PyObject_New is inlined, and shows the important
+ distinction between two steps (at least):
+ 1) the actual allocation of the object storage;
+ 2) the initialization of the Python specific fields
+ in this storage with PyObject_{Init, InitVar}.
+
+ PyObject *
+ YourObject_New(...)
+ {
+ PyObject *op;
+
+ op = (PyObject *) Your_Allocator(_PyObject_SIZE(YourTypeStruct));
+ if (op == NULL)
+ return PyErr_NoMemory();
+
+ PyObject_Init(op, &YourTypeStruct);
+
+ op->ob_field = value;
+ ...
+ return op;
+ }
+
+ Note that in C++, the use of the new operator usually implies that
+ the 1st step is performed automatically for you, so in a C++ class
+ constructor you would start directly with PyObject_Init/InitVar
+*/
+
+/*
+ * Garbage Collection Support
+ * ==========================
+ */
+
+/* C equivalent of gc.collect(). */
+PyAPI_FUNC(Py_ssize_t) PyGC_Collect(void);
+
+/* Test if a type has a GC head */
+#define PyType_IS_GC(t) PyType_HasFeature((t), Py_TPFLAGS_HAVE_GC)
+
+/* Test if an object has a GC head */
+#define PyObject_IS_GC(o) (PyType_IS_GC(Py_TYPE(o)) && \
+ (Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o)))
+
+PyAPI_FUNC(PyVarObject *) _PyObject_GC_Resize(PyVarObject *, Py_ssize_t);
+#define PyObject_GC_Resize(type, op, n) \
+ ( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) )
+
+/* for source compatibility with 2.2 */
+#define _PyObject_GC_Del PyObject_GC_Del
+
+/* GC information is stored BEFORE the object structure. */
+typedef union _gc_head {
+ struct {
+ union _gc_head *gc_next;
+ union _gc_head *gc_prev;
+ Py_ssize_t gc_refs;
+ } gc;
+ long double dummy; /* force worst-case alignment */
+} PyGC_Head;
+
+extern PyGC_Head *_PyGC_generation0;
+
+#define _Py_AS_GC(o) ((PyGC_Head *)(o)-1)
+
+#define _PyGC_REFS_UNTRACKED (-2)
+#define _PyGC_REFS_REACHABLE (-3)
+#define _PyGC_REFS_TENTATIVELY_UNREACHABLE (-4)
+
+/* Tell the GC to track this object. NB: While the object is tracked the
+ * collector it must be safe to call the ob_traverse method. */
+#define _PyObject_GC_TRACK(o) do { \
+ PyGC_Head *g = _Py_AS_GC(o); \
+ if (g->gc.gc_refs != _PyGC_REFS_UNTRACKED) \
+ Py_FatalError("GC object already tracked"); \
+ g->gc.gc_refs = _PyGC_REFS_REACHABLE; \
+ g->gc.gc_next = _PyGC_generation0; \
+ g->gc.gc_prev = _PyGC_generation0->gc.gc_prev; \
+ g->gc.gc_prev->gc.gc_next = g; \
+ _PyGC_generation0->gc.gc_prev = g; \
+ } while (0);
+
+/* Tell the GC to stop tracking this object.
+ * gc_next doesn't need to be set to NULL, but doing so is a good
+ * way to provoke memory errors if calling code is confused.
+ */
+#define _PyObject_GC_UNTRACK(o) do { \
+ PyGC_Head *g = _Py_AS_GC(o); \
+ assert(g->gc.gc_refs != _PyGC_REFS_UNTRACKED); \
+ g->gc.gc_refs = _PyGC_REFS_UNTRACKED; \
+ g->gc.gc_prev->gc.gc_next = g->gc.gc_next; \
+ g->gc.gc_next->gc.gc_prev = g->gc.gc_prev; \
+ g->gc.gc_next = NULL; \
+ } while (0);
+
+/* True if the object is currently tracked by the GC. */
+#define _PyObject_GC_IS_TRACKED(o) \
+ ((_Py_AS_GC(o))->gc.gc_refs != _PyGC_REFS_UNTRACKED)
+
+/* True if the object may be tracked by the GC in the future, or already is.
+ This can be useful to implement some optimizations. */
+#define _PyObject_GC_MAY_BE_TRACKED(obj) \
+ (PyObject_IS_GC(obj) && \
+ (!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj)))
+
+
+PyAPI_FUNC(PyObject *) _PyObject_GC_Malloc(size_t);
+PyAPI_FUNC(PyObject *) _PyObject_GC_New(PyTypeObject *);
+PyAPI_FUNC(PyVarObject *) _PyObject_GC_NewVar(PyTypeObject *, Py_ssize_t);
+PyAPI_FUNC(void) PyObject_GC_Track(void *);
+PyAPI_FUNC(void) PyObject_GC_UnTrack(void *);
+PyAPI_FUNC(void) PyObject_GC_Del(void *);
+
+#define PyObject_GC_New(type, typeobj) \
+ ( (type *) _PyObject_GC_New(typeobj) )
+#define PyObject_GC_NewVar(type, typeobj, n) \
+ ( (type *) _PyObject_GC_NewVar((typeobj), (n)) )
+
+
+/* Utility macro to help write tp_traverse functions.
+ * To use this macro, the tp_traverse function must name its arguments
+ * "visit" and "arg". This is intended to keep tp_traverse functions
+ * looking as much alike as possible.
+ */
+#define Py_VISIT(op) \
+ do { \
+ if (op) { \
+ int vret = visit((PyObject *)(op), arg); \
+ if (vret) \
+ return vret; \
+ } \
+ } while (0)
+
+/* This is here for the sake of backwards compatibility. Extensions that
+ * use the old GC API will still compile but the objects will not be
+ * tracked by the GC. */
+#define PyGC_HEAD_SIZE 0
+#define PyObject_GC_Init(op)
+#define PyObject_GC_Fini(op)
+#define PyObject_AS_GC(op) (op)
+#define PyObject_FROM_GC(op) (op)
+
+
+/* Test if a type supports weak references */
+#define PyType_SUPPORTS_WEAKREFS(t) \
+ (PyType_HasFeature((t), Py_TPFLAGS_HAVE_WEAKREFS) \
+ && ((t)->tp_weaklistoffset > 0))
+
+#define PyObject_GET_WEAKREFS_LISTPTR(o) \
+ ((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset))
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_OBJIMPL_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/opcode.h b/AppPkg/Applications/Python/Python-2.7.2/Include/opcode.h
new file mode 100644
index 0000000000..fe2a690305
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/opcode.h
@@ -0,0 +1,162 @@
+#ifndef Py_OPCODE_H
+#define Py_OPCODE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Instruction opcodes for compiled code */
+
+#define STOP_CODE 0
+#define POP_TOP 1
+#define ROT_TWO 2
+#define ROT_THREE 3
+#define DUP_TOP 4
+#define ROT_FOUR 5
+#define NOP 9
+
+#define UNARY_POSITIVE 10
+#define UNARY_NEGATIVE 11
+#define UNARY_NOT 12
+#define UNARY_CONVERT 13
+
+#define UNARY_INVERT 15
+
+#define BINARY_POWER 19
+
+#define BINARY_MULTIPLY 20
+#define BINARY_DIVIDE 21
+#define BINARY_MODULO 22
+#define BINARY_ADD 23
+#define BINARY_SUBTRACT 24
+#define BINARY_SUBSCR 25
+#define BINARY_FLOOR_DIVIDE 26
+#define BINARY_TRUE_DIVIDE 27
+#define INPLACE_FLOOR_DIVIDE 28
+#define INPLACE_TRUE_DIVIDE 29
+
+#define SLICE 30
+/* Also uses 31-33 */
+
+#define STORE_SLICE 40
+/* Also uses 41-43 */
+
+#define DELETE_SLICE 50
+/* Also uses 51-53 */
+
+#define STORE_MAP 54
+#define INPLACE_ADD 55
+#define INPLACE_SUBTRACT 56
+#define INPLACE_MULTIPLY 57
+#define INPLACE_DIVIDE 58
+#define INPLACE_MODULO 59
+#define STORE_SUBSCR 60
+#define DELETE_SUBSCR 61
+
+#define BINARY_LSHIFT 62
+#define BINARY_RSHIFT 63
+#define BINARY_AND 64
+#define BINARY_XOR 65
+#define BINARY_OR 66
+#define INPLACE_POWER 67
+#define GET_ITER 68
+
+#define PRINT_EXPR 70
+#define PRINT_ITEM 71
+#define PRINT_NEWLINE 72
+#define PRINT_ITEM_TO 73
+#define PRINT_NEWLINE_TO 74
+#define INPLACE_LSHIFT 75
+#define INPLACE_RSHIFT 76
+#define INPLACE_AND 77
+#define INPLACE_XOR 78
+#define INPLACE_OR 79
+#define BREAK_LOOP 80
+#define WITH_CLEANUP 81
+#define LOAD_LOCALS 82
+#define RETURN_VALUE 83
+#define IMPORT_STAR 84
+#define EXEC_STMT 85
+#define YIELD_VALUE 86
+#define POP_BLOCK 87
+#define END_FINALLY 88
+#define BUILD_CLASS 89
+
+#define HAVE_ARGUMENT 90 /* Opcodes from here have an argument: */
+
+#define STORE_NAME 90 /* Index in name list */
+#define DELETE_NAME 91 /* "" */
+#define UNPACK_SEQUENCE 92 /* Number of sequence items */
+#define FOR_ITER 93
+#define LIST_APPEND 94
+
+#define STORE_ATTR 95 /* Index in name list */
+#define DELETE_ATTR 96 /* "" */
+#define STORE_GLOBAL 97 /* "" */
+#define DELETE_GLOBAL 98 /* "" */
+#define DUP_TOPX 99 /* number of items to duplicate */
+#define LOAD_CONST 100 /* Index in const list */
+#define LOAD_NAME 101 /* Index in name list */
+#define BUILD_TUPLE 102 /* Number of tuple items */
+#define BUILD_LIST 103 /* Number of list items */
+#define BUILD_SET 104 /* Number of set items */
+#define BUILD_MAP 105 /* Always zero for now */
+#define LOAD_ATTR 106 /* Index in name list */
+#define COMPARE_OP 107 /* Comparison operator */
+#define IMPORT_NAME 108 /* Index in name list */
+#define IMPORT_FROM 109 /* Index in name list */
+#define JUMP_FORWARD 110 /* Number of bytes to skip */
+
+#define JUMP_IF_FALSE_OR_POP 111 /* Target byte offset from beginning
+ of code */
+#define JUMP_IF_TRUE_OR_POP 112 /* "" */
+#define JUMP_ABSOLUTE 113 /* "" */
+#define POP_JUMP_IF_FALSE 114 /* "" */
+#define POP_JUMP_IF_TRUE 115 /* "" */
+
+#define LOAD_GLOBAL 116 /* Index in name list */
+
+#define CONTINUE_LOOP 119 /* Start of loop (absolute) */
+#define SETUP_LOOP 120 /* Target address (relative) */
+#define SETUP_EXCEPT 121 /* "" */
+#define SETUP_FINALLY 122 /* "" */
+
+#define LOAD_FAST 124 /* Local variable number */
+#define STORE_FAST 125 /* Local variable number */
+#define DELETE_FAST 126 /* Local variable number */
+
+#define RAISE_VARARGS 130 /* Number of raise arguments (1, 2 or 3) */
+/* CALL_FUNCTION_XXX opcodes defined below depend on this definition */
+#define CALL_FUNCTION 131 /* #args + (#kwargs<<8) */
+#define MAKE_FUNCTION 132 /* #defaults */
+#define BUILD_SLICE 133 /* Number of items */
+
+#define MAKE_CLOSURE 134 /* #free vars */
+#define LOAD_CLOSURE 135 /* Load free variable from closure */
+#define LOAD_DEREF 136 /* Load and dereference from closure cell */
+#define STORE_DEREF 137 /* Store into cell */
+
+/* The next 3 opcodes must be contiguous and satisfy
+ (CALL_FUNCTION_VAR - CALL_FUNCTION) & 3 == 1 */
+#define CALL_FUNCTION_VAR 140 /* #args + (#kwargs<<8) */
+#define CALL_FUNCTION_KW 141 /* #args + (#kwargs<<8) */
+#define CALL_FUNCTION_VAR_KW 142 /* #args + (#kwargs<<8) */
+
+#define SETUP_WITH 143
+
+/* Support for opargs more than 16 bits long */
+#define EXTENDED_ARG 145
+
+#define SET_ADD 146
+#define MAP_ADD 147
+
+
+enum cmp_op {PyCmp_LT=Py_LT, PyCmp_LE=Py_LE, PyCmp_EQ=Py_EQ, PyCmp_NE=Py_NE, PyCmp_GT=Py_GT, PyCmp_GE=Py_GE,
+ PyCmp_IN, PyCmp_NOT_IN, PyCmp_IS, PyCmp_IS_NOT, PyCmp_EXC_MATCH, PyCmp_BAD};
+
+#define HAS_ARG(op) ((op) >= HAVE_ARGUMENT)
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_OPCODE_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/osdefs.h b/AppPkg/Applications/Python/Python-2.7.2/Include/osdefs.h
new file mode 100644
index 0000000000..bf6ec1100e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/osdefs.h
@@ -0,0 +1,71 @@
+/** @file
+ Operating system dependencies.
+
+ Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.
+ This program and the accompanying materials are licensed and made available under
+ the terms and conditions of the BSD License that accompanies this distribution.
+ The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+**/
+#ifndef Py_OSDEFS_H
+#define Py_OSDEFS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Mod by chrish: QNX has WATCOM, but isn't DOS */
+#if !defined(__QNX__) && !defined(UEFI_C_SOURCE)
+#if defined(MS_WINDOWS) || defined(__BORLANDC__) || defined(__WATCOMC__) || defined(__DJGPP__) || defined(PYOS_OS2)
+#if defined(PYOS_OS2) && defined(PYCC_GCC)
+#define MAXPATHLEN 260
+#define SEP '/'
+#define ALTSEP '\\'
+#else
+#define SEP '\\'
+#define ALTSEP '/'
+#define MAXPATHLEN 256
+#endif
+#define DELIM ';'
+#endif
+#endif
+
+#ifdef RISCOS
+#define SEP '.'
+#define MAXPATHLEN 256
+#define DELIM ','
+#endif
+
+
+/* Filename separator */
+#ifndef SEP
+#define SEP '/'
+#define ALTSEP '\\'
+#endif
+
+/* Max pathname length */
+#ifndef MAXPATHLEN
+#if defined(PATH_MAX) && PATH_MAX > 1024
+#define MAXPATHLEN PATH_MAX
+#else
+#define MAXPATHLEN 1024
+#endif
+#endif
+
+/* Search path entry delimiter */
+#ifndef DELIM
+ #ifdef UEFI_C_SOURCE
+ #define DELIM ';'
+ #define DELIM_STR ";"
+ #else
+ #define DELIM ':'
+ #endif
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_OSDEFS_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/parsetok.h b/AppPkg/Applications/Python/Python-2.7.2/Include/parsetok.h
new file mode 100644
index 0000000000..915bdba234
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/parsetok.h
@@ -0,0 +1,64 @@
+
+/* Parser-tokenizer link interface */
+
+#ifndef Py_PARSETOK_H
+#define Py_PARSETOK_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ int error;
+ const char *filename;
+ int lineno;
+ int offset;
+ char *text;
+ int token;
+ int expected;
+} perrdetail;
+
+#if 0
+#define PyPARSE_YIELD_IS_KEYWORD 0x0001
+#endif
+
+#define PyPARSE_DONT_IMPLY_DEDENT 0x0002
+
+#if 0
+#define PyPARSE_WITH_IS_KEYWORD 0x0003
+#endif
+
+#define PyPARSE_PRINT_IS_FUNCTION 0x0004
+#define PyPARSE_UNICODE_LITERALS 0x0008
+
+
+
+PyAPI_FUNC(node *) PyParser_ParseString(const char *, grammar *, int,
+ perrdetail *);
+PyAPI_FUNC(node *) PyParser_ParseFile (FILE *, const char *, grammar *, int,
+ char *, char *, perrdetail *);
+
+PyAPI_FUNC(node *) PyParser_ParseStringFlags(const char *, grammar *, int,
+ perrdetail *, int);
+PyAPI_FUNC(node *) PyParser_ParseFileFlags(FILE *, const char *, grammar *,
+ int, char *, char *,
+ perrdetail *, int);
+PyAPI_FUNC(node *) PyParser_ParseFileFlagsEx(FILE *, const char *, grammar *,
+ int, char *, char *,
+ perrdetail *, int *);
+
+PyAPI_FUNC(node *) PyParser_ParseStringFlagsFilename(const char *,
+ const char *,
+ grammar *, int,
+ perrdetail *, int);
+PyAPI_FUNC(node *) PyParser_ParseStringFlagsFilenameEx(const char *,
+ const char *,
+ grammar *, int,
+ perrdetail *, int *);
+
+/* Note that he following function is defined in pythonrun.c not parsetok.c. */
+PyAPI_FUNC(void) PyParser_SetError(perrdetail *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_PARSETOK_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/patchlevel.h b/AppPkg/Applications/Python/Python-2.7.2/Include/patchlevel.h
new file mode 100644
index 0000000000..f4bbba3b04
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/patchlevel.h
@@ -0,0 +1,43 @@
+
+/* Newfangled version identification scheme.
+
+ This scheme was added in Python 1.5.2b2; before that time, only PATCHLEVEL
+ was available. To test for presence of the scheme, test for
+ defined(PY_MAJOR_VERSION).
+
+ When the major or minor version changes, the VERSION variable in
+ configure.in must also be changed.
+
+ There is also (independent) API version information in modsupport.h.
+*/
+
+/* Values for PY_RELEASE_LEVEL */
+#define PY_RELEASE_LEVEL_ALPHA 0xA
+#define PY_RELEASE_LEVEL_BETA 0xB
+#define PY_RELEASE_LEVEL_GAMMA 0xC /* For release candidates */
+#define PY_RELEASE_LEVEL_FINAL 0xF /* Serial should be 0 here */
+ /* Higher for patch releases */
+
+/* Version parsed out into numeric values */
+/*--start constants--*/
+#define PY_MAJOR_VERSION 2
+#define PY_MINOR_VERSION 7
+#define PY_MICRO_VERSION 2
+#define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_FINAL
+#define PY_RELEASE_SERIAL 0
+
+/* Version as a string */
+#define PY_VERSION "2.7.2"
+/*--end constants--*/
+
+/* Subversion Revision number of this file (not of the repository). Empty
+ since Mercurial migration. */
+#define PY_PATCHLEVEL_REVISION ""
+
+/* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2.
+ Use this for numeric comparisons, e.g. #if PY_VERSION_HEX >= ... */
+#define PY_VERSION_HEX ((PY_MAJOR_VERSION << 24) | \
+ (PY_MINOR_VERSION << 16) | \
+ (PY_MICRO_VERSION << 8) | \
+ (PY_RELEASE_LEVEL << 4) | \
+ (PY_RELEASE_SERIAL << 0))
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pgen.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pgen.h
new file mode 100644
index 0000000000..af84852b39
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pgen.h
@@ -0,0 +1,18 @@
+#ifndef Py_PGEN_H
+#define Py_PGEN_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Parser generator interface */
+
+extern grammar *meta_grammar(void);
+
+struct _node;
+extern grammar *pgen(struct _node *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_PGEN_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pgenheaders.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pgenheaders.h
new file mode 100644
index 0000000000..7aac4e2b6a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pgenheaders.h
@@ -0,0 +1,42 @@
+#ifndef Py_PGENHEADERS_H
+#define Py_PGENHEADERS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Include files and extern declarations used by most of the parser. */
+
+#include "Python.h"
+
+PyAPI_FUNC(void) PySys_WriteStdout(const char *format, ...)
+ Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
+PyAPI_FUNC(void) PySys_WriteStderr(const char *format, ...)
+ Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
+
+#define addarc _Py_addarc
+#define addbit _Py_addbit
+#define adddfa _Py_adddfa
+#define addfirstsets _Py_addfirstsets
+#define addlabel _Py_addlabel
+#define addstate _Py_addstate
+#define delbitset _Py_delbitset
+#define dumptree _Py_dumptree
+#define findlabel _Py_findlabel
+#define mergebitset _Py_mergebitset
+#define meta_grammar _Py_meta_grammar
+#define newbitset _Py_newbitset
+#define newgrammar _Py_newgrammar
+#define pgen _Py_pgen
+#define printgrammar _Py_printgrammar
+#define printnonterminals _Py_printnonterminals
+#define printtree _Py_printtree
+#define samebitset _Py_samebitset
+#define showtree _Py_showtree
+#define tok_dump _Py_tok_dump
+#define translatelabels _Py_translatelabels
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_PGENHEADERS_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/py_curses.h b/AppPkg/Applications/Python/Python-2.7.2/Include/py_curses.h
new file mode 100644
index 0000000000..212060735b
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/py_curses.h
@@ -0,0 +1,176 @@
+
+#ifndef Py_CURSES_H
+#define Py_CURSES_H
+
+#ifdef __APPLE__
+/*
+** On Mac OS X 10.2 [n]curses.h and stdlib.h use different guards
+** against multiple definition of wchar_t.
+*/
+#ifdef _BSD_WCHAR_T_DEFINED_
+#define _WCHAR_T
+#endif
+
+/* the following define is necessary for OS X 10.6; without it, the
+ Apple-supplied ncurses.h sets NCURSES_OPAQUE to 1, and then Python
+ can't get at the WINDOW flags field. */
+#define NCURSES_OPAQUE 0
+#endif /* __APPLE__ */
+
+#ifdef __FreeBSD__
+/*
+** On FreeBSD, [n]curses.h and stdlib.h/wchar.h use different guards
+** against multiple definition of wchar_t and wint_t.
+*/
+#ifdef _XOPEN_SOURCE_EXTENDED
+#ifndef __FreeBSD_version
+#include
+#endif
+#if __FreeBSD_version >= 500000
+#ifndef __wchar_t
+#define __wchar_t
+#endif
+#ifndef __wint_t
+#define __wint_t
+#endif
+#else
+#ifndef _WCHAR_T
+#define _WCHAR_T
+#endif
+#ifndef _WINT_T
+#define _WINT_T
+#endif
+#endif
+#endif
+#endif
+
+#ifdef HAVE_NCURSES_H
+#include
+#else
+#include
+#ifdef HAVE_TERM_H
+/* for tigetstr, which is not declared in SysV curses */
+#include
+#endif
+#endif
+
+#ifdef HAVE_NCURSES_H
+/* configure was checking , but we will
+ use , which has all these features. */
+#ifndef WINDOW_HAS_FLAGS
+#define WINDOW_HAS_FLAGS 1
+#endif
+#ifndef MVWDELCH_IS_EXPRESSION
+#define MVWDELCH_IS_EXPRESSION 1
+#endif
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define PyCurses_API_pointers 4
+
+/* Type declarations */
+
+typedef struct {
+ PyObject_HEAD
+ WINDOW *win;
+} PyCursesWindowObject;
+
+#define PyCursesWindow_Check(v) (Py_TYPE(v) == &PyCursesWindow_Type)
+
+#define PyCurses_CAPSULE_NAME "_curses._C_API"
+
+
+#ifdef CURSES_MODULE
+/* This section is used when compiling _cursesmodule.c */
+
+#else
+/* This section is used in modules that use the _cursesmodule API */
+
+static void **PyCurses_API;
+
+#define PyCursesWindow_Type (*(PyTypeObject *) PyCurses_API[0])
+#define PyCursesSetupTermCalled {if (! ((int (*)(void))PyCurses_API[1]) () ) return NULL;}
+#define PyCursesInitialised {if (! ((int (*)(void))PyCurses_API[2]) () ) return NULL;}
+#define PyCursesInitialisedColor {if (! ((int (*)(void))PyCurses_API[3]) () ) return NULL;}
+
+#define import_curses() \
+ PyCurses_API = (void **)PyCapsule_Import(PyCurses_CAPSULE_NAME, 1);
+
+#endif
+
+/* general error messages */
+static char *catchall_ERR = "curses function returned ERR";
+static char *catchall_NULL = "curses function returned NULL";
+
+/* Function Prototype Macros - They are ugly but very, very useful. ;-)
+
+ X - function name
+ TYPE - parameter Type
+ ERGSTR - format string for construction of the return value
+ PARSESTR - format string for argument parsing
+ */
+
+#define NoArgNoReturnFunction(X) \
+static PyObject *PyCurses_ ## X (PyObject *self) \
+{ \
+ PyCursesInitialised \
+ return PyCursesCheckERR(X(), # X); }
+
+#define NoArgOrFlagNoReturnFunction(X) \
+static PyObject *PyCurses_ ## X (PyObject *self, PyObject *args) \
+{ \
+ int flag = 0; \
+ PyCursesInitialised \
+ switch(PyTuple_Size(args)) { \
+ case 0: \
+ return PyCursesCheckERR(X(), # X); \
+ case 1: \
+ if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; \
+ if (flag) return PyCursesCheckERR(X(), # X); \
+ else return PyCursesCheckERR(no ## X (), # X); \
+ default: \
+ PyErr_SetString(PyExc_TypeError, # X " requires 0 or 1 arguments"); \
+ return NULL; } }
+
+#define NoArgReturnIntFunction(X) \
+static PyObject *PyCurses_ ## X (PyObject *self) \
+{ \
+ PyCursesInitialised \
+ return PyInt_FromLong((long) X()); }
+
+
+#define NoArgReturnStringFunction(X) \
+static PyObject *PyCurses_ ## X (PyObject *self) \
+{ \
+ PyCursesInitialised \
+ return PyString_FromString(X()); }
+
+#define NoArgTrueFalseFunction(X) \
+static PyObject *PyCurses_ ## X (PyObject *self) \
+{ \
+ PyCursesInitialised \
+ if (X () == FALSE) { \
+ Py_INCREF(Py_False); \
+ return Py_False; \
+ } \
+ Py_INCREF(Py_True); \
+ return Py_True; }
+
+#define NoArgNoReturnVoidFunction(X) \
+static PyObject *PyCurses_ ## X (PyObject *self) \
+{ \
+ PyCursesInitialised \
+ X(); \
+ Py_INCREF(Py_None); \
+ return Py_None; }
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !defined(Py_CURSES_H) */
+
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pyarena.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pyarena.h
new file mode 100644
index 0000000000..fec1afa820
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pyarena.h
@@ -0,0 +1,62 @@
+/* An arena-like memory interface for the compiler.
+ */
+
+#ifndef Py_PYARENA_H
+#define Py_PYARENA_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ typedef struct _arena PyArena;
+
+ /* PyArena_New() and PyArena_Free() create a new arena and free it,
+ respectively. Once an arena has been created, it can be used
+ to allocate memory via PyArena_Malloc(). Pointers to PyObject can
+ also be registered with the arena via PyArena_AddPyObject(), and the
+ arena will ensure that the PyObjects stay alive at least until
+ PyArena_Free() is called. When an arena is freed, all the memory it
+ allocated is freed, the arena releases internal references to registered
+ PyObject*, and none of its pointers are valid.
+ XXX (tim) What does "none of its pointers are valid" mean? Does it
+ XXX mean that pointers previously obtained via PyArena_Malloc() are
+ XXX no longer valid? (That's clearly true, but not sure that's what
+ XXX the text is trying to say.)
+
+ PyArena_New() returns an arena pointer. On error, it
+ returns a negative number and sets an exception.
+ XXX (tim): Not true. On error, PyArena_New() actually returns NULL,
+ XXX and looks like it may or may not set an exception (e.g., if the
+ XXX internal PyList_New(0) returns NULL, PyArena_New() passes that on
+ XXX and an exception is set; OTOH, if the internal
+ XXX block_new(DEFAULT_BLOCK_SIZE) returns NULL, that's passed on but
+ XXX an exception is not set in that case).
+ */
+ PyAPI_FUNC(PyArena *) PyArena_New(void);
+ PyAPI_FUNC(void) PyArena_Free(PyArena *);
+
+ /* Mostly like malloc(), return the address of a block of memory spanning
+ * `size` bytes, or return NULL (without setting an exception) if enough
+ * new memory can't be obtained. Unlike malloc(0), PyArena_Malloc() with
+ * size=0 does not guarantee to return a unique pointer (the pointer
+ * returned may equal one or more other pointers obtained from
+ * PyArena_Malloc()).
+ * Note that pointers obtained via PyArena_Malloc() must never be passed to
+ * the system free() or realloc(), or to any of Python's similar memory-
+ * management functions. PyArena_Malloc()-obtained pointers remain valid
+ * until PyArena_Free(ar) is called, at which point all pointers obtained
+ * from the arena `ar` become invalid simultaneously.
+ */
+ PyAPI_FUNC(void *) PyArena_Malloc(PyArena *, size_t size);
+
+ /* This routine isn't a proper arena allocation routine. It takes
+ * a PyObject* and records it so that it can be DECREFed when the
+ * arena is freed.
+ */
+ PyAPI_FUNC(int) PyArena_AddPyObject(PyArena *, PyObject *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !Py_PYARENA_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pycapsule.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pycapsule.h
new file mode 100644
index 0000000000..d4144350b3
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pycapsule.h
@@ -0,0 +1,56 @@
+
+/* Capsule objects let you wrap a C "void *" pointer in a Python
+ object. They're a way of passing data through the Python interpreter
+ without creating your own custom type.
+
+ Capsules are used for communication between extension modules.
+ They provide a way for an extension module to export a C interface
+ to other extension modules, so that extension modules can use the
+ Python import mechanism to link to one another.
+
+ For more information, please see "c-api/capsule.html" in the
+ documentation.
+*/
+
+#ifndef Py_CAPSULE_H
+#define Py_CAPSULE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_DATA(PyTypeObject) PyCapsule_Type;
+
+typedef void (*PyCapsule_Destructor)(PyObject *);
+
+#define PyCapsule_CheckExact(op) (Py_TYPE(op) == &PyCapsule_Type)
+
+
+PyAPI_FUNC(PyObject *) PyCapsule_New(
+ void *pointer,
+ const char *name,
+ PyCapsule_Destructor destructor);
+
+PyAPI_FUNC(void *) PyCapsule_GetPointer(PyObject *capsule, const char *name);
+
+PyAPI_FUNC(PyCapsule_Destructor) PyCapsule_GetDestructor(PyObject *capsule);
+
+PyAPI_FUNC(const char *) PyCapsule_GetName(PyObject *capsule);
+
+PyAPI_FUNC(void *) PyCapsule_GetContext(PyObject *capsule);
+
+PyAPI_FUNC(int) PyCapsule_IsValid(PyObject *capsule, const char *name);
+
+PyAPI_FUNC(int) PyCapsule_SetPointer(PyObject *capsule, void *pointer);
+
+PyAPI_FUNC(int) PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor);
+
+PyAPI_FUNC(int) PyCapsule_SetName(PyObject *capsule, const char *name);
+
+PyAPI_FUNC(int) PyCapsule_SetContext(PyObject *capsule, void *context);
+
+PyAPI_FUNC(void *) PyCapsule_Import(const char *name, int no_block);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_CAPSULE_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pyctype.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pyctype.h
new file mode 100644
index 0000000000..82feefb746
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pyctype.h
@@ -0,0 +1,31 @@
+#ifndef PYCTYPE_H
+#define PYCTYPE_H
+
+#define PY_CTF_LOWER 0x01
+#define PY_CTF_UPPER 0x02
+#define PY_CTF_ALPHA (PY_CTF_LOWER|PY_CTF_UPPER)
+#define PY_CTF_DIGIT 0x04
+#define PY_CTF_ALNUM (PY_CTF_ALPHA|PY_CTF_DIGIT)
+#define PY_CTF_SPACE 0x08
+#define PY_CTF_XDIGIT 0x10
+
+extern const unsigned int _Py_ctype_table[256];
+
+/* Unlike their C counterparts, the following macros are not meant to
+ * handle an int with any of the values [EOF, 0-UCHAR_MAX]. The argument
+ * must be a signed/unsigned char. */
+#define Py_ISLOWER(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_LOWER)
+#define Py_ISUPPER(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_UPPER)
+#define Py_ISALPHA(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_ALPHA)
+#define Py_ISDIGIT(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_DIGIT)
+#define Py_ISXDIGIT(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_XDIGIT)
+#define Py_ISALNUM(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_ALNUM)
+#define Py_ISSPACE(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_SPACE)
+
+extern const unsigned char _Py_ctype_tolower[256];
+extern const unsigned char _Py_ctype_toupper[256];
+
+#define Py_TOLOWER(c) (_Py_ctype_tolower[Py_CHARMASK(c)])
+#define Py_TOUPPER(c) (_Py_ctype_toupper[Py_CHARMASK(c)])
+
+#endif /* !PYCTYPE_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pydebug.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pydebug.h
new file mode 100644
index 0000000000..cc6363bd8b
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pydebug.h
@@ -0,0 +1,40 @@
+
+#ifndef Py_PYDEBUG_H
+#define Py_PYDEBUG_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_DATA(int) Py_DebugFlag;
+PyAPI_DATA(int) Py_VerboseFlag;
+PyAPI_DATA(int) Py_InteractiveFlag;
+PyAPI_DATA(int) Py_InspectFlag;
+PyAPI_DATA(int) Py_OptimizeFlag;
+PyAPI_DATA(int) Py_NoSiteFlag;
+PyAPI_DATA(int) Py_BytesWarningFlag;
+PyAPI_DATA(int) Py_UseClassExceptionsFlag;
+PyAPI_DATA(int) Py_FrozenFlag;
+PyAPI_DATA(int) Py_TabcheckFlag;
+PyAPI_DATA(int) Py_UnicodeFlag;
+PyAPI_DATA(int) Py_IgnoreEnvironmentFlag;
+PyAPI_DATA(int) Py_DivisionWarningFlag;
+PyAPI_DATA(int) Py_DontWriteBytecodeFlag;
+PyAPI_DATA(int) Py_NoUserSiteDirectory;
+/* _XXX Py_QnewFlag should go away in 3.0. It's true iff -Qnew is passed,
+ on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
+ true divisions (which they will be in 3.0). */
+PyAPI_DATA(int) _Py_QnewFlag;
+/* Warn about 3.x issues */
+PyAPI_DATA(int) Py_Py3kWarningFlag;
+
+/* this is a wrapper around getenv() that pays attention to
+ Py_IgnoreEnvironmentFlag. It should be used for getting variables like
+ PYTHONPATH and PYTHONHOME from the environment */
+#define Py_GETENV(s) (Py_IgnoreEnvironmentFlag ? NULL : getenv(s))
+
+PyAPI_FUNC(void) Py_FatalError(const char *message);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_PYDEBUG_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pyerrors.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pyerrors.h
new file mode 100644
index 0000000000..4d4444cec8
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pyerrors.h
@@ -0,0 +1,328 @@
+#ifndef Py_ERRORS_H
+#define Py_ERRORS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Error objects */
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *dict;
+ PyObject *args;
+ PyObject *message;
+} PyBaseExceptionObject;
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *dict;
+ PyObject *args;
+ PyObject *message;
+ PyObject *msg;
+ PyObject *filename;
+ PyObject *lineno;
+ PyObject *offset;
+ PyObject *text;
+ PyObject *print_file_and_line;
+} PySyntaxErrorObject;
+
+#ifdef Py_USING_UNICODE
+typedef struct {
+ PyObject_HEAD
+ PyObject *dict;
+ PyObject *args;
+ PyObject *message;
+ PyObject *encoding;
+ PyObject *object;
+ Py_ssize_t start;
+ Py_ssize_t end;
+ PyObject *reason;
+} PyUnicodeErrorObject;
+#endif
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *dict;
+ PyObject *args;
+ PyObject *message;
+ PyObject *code;
+} PySystemExitObject;
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *dict;
+ PyObject *args;
+ PyObject *message;
+ PyObject *myerrno;
+ PyObject *strerror;
+ PyObject *filename;
+} PyEnvironmentErrorObject;
+
+#ifdef MS_WINDOWS
+typedef struct {
+ PyObject_HEAD
+ PyObject *dict;
+ PyObject *args;
+ PyObject *message;
+ PyObject *myerrno;
+ PyObject *strerror;
+ PyObject *filename;
+ PyObject *winerror;
+} PyWindowsErrorObject;
+#endif
+
+/* Error handling definitions */
+
+PyAPI_FUNC(void) PyErr_SetNone(PyObject *);
+PyAPI_FUNC(void) PyErr_SetObject(PyObject *, PyObject *);
+PyAPI_FUNC(void) PyErr_SetString(PyObject *, const char *);
+PyAPI_FUNC(PyObject *) PyErr_Occurred(void);
+PyAPI_FUNC(void) PyErr_Clear(void);
+PyAPI_FUNC(void) PyErr_Fetch(PyObject **, PyObject **, PyObject **);
+PyAPI_FUNC(void) PyErr_Restore(PyObject *, PyObject *, PyObject *);
+
+#ifdef Py_DEBUG
+#define _PyErr_OCCURRED() PyErr_Occurred()
+#else
+#define _PyErr_OCCURRED() (_PyThreadState_Current->curexc_type)
+#endif
+
+/* Error testing and normalization */
+PyAPI_FUNC(int) PyErr_GivenExceptionMatches(PyObject *, PyObject *);
+PyAPI_FUNC(int) PyErr_ExceptionMatches(PyObject *);
+PyAPI_FUNC(void) PyErr_NormalizeException(PyObject**, PyObject**, PyObject**);
+
+/* */
+
+#define PyExceptionClass_Check(x) \
+ (PyClass_Check((x)) || (PyType_Check((x)) && \
+ PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)))
+
+#define PyExceptionInstance_Check(x) \
+ (PyInstance_Check((x)) || \
+ PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS))
+
+#define PyExceptionClass_Name(x) \
+ (PyClass_Check((x)) \
+ ? PyString_AS_STRING(((PyClassObject*)(x))->cl_name) \
+ : (char *)(((PyTypeObject*)(x))->tp_name))
+
+#define PyExceptionInstance_Class(x) \
+ ((PyInstance_Check((x)) \
+ ? (PyObject*)((PyInstanceObject*)(x))->in_class \
+ : (PyObject*)((x)->ob_type)))
+
+
+/* Predefined exceptions */
+
+PyAPI_DATA(PyObject *) PyExc_BaseException;
+PyAPI_DATA(PyObject *) PyExc_Exception;
+PyAPI_DATA(PyObject *) PyExc_StopIteration;
+PyAPI_DATA(PyObject *) PyExc_GeneratorExit;
+PyAPI_DATA(PyObject *) PyExc_StandardError;
+PyAPI_DATA(PyObject *) PyExc_ArithmeticError;
+PyAPI_DATA(PyObject *) PyExc_LookupError;
+
+PyAPI_DATA(PyObject *) PyExc_AssertionError;
+PyAPI_DATA(PyObject *) PyExc_AttributeError;
+PyAPI_DATA(PyObject *) PyExc_EOFError;
+PyAPI_DATA(PyObject *) PyExc_FloatingPointError;
+PyAPI_DATA(PyObject *) PyExc_EnvironmentError;
+PyAPI_DATA(PyObject *) PyExc_IOError;
+PyAPI_DATA(PyObject *) PyExc_OSError;
+PyAPI_DATA(PyObject *) PyExc_ImportError;
+PyAPI_DATA(PyObject *) PyExc_IndexError;
+PyAPI_DATA(PyObject *) PyExc_KeyError;
+PyAPI_DATA(PyObject *) PyExc_KeyboardInterrupt;
+PyAPI_DATA(PyObject *) PyExc_MemoryError;
+PyAPI_DATA(PyObject *) PyExc_NameError;
+PyAPI_DATA(PyObject *) PyExc_OverflowError;
+PyAPI_DATA(PyObject *) PyExc_RuntimeError;
+PyAPI_DATA(PyObject *) PyExc_NotImplementedError;
+PyAPI_DATA(PyObject *) PyExc_SyntaxError;
+PyAPI_DATA(PyObject *) PyExc_IndentationError;
+PyAPI_DATA(PyObject *) PyExc_TabError;
+PyAPI_DATA(PyObject *) PyExc_ReferenceError;
+PyAPI_DATA(PyObject *) PyExc_SystemError;
+PyAPI_DATA(PyObject *) PyExc_SystemExit;
+PyAPI_DATA(PyObject *) PyExc_TypeError;
+PyAPI_DATA(PyObject *) PyExc_UnboundLocalError;
+PyAPI_DATA(PyObject *) PyExc_UnicodeError;
+PyAPI_DATA(PyObject *) PyExc_UnicodeEncodeError;
+PyAPI_DATA(PyObject *) PyExc_UnicodeDecodeError;
+PyAPI_DATA(PyObject *) PyExc_UnicodeTranslateError;
+PyAPI_DATA(PyObject *) PyExc_ValueError;
+PyAPI_DATA(PyObject *) PyExc_ZeroDivisionError;
+#ifdef MS_WINDOWS
+PyAPI_DATA(PyObject *) PyExc_WindowsError;
+#endif
+#ifdef __VMS
+PyAPI_DATA(PyObject *) PyExc_VMSError;
+#endif
+
+PyAPI_DATA(PyObject *) PyExc_BufferError;
+
+PyAPI_DATA(PyObject *) PyExc_MemoryErrorInst;
+PyAPI_DATA(PyObject *) PyExc_RecursionErrorInst;
+
+/* Predefined warning categories */
+PyAPI_DATA(PyObject *) PyExc_Warning;
+PyAPI_DATA(PyObject *) PyExc_UserWarning;
+PyAPI_DATA(PyObject *) PyExc_DeprecationWarning;
+PyAPI_DATA(PyObject *) PyExc_PendingDeprecationWarning;
+PyAPI_DATA(PyObject *) PyExc_SyntaxWarning;
+PyAPI_DATA(PyObject *) PyExc_RuntimeWarning;
+PyAPI_DATA(PyObject *) PyExc_FutureWarning;
+PyAPI_DATA(PyObject *) PyExc_ImportWarning;
+PyAPI_DATA(PyObject *) PyExc_UnicodeWarning;
+PyAPI_DATA(PyObject *) PyExc_BytesWarning;
+
+
+/* Convenience functions */
+
+PyAPI_FUNC(int) PyErr_BadArgument(void);
+PyAPI_FUNC(PyObject *) PyErr_NoMemory(void);
+PyAPI_FUNC(PyObject *) PyErr_SetFromErrno(PyObject *);
+PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilenameObject(
+ PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilename(
+ PyObject *, const char *);
+#ifdef MS_WINDOWS
+PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithUnicodeFilename(
+ PyObject *, const Py_UNICODE *);
+#endif /* MS_WINDOWS */
+
+PyAPI_FUNC(PyObject *) PyErr_Format(PyObject *, const char *, ...)
+ Py_GCC_ATTRIBUTE((format(printf, 2, 3)));
+
+#ifdef MS_WINDOWS
+PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilenameObject(
+ int, const char *);
+PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilename(
+ int, const char *);
+PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithUnicodeFilename(
+ int, const Py_UNICODE *);
+PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErr(int);
+PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObject(
+ PyObject *,int, PyObject *);
+PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilename(
+ PyObject *,int, const char *);
+PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithUnicodeFilename(
+ PyObject *,int, const Py_UNICODE *);
+PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErr(PyObject *, int);
+#endif /* MS_WINDOWS */
+
+/* Export the old function so that the existing API remains available: */
+PyAPI_FUNC(void) PyErr_BadInternalCall(void);
+PyAPI_FUNC(void) _PyErr_BadInternalCall(char *filename, int lineno);
+/* Mask the old API with a call to the new API for code compiled under
+ Python 2.0: */
+#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
+
+/* Function to create a new exception */
+PyAPI_FUNC(PyObject *) PyErr_NewException(
+ char *name, PyObject *base, PyObject *dict);
+PyAPI_FUNC(PyObject *) PyErr_NewExceptionWithDoc(
+ char *name, char *doc, PyObject *base, PyObject *dict);
+PyAPI_FUNC(void) PyErr_WriteUnraisable(PyObject *);
+
+/* In sigcheck.c or signalmodule.c */
+PyAPI_FUNC(int) PyErr_CheckSignals(void);
+PyAPI_FUNC(void) PyErr_SetInterrupt(void);
+
+/* In signalmodule.c */
+int PySignal_SetWakeupFd(int fd);
+
+/* Support for adding program text to SyntaxErrors */
+PyAPI_FUNC(void) PyErr_SyntaxLocation(const char *, int);
+PyAPI_FUNC(PyObject *) PyErr_ProgramText(const char *, int);
+
+#ifdef Py_USING_UNICODE
+/* The following functions are used to create and modify unicode
+ exceptions from C */
+
+/* create a UnicodeDecodeError object */
+PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_Create(
+ const char *, const char *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
+
+/* create a UnicodeEncodeError object */
+PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_Create(
+ const char *, const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
+
+/* create a UnicodeTranslateError object */
+PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_Create(
+ const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
+
+/* get the encoding attribute */
+PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetEncoding(PyObject *);
+PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_GetEncoding(PyObject *);
+
+/* get the object attribute */
+PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetObject(PyObject *);
+PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_GetObject(PyObject *);
+PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_GetObject(PyObject *);
+
+/* get the value of the start attribute (the int * may not be NULL)
+ return 0 on success, -1 on failure */
+PyAPI_FUNC(int) PyUnicodeEncodeError_GetStart(PyObject *, Py_ssize_t *);
+PyAPI_FUNC(int) PyUnicodeDecodeError_GetStart(PyObject *, Py_ssize_t *);
+PyAPI_FUNC(int) PyUnicodeTranslateError_GetStart(PyObject *, Py_ssize_t *);
+
+/* assign a new value to the start attribute
+ return 0 on success, -1 on failure */
+PyAPI_FUNC(int) PyUnicodeEncodeError_SetStart(PyObject *, Py_ssize_t);
+PyAPI_FUNC(int) PyUnicodeDecodeError_SetStart(PyObject *, Py_ssize_t);
+PyAPI_FUNC(int) PyUnicodeTranslateError_SetStart(PyObject *, Py_ssize_t);
+
+/* get the value of the end attribute (the int *may not be NULL)
+ return 0 on success, -1 on failure */
+PyAPI_FUNC(int) PyUnicodeEncodeError_GetEnd(PyObject *, Py_ssize_t *);
+PyAPI_FUNC(int) PyUnicodeDecodeError_GetEnd(PyObject *, Py_ssize_t *);
+PyAPI_FUNC(int) PyUnicodeTranslateError_GetEnd(PyObject *, Py_ssize_t *);
+
+/* assign a new value to the end attribute
+ return 0 on success, -1 on failure */
+PyAPI_FUNC(int) PyUnicodeEncodeError_SetEnd(PyObject *, Py_ssize_t);
+PyAPI_FUNC(int) PyUnicodeDecodeError_SetEnd(PyObject *, Py_ssize_t);
+PyAPI_FUNC(int) PyUnicodeTranslateError_SetEnd(PyObject *, Py_ssize_t);
+
+/* get the value of the reason attribute */
+PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetReason(PyObject *);
+PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_GetReason(PyObject *);
+PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_GetReason(PyObject *);
+
+/* assign a new value to the reason attribute
+ return 0 on success, -1 on failure */
+PyAPI_FUNC(int) PyUnicodeEncodeError_SetReason(
+ PyObject *, const char *);
+PyAPI_FUNC(int) PyUnicodeDecodeError_SetReason(
+ PyObject *, const char *);
+PyAPI_FUNC(int) PyUnicodeTranslateError_SetReason(
+ PyObject *, const char *);
+#endif
+
+
+/* These APIs aren't really part of the error implementation, but
+ often needed to format error messages; the native C lib APIs are
+ not available on all platforms, which is why we provide emulations
+ for those platforms in Python/mysnprintf.c,
+ WARNING: The return value of snprintf varies across platforms; do
+ not rely on any particular behavior; eventually the C99 defn may
+ be reliable.
+*/
+#if defined(MS_WIN32) && !defined(HAVE_SNPRINTF)
+# define HAVE_SNPRINTF
+# define snprintf _snprintf
+# define vsnprintf _vsnprintf
+#endif
+
+#include
+PyAPI_FUNC(int) PyOS_snprintf(char *str, size_t size, const char *format, ...)
+ Py_GCC_ATTRIBUTE((format(printf, 3, 4)));
+PyAPI_FUNC(int) PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
+ Py_GCC_ATTRIBUTE((format(printf, 3, 0)));
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_ERRORS_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pyexpat.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pyexpat.h
new file mode 100644
index 0000000000..fdce98862f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pyexpat.h
@@ -0,0 +1,48 @@
+/* Stuff to export relevant 'expat' entry points from pyexpat to other
+ * parser modules, such as cElementTree. */
+
+/* note: you must import expat.h before importing this module! */
+
+#define PyExpat_CAPI_MAGIC "pyexpat.expat_CAPI 1.0"
+#define PyExpat_CAPSULE_NAME "pyexpat.expat_CAPI"
+
+struct PyExpat_CAPI
+{
+ char* magic; /* set to PyExpat_CAPI_MAGIC */
+ int size; /* set to sizeof(struct PyExpat_CAPI) */
+ int MAJOR_VERSION;
+ int MINOR_VERSION;
+ int MICRO_VERSION;
+ /* pointers to selected expat functions. add new functions at
+ the end, if needed */
+ const XML_LChar * (*ErrorString)(enum XML_Error code);
+ enum XML_Error (*GetErrorCode)(XML_Parser parser);
+ XML_Size (*GetErrorColumnNumber)(XML_Parser parser);
+ XML_Size (*GetErrorLineNumber)(XML_Parser parser);
+ enum XML_Status (*Parse)(
+ XML_Parser parser, const char *s, int len, int isFinal);
+ XML_Parser (*ParserCreate_MM)(
+ const XML_Char *encoding, const XML_Memory_Handling_Suite *memsuite,
+ const XML_Char *namespaceSeparator);
+ void (*ParserFree)(XML_Parser parser);
+ void (*SetCharacterDataHandler)(
+ XML_Parser parser, XML_CharacterDataHandler handler);
+ void (*SetCommentHandler)(
+ XML_Parser parser, XML_CommentHandler handler);
+ void (*SetDefaultHandlerExpand)(
+ XML_Parser parser, XML_DefaultHandler handler);
+ void (*SetElementHandler)(
+ XML_Parser parser, XML_StartElementHandler start,
+ XML_EndElementHandler end);
+ void (*SetNamespaceDeclHandler)(
+ XML_Parser parser, XML_StartNamespaceDeclHandler start,
+ XML_EndNamespaceDeclHandler end);
+ void (*SetProcessingInstructionHandler)(
+ XML_Parser parser, XML_ProcessingInstructionHandler handler);
+ void (*SetUnknownEncodingHandler)(
+ XML_Parser parser, XML_UnknownEncodingHandler handler,
+ void *encodingHandlerData);
+ void (*SetUserData)(XML_Parser parser, void *userData);
+ /* always add new stuff to the end! */
+};
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pyfpe.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pyfpe.h
new file mode 100644
index 0000000000..4da66ef97a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pyfpe.h
@@ -0,0 +1,176 @@
+#ifndef Py_PYFPE_H
+#define Py_PYFPE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+/*
+ ---------------------------------------------------------------------
+ / Copyright (c) 1996. \
+ | The Regents of the University of California. |
+ | All rights reserved. |
+ | |
+ | Permission to use, copy, modify, and distribute this software for |
+ | any purpose without fee is hereby granted, provided that this en- |
+ | tire notice is included in all copies of any software which is or |
+ | includes a copy or modification of this software and in all |
+ | copies of the supporting documentation for such software. |
+ | |
+ | This work was produced at the University of California, Lawrence |
+ | Livermore National Laboratory under contract no. W-7405-ENG-48 |
+ | between the U.S. Department of Energy and The Regents of the |
+ | University of California for the operation of UC LLNL. |
+ | |
+ | DISCLAIMER |
+ | |
+ | This software was prepared as an account of work sponsored by an |
+ | agency of the United States Government. Neither the United States |
+ | Government nor the University of California nor any of their em- |
+ | ployees, makes any warranty, express or implied, or assumes any |
+ | liability or responsibility for the accuracy, completeness, or |
+ | usefulness of any information, apparatus, product, or process |
+ | disclosed, or represents that its use would not infringe |
+ | privately-owned rights. Reference herein to any specific commer- |
+ | cial products, process, or service by trade name, trademark, |
+ | manufacturer, or otherwise, does not necessarily constitute or |
+ | imply its endorsement, recommendation, or favoring by the United |
+ | States Government or the University of California. The views and |
+ | opinions of authors expressed herein do not necessarily state or |
+ | reflect those of the United States Government or the University |
+ | of California, and shall not be used for advertising or product |
+ \ endorsement purposes. /
+ ---------------------------------------------------------------------
+*/
+
+/*
+ * Define macros for handling SIGFPE.
+ * Lee Busby, LLNL, November, 1996
+ * busby1@llnl.gov
+ *
+ *********************************************
+ * Overview of the system for handling SIGFPE:
+ *
+ * This file (Include/pyfpe.h) defines a couple of "wrapper" macros for
+ * insertion into your Python C code of choice. Their proper use is
+ * discussed below. The file Python/pyfpe.c defines a pair of global
+ * variables PyFPE_jbuf and PyFPE_counter which are used by the signal
+ * handler for SIGFPE to decide if a particular exception was protected
+ * by the macros. The signal handler itself, and code for enabling the
+ * generation of SIGFPE in the first place, is in a (new) Python module
+ * named fpectl. This module is standard in every respect. It can be loaded
+ * either statically or dynamically as you choose, and like any other
+ * Python module, has no effect until you import it.
+ *
+ * In the general case, there are three steps toward handling SIGFPE in any
+ * Python code:
+ *
+ * 1) Add the *_PROTECT macros to your C code as required to protect
+ * dangerous floating point sections.
+ *
+ * 2) Turn on the inclusion of the code by adding the ``--with-fpectl''
+ * flag at the time you run configure. If the fpectl or other modules
+ * which use the *_PROTECT macros are to be dynamically loaded, be
+ * sure they are compiled with WANT_SIGFPE_HANDLER defined.
+ *
+ * 3) When python is built and running, import fpectl, and execute
+ * fpectl.turnon_sigfpe(). This sets up the signal handler and enables
+ * generation of SIGFPE whenever an exception occurs. From this point
+ * on, any properly trapped SIGFPE should result in the Python
+ * FloatingPointError exception.
+ *
+ * Step 1 has been done already for the Python kernel code, and should be
+ * done soon for the NumPy array package. Step 2 is usually done once at
+ * python install time. Python's behavior with respect to SIGFPE is not
+ * changed unless you also do step 3. Thus you can control this new
+ * facility at compile time, or run time, or both.
+ *
+ ********************************
+ * Using the macros in your code:
+ *
+ * static PyObject *foobar(PyObject *self,PyObject *args)
+ * {
+ * ....
+ * PyFPE_START_PROTECT("Error in foobar", return 0)
+ * result = dangerous_op(somearg1, somearg2, ...);
+ * PyFPE_END_PROTECT(result)
+ * ....
+ * }
+ *
+ * If a floating point error occurs in dangerous_op, foobar returns 0 (NULL),
+ * after setting the associated value of the FloatingPointError exception to
+ * "Error in foobar". ``Dangerous_op'' can be a single operation, or a block
+ * of code, function calls, or any combination, so long as no alternate
+ * return is possible before the PyFPE_END_PROTECT macro is reached.
+ *
+ * The macros can only be used in a function context where an error return
+ * can be recognized as signaling a Python exception. (Generally, most
+ * functions that return a PyObject * will qualify.)
+ *
+ * Guido's original design suggestion for PyFPE_START_PROTECT and
+ * PyFPE_END_PROTECT had them open and close a local block, with a locally
+ * defined jmp_buf and jmp_buf pointer. This would allow recursive nesting
+ * of the macros. The Ansi C standard makes it clear that such local
+ * variables need to be declared with the "volatile" type qualifier to keep
+ * setjmp from corrupting their values. Some current implementations seem
+ * to be more restrictive. For example, the HPUX man page for setjmp says
+ *
+ * Upon the return from a setjmp() call caused by a longjmp(), the
+ * values of any non-static local variables belonging to the routine
+ * from which setjmp() was called are undefined. Code which depends on
+ * such values is not guaranteed to be portable.
+ *
+ * I therefore decided on a more limited form of nesting, using a counter
+ * variable (PyFPE_counter) to keep track of any recursion. If an exception
+ * occurs in an ``inner'' pair of macros, the return will apparently
+ * come from the outermost level.
+ *
+ */
+
+#ifdef WANT_SIGFPE_HANDLER
+#include
+#include
+#include
+extern jmp_buf PyFPE_jbuf;
+extern int PyFPE_counter;
+extern double PyFPE_dummy(void *);
+
+#define PyFPE_START_PROTECT(err_string, leave_stmt) \
+if (!PyFPE_counter++ && setjmp(PyFPE_jbuf)) { \
+ PyErr_SetString(PyExc_FloatingPointError, err_string); \
+ PyFPE_counter = 0; \
+ leave_stmt; \
+}
+
+/*
+ * This (following) is a heck of a way to decrement a counter. However,
+ * unless the macro argument is provided, code optimizers will sometimes move
+ * this statement so that it gets executed *before* the unsafe expression
+ * which we're trying to protect. That pretty well messes things up,
+ * of course.
+ *
+ * If the expression(s) you're trying to protect don't happen to return a
+ * value, you will need to manufacture a dummy result just to preserve the
+ * correct ordering of statements. Note that the macro passes the address
+ * of its argument (so you need to give it something which is addressable).
+ * If your expression returns multiple results, pass the last such result
+ * to PyFPE_END_PROTECT.
+ *
+ * Note that PyFPE_dummy returns a double, which is cast to int.
+ * This seeming insanity is to tickle the Floating Point Unit (FPU).
+ * If an exception has occurred in a preceding floating point operation,
+ * some architectures (notably Intel 80x86) will not deliver the interrupt
+ * until the *next* floating point operation. This is painful if you've
+ * already decremented PyFPE_counter.
+ */
+#define PyFPE_END_PROTECT(v) PyFPE_counter -= (int)PyFPE_dummy(&(v));
+
+#else
+
+#define PyFPE_START_PROTECT(err_string, leave_stmt)
+#define PyFPE_END_PROTECT(v)
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_PYFPE_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pygetopt.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pygetopt.h
new file mode 100644
index 0000000000..8031346d0d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pygetopt.h
@@ -0,0 +1,17 @@
+
+#ifndef Py_PYGETOPT_H
+#define Py_PYGETOPT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_DATA(int) _PyOS_opterr;
+PyAPI_DATA(int) _PyOS_optind;
+PyAPI_DATA(char *) _PyOS_optarg;
+
+PyAPI_FUNC(int) _PyOS_GetOpt(int argc, char **argv, char *optstring);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_PYGETOPT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pymacconfig.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pymacconfig.h
new file mode 100644
index 0000000000..f647b478ca
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pymacconfig.h
@@ -0,0 +1,102 @@
+#ifndef PYMACCONFIG_H
+#define PYMACCONFIG_H
+ /*
+ * This file moves some of the autoconf magic to compile-time
+ * when building on MacOSX. This is needed for building 4-way
+ * universal binaries and for 64-bit universal binaries because
+ * the values redefined below aren't configure-time constant but
+ * only compile-time constant in these scenarios.
+ */
+
+#if defined(__APPLE__)
+
+# undef SIZEOF_LONG
+# undef SIZEOF_PTHREAD_T
+# undef SIZEOF_SIZE_T
+# undef SIZEOF_TIME_T
+# undef SIZEOF_VOID_P
+# undef SIZEOF__BOOL
+# undef SIZEOF_UINTPTR_T
+# undef SIZEOF_PTHREAD_T
+# undef WORDS_BIGENDIAN
+# undef DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754
+# undef DOUBLE_IS_BIG_ENDIAN_IEEE754
+# undef DOUBLE_IS_LITTLE_ENDIAN_IEEE754
+# undef HAVE_GCC_ASM_FOR_X87
+
+# undef VA_LIST_IS_ARRAY
+# if defined(__LP64__) && defined(__x86_64__)
+# define VA_LIST_IS_ARRAY 1
+# endif
+
+# undef HAVE_LARGEFILE_SUPPORT
+# ifndef __LP64__
+# define HAVE_LARGEFILE_SUPPORT 1
+# endif
+
+# undef SIZEOF_LONG
+# ifdef __LP64__
+# define SIZEOF__BOOL 1
+# define SIZEOF__BOOL 1
+# define SIZEOF_LONG 8
+# define SIZEOF_PTHREAD_T 8
+# define SIZEOF_SIZE_T 8
+# define SIZEOF_TIME_T 8
+# define SIZEOF_VOID_P 8
+# define SIZEOF_UINTPTR_T 8
+# define SIZEOF_PTHREAD_T 8
+# else
+# ifdef __ppc__
+# define SIZEOF__BOOL 4
+# else
+# define SIZEOF__BOOL 1
+# endif
+# define SIZEOF_LONG 4
+# define SIZEOF_PTHREAD_T 4
+# define SIZEOF_SIZE_T 4
+# define SIZEOF_TIME_T 4
+# define SIZEOF_VOID_P 4
+# define SIZEOF_UINTPTR_T 4
+# define SIZEOF_PTHREAD_T 4
+# endif
+
+# if defined(__LP64__)
+ /* MacOSX 10.4 (the first release to support 64-bit code
+ * at all) only supports 64-bit in the UNIX layer.
+ * Therefore surpress the toolbox-glue in 64-bit mode.
+ */
+
+ /* In 64-bit mode setpgrp always has no argments, in 32-bit
+ * mode that depends on the compilation environment
+ */
+# undef SETPGRP_HAVE_ARG
+
+# endif
+
+#ifdef __BIG_ENDIAN__
+#define WORDS_BIGENDIAN 1
+#define DOUBLE_IS_BIG_ENDIAN_IEEE754
+#else
+#define DOUBLE_IS_LITTLE_ENDIAN_IEEE754
+#endif /* __BIG_ENDIAN */
+
+#ifdef __i386__
+# define HAVE_GCC_ASM_FOR_X87
+#endif
+
+ /*
+ * The definition in pyconfig.h is only valid on the OS release
+ * where configure ran on and not necessarily for all systems where
+ * the executable can be used on.
+ *
+ * Specifically: OSX 10.4 has limited supported for '%zd', while
+ * 10.5 has full support for '%zd'. A binary built on 10.5 won't
+ * work properly on 10.4 unless we surpress the definition
+ * of PY_FORMAT_SIZE_T
+ */
+#undef PY_FORMAT_SIZE_T
+
+
+#endif /* defined(_APPLE__) */
+
+#endif /* PYMACCONFIG_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pymactoolbox.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pymactoolbox.h
new file mode 100644
index 0000000000..a0ac1c26b7
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pymactoolbox.h
@@ -0,0 +1,217 @@
+/*
+** pymactoolbox.h - globals defined in mactoolboxglue.c
+*/
+#ifndef Py_PYMACTOOLBOX_H
+#define Py_PYMACTOOLBOX_H
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#include
+
+#ifndef __LP64__
+#include
+#endif /* !__LP64__ */
+
+/*
+** Helper routines for error codes and such.
+*/
+char *PyMac_StrError(int); /* strerror with mac errors */
+extern PyObject *PyMac_OSErrException; /* Exception for OSErr */
+PyObject *PyMac_GetOSErrException(void); /* Initialize & return it */
+PyObject *PyErr_Mac(PyObject *, int); /* Exception with a mac error */
+PyObject *PyMac_Error(OSErr); /* Uses PyMac_GetOSErrException */
+#ifndef __LP64__
+extern OSErr PyMac_GetFullPathname(FSSpec *, char *, int); /* convert
+ fsspec->path */
+#endif /* __LP64__ */
+
+/*
+** These conversion routines are defined in mactoolboxglue.c itself.
+*/
+int PyMac_GetOSType(PyObject *, OSType *); /* argument parser for OSType */
+PyObject *PyMac_BuildOSType(OSType); /* Convert OSType to PyObject */
+
+PyObject *PyMac_BuildNumVersion(NumVersion);/* Convert NumVersion to PyObject */
+
+int PyMac_GetStr255(PyObject *, Str255); /* argument parser for Str255 */
+PyObject *PyMac_BuildStr255(Str255); /* Convert Str255 to PyObject */
+PyObject *PyMac_BuildOptStr255(Str255); /* Convert Str255 to PyObject,
+ NULL to None */
+
+int PyMac_GetRect(PyObject *, Rect *); /* argument parser for Rect */
+PyObject *PyMac_BuildRect(Rect *); /* Convert Rect to PyObject */
+
+int PyMac_GetPoint(PyObject *, Point *); /* argument parser for Point */
+PyObject *PyMac_BuildPoint(Point); /* Convert Point to PyObject */
+
+int PyMac_GetEventRecord(PyObject *, EventRecord *); /* argument parser for
+ EventRecord */
+PyObject *PyMac_BuildEventRecord(EventRecord *); /* Convert EventRecord to
+ PyObject */
+
+int PyMac_GetFixed(PyObject *, Fixed *); /* argument parser for Fixed */
+PyObject *PyMac_BuildFixed(Fixed); /* Convert Fixed to PyObject */
+int PyMac_Getwide(PyObject *, wide *); /* argument parser for wide */
+PyObject *PyMac_Buildwide(wide *); /* Convert wide to PyObject */
+
+/*
+** The rest of the routines are implemented by extension modules. If they are
+** dynamically loaded mactoolboxglue will contain a stub implementation of the
+** routine, which imports the module, whereupon the module's init routine will
+** communicate the routine pointer back to the stub.
+** If USE_TOOLBOX_OBJECT_GLUE is not defined there is no glue code, and the
+** extension modules simply declare the routine. This is the case for static
+** builds (and could be the case for MacPython CFM builds, because CFM extension
+** modules can reference each other without problems).
+*/
+
+#ifdef USE_TOOLBOX_OBJECT_GLUE
+/*
+** These macros are used in the module init code. If we use toolbox object glue
+** it sets the function pointer to point to the real function.
+*/
+#define PyMac_INIT_TOOLBOX_OBJECT_NEW(object, rtn) { \
+ extern PyObject *(*PyMacGluePtr_##rtn)(object); \
+ PyMacGluePtr_##rtn = _##rtn; \
+}
+#define PyMac_INIT_TOOLBOX_OBJECT_CONVERT(object, rtn) { \
+ extern int (*PyMacGluePtr_##rtn)(PyObject *, object *); \
+ PyMacGluePtr_##rtn = _##rtn; \
+}
+#else
+/*
+** If we don't use toolbox object glue the init macros are empty. Moreover, we define
+** _xxx_New to be the same as xxx_New, and the code in mactoolboxglue isn't included.
+*/
+#define PyMac_INIT_TOOLBOX_OBJECT_NEW(object, rtn)
+#define PyMac_INIT_TOOLBOX_OBJECT_CONVERT(object, rtn)
+#endif /* USE_TOOLBOX_OBJECT_GLUE */
+
+/* macfs exports */
+#ifndef __LP64__
+int PyMac_GetFSSpec(PyObject *, FSSpec *); /* argument parser for FSSpec */
+PyObject *PyMac_BuildFSSpec(FSSpec *); /* Convert FSSpec to PyObject */
+#endif /* !__LP64__ */
+
+int PyMac_GetFSRef(PyObject *, FSRef *); /* argument parser for FSRef */
+PyObject *PyMac_BuildFSRef(FSRef *); /* Convert FSRef to PyObject */
+
+/* AE exports */
+extern PyObject *AEDesc_New(AppleEvent *); /* XXXX Why passed by address?? */
+extern PyObject *AEDesc_NewBorrowed(AppleEvent *);
+extern int AEDesc_Convert(PyObject *, AppleEvent *);
+
+/* Cm exports */
+extern PyObject *CmpObj_New(Component);
+extern int CmpObj_Convert(PyObject *, Component *);
+extern PyObject *CmpInstObj_New(ComponentInstance);
+extern int CmpInstObj_Convert(PyObject *, ComponentInstance *);
+
+/* Ctl exports */
+#ifndef __LP64__
+extern PyObject *CtlObj_New(ControlHandle);
+extern int CtlObj_Convert(PyObject *, ControlHandle *);
+#endif /* !__LP64__ */
+
+/* Dlg exports */
+#ifndef __LP64__
+extern PyObject *DlgObj_New(DialogPtr);
+extern int DlgObj_Convert(PyObject *, DialogPtr *);
+extern PyObject *DlgObj_WhichDialog(DialogPtr);
+#endif /* !__LP64__ */
+
+/* Drag exports */
+#ifndef __LP64__
+extern PyObject *DragObj_New(DragReference);
+extern int DragObj_Convert(PyObject *, DragReference *);
+#endif /* !__LP64__ */
+
+/* List exports */
+#ifndef __LP64__
+extern PyObject *ListObj_New(ListHandle);
+extern int ListObj_Convert(PyObject *, ListHandle *);
+#endif /* !__LP64__ */
+
+/* Menu exports */
+#ifndef __LP64__
+extern PyObject *MenuObj_New(MenuHandle);
+extern int MenuObj_Convert(PyObject *, MenuHandle *);
+#endif /* !__LP64__ */
+
+/* Qd exports */
+#ifndef __LP64__
+extern PyObject *GrafObj_New(GrafPtr);
+extern int GrafObj_Convert(PyObject *, GrafPtr *);
+extern PyObject *BMObj_New(BitMapPtr);
+extern int BMObj_Convert(PyObject *, BitMapPtr *);
+extern PyObject *QdRGB_New(RGBColor *);
+extern int QdRGB_Convert(PyObject *, RGBColor *);
+#endif /* !__LP64__ */
+
+/* Qdoffs exports */
+#ifndef __LP64__
+extern PyObject *GWorldObj_New(GWorldPtr);
+extern int GWorldObj_Convert(PyObject *, GWorldPtr *);
+#endif /* !__LP64__ */
+
+/* Qt exports */
+#ifndef __LP64__
+extern PyObject *TrackObj_New(Track);
+extern int TrackObj_Convert(PyObject *, Track *);
+extern PyObject *MovieObj_New(Movie);
+extern int MovieObj_Convert(PyObject *, Movie *);
+extern PyObject *MovieCtlObj_New(MovieController);
+extern int MovieCtlObj_Convert(PyObject *, MovieController *);
+extern PyObject *TimeBaseObj_New(TimeBase);
+extern int TimeBaseObj_Convert(PyObject *, TimeBase *);
+extern PyObject *UserDataObj_New(UserData);
+extern int UserDataObj_Convert(PyObject *, UserData *);
+extern PyObject *MediaObj_New(Media);
+extern int MediaObj_Convert(PyObject *, Media *);
+#endif /* !__LP64__ */
+
+/* Res exports */
+extern PyObject *ResObj_New(Handle);
+extern int ResObj_Convert(PyObject *, Handle *);
+extern PyObject *OptResObj_New(Handle);
+extern int OptResObj_Convert(PyObject *, Handle *);
+
+/* TE exports */
+#ifndef __LP64__
+extern PyObject *TEObj_New(TEHandle);
+extern int TEObj_Convert(PyObject *, TEHandle *);
+#endif /* !__LP64__ */
+
+/* Win exports */
+#ifndef __LP64__
+extern PyObject *WinObj_New(WindowPtr);
+extern int WinObj_Convert(PyObject *, WindowPtr *);
+extern PyObject *WinObj_WhichWindow(WindowPtr);
+#endif /* !__LP64__ */
+
+/* CF exports */
+extern PyObject *CFObj_New(CFTypeRef);
+extern int CFObj_Convert(PyObject *, CFTypeRef *);
+extern PyObject *CFTypeRefObj_New(CFTypeRef);
+extern int CFTypeRefObj_Convert(PyObject *, CFTypeRef *);
+extern PyObject *CFStringRefObj_New(CFStringRef);
+extern int CFStringRefObj_Convert(PyObject *, CFStringRef *);
+extern PyObject *CFMutableStringRefObj_New(CFMutableStringRef);
+extern int CFMutableStringRefObj_Convert(PyObject *, CFMutableStringRef *);
+extern PyObject *CFArrayRefObj_New(CFArrayRef);
+extern int CFArrayRefObj_Convert(PyObject *, CFArrayRef *);
+extern PyObject *CFMutableArrayRefObj_New(CFMutableArrayRef);
+extern int CFMutableArrayRefObj_Convert(PyObject *, CFMutableArrayRef *);
+extern PyObject *CFDictionaryRefObj_New(CFDictionaryRef);
+extern int CFDictionaryRefObj_Convert(PyObject *, CFDictionaryRef *);
+extern PyObject *CFMutableDictionaryRefObj_New(CFMutableDictionaryRef);
+extern int CFMutableDictionaryRefObj_Convert(PyObject *, CFMutableDictionaryRef *);
+extern PyObject *CFURLRefObj_New(CFURLRef);
+extern int CFURLRefObj_Convert(PyObject *, CFURLRef *);
+extern int OptionalCFURLRefObj_Convert(PyObject *, CFURLRef *);
+
+#ifdef __cplusplus
+ }
+#endif
+#endif
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pymath.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pymath.h
new file mode 100644
index 0000000000..f63ddb7a69
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pymath.h
@@ -0,0 +1,192 @@
+#ifndef Py_PYMATH_H
+#define Py_PYMATH_H
+
+#include "pyconfig.h" /* include for defines */
+
+/**************************************************************************
+Symbols and macros to supply platform-independent interfaces to mathematical
+functions and constants
+**************************************************************************/
+
+/* Python provides implementations for copysign, round and hypot in
+ * Python/pymath.c just in case your math library doesn't provide the
+ * functions.
+ *
+ *Note: PC/pyconfig.h defines copysign as _copysign
+ */
+#ifndef HAVE_COPYSIGN
+extern double copysign(double, double);
+#endif
+
+#ifndef HAVE_ROUND
+extern double round(double);
+#endif
+
+#ifndef HAVE_HYPOT
+extern double hypot(double, double);
+#endif
+
+/* extra declarations */
+#ifndef _MSC_VER
+#ifndef __STDC__
+extern double fmod (double, double);
+extern double frexp (double, int *);
+extern double ldexp (double, int);
+extern double modf (double, double *);
+extern double pow(double, double);
+#endif /* __STDC__ */
+#endif /* _MSC_VER */
+
+#ifdef _OSF_SOURCE
+/* OSF1 5.1 doesn't make these available with XOPEN_SOURCE_EXTENDED defined */
+extern int finite(double);
+extern double copysign(double, double);
+#endif
+
+/* High precision defintion of pi and e (Euler)
+ * The values are taken from libc6's math.h.
+ */
+#ifndef Py_MATH_PIl
+#define Py_MATH_PIl 3.1415926535897932384626433832795029L
+#endif
+#ifndef Py_MATH_PI
+#define Py_MATH_PI 3.14159265358979323846
+#endif
+
+#ifndef Py_MATH_El
+#define Py_MATH_El 2.7182818284590452353602874713526625L
+#endif
+
+#ifndef Py_MATH_E
+#define Py_MATH_E 2.7182818284590452354
+#endif
+
+/* On x86, Py_FORCE_DOUBLE forces a floating-point number out of an x87 FPU
+ register and into a 64-bit memory location, rounding from extended
+ precision to double precision in the process. On other platforms it does
+ nothing. */
+
+/* we take double rounding as evidence of x87 usage */
+#ifndef Py_FORCE_DOUBLE
+# ifdef X87_DOUBLE_ROUNDING
+PyAPI_FUNC(double) _Py_force_double(double);
+# define Py_FORCE_DOUBLE(X) (_Py_force_double(X))
+# else
+# define Py_FORCE_DOUBLE(X) (X)
+# endif
+#endif
+
+#ifdef HAVE_GCC_ASM_FOR_X87
+PyAPI_FUNC(unsigned short) _Py_get_387controlword(void);
+PyAPI_FUNC(void) _Py_set_387controlword(unsigned short);
+#endif
+
+/* Py_IS_NAN(X)
+ * Return 1 if float or double arg is a NaN, else 0.
+ * Caution:
+ * X is evaluated more than once.
+ * This may not work on all platforms. Each platform has *some*
+ * way to spell this, though -- override in pyconfig.h if you have
+ * a platform where it doesn't work.
+ * Note: PC/pyconfig.h defines Py_IS_NAN as _isnan
+ */
+#ifndef Py_IS_NAN
+#if defined HAVE_DECL_ISNAN && HAVE_DECL_ISNAN == 1
+#define Py_IS_NAN(X) isnan(X)
+#else
+#define Py_IS_NAN(X) ((X) != (X))
+#endif
+#endif
+
+/* Py_IS_INFINITY(X)
+ * Return 1 if float or double arg is an infinity, else 0.
+ * Caution:
+ * X is evaluated more than once.
+ * This implementation may set the underflow flag if |X| is very small;
+ * it really can't be implemented correctly (& easily) before C99.
+ * Override in pyconfig.h if you have a better spelling on your platform.
+ * Py_FORCE_DOUBLE is used to avoid getting false negatives from a
+ * non-infinite value v sitting in an 80-bit x87 register such that
+ * v becomes infinite when spilled from the register to 64-bit memory.
+ * Note: PC/pyconfig.h defines Py_IS_INFINITY as _isinf
+ */
+#ifndef Py_IS_INFINITY
+# if defined HAVE_DECL_ISINF && HAVE_DECL_ISINF == 1
+# define Py_IS_INFINITY(X) isinf(X)
+# else
+# define Py_IS_INFINITY(X) ((X) && \
+ (Py_FORCE_DOUBLE(X)*0.5 == Py_FORCE_DOUBLE(X)))
+# endif
+#endif
+
+/* Py_IS_FINITE(X)
+ * Return 1 if float or double arg is neither infinite nor NAN, else 0.
+ * Some compilers (e.g. VisualStudio) have intrisics for this, so a special
+ * macro for this particular test is useful
+ * Note: PC/pyconfig.h defines Py_IS_FINITE as _finite
+ */
+#ifndef Py_IS_FINITE
+#if defined HAVE_DECL_ISFINITE && HAVE_DECL_ISFINITE == 1
+#define Py_IS_FINITE(X) isfinite(X)
+#elif defined HAVE_FINITE
+#define Py_IS_FINITE(X) finite(X)
+#else
+#define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X))
+#endif
+#endif
+
+/* HUGE_VAL is supposed to expand to a positive double infinity. Python
+ * uses Py_HUGE_VAL instead because some platforms are broken in this
+ * respect. We used to embed code in pyport.h to try to worm around that,
+ * but different platforms are broken in conflicting ways. If you're on
+ * a platform where HUGE_VAL is defined incorrectly, fiddle your Python
+ * config to #define Py_HUGE_VAL to something that works on your platform.
+ */
+#ifndef Py_HUGE_VAL
+#define Py_HUGE_VAL HUGE_VAL
+#endif
+
+/* Py_NAN
+ * A value that evaluates to a NaN. On IEEE 754 platforms INF*0 or
+ * INF/INF works. Define Py_NO_NAN in pyconfig.h if your platform
+ * doesn't support NaNs.
+ */
+#if !defined(Py_NAN) && !defined(Py_NO_NAN)
+#define Py_NAN (Py_HUGE_VAL * 0.)
+#endif
+
+/* Py_OVERFLOWED(X)
+ * Return 1 iff a libm function overflowed. Set errno to 0 before calling
+ * a libm function, and invoke this macro after, passing the function
+ * result.
+ * Caution:
+ * This isn't reliable. C99 no longer requires libm to set errno under
+ * any exceptional condition, but does require +- HUGE_VAL return
+ * values on overflow. A 754 box *probably* maps HUGE_VAL to a
+ * double infinity, and we're cool if that's so, unless the input
+ * was an infinity and an infinity is the expected result. A C89
+ * system sets errno to ERANGE, so we check for that too. We're
+ * out of luck if a C99 754 box doesn't map HUGE_VAL to +Inf, or
+ * if the returned result is a NaN, or if a C89 box returns HUGE_VAL
+ * in non-overflow cases.
+ * X is evaluated more than once.
+ * Some platforms have better way to spell this, so expect some #ifdef'ery.
+ *
+ * OpenBSD uses 'isinf()' because a compiler bug on that platform causes
+ * the longer macro version to be mis-compiled. This isn't optimal, and
+ * should be removed once a newer compiler is available on that platform.
+ * The system that had the failure was running OpenBSD 3.2 on Intel, with
+ * gcc 2.95.3.
+ *
+ * According to Tim's checkin, the FreeBSD systems use isinf() to work
+ * around a FPE bug on that platform.
+ */
+#if defined(__FreeBSD__) || defined(__OpenBSD__)
+#define Py_OVERFLOWED(X) isinf(X)
+#else
+#define Py_OVERFLOWED(X) ((X) != 0.0 && (errno == ERANGE || \
+ (X) == Py_HUGE_VAL || \
+ (X) == -Py_HUGE_VAL))
+#endif
+
+#endif /* Py_PYMATH_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pymem.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pymem.h
new file mode 100644
index 0000000000..27c72f132f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pymem.h
@@ -0,0 +1,122 @@
+/* The PyMem_ family: low-level memory allocation interfaces.
+ See objimpl.h for the PyObject_ memory family.
+*/
+
+#ifndef Py_PYMEM_H
+#define Py_PYMEM_H
+
+#include "pyport.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* BEWARE:
+
+ Each interface exports both functions and macros. Extension modules should
+ use the functions, to ensure binary compatibility across Python versions.
+ Because the Python implementation is free to change internal details, and
+ the macros may (or may not) expose details for speed, if you do use the
+ macros you must recompile your extensions with each Python release.
+
+ Never mix calls to PyMem_ with calls to the platform malloc/realloc/
+ calloc/free. For example, on Windows different DLLs may end up using
+ different heaps, and if you use PyMem_Malloc you'll get the memory from the
+ heap used by the Python DLL; it could be a disaster if you free()'ed that
+ directly in your own extension. Using PyMem_Free instead ensures Python
+ can return the memory to the proper heap. As another example, in
+ PYMALLOC_DEBUG mode, Python wraps all calls to all PyMem_ and PyObject_
+ memory functions in special debugging wrappers that add additional
+ debugging info to dynamic memory blocks. The system routines have no idea
+ what to do with that stuff, and the Python wrappers have no idea what to do
+ with raw blocks obtained directly by the system routines then.
+
+ The GIL must be held when using these APIs.
+*/
+
+/*
+ * Raw memory interface
+ * ====================
+ */
+
+/* Functions
+
+ Functions supplying platform-independent semantics for malloc/realloc/
+ free. These functions make sure that allocating 0 bytes returns a distinct
+ non-NULL pointer (whenever possible -- if we're flat out of memory, NULL
+ may be returned), even if the platform malloc and realloc don't.
+ Returned pointers must be checked for NULL explicitly. No action is
+ performed on failure (no exception is set, no warning is printed, etc).
+*/
+
+PyAPI_FUNC(void *) PyMem_Malloc(size_t);
+PyAPI_FUNC(void *) PyMem_Realloc(void *, size_t);
+PyAPI_FUNC(void) PyMem_Free(void *);
+
+/* Starting from Python 1.6, the wrappers Py_{Malloc,Realloc,Free} are
+ no longer supported. They used to call PyErr_NoMemory() on failure. */
+
+/* Macros. */
+#ifdef PYMALLOC_DEBUG
+/* Redirect all memory operations to Python's debugging allocator. */
+#define PyMem_MALLOC _PyMem_DebugMalloc
+#define PyMem_REALLOC _PyMem_DebugRealloc
+#define PyMem_FREE _PyMem_DebugFree
+
+#else /* ! PYMALLOC_DEBUG */
+
+/* PyMem_MALLOC(0) means malloc(1). Some systems would return NULL
+ for malloc(0), which would be treated as an error. Some platforms
+ would return a pointer with no memory behind it, which would break
+ pymalloc. To solve these problems, allocate an extra byte. */
+/* Returns NULL to indicate error if a negative size or size larger than
+ Py_ssize_t can represent is supplied. Helps prevents security holes. */
+#define PyMem_MALLOC(n) ((size_t)(n) > (size_t)PY_SSIZE_T_MAX ? NULL \
+ : malloc((n) ? (n) : 1))
+#define PyMem_REALLOC(p, n) ((size_t)(n) > (size_t)PY_SSIZE_T_MAX ? NULL \
+ : realloc((p), (n) ? (n) : 1))
+#define PyMem_FREE free
+
+#endif /* PYMALLOC_DEBUG */
+
+/*
+ * Type-oriented memory interface
+ * ==============================
+ *
+ * Allocate memory for n objects of the given type. Returns a new pointer
+ * or NULL if the request was too large or memory allocation failed. Use
+ * these macros rather than doing the multiplication yourself so that proper
+ * overflow checking is always done.
+ */
+
+#define PyMem_New(type, n) \
+ ( ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \
+ ( (type *) PyMem_Malloc((n) * sizeof(type)) ) )
+#define PyMem_NEW(type, n) \
+ ( ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \
+ ( (type *) PyMem_MALLOC((n) * sizeof(type)) ) )
+
+/*
+ * The value of (p) is always clobbered by this macro regardless of success.
+ * The caller MUST check if (p) is NULL afterwards and deal with the memory
+ * error if so. This means the original value of (p) MUST be saved for the
+ * caller's memory error handler to not lose track of it.
+ */
+#define PyMem_Resize(p, type, n) \
+ ( (p) = ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \
+ (type *) PyMem_Realloc((p), (n) * sizeof(type)) )
+#define PyMem_RESIZE(p, type, n) \
+ ( (p) = ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \
+ (type *) PyMem_REALLOC((p), (n) * sizeof(type)) )
+
+/* PyMem{Del,DEL} are left over from ancient days, and shouldn't be used
+ * anymore. They're just confusing aliases for PyMem_{Free,FREE} now.
+ */
+#define PyMem_Del PyMem_Free
+#define PyMem_DEL PyMem_FREE
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !Py_PYMEM_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pyport.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pyport.h
new file mode 100644
index 0000000000..d1494d3971
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pyport.h
@@ -0,0 +1,918 @@
+/** @file
+ Symbols and macros to supply platform-independent interfaces to basic
+ C language & library operations whose spellings vary across platforms.
+
+ Copyright (c) 2011, Intel Corporation. All rights reserved.
+ This program and the accompanying materials are licensed and made available under
+ the terms and conditions of the BSD License that accompanies this distribution.
+ The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+**/
+#ifndef Py_PYPORT_H
+#define Py_PYPORT_H
+
+#include "pyconfig.h" /* include for defines */
+
+/* Some versions of HP-UX & Solaris need inttypes.h for int32_t,
+ INT32_MAX, etc. */
+#ifdef HAVE_INTTYPES_H
+#include
+#endif
+
+#ifdef HAVE_STDINT_H
+#include
+#endif
+
+/**************************************************************************
+Symbols and macros to supply platform-independent interfaces to basic
+C language & library operations whose spellings vary across platforms.
+
+Please try to make documentation here as clear as possible: by definition,
+the stuff here is trying to illuminate C's darkest corners.
+
+Config #defines referenced here:
+
+SIGNED_RIGHT_SHIFT_ZERO_FILLS
+Meaning: To be defined iff i>>j does not extend the sign bit when i is a
+ signed integral type and i < 0.
+Used in: Py_ARITHMETIC_RIGHT_SHIFT
+
+Py_DEBUG
+Meaning: Extra checks compiled in for debug mode.
+Used in: Py_SAFE_DOWNCAST
+
+HAVE_UINTPTR_T
+Meaning: The C9X type uintptr_t is supported by the compiler
+Used in: Py_uintptr_t
+
+HAVE_LONG_LONG
+Meaning: The compiler supports the C type "long long"
+Used in: PY_LONG_LONG
+
+**************************************************************************/
+
+
+/* For backward compatibility only. Obsolete, do not use. */
+#ifdef HAVE_PROTOTYPES
+#define Py_PROTO(x) x
+#else
+#define Py_PROTO(x) ()
+#endif
+#ifndef Py_FPROTO
+#define Py_FPROTO(x) Py_PROTO(x)
+#endif
+
+/* typedefs for some C9X-defined synonyms for integral types.
+ *
+ * The names in Python are exactly the same as the C9X names, except with a
+ * Py_ prefix. Until C9X is universally implemented, this is the only way
+ * to ensure that Python gets reliable names that don't conflict with names
+ * in non-Python code that are playing their own tricks to define the C9X
+ * names.
+ *
+ * NOTE: don't go nuts here! Python has no use for *most* of the C9X
+ * integral synonyms. Only define the ones we actually need.
+ */
+
+#ifdef HAVE_LONG_LONG
+#ifndef PY_LONG_LONG
+#define PY_LONG_LONG long long
+#if defined(LLONG_MAX)
+/* If LLONG_MAX is defined in limits.h, use that. */
+#define PY_LLONG_MIN LLONG_MIN
+#define PY_LLONG_MAX LLONG_MAX
+#define PY_ULLONG_MAX ULLONG_MAX
+#elif defined(__LONG_LONG_MAX__)
+/* Otherwise, if GCC has a builtin define, use that. */
+#define PY_LLONG_MAX __LONG_LONG_MAX__
+#define PY_LLONG_MIN (-PY_LLONG_MAX-1)
+#define PY_ULLONG_MAX (__LONG_LONG_MAX__*2ULL + 1ULL)
+#else
+/* Otherwise, rely on two's complement. */
+#define PY_ULLONG_MAX (~0ULL)
+#define PY_LLONG_MAX ((long long)(PY_ULLONG_MAX>>1))
+#define PY_LLONG_MIN (-PY_LLONG_MAX-1)
+#endif /* LLONG_MAX */
+#endif
+#endif /* HAVE_LONG_LONG */
+
+/* a build with 30-bit digits for Python long integers needs an exact-width
+ * 32-bit unsigned integer type to store those digits. (We could just use
+ * type 'unsigned long', but that would be wasteful on a system where longs
+ * are 64-bits.) On Unix systems, the autoconf macro AC_TYPE_UINT32_T defines
+ * uint32_t to be such a type unless stdint.h or inttypes.h defines uint32_t.
+ * However, it doesn't set HAVE_UINT32_T, so we do that here.
+ */
+#if (defined UINT32_MAX || defined uint32_t)
+#ifndef PY_UINT32_T
+#define HAVE_UINT32_T 1
+#define PY_UINT32_T uint32_t
+#endif
+#endif
+
+/* Macros for a 64-bit unsigned integer type; used for type 'twodigits' in the
+ * long integer implementation, when 30-bit digits are enabled.
+ */
+#if (defined UINT64_MAX || defined uint64_t)
+#ifndef PY_UINT64_T
+#define HAVE_UINT64_T 1
+#define PY_UINT64_T uint64_t
+#endif
+#endif
+
+/* Signed variants of the above */
+#if (defined INT32_MAX || defined int32_t)
+#ifndef PY_INT32_T
+#define HAVE_INT32_T 1
+#define PY_INT32_T int32_t
+#endif
+#endif
+#if (defined INT64_MAX || defined int64_t)
+#ifndef PY_INT64_T
+#define HAVE_INT64_T 1
+#define PY_INT64_T int64_t
+#endif
+#endif
+
+/* If PYLONG_BITS_IN_DIGIT is not defined then we'll use 30-bit digits if all
+ the necessary integer types are available, and we're on a 64-bit platform
+ (as determined by SIZEOF_VOID_P); otherwise we use 15-bit digits. */
+
+#ifndef PYLONG_BITS_IN_DIGIT
+#if (defined HAVE_UINT64_T && defined HAVE_INT64_T && \
+ defined HAVE_UINT32_T && defined HAVE_INT32_T && SIZEOF_VOID_P >= 8)
+#define PYLONG_BITS_IN_DIGIT 30
+#else
+#define PYLONG_BITS_IN_DIGIT 15
+#endif
+#endif
+
+/* uintptr_t is the C9X name for an unsigned integral type such that a
+ * legitimate void* can be cast to uintptr_t and then back to void* again
+ * without loss of information. Similarly for intptr_t, wrt a signed
+ * integral type.
+ */
+#ifdef HAVE_UINTPTR_T
+typedef uintptr_t Py_uintptr_t;
+typedef intptr_t Py_intptr_t;
+
+#elif SIZEOF_VOID_P <= SIZEOF_INT
+typedef unsigned int Py_uintptr_t;
+typedef int Py_intptr_t;
+
+#elif SIZEOF_VOID_P <= SIZEOF_LONG
+typedef unsigned long Py_uintptr_t;
+typedef long Py_intptr_t;
+
+#elif defined(HAVE_LONG_LONG) && (SIZEOF_VOID_P <= SIZEOF_LONG_LONG)
+typedef unsigned PY_LONG_LONG Py_uintptr_t;
+typedef PY_LONG_LONG Py_intptr_t;
+
+#else
+# error "Python needs a typedef for Py_uintptr_t in pyport.h."
+#endif /* HAVE_UINTPTR_T */
+
+/* Py_ssize_t is a signed integral type such that sizeof(Py_ssize_t) ==
+ * sizeof(size_t). C99 doesn't define such a thing directly (size_t is an
+ * unsigned integral type). See PEP 353 for details.
+ */
+#ifdef HAVE_SSIZE_T
+typedef ssize_t Py_ssize_t;
+#elif SIZEOF_VOID_P == SIZEOF_SIZE_T
+typedef Py_intptr_t Py_ssize_t;
+#else
+# error "Python needs a typedef for Py_ssize_t in pyport.h."
+#endif
+
+/* Largest possible value of size_t.
+ SIZE_MAX is part of C99, so it might be defined on some
+ platforms. If it is not defined, (size_t)-1 is a portable
+ definition for C89, due to the way signed->unsigned
+ conversion is defined. */
+#ifdef SIZE_MAX
+#define PY_SIZE_MAX SIZE_MAX
+#else
+#define PY_SIZE_MAX ((size_t)-1)
+#endif
+
+/* Largest positive value of type Py_ssize_t. */
+#define PY_SSIZE_T_MAX ((Py_ssize_t)(((size_t)-1)>>1))
+/* Smallest negative value of type Py_ssize_t. */
+#define PY_SSIZE_T_MIN (-PY_SSIZE_T_MAX-1)
+
+#if SIZEOF_PID_T > SIZEOF_LONG
+# error "Python doesn't support sizeof(pid_t) > sizeof(long)"
+#endif
+
+/* PY_FORMAT_SIZE_T is a platform-specific modifier for use in a printf
+ * format to convert an argument with the width of a size_t or Py_ssize_t.
+ * C99 introduced "z" for this purpose, but not all platforms support that;
+ * e.g., MS compilers use "I" instead.
+ *
+ * These "high level" Python format functions interpret "z" correctly on
+ * all platforms (Python interprets the format string itself, and does whatever
+ * the platform C requires to convert a size_t/Py_ssize_t argument):
+ *
+ * PyString_FromFormat
+ * PyErr_Format
+ * PyString_FromFormatV
+ *
+ * Lower-level uses require that you interpolate the correct format modifier
+ * yourself (e.g., calling printf, fprintf, sprintf, PyOS_snprintf); for
+ * example,
+ *
+ * Py_ssize_t index;
+ * fprintf(stderr, "index %" PY_FORMAT_SIZE_T "d sucks\n", index);
+ *
+ * That will expand to %ld, or %Id, or to something else correct for a
+ * Py_ssize_t on the platform.
+ */
+#ifndef PY_FORMAT_SIZE_T
+# if SIZEOF_SIZE_T == SIZEOF_INT && !defined(__APPLE__)
+# define PY_FORMAT_SIZE_T ""
+# elif SIZEOF_SIZE_T == SIZEOF_LONG
+# define PY_FORMAT_SIZE_T "l"
+# elif defined(MS_WINDOWS)
+# define PY_FORMAT_SIZE_T "I"
+# else
+# error "This platform's pyconfig.h needs to define PY_FORMAT_SIZE_T"
+# endif
+#endif
+
+/* PY_FORMAT_LONG_LONG is analogous to PY_FORMAT_SIZE_T above, but for
+ * the long long type instead of the size_t type. It's only available
+ * when HAVE_LONG_LONG is defined. The "high level" Python format
+ * functions listed above will interpret "lld" or "llu" correctly on
+ * all platforms.
+ */
+#ifdef HAVE_LONG_LONG
+# ifndef PY_FORMAT_LONG_LONG
+# if defined(MS_WIN64) || defined(MS_WINDOWS)
+# define PY_FORMAT_LONG_LONG "I64"
+# else
+# error "This platform's pyconfig.h needs to define PY_FORMAT_LONG_LONG"
+# endif
+# endif
+#endif
+
+/* Py_LOCAL can be used instead of static to get the fastest possible calling
+ * convention for functions that are local to a given module.
+ *
+ * Py_LOCAL_INLINE does the same thing, and also explicitly requests inlining,
+ * for platforms that support that.
+ *
+ * If PY_LOCAL_AGGRESSIVE is defined before python.h is included, more
+ * "aggressive" inlining/optimizaion is enabled for the entire module. This
+ * may lead to code bloat, and may slow things down for those reasons. It may
+ * also lead to errors, if the code relies on pointer aliasing. Use with
+ * care.
+ *
+ * NOTE: You can only use this for functions that are entirely local to a
+ * module; functions that are exported via method tables, callbacks, etc,
+ * should keep using static.
+ */
+
+#undef USE_INLINE /* XXX - set via configure? */
+
+#if defined(_MSC_VER)
+#if defined(PY_LOCAL_AGGRESSIVE)
+/* enable more aggressive optimization for visual studio */
+//#pragma optimize("agtw", on)
+#pragma optimize("gt", on) // a and w are not legal for VS2005
+#endif
+/* ignore warnings if the compiler decides not to inline a function */
+#pragma warning(disable: 4710)
+/* fastest possible local call under MSVC */
+#define Py_LOCAL(type) static type __fastcall
+#define Py_LOCAL_INLINE(type) static __inline type __fastcall
+#elif defined(USE_INLINE)
+#define Py_LOCAL(type) static type
+#define Py_LOCAL_INLINE(type) static inline type
+#else
+#define Py_LOCAL(type) static type
+#define Py_LOCAL_INLINE(type) static type
+#endif
+
+/* Py_MEMCPY can be used instead of memcpy in cases where the copied blocks
+ * are often very short. While most platforms have highly optimized code for
+ * large transfers, the setup costs for memcpy are often quite high. MEMCPY
+ * solves this by doing short copies "in line".
+ */
+
+#if defined(_MSC_VER)
+#define Py_MEMCPY(target, source, length) do { \
+ size_t i_, n_ = (length); \
+ char *t_ = (void*) (target); \
+ const char *s_ = (void*) (source); \
+ if (n_ >= 16) \
+ memcpy(t_, s_, n_); \
+ else \
+ for (i_ = 0; i_ < n_; i_++) \
+ t_[i_] = s_[i_]; \
+ } while (0)
+#else
+#define Py_MEMCPY memcpy
+#endif
+
+#include
+
+#ifdef HAVE_IEEEFP_H
+#include /* needed for 'finite' declaration on some platforms */
+#endif
+
+#include /* Moved here from the math section, before extern "C" */
+
+/********************************************
+ * WRAPPER FOR and/or *
+ ********************************************/
+
+#ifdef TIME_WITH_SYS_TIME
+#include
+#include
+#else /* !TIME_WITH_SYS_TIME */
+#ifdef HAVE_SYS_TIME_H
+#include
+#else /* !HAVE_SYS_TIME_H */
+#include
+#endif /* !HAVE_SYS_TIME_H */
+#endif /* !TIME_WITH_SYS_TIME */
+
+
+/******************************
+ * WRAPPER FOR *
+ ******************************/
+
+/* NB caller must include */
+
+#ifdef HAVE_SYS_SELECT_H
+
+#include
+
+#endif /* !HAVE_SYS_SELECT_H */
+
+/*******************************
+ * stat() and fstat() fiddling *
+ *******************************/
+
+/* We expect that stat and fstat exist on most systems.
+ * It's confirmed on Unix, Mac and Windows.
+ * If you don't have them, add
+ * #define DONT_HAVE_STAT
+ * and/or
+ * #define DONT_HAVE_FSTAT
+ * to your pyconfig.h. Python code beyond this should check HAVE_STAT and
+ * HAVE_FSTAT instead.
+ * Also
+ * #define HAVE_SYS_STAT_H
+ * if exists on your platform, and
+ * #define HAVE_STAT_H
+ * if does.
+ */
+#ifndef DONT_HAVE_STAT
+#define HAVE_STAT
+#endif
+
+#ifndef DONT_HAVE_FSTAT
+#define HAVE_FSTAT
+#endif
+
+#ifdef RISCOS
+#include
+#include "unixstuff.h"
+#endif
+
+#ifdef HAVE_SYS_STAT_H
+#if defined(PYOS_OS2) && defined(PYCC_GCC)
+#include
+#endif
+#include
+#elif defined(HAVE_STAT_H)
+#include
+#endif
+
+#if defined(PYCC_VACPP)
+/* VisualAge C/C++ Failed to Define MountType Field in sys/stat.h */
+#define S_IFMT (S_IFDIR|S_IFCHR|S_IFREG)
+#endif
+
+#ifndef S_ISREG
+#define S_ISREG(x) (((x) & S_IFMT) == S_IFREG)
+#endif
+
+#ifndef S_ISDIR
+#define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR)
+#endif
+
+
+#ifdef __cplusplus
+/* Move this down here since some C++ #include's don't like to be included
+ inside an extern "C" */
+extern "C" {
+#endif
+
+
+/* Py_ARITHMETIC_RIGHT_SHIFT
+ * C doesn't define whether a right-shift of a signed integer sign-extends
+ * or zero-fills. Here a macro to force sign extension:
+ * Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J)
+ * Return I >> J, forcing sign extension. Arithmetically, return the
+ * floor of I/2**J.
+ * Requirements:
+ * I should have signed integer type. In the terminology of C99, this can
+ * be either one of the five standard signed integer types (signed char,
+ * short, int, long, long long) or an extended signed integer type.
+ * J is an integer >= 0 and strictly less than the number of bits in the
+ * type of I (because C doesn't define what happens for J outside that
+ * range either).
+ * TYPE used to specify the type of I, but is now ignored. It's been left
+ * in for backwards compatibility with versions <= 2.6 or 3.0.
+ * Caution:
+ * I may be evaluated more than once.
+ */
+#ifdef SIGNED_RIGHT_SHIFT_ZERO_FILLS
+#define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) \
+ ((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J))
+#else
+#define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) ((I) >> (J))
+#endif
+
+/* Py_FORCE_EXPANSION(X)
+ * "Simply" returns its argument. However, macro expansions within the
+ * argument are evaluated. This unfortunate trickery is needed to get
+ * token-pasting to work as desired in some cases.
+ */
+#define Py_FORCE_EXPANSION(X) X
+
+/* Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW)
+ * Cast VALUE to type NARROW from type WIDE. In Py_DEBUG mode, this
+ * assert-fails if any information is lost.
+ * Caution:
+ * VALUE may be evaluated more than once.
+ */
+#ifdef Py_DEBUG
+#define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) \
+ (assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE))
+#else
+#define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) (NARROW)(VALUE)
+#endif
+
+/* Py_SET_ERRNO_ON_MATH_ERROR(x)
+ * If a libm function did not set errno, but it looks like the result
+ * overflowed or not-a-number, set errno to ERANGE or EDOM. Set errno
+ * to 0 before calling a libm function, and invoke this macro after,
+ * passing the function result.
+ * Caution:
+ * This isn't reliable. See Py_OVERFLOWED comments.
+ * X is evaluated more than once.
+ */
+#if defined(__FreeBSD__) || defined(__OpenBSD__) || (defined(__hpux) && defined(__ia64))
+#define _Py_SET_EDOM_FOR_NAN(X) if (isnan(X)) errno = EDOM;
+#else
+#define _Py_SET_EDOM_FOR_NAN(X) ;
+#endif
+#define Py_SET_ERRNO_ON_MATH_ERROR(X) \
+ do { \
+ if (errno == 0) { \
+ if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \
+ errno = ERANGE; \
+ else _Py_SET_EDOM_FOR_NAN(X) \
+ } \
+ } while(0)
+
+/* Py_SET_ERANGE_ON_OVERFLOW(x)
+ * An alias of Py_SET_ERRNO_ON_MATH_ERROR for backward-compatibility.
+ */
+#define Py_SET_ERANGE_IF_OVERFLOW(X) Py_SET_ERRNO_ON_MATH_ERROR(X)
+
+/* Py_ADJUST_ERANGE1(x)
+ * Py_ADJUST_ERANGE2(x, y)
+ * Set errno to 0 before calling a libm function, and invoke one of these
+ * macros after, passing the function result(s) (Py_ADJUST_ERANGE2 is useful
+ * for functions returning complex results). This makes two kinds of
+ * adjustments to errno: (A) If it looks like the platform libm set
+ * errno=ERANGE due to underflow, clear errno. (B) If it looks like the
+ * platform libm overflowed but didn't set errno, force errno to ERANGE. In
+ * effect, we're trying to force a useful implementation of C89 errno
+ * behavior.
+ * Caution:
+ * This isn't reliable. See Py_OVERFLOWED comments.
+ * X and Y may be evaluated more than once.
+ */
+#define Py_ADJUST_ERANGE1(X) \
+ do { \
+ if (errno == 0) { \
+ if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \
+ errno = ERANGE; \
+ } \
+ else if (errno == ERANGE && (X) == 0.0) \
+ errno = 0; \
+ } while(0)
+
+#define Py_ADJUST_ERANGE2(X, Y) \
+ do { \
+ if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \
+ (Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \
+ if (errno == 0) \
+ errno = ERANGE; \
+ } \
+ else if (errno == ERANGE) \
+ errno = 0; \
+ } while(0)
+
+/* The functions _Py_dg_strtod and _Py_dg_dtoa in Python/dtoa.c (which are
+ * required to support the short float repr introduced in Python 3.1) require
+ * that the floating-point unit that's being used for arithmetic operations
+ * on C doubles is set to use 53-bit precision. It also requires that the
+ * FPU rounding mode is round-half-to-even, but that's less often an issue.
+ *
+ * If your FPU isn't already set to 53-bit precision/round-half-to-even, and
+ * you want to make use of _Py_dg_strtod and _Py_dg_dtoa, then you should
+ *
+ * #define HAVE_PY_SET_53BIT_PRECISION 1
+ *
+ * and also give appropriate definitions for the following three macros:
+ *
+ * _PY_SET_53BIT_PRECISION_START : store original FPU settings, and
+ * set FPU to 53-bit precision/round-half-to-even
+ * _PY_SET_53BIT_PRECISION_END : restore original FPU settings
+ * _PY_SET_53BIT_PRECISION_HEADER : any variable declarations needed to
+ * use the two macros above.
+ *
+ * The macros are designed to be used within a single C function: see
+ * Python/pystrtod.c for an example of their use.
+ */
+
+/* get and set x87 control word for gcc/x86 */
+#ifdef HAVE_GCC_ASM_FOR_X87
+#define HAVE_PY_SET_53BIT_PRECISION 1
+/* _Py_get/set_387controlword functions are defined in Python/pymath.c */
+#define _Py_SET_53BIT_PRECISION_HEADER \
+ unsigned short old_387controlword, new_387controlword
+#define _Py_SET_53BIT_PRECISION_START \
+ do { \
+ old_387controlword = _Py_get_387controlword(); \
+ new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \
+ if (new_387controlword != old_387controlword) \
+ _Py_set_387controlword(new_387controlword); \
+ } while (0)
+#define _Py_SET_53BIT_PRECISION_END \
+ if (new_387controlword != old_387controlword) \
+ _Py_set_387controlword(old_387controlword)
+#endif
+
+/* default definitions are empty */
+#ifndef HAVE_PY_SET_53BIT_PRECISION
+#define _Py_SET_53BIT_PRECISION_HEADER
+#define _Py_SET_53BIT_PRECISION_START
+#define _Py_SET_53BIT_PRECISION_END
+#endif
+
+/* If we can't guarantee 53-bit precision, don't use the code
+ in Python/dtoa.c, but fall back to standard code. This
+ means that repr of a float will be long (17 sig digits).
+
+ Realistically, there are two things that could go wrong:
+
+ (1) doubles aren't IEEE 754 doubles, or
+ (2) we're on x86 with the rounding precision set to 64-bits
+ (extended precision), and we don't know how to change
+ the rounding precision.
+ */
+
+#if !defined(DOUBLE_IS_LITTLE_ENDIAN_IEEE754) && \
+ !defined(DOUBLE_IS_BIG_ENDIAN_IEEE754) && \
+ !defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754)
+#define PY_NO_SHORT_FLOAT_REPR
+#endif
+
+/* double rounding is symptomatic of use of extended precision on x86. If
+ we're seeing double rounding, and we don't have any mechanism available for
+ changing the FPU rounding precision, then don't use Python/dtoa.c. */
+#if defined(X87_DOUBLE_ROUNDING) && !defined(HAVE_PY_SET_53BIT_PRECISION)
+#define PY_NO_SHORT_FLOAT_REPR
+#endif
+
+/* Py_DEPRECATED(version)
+ * Declare a variable, type, or function deprecated.
+ * Usage:
+ * extern int old_var Py_DEPRECATED(2.3);
+ * typedef int T1 Py_DEPRECATED(2.4);
+ * extern int x() Py_DEPRECATED(2.5);
+ */
+#if defined(__GNUC__) && ((__GNUC__ >= 4) || \
+ (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))
+#define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__))
+#else
+#define Py_DEPRECATED(VERSION_UNUSED)
+#endif
+
+/**************************************************************************
+Prototypes that are missing from the standard include files on some systems
+(and possibly only some versions of such systems.)
+
+Please be conservative with adding new ones, document them and enclose them
+in platform-specific #ifdefs.
+**************************************************************************/
+
+#ifdef SOLARIS
+/* Unchecked */
+extern int gethostname(char *, int);
+#endif
+
+#ifdef __BEOS__
+/* Unchecked */
+/* It's in the libs, but not the headers... - [cjh] */
+int shutdown( int, int );
+#endif
+
+#ifdef HAVE__GETPTY
+#include /* we need to import mode_t */
+extern char * _getpty(int *, int, mode_t, int);
+#endif
+
+/* On QNX 6, struct termio must be declared by including sys/termio.h
+ if TCGETA, TCSETA, TCSETAW, or TCSETAF are used. sys/termio.h must
+ be included before termios.h or it will generate an error. */
+#ifdef HAVE_SYS_TERMIO_H
+#include
+#endif
+
+#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY)
+#if !defined(HAVE_PTY_H) && !defined(HAVE_LIBUTIL_H) && !defined(HAVE_UTIL_H)
+/* BSDI does not supply a prototype for the 'openpty' and 'forkpty'
+ functions, even though they are included in libutil. */
+#include
+extern int openpty(int *, int *, char *, struct termios *, struct winsize *);
+extern pid_t forkpty(int *, char *, struct termios *, struct winsize *);
+#endif /* !defined(HAVE_PTY_H) && !defined(HAVE_LIBUTIL_H) */
+#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) */
+
+
+/* These are pulled from various places. It isn't obvious on what platforms
+ they are necessary, nor what the exact prototype should look like (which
+ is likely to vary between platforms!) If you find you need one of these
+ declarations, please move them to a platform-specific block and include
+ proper prototypes. */
+#if 0
+
+/* From Modules/resource.c */
+extern int getrusage();
+extern int getpagesize();
+
+/* From Python/sysmodule.c and Modules/posixmodule.c */
+extern int fclose(FILE *);
+
+/* From Modules/posixmodule.c */
+extern int fdatasync(int);
+#endif /* 0 */
+
+
+/* On 4.4BSD-descendants, ctype functions serves the whole range of
+ * wchar_t character set rather than single byte code points only.
+ * This characteristic can break some operations of string object
+ * including str.upper() and str.split() on UTF-8 locales. This
+ * workaround was provided by Tim Robbins of FreeBSD project.
+ */
+
+#ifdef __FreeBSD__
+#include
+#if __FreeBSD_version > 500039
+# define _PY_PORT_CTYPE_UTF8_ISSUE
+#endif
+#endif
+
+
+#if defined(__APPLE__)
+# define _PY_PORT_CTYPE_UTF8_ISSUE
+#endif
+
+#ifdef _PY_PORT_CTYPE_UTF8_ISSUE
+#include
+#include
+#undef isalnum
+#define isalnum(c) iswalnum(btowc(c))
+#undef isalpha
+#define isalpha(c) iswalpha(btowc(c))
+#undef islower
+#define islower(c) iswlower(btowc(c))
+#undef isspace
+#define isspace(c) iswspace(btowc(c))
+#undef isupper
+#define isupper(c) iswupper(btowc(c))
+#undef tolower
+#define tolower(c) towlower(btowc(c))
+#undef toupper
+#define toupper(c) towupper(btowc(c))
+#endif
+
+
+/* Declarations for symbol visibility.
+
+ PyAPI_FUNC(type): Declares a public Python API function and return type
+ PyAPI_DATA(type): Declares public Python data and its type
+ PyMODINIT_FUNC: A Python module init function. If these functions are
+ inside the Python core, they are private to the core.
+ If in an extension module, it may be declared with
+ external linkage depending on the platform.
+
+ As a number of platforms support/require "__declspec(dllimport/dllexport)",
+ we support a HAVE_DECLSPEC_DLL macro to save duplication.
+*/
+
+/*
+ All windows ports, except cygwin, are handled in PC/pyconfig.h.
+
+ BeOS and cygwin are the only other autoconf platform requiring special
+ linkage handling and both of these use __declspec().
+*/
+#if defined(__CYGWIN__) || defined(__BEOS__)
+# define HAVE_DECLSPEC_DLL
+#endif
+
+/* only get special linkage if built as shared or platform is Cygwin */
+#if defined(Py_ENABLE_SHARED) || defined(__CYGWIN__)
+# if defined(HAVE_DECLSPEC_DLL)
+# ifdef Py_BUILD_CORE
+# define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE
+# define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE
+ /* module init functions inside the core need no external linkage */
+ /* except for Cygwin to handle embedding (FIXME: BeOS too?) */
+# if defined(__CYGWIN__)
+# define PyMODINIT_FUNC __declspec(dllexport) void
+# else /* __CYGWIN__ */
+# define PyMODINIT_FUNC void
+# endif /* __CYGWIN__ */
+# else /* Py_BUILD_CORE */
+ /* Building an extension module, or an embedded situation */
+ /* public Python functions and data are imported */
+ /* Under Cygwin, auto-import functions to prevent compilation */
+ /* failures similar to those described at the bottom of 4.1: */
+ /* http://docs.python.org/extending/windows.html#a-cookbook-approach */
+# if !defined(__CYGWIN__)
+# define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE
+# endif /* !__CYGWIN__ */
+# define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE
+ /* module init functions outside the core must be exported */
+# if defined(__cplusplus)
+# define PyMODINIT_FUNC extern "C" __declspec(dllexport) void
+# else /* __cplusplus */
+# define PyMODINIT_FUNC __declspec(dllexport) void
+# endif /* __cplusplus */
+# endif /* Py_BUILD_CORE */
+# endif /* HAVE_DECLSPEC */
+#endif /* Py_ENABLE_SHARED */
+
+/* If no external linkage macros defined by now, create defaults */
+#ifndef PyAPI_FUNC
+# define PyAPI_FUNC(RTYPE) RTYPE
+#endif
+#ifndef PyAPI_DATA
+# define PyAPI_DATA(RTYPE) extern RTYPE
+#endif
+#ifndef PyMODINIT_FUNC
+# if defined(__cplusplus)
+# define PyMODINIT_FUNC extern "C" void
+# else /* __cplusplus */
+# define PyMODINIT_FUNC void
+# endif /* __cplusplus */
+#endif
+
+/* Deprecated DL_IMPORT and DL_EXPORT macros */
+#if defined(Py_ENABLE_SHARED) && defined (HAVE_DECLSPEC_DLL)
+# if defined(Py_BUILD_CORE)
+# define DL_IMPORT(RTYPE) __declspec(dllexport) RTYPE
+# define DL_EXPORT(RTYPE) __declspec(dllexport) RTYPE
+# else
+# define DL_IMPORT(RTYPE) __declspec(dllimport) RTYPE
+# define DL_EXPORT(RTYPE) __declspec(dllexport) RTYPE
+# endif
+#endif
+#ifndef DL_EXPORT
+# define DL_EXPORT(RTYPE) RTYPE
+#endif
+#ifndef DL_IMPORT
+# define DL_IMPORT(RTYPE) RTYPE
+#endif
+/* End of deprecated DL_* macros */
+
+/* If the fd manipulation macros aren't defined,
+ here is a set that should do the job */
+
+#if 0 /* disabled and probably obsolete */
+
+#ifndef FD_SETSIZE
+#define FD_SETSIZE 256
+#endif
+
+#ifndef FD_SET
+
+typedef long fd_mask;
+
+#define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask */
+#ifndef howmany
+#define howmany(x, y) (((x)+((y)-1))/(y))
+#endif /* howmany */
+
+typedef struct fd_set {
+ fd_mask fds_bits[howmany(FD_SETSIZE, NFDBITS)];
+} fd_set;
+
+#define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
+#define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
+#define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
+#define FD_ZERO(p) memset((char *)(p), '\0', sizeof(*(p)))
+
+#endif /* FD_SET */
+
+#endif /* fd manipulation macros */
+
+
+/* limits.h constants that may be missing */
+
+#ifndef INT_MAX
+#define INT_MAX 2147483647
+#endif
+
+#ifndef LONG_MAX
+#if SIZEOF_LONG == 4
+#define LONG_MAX 0X7FFFFFFFL
+#elif SIZEOF_LONG == 8
+#define LONG_MAX 0X7FFFFFFFFFFFFFFFL
+#else
+#error "could not set LONG_MAX in pyport.h"
+#endif
+#endif
+
+#ifndef LONG_MIN
+#define LONG_MIN (-LONG_MAX-1)
+#endif
+
+#ifndef LONG_BIT
+#define LONG_BIT (8 * SIZEOF_LONG)
+#endif
+
+#if LONG_BIT != 8 * SIZEOF_LONG
+/* 04-Oct-2000 LONG_BIT is apparently (mis)defined as 64 on some recent
+ * 32-bit platforms using gcc. We try to catch that here at compile-time
+ * rather than waiting for integer multiplication to trigger bogus
+ * overflows.
+ */
+#error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)."
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+/*
+ * Hide GCC attributes from compilers that don't support them.
+ */
+#if (!defined(__GNUC__) || __GNUC__ < 2 || \
+ (__GNUC__ == 2 && __GNUC_MINOR__ < 7) ) && \
+ !defined(RISCOS)
+#define Py_GCC_ATTRIBUTE(x)
+#else
+#define Py_GCC_ATTRIBUTE(x) __attribute__(x)
+#endif
+
+/*
+ * Add PyArg_ParseTuple format where available.
+ */
+#ifdef HAVE_ATTRIBUTE_FORMAT_PARSETUPLE
+#define Py_FORMAT_PARSETUPLE(func,p1,p2) __attribute__((format(func,p1,p2)))
+#else
+#define Py_FORMAT_PARSETUPLE(func,p1,p2)
+#endif
+
+/*
+ * Specify alignment on compilers that support it.
+ */
+#if defined(__GNUC__) && __GNUC__ >= 3
+#define Py_ALIGNED(x) __attribute__((aligned(x)))
+#else
+#define Py_ALIGNED(x)
+#endif
+
+/* Eliminate end-of-loop code not reached warnings from SunPro C
+ * when using do{...}while(0) macros
+ */
+#ifdef __SUNPRO_C
+#pragma error_messages (off,E_END_OF_LOOP_CODE_NOT_REACHED)
+#endif
+
+/*
+ * Older Microsoft compilers don't support the C99 long long literal suffixes,
+ * so these will be defined in PC/pyconfig.h for those compilers.
+ */
+#ifndef Py_LL
+#define Py_LL(x) x##LL
+#endif
+
+#ifndef Py_ULL
+#define Py_ULL(x) Py_LL(x##U)
+#endif
+
+#endif /* Py_PYPORT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pystate.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pystate.h
new file mode 100644
index 0000000000..6d11e4943a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pystate.h
@@ -0,0 +1,198 @@
+
+/* Thread and interpreter state structures and their interfaces */
+
+
+#ifndef Py_PYSTATE_H
+#define Py_PYSTATE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* State shared between threads */
+
+struct _ts; /* Forward */
+struct _is; /* Forward */
+
+typedef struct _is {
+
+ struct _is *next;
+ struct _ts *tstate_head;
+
+ PyObject *modules;
+ PyObject *sysdict;
+ PyObject *builtins;
+ PyObject *modules_reloading;
+
+ PyObject *codec_search_path;
+ PyObject *codec_search_cache;
+ PyObject *codec_error_registry;
+
+#ifdef HAVE_DLOPEN
+ int dlopenflags;
+#endif
+#ifdef WITH_TSC
+ int tscdump;
+#endif
+
+} PyInterpreterState;
+
+
+/* State unique per thread */
+
+struct _frame; /* Avoid including frameobject.h */
+
+/* Py_tracefunc return -1 when raising an exception, or 0 for success. */
+typedef int (*Py_tracefunc)(PyObject *, struct _frame *, int, PyObject *);
+
+/* The following values are used for 'what' for tracefunc functions: */
+#define PyTrace_CALL 0
+#define PyTrace_EXCEPTION 1
+#define PyTrace_LINE 2
+#define PyTrace_RETURN 3
+#define PyTrace_C_CALL 4
+#define PyTrace_C_EXCEPTION 5
+#define PyTrace_C_RETURN 6
+
+typedef struct _ts {
+ /* See Python/ceval.c for comments explaining most fields */
+
+ struct _ts *next;
+ PyInterpreterState *interp;
+
+ struct _frame *frame;
+ int recursion_depth;
+ /* 'tracing' keeps track of the execution depth when tracing/profiling.
+ This is to prevent the actual trace/profile code from being recorded in
+ the trace/profile. */
+ int tracing;
+ int use_tracing;
+
+ Py_tracefunc c_profilefunc;
+ Py_tracefunc c_tracefunc;
+ PyObject *c_profileobj;
+ PyObject *c_traceobj;
+
+ PyObject *curexc_type;
+ PyObject *curexc_value;
+ PyObject *curexc_traceback;
+
+ PyObject *exc_type;
+ PyObject *exc_value;
+ PyObject *exc_traceback;
+
+ PyObject *dict; /* Stores per-thread state */
+
+ /* tick_counter is incremented whenever the check_interval ticker
+ * reaches zero. The purpose is to give a useful measure of the number
+ * of interpreted bytecode instructions in a given thread. This
+ * extremely lightweight statistic collector may be of interest to
+ * profilers (like psyco.jit()), although nothing in the core uses it.
+ */
+ int tick_counter;
+
+ int gilstate_counter;
+
+ PyObject *async_exc; /* Asynchronous exception to raise */
+ long thread_id; /* Thread id where this tstate was created */
+
+ /* XXX signal handlers should also be here */
+
+} PyThreadState;
+
+
+PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_New(void);
+PyAPI_FUNC(void) PyInterpreterState_Clear(PyInterpreterState *);
+PyAPI_FUNC(void) PyInterpreterState_Delete(PyInterpreterState *);
+
+PyAPI_FUNC(PyThreadState *) PyThreadState_New(PyInterpreterState *);
+PyAPI_FUNC(PyThreadState *) _PyThreadState_Prealloc(PyInterpreterState *);
+PyAPI_FUNC(void) _PyThreadState_Init(PyThreadState *);
+PyAPI_FUNC(void) PyThreadState_Clear(PyThreadState *);
+PyAPI_FUNC(void) PyThreadState_Delete(PyThreadState *);
+#ifdef WITH_THREAD
+PyAPI_FUNC(void) PyThreadState_DeleteCurrent(void);
+PyAPI_FUNC(void) _PyGILState_Reinit(void);
+#endif
+
+PyAPI_FUNC(PyThreadState *) PyThreadState_Get(void);
+PyAPI_FUNC(PyThreadState *) PyThreadState_Swap(PyThreadState *);
+PyAPI_FUNC(PyObject *) PyThreadState_GetDict(void);
+PyAPI_FUNC(int) PyThreadState_SetAsyncExc(long, PyObject *);
+
+
+/* Variable and macro for in-line access to current thread state */
+
+PyAPI_DATA(PyThreadState *) _PyThreadState_Current;
+
+#ifdef Py_DEBUG
+#define PyThreadState_GET() PyThreadState_Get()
+#else
+#define PyThreadState_GET() (_PyThreadState_Current)
+#endif
+
+typedef
+ enum {PyGILState_LOCKED, PyGILState_UNLOCKED}
+ PyGILState_STATE;
+
+/* Ensure that the current thread is ready to call the Python
+ C API, regardless of the current state of Python, or of its
+ thread lock. This may be called as many times as desired
+ by a thread so long as each call is matched with a call to
+ PyGILState_Release(). In general, other thread-state APIs may
+ be used between _Ensure() and _Release() calls, so long as the
+ thread-state is restored to its previous state before the Release().
+ For example, normal use of the Py_BEGIN_ALLOW_THREADS/
+ Py_END_ALLOW_THREADS macros are acceptable.
+
+ The return value is an opaque "handle" to the thread state when
+ PyGILState_Ensure() was called, and must be passed to
+ PyGILState_Release() to ensure Python is left in the same state. Even
+ though recursive calls are allowed, these handles can *not* be shared -
+ each unique call to PyGILState_Ensure must save the handle for its
+ call to PyGILState_Release.
+
+ When the function returns, the current thread will hold the GIL.
+
+ Failure is a fatal error.
+*/
+PyAPI_FUNC(PyGILState_STATE) PyGILState_Ensure(void);
+
+/* Release any resources previously acquired. After this call, Python's
+ state will be the same as it was prior to the corresponding
+ PyGILState_Ensure() call (but generally this state will be unknown to
+ the caller, hence the use of the GILState API.)
+
+ Every call to PyGILState_Ensure must be matched by a call to
+ PyGILState_Release on the same thread.
+*/
+PyAPI_FUNC(void) PyGILState_Release(PyGILState_STATE);
+
+/* Helper/diagnostic function - get the current thread state for
+ this thread. May return NULL if no GILState API has been used
+ on the current thread. Note the main thread always has such a
+ thread-state, even if no auto-thread-state call has been made
+ on the main thread.
+*/
+PyAPI_FUNC(PyThreadState *) PyGILState_GetThisThreadState(void);
+
+/* The implementation of sys._current_frames() Returns a dict mapping
+ thread id to that thread's current frame.
+*/
+PyAPI_FUNC(PyObject *) _PyThread_CurrentFrames(void);
+
+/* Routines for advanced debuggers, requested by David Beazley.
+ Don't use unless you know what you are doing! */
+PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Head(void);
+PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Next(PyInterpreterState *);
+PyAPI_FUNC(PyThreadState *) PyInterpreterState_ThreadHead(PyInterpreterState *);
+PyAPI_FUNC(PyThreadState *) PyThreadState_Next(PyThreadState *);
+
+typedef struct _frame *(*PyThreadFrameGetter)(PyThreadState *self_);
+
+/* hook for PyEval_GetFrame(), requested for Psyco */
+PyAPI_DATA(PyThreadFrameGetter) _PyThreadState_GetFrame;
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_PYSTATE_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pystrcmp.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pystrcmp.h
new file mode 100644
index 0000000000..542399de36
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pystrcmp.h
@@ -0,0 +1,23 @@
+#ifndef Py_STRCMP_H
+#define Py_STRCMP_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_FUNC(int) PyOS_mystrnicmp(const char *, const char *, Py_ssize_t);
+PyAPI_FUNC(int) PyOS_mystricmp(const char *, const char *);
+
+#if defined(MS_WINDOWS) || defined(PYOS_OS2)
+#define PyOS_strnicmp strnicmp
+#define PyOS_stricmp stricmp
+#else
+#define PyOS_strnicmp PyOS_mystrnicmp
+#define PyOS_stricmp PyOS_mystricmp
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !Py_STRCMP_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pystrtod.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pystrtod.h
new file mode 100644
index 0000000000..f2ecc60e23
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pystrtod.h
@@ -0,0 +1,45 @@
+#ifndef Py_STRTOD_H
+#define Py_STRTOD_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+PyAPI_FUNC(double) PyOS_ascii_strtod(const char *str, char **ptr);
+PyAPI_FUNC(double) PyOS_ascii_atof(const char *str);
+
+/* Deprecated in 2.7 and 3.1. Will disappear in 2.8 (if it exists) and 3.2 */
+PyAPI_FUNC(char *) PyOS_ascii_formatd(char *buffer, size_t buf_len,
+ const char *format, double d);
+PyAPI_FUNC(double) PyOS_string_to_double(const char *str,
+ char **endptr,
+ PyObject *overflow_exception);
+
+/* The caller is responsible for calling PyMem_Free to free the buffer
+ that's is returned. */
+PyAPI_FUNC(char *) PyOS_double_to_string(double val,
+ char format_code,
+ int precision,
+ int flags,
+ int *type);
+
+PyAPI_FUNC(double) _Py_parse_inf_or_nan(const char *p, char **endptr);
+
+
+/* PyOS_double_to_string's "flags" parameter can be set to 0 or more of: */
+#define Py_DTSF_SIGN 0x01 /* always add the sign */
+#define Py_DTSF_ADD_DOT_0 0x02 /* if the result is an integer add ".0" */
+#define Py_DTSF_ALT 0x04 /* "alternate" formatting. it's format_code
+ specific */
+
+/* PyOS_double_to_string's "type", if non-NULL, will be set to one of: */
+#define Py_DTST_FINITE 0
+#define Py_DTST_INFINITE 1
+#define Py_DTST_NAN 2
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !Py_STRTOD_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pythonrun.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pythonrun.h
new file mode 100644
index 0000000000..7584ee5a7e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pythonrun.h
@@ -0,0 +1,178 @@
+
+/* Interfaces to parse and execute pieces of python code */
+
+#ifndef Py_PYTHONRUN_H
+#define Py_PYTHONRUN_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define PyCF_MASK (CO_FUTURE_DIVISION | CO_FUTURE_ABSOLUTE_IMPORT | \
+ CO_FUTURE_WITH_STATEMENT | CO_FUTURE_PRINT_FUNCTION | \
+ CO_FUTURE_UNICODE_LITERALS)
+#define PyCF_MASK_OBSOLETE (CO_NESTED)
+#define PyCF_SOURCE_IS_UTF8 0x0100
+#define PyCF_DONT_IMPLY_DEDENT 0x0200
+#define PyCF_ONLY_AST 0x0400
+
+typedef struct {
+ int cf_flags; /* bitmask of CO_xxx flags relevant to future */
+} PyCompilerFlags;
+
+PyAPI_FUNC(void) Py_SetProgramName(char *);
+PyAPI_FUNC(char *) Py_GetProgramName(void);
+
+PyAPI_FUNC(void) Py_SetPythonHome(char *);
+PyAPI_FUNC(char *) Py_GetPythonHome(void);
+
+PyAPI_FUNC(void) Py_Initialize(void);
+PyAPI_FUNC(void) Py_InitializeEx(int);
+PyAPI_FUNC(void) Py_Finalize(void);
+PyAPI_FUNC(int) Py_IsInitialized(void);
+PyAPI_FUNC(PyThreadState *) Py_NewInterpreter(void);
+PyAPI_FUNC(void) Py_EndInterpreter(PyThreadState *);
+
+PyAPI_FUNC(int) PyRun_AnyFileFlags(FILE *, const char *, PyCompilerFlags *);
+PyAPI_FUNC(int) PyRun_AnyFileExFlags(FILE *, const char *, int, PyCompilerFlags *);
+PyAPI_FUNC(int) PyRun_SimpleStringFlags(const char *, PyCompilerFlags *);
+PyAPI_FUNC(int) PyRun_SimpleFileExFlags(FILE *, const char *, int, PyCompilerFlags *);
+PyAPI_FUNC(int) PyRun_InteractiveOneFlags(FILE *, const char *, PyCompilerFlags *);
+PyAPI_FUNC(int) PyRun_InteractiveLoopFlags(FILE *, const char *, PyCompilerFlags *);
+
+PyAPI_FUNC(struct _mod *) PyParser_ASTFromString(const char *, const char *,
+ int, PyCompilerFlags *flags,
+ PyArena *);
+PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(FILE *, const char *, int,
+ char *, char *,
+ PyCompilerFlags *, int *,
+ PyArena *);
+#define PyParser_SimpleParseString(S, B) \
+ PyParser_SimpleParseStringFlags(S, B, 0)
+#define PyParser_SimpleParseFile(FP, S, B) \
+ PyParser_SimpleParseFileFlags(FP, S, B, 0)
+PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int,
+ int);
+PyAPI_FUNC(struct _node *) PyParser_SimpleParseFileFlags(FILE *, const char *,
+ int, int);
+
+PyAPI_FUNC(PyObject *) PyRun_StringFlags(const char *, int, PyObject *,
+ PyObject *, PyCompilerFlags *);
+
+PyAPI_FUNC(PyObject *) PyRun_FileExFlags(FILE *, const char *, int,
+ PyObject *, PyObject *, int,
+ PyCompilerFlags *);
+
+#define Py_CompileString(str, p, s) Py_CompileStringFlags(str, p, s, NULL)
+PyAPI_FUNC(PyObject *) Py_CompileStringFlags(const char *, const char *, int,
+ PyCompilerFlags *);
+PyAPI_FUNC(struct symtable *) Py_SymtableString(const char *, const char *, int);
+
+PyAPI_FUNC(void) PyErr_Print(void);
+PyAPI_FUNC(void) PyErr_PrintEx(int);
+PyAPI_FUNC(void) PyErr_Display(PyObject *, PyObject *, PyObject *);
+
+PyAPI_FUNC(int) Py_AtExit(void (*func)(void));
+
+PyAPI_FUNC(void) Py_Exit(int);
+
+PyAPI_FUNC(int) Py_FdIsInteractive(FILE *, const char *);
+
+/* Bootstrap */
+PyAPI_FUNC(int) Py_Main(int argc, char **argv);
+
+/* Use macros for a bunch of old variants */
+#define PyRun_String(str, s, g, l) PyRun_StringFlags(str, s, g, l, NULL)
+#define PyRun_AnyFile(fp, name) PyRun_AnyFileExFlags(fp, name, 0, NULL)
+#define PyRun_AnyFileEx(fp, name, closeit) \
+ PyRun_AnyFileExFlags(fp, name, closeit, NULL)
+#define PyRun_AnyFileFlags(fp, name, flags) \
+ PyRun_AnyFileExFlags(fp, name, 0, flags)
+#define PyRun_SimpleString(s) PyRun_SimpleStringFlags(s, NULL)
+#define PyRun_SimpleFile(f, p) PyRun_SimpleFileExFlags(f, p, 0, NULL)
+#define PyRun_SimpleFileEx(f, p, c) PyRun_SimpleFileExFlags(f, p, c, NULL)
+#define PyRun_InteractiveOne(f, p) PyRun_InteractiveOneFlags(f, p, NULL)
+#define PyRun_InteractiveLoop(f, p) PyRun_InteractiveLoopFlags(f, p, NULL)
+#define PyRun_File(fp, p, s, g, l) \
+ PyRun_FileExFlags(fp, p, s, g, l, 0, NULL)
+#define PyRun_FileEx(fp, p, s, g, l, c) \
+ PyRun_FileExFlags(fp, p, s, g, l, c, NULL)
+#define PyRun_FileFlags(fp, p, s, g, l, flags) \
+ PyRun_FileExFlags(fp, p, s, g, l, 0, flags)
+
+/* In getpath.c */
+PyAPI_FUNC(char *) Py_GetProgramFullPath(void);
+PyAPI_FUNC(char *) Py_GetPrefix(void);
+PyAPI_FUNC(char *) Py_GetExecPrefix(void);
+PyAPI_FUNC(char *) Py_GetPath(void);
+
+/* In their own files */
+PyAPI_FUNC(const char *) Py_GetVersion(void);
+PyAPI_FUNC(const char *) Py_GetPlatform(void);
+PyAPI_FUNC(const char *) Py_GetCopyright(void);
+PyAPI_FUNC(const char *) Py_GetCompiler(void);
+PyAPI_FUNC(const char *) Py_GetBuildInfo(void);
+PyAPI_FUNC(const char *) _Py_svnversion(void);
+PyAPI_FUNC(const char *) Py_SubversionRevision(void);
+PyAPI_FUNC(const char *) Py_SubversionShortBranch(void);
+PyAPI_FUNC(const char *) _Py_hgidentifier(void);
+PyAPI_FUNC(const char *) _Py_hgversion(void);
+
+/* Internal -- various one-time initializations */
+PyAPI_FUNC(PyObject *) _PyBuiltin_Init(void);
+PyAPI_FUNC(PyObject *) _PySys_Init(void);
+PyAPI_FUNC(void) _PyImport_Init(void);
+PyAPI_FUNC(void) _PyExc_Init(void);
+PyAPI_FUNC(void) _PyImportHooks_Init(void);
+PyAPI_FUNC(int) _PyFrame_Init(void);
+PyAPI_FUNC(int) _PyInt_Init(void);
+PyAPI_FUNC(int) _PyLong_Init(void);
+PyAPI_FUNC(void) _PyFloat_Init(void);
+PyAPI_FUNC(int) PyByteArray_Init(void);
+
+/* Various internal finalizers */
+PyAPI_FUNC(void) _PyExc_Fini(void);
+PyAPI_FUNC(void) _PyImport_Fini(void);
+PyAPI_FUNC(void) PyMethod_Fini(void);
+PyAPI_FUNC(void) PyFrame_Fini(void);
+PyAPI_FUNC(void) PyCFunction_Fini(void);
+PyAPI_FUNC(void) PyDict_Fini(void);
+PyAPI_FUNC(void) PyTuple_Fini(void);
+PyAPI_FUNC(void) PyList_Fini(void);
+PyAPI_FUNC(void) PySet_Fini(void);
+PyAPI_FUNC(void) PyString_Fini(void);
+PyAPI_FUNC(void) PyInt_Fini(void);
+PyAPI_FUNC(void) PyFloat_Fini(void);
+PyAPI_FUNC(void) PyOS_FiniInterrupts(void);
+PyAPI_FUNC(void) PyByteArray_Fini(void);
+
+/* Stuff with no proper home (yet) */
+PyAPI_FUNC(char *) PyOS_Readline(FILE *, FILE *, char *);
+PyAPI_DATA(int) (*PyOS_InputHook)(void);
+PyAPI_DATA(char) *(*PyOS_ReadlineFunctionPointer)(FILE *, FILE *, char *);
+PyAPI_DATA(PyThreadState*) _PyOS_ReadlineTState;
+
+/* Stack size, in "pointers" (so we get extra safety margins
+ on 64-bit platforms). On a 32-bit platform, this translates
+ to a 8k margin. */
+#define PYOS_STACK_MARGIN 2048
+
+#if defined(WIN32) && !defined(MS_WIN64) && defined(_MSC_VER) && _MSC_VER >= 1300
+/* Enable stack checking under Microsoft C */
+#define USE_STACKCHECK
+#endif
+
+#ifdef USE_STACKCHECK
+/* Check that we aren't overflowing our stack */
+PyAPI_FUNC(int) PyOS_CheckStack(void);
+#endif
+
+/* Signals */
+typedef void (*PyOS_sighandler_t)(int);
+PyAPI_FUNC(PyOS_sighandler_t) PyOS_getsig(int);
+PyAPI_FUNC(PyOS_sighandler_t) PyOS_setsig(int, PyOS_sighandler_t);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_PYTHONRUN_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/pythread.h b/AppPkg/Applications/Python/Python-2.7.2/Include/pythread.h
new file mode 100644
index 0000000000..d3c587b6f8
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/pythread.h
@@ -0,0 +1,41 @@
+
+#ifndef Py_PYTHREAD_H
+#define Py_PYTHREAD_H
+
+typedef void *PyThread_type_lock;
+typedef void *PyThread_type_sema;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_FUNC(void) PyThread_init_thread(void);
+PyAPI_FUNC(long) PyThread_start_new_thread(void (*)(void *), void *);
+PyAPI_FUNC(void) PyThread_exit_thread(void);
+PyAPI_FUNC(long) PyThread_get_thread_ident(void);
+
+PyAPI_FUNC(PyThread_type_lock) PyThread_allocate_lock(void);
+PyAPI_FUNC(void) PyThread_free_lock(PyThread_type_lock);
+PyAPI_FUNC(int) PyThread_acquire_lock(PyThread_type_lock, int);
+#define WAIT_LOCK 1
+#define NOWAIT_LOCK 0
+PyAPI_FUNC(void) PyThread_release_lock(PyThread_type_lock);
+
+PyAPI_FUNC(size_t) PyThread_get_stacksize(void);
+PyAPI_FUNC(int) PyThread_set_stacksize(size_t);
+
+/* Thread Local Storage (TLS) API */
+PyAPI_FUNC(int) PyThread_create_key(void);
+PyAPI_FUNC(void) PyThread_delete_key(int);
+PyAPI_FUNC(int) PyThread_set_key_value(int, void *);
+PyAPI_FUNC(void *) PyThread_get_key_value(int);
+PyAPI_FUNC(void) PyThread_delete_key_value(int key);
+
+/* Cleanup after a fork */
+PyAPI_FUNC(void) PyThread_ReInitTLS(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !Py_PYTHREAD_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/rangeobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/rangeobject.h
new file mode 100644
index 0000000000..b8dcb40223
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/rangeobject.h
@@ -0,0 +1,28 @@
+
+/* Range object interface */
+
+#ifndef Py_RANGEOBJECT_H
+#define Py_RANGEOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* This is about the type 'xrange', not the built-in function range(), which
+ returns regular lists. */
+
+/*
+A range object represents an integer range. This is an immutable object;
+a range cannot change its value after creation.
+
+Range objects behave like the corresponding tuple objects except that
+they are represented by a start, stop, and step datamembers.
+*/
+
+PyAPI_DATA(PyTypeObject) PyRange_Type;
+
+#define PyRange_Check(op) (Py_TYPE(op) == &PyRange_Type)
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_RANGEOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/setobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/setobject.h
new file mode 100644
index 0000000000..6ded153449
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/setobject.h
@@ -0,0 +1,99 @@
+/* Set object interface */
+
+#ifndef Py_SETOBJECT_H
+#define Py_SETOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/*
+There are three kinds of slots in the table:
+
+1. Unused: key == NULL
+2. Active: key != NULL and key != dummy
+3. Dummy: key == dummy
+
+Note: .pop() abuses the hash field of an Unused or Dummy slot to
+hold a search finger. The hash field of Unused or Dummy slots has
+no meaning otherwise.
+*/
+
+#define PySet_MINSIZE 8
+
+typedef struct {
+ long hash; /* cached hash code for the entry key */
+ PyObject *key;
+} setentry;
+
+
+/*
+This data structure is shared by set and frozenset objects.
+*/
+
+typedef struct _setobject PySetObject;
+struct _setobject {
+ PyObject_HEAD
+
+ Py_ssize_t fill; /* # Active + # Dummy */
+ Py_ssize_t used; /* # Active */
+
+ /* The table contains mask + 1 slots, and that's a power of 2.
+ * We store the mask instead of the size because the mask is more
+ * frequently needed.
+ */
+ Py_ssize_t mask;
+
+ /* table points to smalltable for small tables, else to
+ * additional malloc'ed memory. table is never NULL! This rule
+ * saves repeated runtime null-tests.
+ */
+ setentry *table;
+ setentry *(*lookup)(PySetObject *so, PyObject *key, long hash);
+ setentry smalltable[PySet_MINSIZE];
+
+ long hash; /* only used by frozenset objects */
+ PyObject *weakreflist; /* List of weak references */
+};
+
+PyAPI_DATA(PyTypeObject) PySet_Type;
+PyAPI_DATA(PyTypeObject) PyFrozenSet_Type;
+
+/* Invariants for frozensets:
+ * data is immutable.
+ * hash is the hash of the frozenset or -1 if not computed yet.
+ * Invariants for sets:
+ * hash is -1
+ */
+
+#define PyFrozenSet_CheckExact(ob) (Py_TYPE(ob) == &PyFrozenSet_Type)
+#define PyAnySet_CheckExact(ob) \
+ (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type)
+#define PyAnySet_Check(ob) \
+ (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type || \
+ PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \
+ PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type))
+#define PySet_Check(ob) \
+ (Py_TYPE(ob) == &PySet_Type || \
+ PyType_IsSubtype(Py_TYPE(ob), &PySet_Type))
+#define PyFrozenSet_Check(ob) \
+ (Py_TYPE(ob) == &PyFrozenSet_Type || \
+ PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type))
+
+PyAPI_FUNC(PyObject *) PySet_New(PyObject *);
+PyAPI_FUNC(PyObject *) PyFrozenSet_New(PyObject *);
+PyAPI_FUNC(Py_ssize_t) PySet_Size(PyObject *anyset);
+#define PySet_GET_SIZE(so) (((PySetObject *)(so))->used)
+PyAPI_FUNC(int) PySet_Clear(PyObject *set);
+PyAPI_FUNC(int) PySet_Contains(PyObject *anyset, PyObject *key);
+PyAPI_FUNC(int) PySet_Discard(PyObject *set, PyObject *key);
+PyAPI_FUNC(int) PySet_Add(PyObject *set, PyObject *key);
+PyAPI_FUNC(int) _PySet_Next(PyObject *set, Py_ssize_t *pos, PyObject **key);
+PyAPI_FUNC(int) _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, long *hash);
+PyAPI_FUNC(PyObject *) PySet_Pop(PyObject *set);
+PyAPI_FUNC(int) _PySet_Update(PyObject *set, PyObject *iterable);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_SETOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/sliceobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/sliceobject.h
new file mode 100644
index 0000000000..469921a99a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/sliceobject.h
@@ -0,0 +1,44 @@
+#ifndef Py_SLICEOBJECT_H
+#define Py_SLICEOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* The unique ellipsis object "..." */
+
+PyAPI_DATA(PyObject) _Py_EllipsisObject; /* Don't use this directly */
+
+#define Py_Ellipsis (&_Py_EllipsisObject)
+
+/* Slice object interface */
+
+/*
+
+A slice object containing start, stop, and step data members (the
+names are from range). After much talk with Guido, it was decided to
+let these be any arbitrary python type. Py_None stands for omitted values.
+*/
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *start, *stop, *step; /* not NULL */
+} PySliceObject;
+
+PyAPI_DATA(PyTypeObject) PySlice_Type;
+PyAPI_DATA(PyTypeObject) PyEllipsis_Type;
+
+#define PySlice_Check(op) (Py_TYPE(op) == &PySlice_Type)
+
+PyAPI_FUNC(PyObject *) PySlice_New(PyObject* start, PyObject* stop,
+ PyObject* step);
+PyAPI_FUNC(PyObject *) _PySlice_FromIndices(Py_ssize_t start, Py_ssize_t stop);
+PyAPI_FUNC(int) PySlice_GetIndices(PySliceObject *r, Py_ssize_t length,
+ Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step);
+PyAPI_FUNC(int) PySlice_GetIndicesEx(PySliceObject *r, Py_ssize_t length,
+ Py_ssize_t *start, Py_ssize_t *stop,
+ Py_ssize_t *step, Py_ssize_t *slicelength);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_SLICEOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/stringobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/stringobject.h
new file mode 100644
index 0000000000..d20d98611d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/stringobject.h
@@ -0,0 +1,210 @@
+
+/* String (str/bytes) object interface */
+
+#ifndef Py_STRINGOBJECT_H
+#define Py_STRINGOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include
+
+/*
+Type PyStringObject represents a character string. An extra zero byte is
+reserved at the end to ensure it is zero-terminated, but a size is
+present so strings with null bytes in them can be represented. This
+is an immutable object type.
+
+There are functions to create new string objects, to test
+an object for string-ness, and to get the
+string value. The latter function returns a null pointer
+if the object is not of the proper type.
+There is a variant that takes an explicit size as well as a
+variant that assumes a zero-terminated string. Note that none of the
+functions should be applied to nil objects.
+*/
+
+/* Caching the hash (ob_shash) saves recalculation of a string's hash value.
+ Interning strings (ob_sstate) tries to ensure that only one string
+ object with a given value exists, so equality tests can be one pointer
+ comparison. This is generally restricted to strings that "look like"
+ Python identifiers, although the intern() builtin can be used to force
+ interning of any string.
+ Together, these sped the interpreter by up to 20%. */
+
+typedef struct {
+ PyObject_VAR_HEAD
+ long ob_shash;
+ int ob_sstate;
+ char ob_sval[1];
+
+ /* Invariants:
+ * ob_sval contains space for 'ob_size+1' elements.
+ * ob_sval[ob_size] == 0.
+ * ob_shash is the hash of the string or -1 if not computed yet.
+ * ob_sstate != 0 iff the string object is in stringobject.c's
+ * 'interned' dictionary; in this case the two references
+ * from 'interned' to this object are *not counted* in ob_refcnt.
+ */
+} PyStringObject;
+
+#define SSTATE_NOT_INTERNED 0
+#define SSTATE_INTERNED_MORTAL 1
+#define SSTATE_INTERNED_IMMORTAL 2
+
+PyAPI_DATA(PyTypeObject) PyBaseString_Type;
+PyAPI_DATA(PyTypeObject) PyString_Type;
+
+#define PyString_Check(op) \
+ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_STRING_SUBCLASS)
+#define PyString_CheckExact(op) (Py_TYPE(op) == &PyString_Type)
+
+PyAPI_FUNC(PyObject *) PyString_FromStringAndSize(const char *, Py_ssize_t);
+PyAPI_FUNC(PyObject *) PyString_FromString(const char *);
+PyAPI_FUNC(PyObject *) PyString_FromFormatV(const char*, va_list)
+ Py_GCC_ATTRIBUTE((format(printf, 1, 0)));
+PyAPI_FUNC(PyObject *) PyString_FromFormat(const char*, ...)
+ Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
+PyAPI_FUNC(Py_ssize_t) PyString_Size(PyObject *);
+PyAPI_FUNC(char *) PyString_AsString(PyObject *);
+PyAPI_FUNC(PyObject *) PyString_Repr(PyObject *, int);
+PyAPI_FUNC(void) PyString_Concat(PyObject **, PyObject *);
+PyAPI_FUNC(void) PyString_ConcatAndDel(PyObject **, PyObject *);
+PyAPI_FUNC(int) _PyString_Resize(PyObject **, Py_ssize_t);
+PyAPI_FUNC(int) _PyString_Eq(PyObject *, PyObject*);
+PyAPI_FUNC(PyObject *) PyString_Format(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) _PyString_FormatLong(PyObject*, int, int,
+ int, char**, int*);
+PyAPI_FUNC(PyObject *) PyString_DecodeEscape(const char *, Py_ssize_t,
+ const char *, Py_ssize_t,
+ const char *);
+
+PyAPI_FUNC(void) PyString_InternInPlace(PyObject **);
+PyAPI_FUNC(void) PyString_InternImmortal(PyObject **);
+PyAPI_FUNC(PyObject *) PyString_InternFromString(const char *);
+PyAPI_FUNC(void) _Py_ReleaseInternedStrings(void);
+
+/* Use only if you know it's a string */
+#define PyString_CHECK_INTERNED(op) (((PyStringObject *)(op))->ob_sstate)
+
+/* Macro, trading safety for speed */
+#define PyString_AS_STRING(op) (((PyStringObject *)(op))->ob_sval)
+#define PyString_GET_SIZE(op) Py_SIZE(op)
+
+/* _PyString_Join(sep, x) is like sep.join(x). sep must be PyStringObject*,
+ x must be an iterable object. */
+PyAPI_FUNC(PyObject *) _PyString_Join(PyObject *sep, PyObject *x);
+
+/* --- Generic Codecs ----------------------------------------------------- */
+
+/* Create an object by decoding the encoded string s of the
+ given size. */
+
+PyAPI_FUNC(PyObject*) PyString_Decode(
+ const char *s, /* encoded string */
+ Py_ssize_t size, /* size of buffer */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Encodes a char buffer of the given size and returns a
+ Python object. */
+
+PyAPI_FUNC(PyObject*) PyString_Encode(
+ const char *s, /* string char buffer */
+ Py_ssize_t size, /* number of chars to encode */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Encodes a string object and returns the result as Python
+ object. */
+
+PyAPI_FUNC(PyObject*) PyString_AsEncodedObject(
+ PyObject *str, /* string object */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Encodes a string object and returns the result as Python string
+ object.
+
+ If the codec returns an Unicode object, the object is converted
+ back to a string using the default encoding.
+
+ DEPRECATED - use PyString_AsEncodedObject() instead. */
+
+PyAPI_FUNC(PyObject*) PyString_AsEncodedString(
+ PyObject *str, /* string object */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Decodes a string object and returns the result as Python
+ object. */
+
+PyAPI_FUNC(PyObject*) PyString_AsDecodedObject(
+ PyObject *str, /* string object */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Decodes a string object and returns the result as Python string
+ object.
+
+ If the codec returns an Unicode object, the object is converted
+ back to a string using the default encoding.
+
+ DEPRECATED - use PyString_AsDecodedObject() instead. */
+
+PyAPI_FUNC(PyObject*) PyString_AsDecodedString(
+ PyObject *str, /* string object */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Provides access to the internal data buffer and size of a string
+ object or the default encoded version of an Unicode object. Passing
+ NULL as *len parameter will force the string buffer to be
+ 0-terminated (passing a string with embedded NULL characters will
+ cause an exception). */
+
+PyAPI_FUNC(int) PyString_AsStringAndSize(
+ register PyObject *obj, /* string or Unicode object */
+ register char **s, /* pointer to buffer variable */
+ register Py_ssize_t *len /* pointer to length variable or NULL
+ (only possible for 0-terminated
+ strings) */
+ );
+
+
+/* Using the current locale, insert the thousands grouping
+ into the string pointed to by buffer. For the argument descriptions,
+ see Objects/stringlib/localeutil.h */
+PyAPI_FUNC(Py_ssize_t) _PyString_InsertThousandsGroupingLocale(char *buffer,
+ Py_ssize_t n_buffer,
+ char *digits,
+ Py_ssize_t n_digits,
+ Py_ssize_t min_width);
+
+/* Using explicit passed-in values, insert the thousands grouping
+ into the string pointed to by buffer. For the argument descriptions,
+ see Objects/stringlib/localeutil.h */
+PyAPI_FUNC(Py_ssize_t) _PyString_InsertThousandsGrouping(char *buffer,
+ Py_ssize_t n_buffer,
+ char *digits,
+ Py_ssize_t n_digits,
+ Py_ssize_t min_width,
+ const char *grouping,
+ const char *thousands_sep);
+
+/* Format the object based on the format_spec, as defined in PEP 3101
+ (Advanced String Formatting). */
+PyAPI_FUNC(PyObject *) _PyBytes_FormatAdvanced(PyObject *obj,
+ char *format_spec,
+ Py_ssize_t format_spec_len);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_STRINGOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/structmember.h b/AppPkg/Applications/Python/Python-2.7.2/Include/structmember.h
new file mode 100644
index 0000000000..8e2425bc79
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/structmember.h
@@ -0,0 +1,99 @@
+#ifndef Py_STRUCTMEMBER_H
+#define Py_STRUCTMEMBER_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Interface to map C struct members to Python object attributes */
+
+#include /* For offsetof */
+
+/* The offsetof() macro calculates the offset of a structure member
+ in its structure. Unfortunately this cannot be written down
+ portably, hence it is provided by a Standard C header file.
+ For pre-Standard C compilers, here is a version that usually works
+ (but watch out!): */
+
+#ifndef offsetof
+#define offsetof(type, member) ( (int) & ((type*)0) -> member )
+#endif
+
+/* An array of memberlist structures defines the name, type and offset
+ of selected members of a C structure. These can be read by
+ PyMember_Get() and set by PyMember_Set() (except if their READONLY flag
+ is set). The array must be terminated with an entry whose name
+ pointer is NULL. */
+
+struct memberlist {
+ /* Obsolete version, for binary backwards compatibility */
+ char *name;
+ int type;
+ int offset;
+ int flags;
+};
+
+typedef struct PyMemberDef {
+ /* Current version, use this */
+ char *name;
+ int type;
+ Py_ssize_t offset;
+ int flags;
+ char *doc;
+} PyMemberDef;
+
+/* Types */
+#define T_SHORT 0
+#define T_INT 1
+#define T_LONG 2
+#define T_FLOAT 3
+#define T_DOUBLE 4
+#define T_STRING 5
+#define T_OBJECT 6
+/* XXX the ordering here is weird for binary compatibility */
+#define T_CHAR 7 /* 1-character string */
+#define T_BYTE 8 /* 8-bit signed int */
+/* unsigned variants: */
+#define T_UBYTE 9
+#define T_USHORT 10
+#define T_UINT 11
+#define T_ULONG 12
+
+/* Added by Jack: strings contained in the structure */
+#define T_STRING_INPLACE 13
+
+/* Added by Lillo: bools contained in the structure (assumed char) */
+#define T_BOOL 14
+
+#define T_OBJECT_EX 16 /* Like T_OBJECT, but raises AttributeError
+ when the value is NULL, instead of
+ converting to None. */
+#ifdef HAVE_LONG_LONG
+#define T_LONGLONG 17
+#define T_ULONGLONG 18
+#endif /* HAVE_LONG_LONG */
+
+#define T_PYSSIZET 19 /* Py_ssize_t */
+
+
+/* Flags */
+#define READONLY 1
+#define RO READONLY /* Shorthand */
+#define READ_RESTRICTED 2
+#define PY_WRITE_RESTRICTED 4
+#define RESTRICTED (READ_RESTRICTED | PY_WRITE_RESTRICTED)
+
+
+/* Obsolete API, for binary backwards compatibility */
+PyAPI_FUNC(PyObject *) PyMember_Get(const char *, struct memberlist *, const char *);
+PyAPI_FUNC(int) PyMember_Set(char *, struct memberlist *, const char *, PyObject *);
+
+/* Current API, use this */
+PyAPI_FUNC(PyObject *) PyMember_GetOne(const char *, struct PyMemberDef *);
+PyAPI_FUNC(int) PyMember_SetOne(char *, struct PyMemberDef *, PyObject *);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_STRUCTMEMBER_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/structseq.h b/AppPkg/Applications/Python/Python-2.7.2/Include/structseq.h
new file mode 100644
index 0000000000..74b1a88120
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/structseq.h
@@ -0,0 +1,41 @@
+
+/* Tuple object interface */
+
+#ifndef Py_STRUCTSEQ_H
+#define Py_STRUCTSEQ_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct PyStructSequence_Field {
+ char *name;
+ char *doc;
+} PyStructSequence_Field;
+
+typedef struct PyStructSequence_Desc {
+ char *name;
+ char *doc;
+ struct PyStructSequence_Field *fields;
+ int n_in_sequence;
+} PyStructSequence_Desc;
+
+extern char* PyStructSequence_UnnamedField;
+
+PyAPI_FUNC(void) PyStructSequence_InitType(PyTypeObject *type,
+ PyStructSequence_Desc *desc);
+
+PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type);
+
+typedef struct {
+ PyObject_VAR_HEAD
+ PyObject *ob_item[1];
+} PyStructSequence;
+
+/* Macro, *only* to be used to fill in brand new objects */
+#define PyStructSequence_SET_ITEM(op, i, v) \
+ (((PyStructSequence *)(op))->ob_item[i] = v)
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_STRUCTSEQ_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/symtable.h b/AppPkg/Applications/Python/Python-2.7.2/Include/symtable.h
new file mode 100644
index 0000000000..dd3e360642
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/symtable.h
@@ -0,0 +1,98 @@
+#ifndef Py_SYMTABLE_H
+#define Py_SYMTABLE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum _block_type { FunctionBlock, ClassBlock, ModuleBlock }
+ _Py_block_ty;
+
+struct _symtable_entry;
+
+struct symtable {
+ const char *st_filename; /* name of file being compiled */
+ struct _symtable_entry *st_cur; /* current symbol table entry */
+ struct _symtable_entry *st_top; /* module entry */
+ PyObject *st_symbols; /* dictionary of symbol table entries */
+ PyObject *st_stack; /* stack of namespace info */
+ PyObject *st_global; /* borrowed ref to MODULE in st_symbols */
+ int st_nblocks; /* number of blocks */
+ PyObject *st_private; /* name of current class or NULL */
+ PyFutureFeatures *st_future; /* module's future features */
+};
+
+typedef struct _symtable_entry {
+ PyObject_HEAD
+ PyObject *ste_id; /* int: key in st_symbols */
+ PyObject *ste_symbols; /* dict: name to flags */
+ PyObject *ste_name; /* string: name of block */
+ PyObject *ste_varnames; /* list of variable names */
+ PyObject *ste_children; /* list of child ids */
+ _Py_block_ty ste_type; /* module, class, or function */
+ int ste_unoptimized; /* false if namespace is optimized */
+ int ste_nested; /* true if block is nested */
+ unsigned ste_free : 1; /* true if block has free variables */
+ unsigned ste_child_free : 1; /* true if a child block has free vars,
+ including free refs to globals */
+ unsigned ste_generator : 1; /* true if namespace is a generator */
+ unsigned ste_varargs : 1; /* true if block has varargs */
+ unsigned ste_varkeywords : 1; /* true if block has varkeywords */
+ unsigned ste_returns_value : 1; /* true if namespace uses return with
+ an argument */
+ int ste_lineno; /* first line of block */
+ int ste_opt_lineno; /* lineno of last exec or import * */
+ int ste_tmpname; /* counter for listcomp temp vars */
+ struct symtable *ste_table;
+} PySTEntryObject;
+
+PyAPI_DATA(PyTypeObject) PySTEntry_Type;
+
+#define PySTEntry_Check(op) (Py_TYPE(op) == &PySTEntry_Type)
+
+PyAPI_FUNC(int) PyST_GetScope(PySTEntryObject *, PyObject *);
+
+PyAPI_FUNC(struct symtable *) PySymtable_Build(mod_ty, const char *,
+ PyFutureFeatures *);
+PyAPI_FUNC(PySTEntryObject *) PySymtable_Lookup(struct symtable *, void *);
+
+PyAPI_FUNC(void) PySymtable_Free(struct symtable *);
+
+/* Flags for def-use information */
+
+#define DEF_GLOBAL 1 /* global stmt */
+#define DEF_LOCAL 2 /* assignment in code block */
+#define DEF_PARAM 2<<1 /* formal parameter */
+#define USE 2<<2 /* name is used */
+#define DEF_FREE 2<<3 /* name used but not defined in nested block */
+#define DEF_FREE_CLASS 2<<4 /* free variable from class's method */
+#define DEF_IMPORT 2<<5 /* assignment occurred via import */
+
+#define DEF_BOUND (DEF_LOCAL | DEF_PARAM | DEF_IMPORT)
+
+/* GLOBAL_EXPLICIT and GLOBAL_IMPLICIT are used internally by the symbol
+ table. GLOBAL is returned from PyST_GetScope() for either of them.
+ It is stored in ste_symbols at bits 12-14.
+*/
+#define SCOPE_OFF 11
+#define SCOPE_MASK 7
+
+#define LOCAL 1
+#define GLOBAL_EXPLICIT 2
+#define GLOBAL_IMPLICIT 3
+#define FREE 4
+#define CELL 5
+
+/* The following three names are used for the ste_unoptimized bit field */
+#define OPT_IMPORT_STAR 1
+#define OPT_EXEC 2
+#define OPT_BARE_EXEC 4
+#define OPT_TOPLEVEL 8 /* top-level names, including eval and exec */
+
+#define GENERATOR 1
+#define GENERATOR_EXPRESSION 2
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_SYMTABLE_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/sysmodule.h b/AppPkg/Applications/Python/Python-2.7.2/Include/sysmodule.h
new file mode 100644
index 0000000000..623d840fe9
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/sysmodule.h
@@ -0,0 +1,32 @@
+
+/* System module interface */
+
+#ifndef Py_SYSMODULE_H
+#define Py_SYSMODULE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_FUNC(PyObject *) PySys_GetObject(char *);
+PyAPI_FUNC(int) PySys_SetObject(char *, PyObject *);
+PyAPI_FUNC(FILE *) PySys_GetFile(char *, FILE *);
+PyAPI_FUNC(void) PySys_SetArgv(int, char **);
+PyAPI_FUNC(void) PySys_SetArgvEx(int, char **, int);
+PyAPI_FUNC(void) PySys_SetPath(char *);
+
+PyAPI_FUNC(void) PySys_WriteStdout(const char *format, ...)
+ Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
+PyAPI_FUNC(void) PySys_WriteStderr(const char *format, ...)
+ Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
+
+PyAPI_DATA(PyObject *) _PySys_TraceFunc, *_PySys_ProfileFunc;
+PyAPI_DATA(int) _PySys_CheckInterval;
+
+PyAPI_FUNC(void) PySys_ResetWarnOptions(void);
+PyAPI_FUNC(void) PySys_AddWarnOption(char *);
+PyAPI_FUNC(int) PySys_HasWarnOptions(void);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_SYSMODULE_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/timefuncs.h b/AppPkg/Applications/Python/Python-2.7.2/Include/timefuncs.h
new file mode 100644
index 0000000000..e6d4b4c9d3
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/timefuncs.h
@@ -0,0 +1,23 @@
+/* timefuncs.h
+ */
+
+/* Utility function related to timemodule.c. */
+
+#ifndef TIMEFUNCS_H
+#define TIMEFUNCS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Cast double x to time_t, but raise ValueError if x is too large
+ * to fit in a time_t. ValueError is set on return iff the return
+ * value is (time_t)-1 and PyErr_Occurred().
+ */
+PyAPI_FUNC(time_t) _PyTime_DoubleToTimet(double x);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* TIMEFUNCS_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/token.h b/AppPkg/Applications/Python/Python-2.7.2/Include/token.h
new file mode 100644
index 0000000000..438f04ba87
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/token.h
@@ -0,0 +1,85 @@
+
+/* Token types */
+
+#ifndef Py_TOKEN_H
+#define Py_TOKEN_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#undef TILDE /* Prevent clash of our definition with system macro. Ex AIX, ioctl.h */
+
+#define ENDMARKER 0
+#define NAME 1
+#define NUMBER 2
+#define STRING 3
+#define NEWLINE 4
+#define INDENT 5
+#define DEDENT 6
+#define LPAR 7
+#define RPAR 8
+#define LSQB 9
+#define RSQB 10
+#define COLON 11
+#define COMMA 12
+#define SEMI 13
+#define PLUS 14
+#define MINUS 15
+#define STAR 16
+#define SLASH 17
+#define VBAR 18
+#define AMPER 19
+#define LESS 20
+#define GREATER 21
+#define EQUAL 22
+#define DOT 23
+#define PERCENT 24
+#define BACKQUOTE 25
+#define LBRACE 26
+#define RBRACE 27
+#define EQEQUAL 28
+#define NOTEQUAL 29
+#define LESSEQUAL 30
+#define GREATEREQUAL 31
+#define TILDE 32
+#define CIRCUMFLEX 33
+#define LEFTSHIFT 34
+#define RIGHTSHIFT 35
+#define DOUBLESTAR 36
+#define PLUSEQUAL 37
+#define MINEQUAL 38
+#define STAREQUAL 39
+#define SLASHEQUAL 40
+#define PERCENTEQUAL 41
+#define AMPEREQUAL 42
+#define VBAREQUAL 43
+#define CIRCUMFLEXEQUAL 44
+#define LEFTSHIFTEQUAL 45
+#define RIGHTSHIFTEQUAL 46
+#define DOUBLESTAREQUAL 47
+#define DOUBLESLASH 48
+#define DOUBLESLASHEQUAL 49
+#define AT 50
+/* Don't forget to update the table _PyParser_TokenNames in tokenizer.c! */
+#define OP 51
+#define ERRORTOKEN 52
+#define N_TOKENS 53
+
+/* Special definitions for cooperation with parser */
+
+#define NT_OFFSET 256
+
+#define ISTERMINAL(x) ((x) < NT_OFFSET)
+#define ISNONTERMINAL(x) ((x) >= NT_OFFSET)
+#define ISEOF(x) ((x) == ENDMARKER)
+
+
+PyAPI_DATA(char *) _PyParser_TokenNames[]; /* Token names */
+PyAPI_FUNC(int) PyToken_OneChar(int);
+PyAPI_FUNC(int) PyToken_TwoChars(int, int);
+PyAPI_FUNC(int) PyToken_ThreeChars(int, int, int);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_TOKEN_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/traceback.h b/AppPkg/Applications/Python/Python-2.7.2/Include/traceback.h
new file mode 100644
index 0000000000..fce0607e3f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/traceback.h
@@ -0,0 +1,31 @@
+
+#ifndef Py_TRACEBACK_H
+#define Py_TRACEBACK_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct _frame;
+
+/* Traceback interface */
+
+typedef struct _traceback {
+ PyObject_HEAD
+ struct _traceback *tb_next;
+ struct _frame *tb_frame;
+ int tb_lasti;
+ int tb_lineno;
+} PyTracebackObject;
+
+PyAPI_FUNC(int) PyTraceBack_Here(struct _frame *);
+PyAPI_FUNC(int) PyTraceBack_Print(PyObject *, PyObject *);
+PyAPI_FUNC(int) _Py_DisplaySourceLine(PyObject *, const char *, int, int);
+
+/* Reveal traceback type so we can typecheck traceback objects */
+PyAPI_DATA(PyTypeObject) PyTraceBack_Type;
+#define PyTraceBack_Check(v) (Py_TYPE(v) == &PyTraceBack_Type)
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_TRACEBACK_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/tupleobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/tupleobject.h
new file mode 100644
index 0000000000..8fdfd596cf
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/tupleobject.h
@@ -0,0 +1,61 @@
+
+/* Tuple object interface */
+
+#ifndef Py_TUPLEOBJECT_H
+#define Py_TUPLEOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+Another generally useful object type is a tuple of object pointers.
+For Python, this is an immutable type. C code can change the tuple items
+(but not their number), and even use tuples are general-purpose arrays of
+object references, but in general only brand new tuples should be mutated,
+not ones that might already have been exposed to Python code.
+
+*** WARNING *** PyTuple_SetItem does not increment the new item's reference
+count, but does decrement the reference count of the item it replaces,
+if not nil. It does *decrement* the reference count if it is *not*
+inserted in the tuple. Similarly, PyTuple_GetItem does not increment the
+returned item's reference count.
+*/
+
+typedef struct {
+ PyObject_VAR_HEAD
+ PyObject *ob_item[1];
+
+ /* ob_item contains space for 'ob_size' elements.
+ * Items must normally not be NULL, except during construction when
+ * the tuple is not yet visible outside the function that builds it.
+ */
+} PyTupleObject;
+
+PyAPI_DATA(PyTypeObject) PyTuple_Type;
+
+#define PyTuple_Check(op) \
+ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TUPLE_SUBCLASS)
+#define PyTuple_CheckExact(op) (Py_TYPE(op) == &PyTuple_Type)
+
+PyAPI_FUNC(PyObject *) PyTuple_New(Py_ssize_t size);
+PyAPI_FUNC(Py_ssize_t) PyTuple_Size(PyObject *);
+PyAPI_FUNC(PyObject *) PyTuple_GetItem(PyObject *, Py_ssize_t);
+PyAPI_FUNC(int) PyTuple_SetItem(PyObject *, Py_ssize_t, PyObject *);
+PyAPI_FUNC(PyObject *) PyTuple_GetSlice(PyObject *, Py_ssize_t, Py_ssize_t);
+PyAPI_FUNC(int) _PyTuple_Resize(PyObject **, Py_ssize_t);
+PyAPI_FUNC(PyObject *) PyTuple_Pack(Py_ssize_t, ...);
+PyAPI_FUNC(void) _PyTuple_MaybeUntrack(PyObject *);
+
+/* Macro, trading safety for speed */
+#define PyTuple_GET_ITEM(op, i) (((PyTupleObject *)(op))->ob_item[i])
+#define PyTuple_GET_SIZE(op) Py_SIZE(op)
+
+/* Macro, *only* to be used to fill in brand new tuples */
+#define PyTuple_SET_ITEM(op, i, v) (((PyTupleObject *)(op))->ob_item[i] = v)
+
+PyAPI_FUNC(int) PyTuple_ClearFreeList(void);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_TUPLEOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/ucnhash.h b/AppPkg/Applications/Python/Python-2.7.2/Include/ucnhash.h
new file mode 100644
index 0000000000..8158730bc0
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/ucnhash.h
@@ -0,0 +1,33 @@
+/* Unicode name database interface */
+
+#ifndef Py_UCNHASH_H
+#define Py_UCNHASH_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* revised ucnhash CAPI interface (exported through a "wrapper") */
+
+#define PyUnicodeData_CAPSULE_NAME "unicodedata.ucnhash_CAPI"
+
+typedef struct {
+
+ /* Size of this struct */
+ int size;
+
+ /* Get name for a given character code. Returns non-zero if
+ success, zero if not. Does not set Python exceptions.
+ If self is NULL, data come from the default version of the database.
+ If it is not NULL, it should be a unicodedata.ucd_X_Y_Z object */
+ int (*getname)(PyObject *self, Py_UCS4 code, char* buffer, int buflen);
+
+ /* Get character code for a given name. Same error handling
+ as for getname. */
+ int (*getcode)(PyObject *self, const char* name, int namelen, Py_UCS4* code);
+
+} _PyUnicode_Name_CAPI;
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_UCNHASH_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/unicodeobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/unicodeobject.h
new file mode 100644
index 0000000000..de52416513
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/unicodeobject.h
@@ -0,0 +1,1413 @@
+#ifndef Py_UNICODEOBJECT_H
+#define Py_UNICODEOBJECT_H
+
+#include
+
+/*
+
+Unicode implementation based on original code by Fredrik Lundh,
+modified by Marc-Andre Lemburg (mal@lemburg.com) according to the
+Unicode Integration Proposal (see file Misc/unicode.txt).
+
+Copyright (c) Corporation for National Research Initiatives.
+
+
+ Original header:
+ --------------------------------------------------------------------
+
+ * Yet another Unicode string type for Python. This type supports the
+ * 16-bit Basic Multilingual Plane (BMP) only.
+ *
+ * Written by Fredrik Lundh, January 1999.
+ *
+ * Copyright (c) 1999 by Secret Labs AB.
+ * Copyright (c) 1999 by Fredrik Lundh.
+ *
+ * fredrik@pythonware.com
+ * http://www.pythonware.com
+ *
+ * --------------------------------------------------------------------
+ * This Unicode String Type is
+ *
+ * Copyright (c) 1999 by Secret Labs AB
+ * Copyright (c) 1999 by Fredrik Lundh
+ *
+ * By obtaining, using, and/or copying this software and/or its
+ * associated documentation, you agree that you have read, understood,
+ * and will comply with the following terms and conditions:
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * associated documentation for any purpose and without fee is hereby
+ * granted, provided that the above copyright notice appears in all
+ * copies, and that both that copyright notice and this permission notice
+ * appear in supporting documentation, and that the name of Secret Labs
+ * AB or the author not be used in advertising or publicity pertaining to
+ * distribution of the software without specific, written prior
+ * permission.
+ *
+ * SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
+ * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+ * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ * -------------------------------------------------------------------- */
+
+#include
+
+/* === Internal API ======================================================= */
+
+/* --- Internal Unicode Format -------------------------------------------- */
+
+#ifndef Py_USING_UNICODE
+
+#define PyUnicode_Check(op) 0
+#define PyUnicode_CheckExact(op) 0
+
+#else
+
+/* FIXME: MvL's new implementation assumes that Py_UNICODE_SIZE is
+ properly set, but the default rules below doesn't set it. I'll
+ sort this out some other day -- fredrik@pythonware.com */
+
+#ifndef Py_UNICODE_SIZE
+#error Must define Py_UNICODE_SIZE
+#endif
+
+/* Setting Py_UNICODE_WIDE enables UCS-4 storage. Otherwise, Unicode
+ strings are stored as UCS-2 (with limited support for UTF-16) */
+
+#if Py_UNICODE_SIZE >= 4
+#define Py_UNICODE_WIDE
+#endif
+
+/* Set these flags if the platform has "wchar.h", "wctype.h" and the
+ wchar_t type is a 16-bit unsigned type */
+/* #define HAVE_WCHAR_H */
+/* #define HAVE_USABLE_WCHAR_T */
+
+/* Defaults for various platforms */
+#ifndef PY_UNICODE_TYPE
+
+/* Windows has a usable wchar_t type (unless we're using UCS-4) */
+# if defined(MS_WIN32) && Py_UNICODE_SIZE == 2
+# define HAVE_USABLE_WCHAR_T
+# define PY_UNICODE_TYPE wchar_t
+# endif
+
+# if defined(Py_UNICODE_WIDE)
+# define PY_UNICODE_TYPE Py_UCS4
+# endif
+
+#endif
+
+/* If the compiler provides a wchar_t type we try to support it
+ through the interface functions PyUnicode_FromWideChar() and
+ PyUnicode_AsWideChar(). */
+
+#ifdef HAVE_USABLE_WCHAR_T
+# ifndef HAVE_WCHAR_H
+# define HAVE_WCHAR_H
+# endif
+#endif
+
+#ifdef HAVE_WCHAR_H
+/* Work around a cosmetic bug in BSDI 4.x wchar.h; thanks to Thomas Wouters */
+# ifdef _HAVE_BSDI
+# include
+# endif
+# include
+#endif
+
+/*
+ * Use this typedef when you need to represent a UTF-16 surrogate pair
+ * as single unsigned integer.
+ */
+#if SIZEOF_INT >= 4
+typedef unsigned int Py_UCS4;
+#elif SIZEOF_LONG >= 4
+typedef unsigned long Py_UCS4;
+#endif
+
+/* Py_UNICODE is the native Unicode storage format (code unit) used by
+ Python and represents a single Unicode element in the Unicode
+ type. */
+
+typedef PY_UNICODE_TYPE Py_UNICODE;
+
+/* --- UCS-2/UCS-4 Name Mangling ------------------------------------------ */
+
+/* Unicode API names are mangled to assure that UCS-2 and UCS-4 builds
+ produce different external names and thus cause import errors in
+ case Python interpreters and extensions with mixed compiled in
+ Unicode width assumptions are combined. */
+
+#ifndef Py_UNICODE_WIDE
+
+# define PyUnicode_AsASCIIString PyUnicodeUCS2_AsASCIIString
+# define PyUnicode_AsCharmapString PyUnicodeUCS2_AsCharmapString
+# define PyUnicode_AsEncodedObject PyUnicodeUCS2_AsEncodedObject
+# define PyUnicode_AsEncodedString PyUnicodeUCS2_AsEncodedString
+# define PyUnicode_AsLatin1String PyUnicodeUCS2_AsLatin1String
+# define PyUnicode_AsRawUnicodeEscapeString PyUnicodeUCS2_AsRawUnicodeEscapeString
+# define PyUnicode_AsUTF32String PyUnicodeUCS2_AsUTF32String
+# define PyUnicode_AsUTF16String PyUnicodeUCS2_AsUTF16String
+# define PyUnicode_AsUTF8String PyUnicodeUCS2_AsUTF8String
+# define PyUnicode_AsUnicode PyUnicodeUCS2_AsUnicode
+# define PyUnicode_AsUnicodeEscapeString PyUnicodeUCS2_AsUnicodeEscapeString
+# define PyUnicode_AsWideChar PyUnicodeUCS2_AsWideChar
+# define PyUnicode_ClearFreeList PyUnicodeUCS2_ClearFreelist
+# define PyUnicode_Compare PyUnicodeUCS2_Compare
+# define PyUnicode_Concat PyUnicodeUCS2_Concat
+# define PyUnicode_Contains PyUnicodeUCS2_Contains
+# define PyUnicode_Count PyUnicodeUCS2_Count
+# define PyUnicode_Decode PyUnicodeUCS2_Decode
+# define PyUnicode_DecodeASCII PyUnicodeUCS2_DecodeASCII
+# define PyUnicode_DecodeCharmap PyUnicodeUCS2_DecodeCharmap
+# define PyUnicode_DecodeLatin1 PyUnicodeUCS2_DecodeLatin1
+# define PyUnicode_DecodeRawUnicodeEscape PyUnicodeUCS2_DecodeRawUnicodeEscape
+# define PyUnicode_DecodeUTF32 PyUnicodeUCS2_DecodeUTF32
+# define PyUnicode_DecodeUTF32Stateful PyUnicodeUCS2_DecodeUTF32Stateful
+# define PyUnicode_DecodeUTF16 PyUnicodeUCS2_DecodeUTF16
+# define PyUnicode_DecodeUTF16Stateful PyUnicodeUCS2_DecodeUTF16Stateful
+# define PyUnicode_DecodeUTF8 PyUnicodeUCS2_DecodeUTF8
+# define PyUnicode_DecodeUTF8Stateful PyUnicodeUCS2_DecodeUTF8Stateful
+# define PyUnicode_DecodeUnicodeEscape PyUnicodeUCS2_DecodeUnicodeEscape
+# define PyUnicode_Encode PyUnicodeUCS2_Encode
+# define PyUnicode_EncodeASCII PyUnicodeUCS2_EncodeASCII
+# define PyUnicode_EncodeCharmap PyUnicodeUCS2_EncodeCharmap
+# define PyUnicode_EncodeDecimal PyUnicodeUCS2_EncodeDecimal
+# define PyUnicode_EncodeLatin1 PyUnicodeUCS2_EncodeLatin1
+# define PyUnicode_EncodeRawUnicodeEscape PyUnicodeUCS2_EncodeRawUnicodeEscape
+# define PyUnicode_EncodeUTF32 PyUnicodeUCS2_EncodeUTF32
+# define PyUnicode_EncodeUTF16 PyUnicodeUCS2_EncodeUTF16
+# define PyUnicode_EncodeUTF8 PyUnicodeUCS2_EncodeUTF8
+# define PyUnicode_EncodeUnicodeEscape PyUnicodeUCS2_EncodeUnicodeEscape
+# define PyUnicode_Find PyUnicodeUCS2_Find
+# define PyUnicode_Format PyUnicodeUCS2_Format
+# define PyUnicode_FromEncodedObject PyUnicodeUCS2_FromEncodedObject
+# define PyUnicode_FromFormat PyUnicodeUCS2_FromFormat
+# define PyUnicode_FromFormatV PyUnicodeUCS2_FromFormatV
+# define PyUnicode_FromObject PyUnicodeUCS2_FromObject
+# define PyUnicode_FromOrdinal PyUnicodeUCS2_FromOrdinal
+# define PyUnicode_FromString PyUnicodeUCS2_FromString
+# define PyUnicode_FromStringAndSize PyUnicodeUCS2_FromStringAndSize
+# define PyUnicode_FromUnicode PyUnicodeUCS2_FromUnicode
+# define PyUnicode_FromWideChar PyUnicodeUCS2_FromWideChar
+# define PyUnicode_GetDefaultEncoding PyUnicodeUCS2_GetDefaultEncoding
+# define PyUnicode_GetMax PyUnicodeUCS2_GetMax
+# define PyUnicode_GetSize PyUnicodeUCS2_GetSize
+# define PyUnicode_Join PyUnicodeUCS2_Join
+# define PyUnicode_Partition PyUnicodeUCS2_Partition
+# define PyUnicode_RPartition PyUnicodeUCS2_RPartition
+# define PyUnicode_RSplit PyUnicodeUCS2_RSplit
+# define PyUnicode_Replace PyUnicodeUCS2_Replace
+# define PyUnicode_Resize PyUnicodeUCS2_Resize
+# define PyUnicode_RichCompare PyUnicodeUCS2_RichCompare
+# define PyUnicode_SetDefaultEncoding PyUnicodeUCS2_SetDefaultEncoding
+# define PyUnicode_Split PyUnicodeUCS2_Split
+# define PyUnicode_Splitlines PyUnicodeUCS2_Splitlines
+# define PyUnicode_Tailmatch PyUnicodeUCS2_Tailmatch
+# define PyUnicode_Translate PyUnicodeUCS2_Translate
+# define PyUnicode_TranslateCharmap PyUnicodeUCS2_TranslateCharmap
+# define _PyUnicode_AsDefaultEncodedString _PyUnicodeUCS2_AsDefaultEncodedString
+# define _PyUnicode_Fini _PyUnicodeUCS2_Fini
+# define _PyUnicode_Init _PyUnicodeUCS2_Init
+# define _PyUnicode_IsAlpha _PyUnicodeUCS2_IsAlpha
+# define _PyUnicode_IsDecimalDigit _PyUnicodeUCS2_IsDecimalDigit
+# define _PyUnicode_IsDigit _PyUnicodeUCS2_IsDigit
+# define _PyUnicode_IsLinebreak _PyUnicodeUCS2_IsLinebreak
+# define _PyUnicode_IsLowercase _PyUnicodeUCS2_IsLowercase
+# define _PyUnicode_IsNumeric _PyUnicodeUCS2_IsNumeric
+# define _PyUnicode_IsTitlecase _PyUnicodeUCS2_IsTitlecase
+# define _PyUnicode_IsUppercase _PyUnicodeUCS2_IsUppercase
+# define _PyUnicode_IsWhitespace _PyUnicodeUCS2_IsWhitespace
+# define _PyUnicode_ToDecimalDigit _PyUnicodeUCS2_ToDecimalDigit
+# define _PyUnicode_ToDigit _PyUnicodeUCS2_ToDigit
+# define _PyUnicode_ToLowercase _PyUnicodeUCS2_ToLowercase
+# define _PyUnicode_ToNumeric _PyUnicodeUCS2_ToNumeric
+# define _PyUnicode_ToTitlecase _PyUnicodeUCS2_ToTitlecase
+# define _PyUnicode_ToUppercase _PyUnicodeUCS2_ToUppercase
+
+#else
+
+# define PyUnicode_AsASCIIString PyUnicodeUCS4_AsASCIIString
+# define PyUnicode_AsCharmapString PyUnicodeUCS4_AsCharmapString
+# define PyUnicode_AsEncodedObject PyUnicodeUCS4_AsEncodedObject
+# define PyUnicode_AsEncodedString PyUnicodeUCS4_AsEncodedString
+# define PyUnicode_AsLatin1String PyUnicodeUCS4_AsLatin1String
+# define PyUnicode_AsRawUnicodeEscapeString PyUnicodeUCS4_AsRawUnicodeEscapeString
+# define PyUnicode_AsUTF32String PyUnicodeUCS4_AsUTF32String
+# define PyUnicode_AsUTF16String PyUnicodeUCS4_AsUTF16String
+# define PyUnicode_AsUTF8String PyUnicodeUCS4_AsUTF8String
+# define PyUnicode_AsUnicode PyUnicodeUCS4_AsUnicode
+# define PyUnicode_AsUnicodeEscapeString PyUnicodeUCS4_AsUnicodeEscapeString
+# define PyUnicode_AsWideChar PyUnicodeUCS4_AsWideChar
+# define PyUnicode_ClearFreeList PyUnicodeUCS4_ClearFreelist
+# define PyUnicode_Compare PyUnicodeUCS4_Compare
+# define PyUnicode_Concat PyUnicodeUCS4_Concat
+# define PyUnicode_Contains PyUnicodeUCS4_Contains
+# define PyUnicode_Count PyUnicodeUCS4_Count
+# define PyUnicode_Decode PyUnicodeUCS4_Decode
+# define PyUnicode_DecodeASCII PyUnicodeUCS4_DecodeASCII
+# define PyUnicode_DecodeCharmap PyUnicodeUCS4_DecodeCharmap
+# define PyUnicode_DecodeLatin1 PyUnicodeUCS4_DecodeLatin1
+# define PyUnicode_DecodeRawUnicodeEscape PyUnicodeUCS4_DecodeRawUnicodeEscape
+# define PyUnicode_DecodeUTF32 PyUnicodeUCS4_DecodeUTF32
+# define PyUnicode_DecodeUTF32Stateful PyUnicodeUCS4_DecodeUTF32Stateful
+# define PyUnicode_DecodeUTF16 PyUnicodeUCS4_DecodeUTF16
+# define PyUnicode_DecodeUTF16Stateful PyUnicodeUCS4_DecodeUTF16Stateful
+# define PyUnicode_DecodeUTF8 PyUnicodeUCS4_DecodeUTF8
+# define PyUnicode_DecodeUTF8Stateful PyUnicodeUCS4_DecodeUTF8Stateful
+# define PyUnicode_DecodeUnicodeEscape PyUnicodeUCS4_DecodeUnicodeEscape
+# define PyUnicode_Encode PyUnicodeUCS4_Encode
+# define PyUnicode_EncodeASCII PyUnicodeUCS4_EncodeASCII
+# define PyUnicode_EncodeCharmap PyUnicodeUCS4_EncodeCharmap
+# define PyUnicode_EncodeDecimal PyUnicodeUCS4_EncodeDecimal
+# define PyUnicode_EncodeLatin1 PyUnicodeUCS4_EncodeLatin1
+# define PyUnicode_EncodeRawUnicodeEscape PyUnicodeUCS4_EncodeRawUnicodeEscape
+# define PyUnicode_EncodeUTF32 PyUnicodeUCS4_EncodeUTF32
+# define PyUnicode_EncodeUTF16 PyUnicodeUCS4_EncodeUTF16
+# define PyUnicode_EncodeUTF8 PyUnicodeUCS4_EncodeUTF8
+# define PyUnicode_EncodeUnicodeEscape PyUnicodeUCS4_EncodeUnicodeEscape
+# define PyUnicode_Find PyUnicodeUCS4_Find
+# define PyUnicode_Format PyUnicodeUCS4_Format
+# define PyUnicode_FromEncodedObject PyUnicodeUCS4_FromEncodedObject
+# define PyUnicode_FromFormat PyUnicodeUCS4_FromFormat
+# define PyUnicode_FromFormatV PyUnicodeUCS4_FromFormatV
+# define PyUnicode_FromObject PyUnicodeUCS4_FromObject
+# define PyUnicode_FromOrdinal PyUnicodeUCS4_FromOrdinal
+# define PyUnicode_FromString PyUnicodeUCS4_FromString
+# define PyUnicode_FromStringAndSize PyUnicodeUCS4_FromStringAndSize
+# define PyUnicode_FromUnicode PyUnicodeUCS4_FromUnicode
+# define PyUnicode_FromWideChar PyUnicodeUCS4_FromWideChar
+# define PyUnicode_GetDefaultEncoding PyUnicodeUCS4_GetDefaultEncoding
+# define PyUnicode_GetMax PyUnicodeUCS4_GetMax
+# define PyUnicode_GetSize PyUnicodeUCS4_GetSize
+# define PyUnicode_Join PyUnicodeUCS4_Join
+# define PyUnicode_Partition PyUnicodeUCS4_Partition
+# define PyUnicode_RPartition PyUnicodeUCS4_RPartition
+# define PyUnicode_RSplit PyUnicodeUCS4_RSplit
+# define PyUnicode_Replace PyUnicodeUCS4_Replace
+# define PyUnicode_Resize PyUnicodeUCS4_Resize
+# define PyUnicode_RichCompare PyUnicodeUCS4_RichCompare
+# define PyUnicode_SetDefaultEncoding PyUnicodeUCS4_SetDefaultEncoding
+# define PyUnicode_Split PyUnicodeUCS4_Split
+# define PyUnicode_Splitlines PyUnicodeUCS4_Splitlines
+# define PyUnicode_Tailmatch PyUnicodeUCS4_Tailmatch
+# define PyUnicode_Translate PyUnicodeUCS4_Translate
+# define PyUnicode_TranslateCharmap PyUnicodeUCS4_TranslateCharmap
+# define _PyUnicode_AsDefaultEncodedString _PyUnicodeUCS4_AsDefaultEncodedString
+# define _PyUnicode_Fini _PyUnicodeUCS4_Fini
+# define _PyUnicode_Init _PyUnicodeUCS4_Init
+# define _PyUnicode_IsAlpha _PyUnicodeUCS4_IsAlpha
+# define _PyUnicode_IsDecimalDigit _PyUnicodeUCS4_IsDecimalDigit
+# define _PyUnicode_IsDigit _PyUnicodeUCS4_IsDigit
+# define _PyUnicode_IsLinebreak _PyUnicodeUCS4_IsLinebreak
+# define _PyUnicode_IsLowercase _PyUnicodeUCS4_IsLowercase
+# define _PyUnicode_IsNumeric _PyUnicodeUCS4_IsNumeric
+# define _PyUnicode_IsTitlecase _PyUnicodeUCS4_IsTitlecase
+# define _PyUnicode_IsUppercase _PyUnicodeUCS4_IsUppercase
+# define _PyUnicode_IsWhitespace _PyUnicodeUCS4_IsWhitespace
+# define _PyUnicode_ToDecimalDigit _PyUnicodeUCS4_ToDecimalDigit
+# define _PyUnicode_ToDigit _PyUnicodeUCS4_ToDigit
+# define _PyUnicode_ToLowercase _PyUnicodeUCS4_ToLowercase
+# define _PyUnicode_ToNumeric _PyUnicodeUCS4_ToNumeric
+# define _PyUnicode_ToTitlecase _PyUnicodeUCS4_ToTitlecase
+# define _PyUnicode_ToUppercase _PyUnicodeUCS4_ToUppercase
+
+
+#endif
+
+/* --- Internal Unicode Operations ---------------------------------------- */
+
+/* If you want Python to use the compiler's wctype.h functions instead
+ of the ones supplied with Python, define WANT_WCTYPE_FUNCTIONS or
+ configure Python using --with-wctype-functions. This reduces the
+ interpreter's code size. */
+
+#if defined(HAVE_USABLE_WCHAR_T) && defined(WANT_WCTYPE_FUNCTIONS)
+
+#include
+
+#define Py_UNICODE_ISSPACE(ch) iswspace(ch)
+
+#define Py_UNICODE_ISLOWER(ch) iswlower(ch)
+#define Py_UNICODE_ISUPPER(ch) iswupper(ch)
+#define Py_UNICODE_ISTITLE(ch) _PyUnicode_IsTitlecase(ch)
+#define Py_UNICODE_ISLINEBREAK(ch) _PyUnicode_IsLinebreak(ch)
+
+#define Py_UNICODE_TOLOWER(ch) towlower(ch)
+#define Py_UNICODE_TOUPPER(ch) towupper(ch)
+#define Py_UNICODE_TOTITLE(ch) _PyUnicode_ToTitlecase(ch)
+
+#define Py_UNICODE_ISDECIMAL(ch) _PyUnicode_IsDecimalDigit(ch)
+#define Py_UNICODE_ISDIGIT(ch) _PyUnicode_IsDigit(ch)
+#define Py_UNICODE_ISNUMERIC(ch) _PyUnicode_IsNumeric(ch)
+
+#define Py_UNICODE_TODECIMAL(ch) _PyUnicode_ToDecimalDigit(ch)
+#define Py_UNICODE_TODIGIT(ch) _PyUnicode_ToDigit(ch)
+#define Py_UNICODE_TONUMERIC(ch) _PyUnicode_ToNumeric(ch)
+
+#define Py_UNICODE_ISALPHA(ch) iswalpha(ch)
+
+#else
+
+/* Since splitting on whitespace is an important use case, and
+ whitespace in most situations is solely ASCII whitespace, we
+ optimize for the common case by using a quick look-up table
+ _Py_ascii_whitespace (see below) with an inlined check.
+
+ */
+#define Py_UNICODE_ISSPACE(ch) \
+ ((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch))
+
+#define Py_UNICODE_ISLOWER(ch) _PyUnicode_IsLowercase(ch)
+#define Py_UNICODE_ISUPPER(ch) _PyUnicode_IsUppercase(ch)
+#define Py_UNICODE_ISTITLE(ch) _PyUnicode_IsTitlecase(ch)
+#define Py_UNICODE_ISLINEBREAK(ch) _PyUnicode_IsLinebreak(ch)
+
+#define Py_UNICODE_TOLOWER(ch) _PyUnicode_ToLowercase(ch)
+#define Py_UNICODE_TOUPPER(ch) _PyUnicode_ToUppercase(ch)
+#define Py_UNICODE_TOTITLE(ch) _PyUnicode_ToTitlecase(ch)
+
+#define Py_UNICODE_ISDECIMAL(ch) _PyUnicode_IsDecimalDigit(ch)
+#define Py_UNICODE_ISDIGIT(ch) _PyUnicode_IsDigit(ch)
+#define Py_UNICODE_ISNUMERIC(ch) _PyUnicode_IsNumeric(ch)
+
+#define Py_UNICODE_TODECIMAL(ch) _PyUnicode_ToDecimalDigit(ch)
+#define Py_UNICODE_TODIGIT(ch) _PyUnicode_ToDigit(ch)
+#define Py_UNICODE_TONUMERIC(ch) _PyUnicode_ToNumeric(ch)
+
+#define Py_UNICODE_ISALPHA(ch) _PyUnicode_IsAlpha(ch)
+
+#endif
+
+#define Py_UNICODE_ISALNUM(ch) \
+ (Py_UNICODE_ISALPHA(ch) || \
+ Py_UNICODE_ISDECIMAL(ch) || \
+ Py_UNICODE_ISDIGIT(ch) || \
+ Py_UNICODE_ISNUMERIC(ch))
+
+#define Py_UNICODE_COPY(target, source, length) \
+ Py_MEMCPY((target), (source), (length)*sizeof(Py_UNICODE))
+
+#define Py_UNICODE_FILL(target, value, length) \
+ do {Py_ssize_t i_; Py_UNICODE *t_ = (target); Py_UNICODE v_ = (value);\
+ for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\
+ } while (0)
+
+/* Check if substring matches at given offset. the offset must be
+ valid, and the substring must not be empty */
+
+#define Py_UNICODE_MATCH(string, offset, substring) \
+ ((*((string)->str + (offset)) == *((substring)->str)) && \
+ ((*((string)->str + (offset) + (substring)->length-1) == *((substring)->str + (substring)->length-1))) && \
+ !memcmp((string)->str + (offset), (substring)->str, (substring)->length*sizeof(Py_UNICODE)))
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* --- Unicode Type ------------------------------------------------------- */
+
+typedef struct {
+ PyObject_HEAD
+ Py_ssize_t length; /* Length of raw Unicode data in buffer */
+ Py_UNICODE *str; /* Raw Unicode buffer */
+ long hash; /* Hash value; -1 if not set */
+ PyObject *defenc; /* (Default) Encoded version as Python
+ string, or NULL; this is used for
+ implementing the buffer protocol */
+} PyUnicodeObject;
+
+PyAPI_DATA(PyTypeObject) PyUnicode_Type;
+
+#define PyUnicode_Check(op) \
+ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_UNICODE_SUBCLASS)
+#define PyUnicode_CheckExact(op) (Py_TYPE(op) == &PyUnicode_Type)
+
+/* Fast access macros */
+#define PyUnicode_GET_SIZE(op) \
+ (((PyUnicodeObject *)(op))->length)
+#define PyUnicode_GET_DATA_SIZE(op) \
+ (((PyUnicodeObject *)(op))->length * sizeof(Py_UNICODE))
+#define PyUnicode_AS_UNICODE(op) \
+ (((PyUnicodeObject *)(op))->str)
+#define PyUnicode_AS_DATA(op) \
+ ((const char *)((PyUnicodeObject *)(op))->str)
+
+/* --- Constants ---------------------------------------------------------- */
+
+/* This Unicode character will be used as replacement character during
+ decoding if the errors argument is set to "replace". Note: the
+ Unicode character U+FFFD is the official REPLACEMENT CHARACTER in
+ Unicode 3.0. */
+
+#define Py_UNICODE_REPLACEMENT_CHARACTER ((Py_UNICODE) 0xFFFD)
+
+/* === Public API ========================================================= */
+
+/* --- Plain Py_UNICODE --------------------------------------------------- */
+
+/* Create a Unicode Object from the Py_UNICODE buffer u of the given
+ size.
+
+ u may be NULL which causes the contents to be undefined. It is the
+ user's responsibility to fill in the needed data afterwards. Note
+ that modifying the Unicode object contents after construction is
+ only allowed if u was set to NULL.
+
+ The buffer is copied into the new object. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_FromUnicode(
+ const Py_UNICODE *u, /* Unicode buffer */
+ Py_ssize_t size /* size of buffer */
+ );
+
+/* Similar to PyUnicode_FromUnicode(), but u points to Latin-1 encoded bytes */
+PyAPI_FUNC(PyObject*) PyUnicode_FromStringAndSize(
+ const char *u, /* char buffer */
+ Py_ssize_t size /* size of buffer */
+ );
+
+/* Similar to PyUnicode_FromUnicode(), but u points to null-terminated
+ Latin-1 encoded bytes */
+PyAPI_FUNC(PyObject*) PyUnicode_FromString(
+ const char *u /* string */
+ );
+
+/* Return a read-only pointer to the Unicode object's internal
+ Py_UNICODE buffer. */
+
+PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicode(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* Get the length of the Unicode object. */
+
+PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* Get the maximum ordinal for a Unicode character. */
+PyAPI_FUNC(Py_UNICODE) PyUnicode_GetMax(void);
+
+/* Resize an already allocated Unicode object to the new size length.
+
+ *unicode is modified to point to the new (resized) object and 0
+ returned on success.
+
+ This API may only be called by the function which also called the
+ Unicode constructor. The refcount on the object must be 1. Otherwise,
+ an error is returned.
+
+ Error handling is implemented as follows: an exception is set, -1
+ is returned and *unicode left untouched.
+
+*/
+
+PyAPI_FUNC(int) PyUnicode_Resize(
+ PyObject **unicode, /* Pointer to the Unicode object */
+ Py_ssize_t length /* New length */
+ );
+
+/* Coerce obj to an Unicode object and return a reference with
+ *incremented* refcount.
+
+ Coercion is done in the following way:
+
+ 1. String and other char buffer compatible objects are decoded
+ under the assumptions that they contain data using the current
+ default encoding. Decoding is done in "strict" mode.
+
+ 2. All other objects (including Unicode objects) raise an
+ exception.
+
+ The API returns NULL in case of an error. The caller is responsible
+ for decref'ing the returned objects.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_FromEncodedObject(
+ register PyObject *obj, /* Object */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Coerce obj to an Unicode object and return a reference with
+ *incremented* refcount.
+
+ Unicode objects are passed back as-is (subclasses are converted to
+ true Unicode objects), all other objects are delegated to
+ PyUnicode_FromEncodedObject(obj, NULL, "strict") which results in
+ using the default encoding as basis for decoding the object.
+
+ The API returns NULL in case of an error. The caller is responsible
+ for decref'ing the returned objects.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_FromObject(
+ register PyObject *obj /* Object */
+ );
+
+PyAPI_FUNC(PyObject *) PyUnicode_FromFormatV(const char*, va_list);
+PyAPI_FUNC(PyObject *) PyUnicode_FromFormat(const char*, ...);
+
+/* Format the object based on the format_spec, as defined in PEP 3101
+ (Advanced String Formatting). */
+PyAPI_FUNC(PyObject *) _PyUnicode_FormatAdvanced(PyObject *obj,
+ Py_UNICODE *format_spec,
+ Py_ssize_t format_spec_len);
+
+/* --- wchar_t support for platforms which support it --------------------- */
+
+#ifdef HAVE_WCHAR_H
+
+/* Create a Unicode Object from the whcar_t buffer w of the given
+ size.
+
+ The buffer is copied into the new object. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_FromWideChar(
+ register const wchar_t *w, /* wchar_t buffer */
+ Py_ssize_t size /* size of buffer */
+ );
+
+/* Copies the Unicode Object contents into the wchar_t buffer w. At
+ most size wchar_t characters are copied.
+
+ Note that the resulting wchar_t string may or may not be
+ 0-terminated. It is the responsibility of the caller to make sure
+ that the wchar_t string is 0-terminated in case this is required by
+ the application.
+
+ Returns the number of wchar_t characters copied (excluding a
+ possibly trailing 0-termination character) or -1 in case of an
+ error. */
+
+PyAPI_FUNC(Py_ssize_t) PyUnicode_AsWideChar(
+ PyUnicodeObject *unicode, /* Unicode object */
+ register wchar_t *w, /* wchar_t buffer */
+ Py_ssize_t size /* size of buffer */
+ );
+
+#endif
+
+/* --- Unicode ordinals --------------------------------------------------- */
+
+/* Create a Unicode Object from the given Unicode code point ordinal.
+
+ The ordinal must be in range(0x10000) on narrow Python builds
+ (UCS2), and range(0x110000) on wide builds (UCS4). A ValueError is
+ raised in case it is not.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_FromOrdinal(int ordinal);
+
+/* --- Free-list management ----------------------------------------------- */
+
+/* Clear the free list used by the Unicode implementation.
+
+ This can be used to release memory used for objects on the free
+ list back to the Python memory allocator.
+
+*/
+
+PyAPI_FUNC(int) PyUnicode_ClearFreeList(void);
+
+/* === Builtin Codecs =====================================================
+
+ Many of these APIs take two arguments encoding and errors. These
+ parameters encoding and errors have the same semantics as the ones
+ of the builtin unicode() API.
+
+ Setting encoding to NULL causes the default encoding to be used.
+
+ Error handling is set by errors which may also be set to NULL
+ meaning to use the default handling defined for the codec. Default
+ error handling for all builtin codecs is "strict" (ValueErrors are
+ raised).
+
+ The codecs all use a similar interface. Only deviation from the
+ generic ones are documented.
+
+*/
+
+/* --- Manage the default encoding ---------------------------------------- */
+
+/* Return a Python string holding the default encoded value of the
+ Unicode object.
+
+ The resulting string is cached in the Unicode object for subsequent
+ usage by this function. The cached version is needed to implement
+ the character buffer interface and will live (at least) as long as
+ the Unicode object itself.
+
+ The refcount of the string is *not* incremented.
+
+ *** Exported for internal use by the interpreter only !!! ***
+
+*/
+
+PyAPI_FUNC(PyObject *) _PyUnicode_AsDefaultEncodedString(
+ PyObject *, const char *);
+
+/* Returns the currently active default encoding.
+
+ The default encoding is currently implemented as run-time settable
+ process global. This may change in future versions of the
+ interpreter to become a parameter which is managed on a per-thread
+ basis.
+
+ */
+
+PyAPI_FUNC(const char*) PyUnicode_GetDefaultEncoding(void);
+
+/* Sets the currently active default encoding.
+
+ Returns 0 on success, -1 in case of an error.
+
+ */
+
+PyAPI_FUNC(int) PyUnicode_SetDefaultEncoding(
+ const char *encoding /* Encoding name in standard form */
+ );
+
+/* --- Generic Codecs ----------------------------------------------------- */
+
+/* Create a Unicode object by decoding the encoded string s of the
+ given size. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_Decode(
+ const char *s, /* encoded string */
+ Py_ssize_t size, /* size of buffer */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Encodes a Py_UNICODE buffer of the given size and returns a
+ Python string object. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_Encode(
+ const Py_UNICODE *s, /* Unicode char buffer */
+ Py_ssize_t size, /* number of Py_UNICODE chars to encode */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Encodes a Unicode object and returns the result as Python
+ object. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedObject(
+ PyObject *unicode, /* Unicode object */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Encodes a Unicode object and returns the result as Python string
+ object. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedString(
+ PyObject *unicode, /* Unicode object */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_BuildEncodingMap(
+ PyObject* string /* 256 character map */
+ );
+
+
+/* --- UTF-7 Codecs ------------------------------------------------------- */
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7(
+ const char *string, /* UTF-7 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7Stateful(
+ const char *string, /* UTF-7 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ Py_ssize_t *consumed /* bytes consumed */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF7(
+ const Py_UNICODE *data, /* Unicode char buffer */
+ Py_ssize_t length, /* number of Py_UNICODE chars to encode */
+ int base64SetO, /* Encode RFC2152 Set O characters in base64 */
+ int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */
+ const char *errors /* error handling */
+ );
+
+/* --- UTF-8 Codecs ------------------------------------------------------- */
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8(
+ const char *string, /* UTF-8 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8Stateful(
+ const char *string, /* UTF-8 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ Py_ssize_t *consumed /* bytes consumed */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsUTF8String(
+ PyObject *unicode /* Unicode object */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF8(
+ const Py_UNICODE *data, /* Unicode char buffer */
+ Py_ssize_t length, /* number of Py_UNICODE chars to encode */
+ const char *errors /* error handling */
+ );
+
+/* --- UTF-32 Codecs ------------------------------------------------------ */
+
+/* Decodes length bytes from a UTF-32 encoded buffer string and returns
+ the corresponding Unicode object.
+
+ errors (if non-NULL) defines the error handling. It defaults
+ to "strict".
+
+ If byteorder is non-NULL, the decoder starts decoding using the
+ given byte order:
+
+ *byteorder == -1: little endian
+ *byteorder == 0: native order
+ *byteorder == 1: big endian
+
+ In native mode, the first four bytes of the stream are checked for a
+ BOM mark. If found, the BOM mark is analysed, the byte order
+ adjusted and the BOM skipped. In the other modes, no BOM mark
+ interpretation is done. After completion, *byteorder is set to the
+ current byte order at the end of input data.
+
+ If byteorder is NULL, the codec starts in native order mode.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32(
+ const char *string, /* UTF-32 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ int *byteorder /* pointer to byteorder to use
+ 0=native;-1=LE,1=BE; updated on
+ exit */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32Stateful(
+ const char *string, /* UTF-32 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ int *byteorder, /* pointer to byteorder to use
+ 0=native;-1=LE,1=BE; updated on
+ exit */
+ Py_ssize_t *consumed /* bytes consumed */
+ );
+
+/* Returns a Python string using the UTF-32 encoding in native byte
+ order. The string always starts with a BOM mark. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsUTF32String(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* Returns a Python string object holding the UTF-32 encoded value of
+ the Unicode data.
+
+ If byteorder is not 0, output is written according to the following
+ byte order:
+
+ byteorder == -1: little endian
+ byteorder == 0: native byte order (writes a BOM mark)
+ byteorder == 1: big endian
+
+ If byteorder is 0, the output string will always start with the
+ Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
+ prepended.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF32(
+ const Py_UNICODE *data, /* Unicode char buffer */
+ Py_ssize_t length, /* number of Py_UNICODE chars to encode */
+ const char *errors, /* error handling */
+ int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */
+ );
+
+/* --- UTF-16 Codecs ------------------------------------------------------ */
+
+/* Decodes length bytes from a UTF-16 encoded buffer string and returns
+ the corresponding Unicode object.
+
+ errors (if non-NULL) defines the error handling. It defaults
+ to "strict".
+
+ If byteorder is non-NULL, the decoder starts decoding using the
+ given byte order:
+
+ *byteorder == -1: little endian
+ *byteorder == 0: native order
+ *byteorder == 1: big endian
+
+ In native mode, the first two bytes of the stream are checked for a
+ BOM mark. If found, the BOM mark is analysed, the byte order
+ adjusted and the BOM skipped. In the other modes, no BOM mark
+ interpretation is done. After completion, *byteorder is set to the
+ current byte order at the end of input data.
+
+ If byteorder is NULL, the codec starts in native order mode.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16(
+ const char *string, /* UTF-16 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ int *byteorder /* pointer to byteorder to use
+ 0=native;-1=LE,1=BE; updated on
+ exit */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16Stateful(
+ const char *string, /* UTF-16 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ int *byteorder, /* pointer to byteorder to use
+ 0=native;-1=LE,1=BE; updated on
+ exit */
+ Py_ssize_t *consumed /* bytes consumed */
+ );
+
+/* Returns a Python string using the UTF-16 encoding in native byte
+ order. The string always starts with a BOM mark. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsUTF16String(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* Returns a Python string object holding the UTF-16 encoded value of
+ the Unicode data.
+
+ If byteorder is not 0, output is written according to the following
+ byte order:
+
+ byteorder == -1: little endian
+ byteorder == 0: native byte order (writes a BOM mark)
+ byteorder == 1: big endian
+
+ If byteorder is 0, the output string will always start with the
+ Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
+ prepended.
+
+ Note that Py_UNICODE data is being interpreted as UTF-16 reduced to
+ UCS-2. This trick makes it possible to add full UTF-16 capabilities
+ at a later point without compromising the APIs.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF16(
+ const Py_UNICODE *data, /* Unicode char buffer */
+ Py_ssize_t length, /* number of Py_UNICODE chars to encode */
+ const char *errors, /* error handling */
+ int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */
+ );
+
+/* --- Unicode-Escape Codecs ---------------------------------------------- */
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUnicodeEscape(
+ const char *string, /* Unicode-Escape encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsUnicodeEscapeString(
+ PyObject *unicode /* Unicode object */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_EncodeUnicodeEscape(
+ const Py_UNICODE *data, /* Unicode char buffer */
+ Py_ssize_t length /* Number of Py_UNICODE chars to encode */
+ );
+
+/* --- Raw-Unicode-Escape Codecs ------------------------------------------ */
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeRawUnicodeEscape(
+ const char *string, /* Raw-Unicode-Escape encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsRawUnicodeEscapeString(
+ PyObject *unicode /* Unicode object */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_EncodeRawUnicodeEscape(
+ const Py_UNICODE *data, /* Unicode char buffer */
+ Py_ssize_t length /* Number of Py_UNICODE chars to encode */
+ );
+
+/* --- Unicode Internal Codec ---------------------------------------------
+
+ Only for internal use in _codecsmodule.c */
+
+PyObject *_PyUnicode_DecodeUnicodeInternal(
+ const char *string,
+ Py_ssize_t length,
+ const char *errors
+ );
+
+/* --- Latin-1 Codecs -----------------------------------------------------
+
+ Note: Latin-1 corresponds to the first 256 Unicode ordinals.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeLatin1(
+ const char *string, /* Latin-1 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsLatin1String(
+ PyObject *unicode /* Unicode object */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_EncodeLatin1(
+ const Py_UNICODE *data, /* Unicode char buffer */
+ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
+ const char *errors /* error handling */
+ );
+
+/* --- ASCII Codecs -------------------------------------------------------
+
+ Only 7-bit ASCII data is excepted. All other codes generate errors.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeASCII(
+ const char *string, /* ASCII encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsASCIIString(
+ PyObject *unicode /* Unicode object */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_EncodeASCII(
+ const Py_UNICODE *data, /* Unicode char buffer */
+ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
+ const char *errors /* error handling */
+ );
+
+/* --- Character Map Codecs -----------------------------------------------
+
+ This codec uses mappings to encode and decode characters.
+
+ Decoding mappings must map single string characters to single
+ Unicode characters, integers (which are then interpreted as Unicode
+ ordinals) or None (meaning "undefined mapping" and causing an
+ error).
+
+ Encoding mappings must map single Unicode characters to single
+ string characters, integers (which are then interpreted as Latin-1
+ ordinals) or None (meaning "undefined mapping" and causing an
+ error).
+
+ If a character lookup fails with a LookupError, the character is
+ copied as-is meaning that its ordinal value will be interpreted as
+ Unicode or Latin-1 ordinal resp. Because of this mappings only need
+ to contain those mappings which map characters to different code
+ points.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeCharmap(
+ const char *string, /* Encoded string */
+ Py_ssize_t length, /* size of string */
+ PyObject *mapping, /* character mapping
+ (char ordinal -> unicode ordinal) */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsCharmapString(
+ PyObject *unicode, /* Unicode object */
+ PyObject *mapping /* character mapping
+ (unicode ordinal -> char ordinal) */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_EncodeCharmap(
+ const Py_UNICODE *data, /* Unicode char buffer */
+ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
+ PyObject *mapping, /* character mapping
+ (unicode ordinal -> char ordinal) */
+ const char *errors /* error handling */
+ );
+
+/* Translate a Py_UNICODE buffer of the given length by applying a
+ character mapping table to it and return the resulting Unicode
+ object.
+
+ The mapping table must map Unicode ordinal integers to Unicode
+ ordinal integers or None (causing deletion of the character).
+
+ Mapping tables may be dictionaries or sequences. Unmapped character
+ ordinals (ones which cause a LookupError) are left untouched and
+ are copied as-is.
+
+*/
+
+PyAPI_FUNC(PyObject *) PyUnicode_TranslateCharmap(
+ const Py_UNICODE *data, /* Unicode char buffer */
+ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
+ PyObject *table, /* Translate table */
+ const char *errors /* error handling */
+ );
+
+#ifdef MS_WIN32
+
+/* --- MBCS codecs for Windows -------------------------------------------- */
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeMBCS(
+ const char *string, /* MBCS encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeMBCSStateful(
+ const char *string, /* MBCS encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ Py_ssize_t *consumed /* bytes consumed */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsMBCSString(
+ PyObject *unicode /* Unicode object */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_EncodeMBCS(
+ const Py_UNICODE *data, /* Unicode char buffer */
+ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
+ const char *errors /* error handling */
+ );
+
+#endif /* MS_WIN32 */
+
+/* --- Decimal Encoder ---------------------------------------------------- */
+
+/* Takes a Unicode string holding a decimal value and writes it into
+ an output buffer using standard ASCII digit codes.
+
+ The output buffer has to provide at least length+1 bytes of storage
+ area. The output string is 0-terminated.
+
+ The encoder converts whitespace to ' ', decimal characters to their
+ corresponding ASCII digit and all other Latin-1 characters except
+ \0 as-is. Characters outside this range (Unicode ordinals 1-256)
+ are treated as errors. This includes embedded NULL bytes.
+
+ Error handling is defined by the errors argument:
+
+ NULL or "strict": raise a ValueError
+ "ignore": ignore the wrong characters (these are not copied to the
+ output buffer)
+ "replace": replaces illegal characters with '?'
+
+ Returns 0 on success, -1 on failure.
+
+*/
+
+PyAPI_FUNC(int) PyUnicode_EncodeDecimal(
+ Py_UNICODE *s, /* Unicode buffer */
+ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
+ char *output, /* Output buffer; must have size >= length */
+ const char *errors /* error handling */
+ );
+
+/* --- Methods & Slots ----------------------------------------------------
+
+ These are capable of handling Unicode objects and strings on input
+ (we refer to them as strings in the descriptions) and return
+ Unicode objects or integers as apporpriate. */
+
+/* Concat two strings giving a new Unicode string. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_Concat(
+ PyObject *left, /* Left string */
+ PyObject *right /* Right string */
+ );
+
+/* Split a string giving a list of Unicode strings.
+
+ If sep is NULL, splitting will be done at all whitespace
+ substrings. Otherwise, splits occur at the given separator.
+
+ At most maxsplit splits will be done. If negative, no limit is set.
+
+ Separators are not included in the resulting list.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_Split(
+ PyObject *s, /* String to split */
+ PyObject *sep, /* String separator */
+ Py_ssize_t maxsplit /* Maxsplit count */
+ );
+
+/* Dito, but split at line breaks.
+
+ CRLF is considered to be one line break. Line breaks are not
+ included in the resulting list. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_Splitlines(
+ PyObject *s, /* String to split */
+ int keepends /* If true, line end markers are included */
+ );
+
+/* Partition a string using a given separator. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_Partition(
+ PyObject *s, /* String to partition */
+ PyObject *sep /* String separator */
+ );
+
+/* Partition a string using a given separator, searching from the end of the
+ string. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_RPartition(
+ PyObject *s, /* String to partition */
+ PyObject *sep /* String separator */
+ );
+
+/* Split a string giving a list of Unicode strings.
+
+ If sep is NULL, splitting will be done at all whitespace
+ substrings. Otherwise, splits occur at the given separator.
+
+ At most maxsplit splits will be done. But unlike PyUnicode_Split
+ PyUnicode_RSplit splits from the end of the string. If negative,
+ no limit is set.
+
+ Separators are not included in the resulting list.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_RSplit(
+ PyObject *s, /* String to split */
+ PyObject *sep, /* String separator */
+ Py_ssize_t maxsplit /* Maxsplit count */
+ );
+
+/* Translate a string by applying a character mapping table to it and
+ return the resulting Unicode object.
+
+ The mapping table must map Unicode ordinal integers to Unicode
+ ordinal integers or None (causing deletion of the character).
+
+ Mapping tables may be dictionaries or sequences. Unmapped character
+ ordinals (ones which cause a LookupError) are left untouched and
+ are copied as-is.
+
+*/
+
+PyAPI_FUNC(PyObject *) PyUnicode_Translate(
+ PyObject *str, /* String */
+ PyObject *table, /* Translate table */
+ const char *errors /* error handling */
+ );
+
+/* Join a sequence of strings using the given separator and return
+ the resulting Unicode string. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_Join(
+ PyObject *separator, /* Separator string */
+ PyObject *seq /* Sequence object */
+ );
+
+/* Return 1 if substr matches str[start:end] at the given tail end, 0
+ otherwise. */
+
+PyAPI_FUNC(Py_ssize_t) PyUnicode_Tailmatch(
+ PyObject *str, /* String */
+ PyObject *substr, /* Prefix or Suffix string */
+ Py_ssize_t start, /* Start index */
+ Py_ssize_t end, /* Stop index */
+ int direction /* Tail end: -1 prefix, +1 suffix */
+ );
+
+/* Return the first position of substr in str[start:end] using the
+ given search direction or -1 if not found. -2 is returned in case
+ an error occurred and an exception is set. */
+
+PyAPI_FUNC(Py_ssize_t) PyUnicode_Find(
+ PyObject *str, /* String */
+ PyObject *substr, /* Substring to find */
+ Py_ssize_t start, /* Start index */
+ Py_ssize_t end, /* Stop index */
+ int direction /* Find direction: +1 forward, -1 backward */
+ );
+
+/* Count the number of occurrences of substr in str[start:end]. */
+
+PyAPI_FUNC(Py_ssize_t) PyUnicode_Count(
+ PyObject *str, /* String */
+ PyObject *substr, /* Substring to count */
+ Py_ssize_t start, /* Start index */
+ Py_ssize_t end /* Stop index */
+ );
+
+/* Replace at most maxcount occurrences of substr in str with replstr
+ and return the resulting Unicode object. */
+
+PyAPI_FUNC(PyObject *) PyUnicode_Replace(
+ PyObject *str, /* String */
+ PyObject *substr, /* Substring to find */
+ PyObject *replstr, /* Substring to replace */
+ Py_ssize_t maxcount /* Max. number of replacements to apply;
+ -1 = all */
+ );
+
+/* Compare two strings and return -1, 0, 1 for less than, equal,
+ greater than resp. */
+
+PyAPI_FUNC(int) PyUnicode_Compare(
+ PyObject *left, /* Left string */
+ PyObject *right /* Right string */
+ );
+
+/* Rich compare two strings and return one of the following:
+
+ - NULL in case an exception was raised
+ - Py_True or Py_False for successfuly comparisons
+ - Py_NotImplemented in case the type combination is unknown
+
+ Note that Py_EQ and Py_NE comparisons can cause a UnicodeWarning in
+ case the conversion of the arguments to Unicode fails with a
+ UnicodeDecodeError.
+
+ Possible values for op:
+
+ Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE
+
+*/
+
+PyAPI_FUNC(PyObject *) PyUnicode_RichCompare(
+ PyObject *left, /* Left string */
+ PyObject *right, /* Right string */
+ int op /* Operation: Py_EQ, Py_NE, Py_GT, etc. */
+ );
+
+/* Apply a argument tuple or dictionary to a format string and return
+ the resulting Unicode string. */
+
+PyAPI_FUNC(PyObject *) PyUnicode_Format(
+ PyObject *format, /* Format string */
+ PyObject *args /* Argument tuple or dictionary */
+ );
+
+/* Checks whether element is contained in container and return 1/0
+ accordingly.
+
+ element has to coerce to an one element Unicode string. -1 is
+ returned in case of an error. */
+
+PyAPI_FUNC(int) PyUnicode_Contains(
+ PyObject *container, /* Container string */
+ PyObject *element /* Element string */
+ );
+
+/* Externally visible for str.strip(unicode) */
+PyAPI_FUNC(PyObject *) _PyUnicode_XStrip(
+ PyUnicodeObject *self,
+ int striptype,
+ PyObject *sepobj
+ );
+
+/* === Characters Type APIs =============================================== */
+
+/* Helper array used by Py_UNICODE_ISSPACE(). */
+
+PyAPI_DATA(const unsigned char) _Py_ascii_whitespace[];
+
+/* These should not be used directly. Use the Py_UNICODE_IS* and
+ Py_UNICODE_TO* macros instead.
+
+ These APIs are implemented in Objects/unicodectype.c.
+
+*/
+
+PyAPI_FUNC(int) _PyUnicode_IsLowercase(
+ Py_UNICODE ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsUppercase(
+ Py_UNICODE ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsTitlecase(
+ Py_UNICODE ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsWhitespace(
+ const Py_UNICODE ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsLinebreak(
+ const Py_UNICODE ch /* Unicode character */
+ );
+
+PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToLowercase(
+ Py_UNICODE ch /* Unicode character */
+ );
+
+PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToUppercase(
+ Py_UNICODE ch /* Unicode character */
+ );
+
+PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToTitlecase(
+ Py_UNICODE ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_ToDecimalDigit(
+ Py_UNICODE ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_ToDigit(
+ Py_UNICODE ch /* Unicode character */
+ );
+
+PyAPI_FUNC(double) _PyUnicode_ToNumeric(
+ Py_UNICODE ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsDecimalDigit(
+ Py_UNICODE ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsDigit(
+ Py_UNICODE ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsNumeric(
+ Py_UNICODE ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsAlpha(
+ Py_UNICODE ch /* Unicode character */
+ );
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* Py_USING_UNICODE */
+#endif /* !Py_UNICODEOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/warnings.h b/AppPkg/Applications/Python/Python-2.7.2/Include/warnings.h
new file mode 100644
index 0000000000..bf8f9636fd
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/warnings.h
@@ -0,0 +1,23 @@
+#ifndef Py_WARNINGS_H
+#define Py_WARNINGS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_FUNC(void) _PyWarnings_Init(void);
+
+PyAPI_FUNC(int) PyErr_WarnEx(PyObject *, const char *, Py_ssize_t);
+PyAPI_FUNC(int) PyErr_WarnExplicit(PyObject *, const char *, const char *, int,
+ const char *, PyObject *);
+
+#define PyErr_WarnPy3k(msg, stacklevel) \
+ (Py_Py3kWarningFlag ? PyErr_WarnEx(PyExc_DeprecationWarning, msg, stacklevel) : 0)
+
+/* DEPRECATED: Use PyErr_WarnEx() instead. */
+#define PyErr_Warn(category, msg) PyErr_WarnEx(category, msg, 1)
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_WARNINGS_H */
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Include/weakrefobject.h b/AppPkg/Applications/Python/Python-2.7.2/Include/weakrefobject.h
new file mode 100644
index 0000000000..99596c5a0f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Include/weakrefobject.h
@@ -0,0 +1,75 @@
+/* Weak references objects for Python. */
+
+#ifndef Py_WEAKREFOBJECT_H
+#define Py_WEAKREFOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+typedef struct _PyWeakReference PyWeakReference;
+
+/* PyWeakReference is the base struct for the Python ReferenceType, ProxyType,
+ * and CallableProxyType.
+ */
+struct _PyWeakReference {
+ PyObject_HEAD
+
+ /* The object to which this is a weak reference, or Py_None if none.
+ * Note that this is a stealth reference: wr_object's refcount is
+ * not incremented to reflect this pointer.
+ */
+ PyObject *wr_object;
+
+ /* A callable to invoke when wr_object dies, or NULL if none. */
+ PyObject *wr_callback;
+
+ /* A cache for wr_object's hash code. As usual for hashes, this is -1
+ * if the hash code isn't known yet.
+ */
+ long hash;
+
+ /* If wr_object is weakly referenced, wr_object has a doubly-linked NULL-
+ * terminated list of weak references to it. These are the list pointers.
+ * If wr_object goes away, wr_object is set to Py_None, and these pointers
+ * have no meaning then.
+ */
+ PyWeakReference *wr_prev;
+ PyWeakReference *wr_next;
+};
+
+PyAPI_DATA(PyTypeObject) _PyWeakref_RefType;
+PyAPI_DATA(PyTypeObject) _PyWeakref_ProxyType;
+PyAPI_DATA(PyTypeObject) _PyWeakref_CallableProxyType;
+
+#define PyWeakref_CheckRef(op) PyObject_TypeCheck(op, &_PyWeakref_RefType)
+#define PyWeakref_CheckRefExact(op) \
+ (Py_TYPE(op) == &_PyWeakref_RefType)
+#define PyWeakref_CheckProxy(op) \
+ ((Py_TYPE(op) == &_PyWeakref_ProxyType) || \
+ (Py_TYPE(op) == &_PyWeakref_CallableProxyType))
+
+/* This macro calls PyWeakref_CheckRef() last since that can involve a
+ function call; this makes it more likely that the function call
+ will be avoided. */
+#define PyWeakref_Check(op) \
+ (PyWeakref_CheckRef(op) || PyWeakref_CheckProxy(op))
+
+
+PyAPI_FUNC(PyObject *) PyWeakref_NewRef(PyObject *ob,
+ PyObject *callback);
+PyAPI_FUNC(PyObject *) PyWeakref_NewProxy(PyObject *ob,
+ PyObject *callback);
+PyAPI_FUNC(PyObject *) PyWeakref_GetObject(PyObject *ref);
+
+PyAPI_FUNC(Py_ssize_t) _PyWeakref_GetWeakrefCount(PyWeakReference *head);
+
+PyAPI_FUNC(void) _PyWeakref_ClearRef(PyWeakReference *self);
+
+#define PyWeakref_GET_OBJECT(ref) (((PyWeakReference *)(ref))->wr_object)
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_WEAKREFOBJECT_H */
diff --git a/AppPkg/Applications/Python/Python-2.7.2/LICENSE b/AppPkg/Applications/Python/Python-2.7.2/LICENSE
new file mode 100644
index 0000000000..1930f18029
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/LICENSE
@@ -0,0 +1,279 @@
+A. HISTORY OF THE SOFTWARE
+==========================
+
+Python was created in the early 1990s by Guido van Rossum at Stichting
+Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
+as a successor of a language called ABC. Guido remains Python's
+principal author, although it includes many contributions from others.
+
+In 1995, Guido continued his work on Python at the Corporation for
+National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
+in Reston, Virginia where he released several versions of the
+software.
+
+In May 2000, Guido and the Python core development team moved to
+BeOpen.com to form the BeOpen PythonLabs team. In October of the same
+year, the PythonLabs team moved to Digital Creations (now Zope
+Corporation, see http://www.zope.com). In 2001, the Python Software
+Foundation (PSF, see http://www.python.org/psf/) was formed, a
+non-profit organization created specifically to own Python-related
+Intellectual Property. Zope Corporation is a sponsoring member of
+the PSF.
+
+All Python releases are Open Source (see http://www.opensource.org for
+the Open Source Definition). Historically, most, but not all, Python
+releases have also been GPL-compatible; the table below summarizes
+the various releases.
+
+ Release Derived Year Owner GPL-
+ from compatible? (1)
+
+ 0.9.0 thru 1.2 1991-1995 CWI yes
+ 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
+ 1.6 1.5.2 2000 CNRI no
+ 2.0 1.6 2000 BeOpen.com no
+ 1.6.1 1.6 2001 CNRI yes (2)
+ 2.1 2.0+1.6.1 2001 PSF no
+ 2.0.1 2.0+1.6.1 2001 PSF yes
+ 2.1.1 2.1+2.0.1 2001 PSF yes
+ 2.2 2.1.1 2001 PSF yes
+ 2.1.2 2.1.1 2002 PSF yes
+ 2.1.3 2.1.2 2002 PSF yes
+ 2.2.1 2.2 2002 PSF yes
+ 2.2.2 2.2.1 2002 PSF yes
+ 2.2.3 2.2.2 2003 PSF yes
+ 2.3 2.2.2 2002-2003 PSF yes
+ 2.3.1 2.3 2002-2003 PSF yes
+ 2.3.2 2.3.1 2002-2003 PSF yes
+ 2.3.3 2.3.2 2002-2003 PSF yes
+ 2.3.4 2.3.3 2004 PSF yes
+ 2.3.5 2.3.4 2005 PSF yes
+ 2.4 2.3 2004 PSF yes
+ 2.4.1 2.4 2005 PSF yes
+ 2.4.2 2.4.1 2005 PSF yes
+ 2.4.3 2.4.2 2006 PSF yes
+ 2.4.4 2.4.3 2006 PSF yes
+ 2.5 2.4 2006 PSF yes
+ 2.5.1 2.5 2007 PSF yes
+ 2.5.2 2.5.1 2008 PSF yes
+ 2.5.3 2.5.2 2008 PSF yes
+ 2.6 2.5 2008 PSF yes
+ 2.6.1 2.6 2008 PSF yes
+ 2.6.2 2.6.1 2009 PSF yes
+ 2.6.3 2.6.2 2009 PSF yes
+ 2.6.4 2.6.3 2009 PSF yes
+ 2.6.5 2.6.4 2010 PSF yes
+ 2.7 2.6 2010 PSF yes
+
+Footnotes:
+
+(1) GPL-compatible doesn't mean that we're distributing Python under
+ the GPL. All Python licenses, unlike the GPL, let you distribute
+ a modified version without making your changes open source. The
+ GPL-compatible licenses make it possible to combine Python with
+ other software that is released under the GPL; the others don't.
+
+(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
+ because its license has a choice of law clause. According to
+ CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
+ is "not incompatible" with the GPL.
+
+Thanks to the many outside volunteers who have worked under Guido's
+direction to make these releases possible.
+
+
+B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
+===============================================================
+
+PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
+--------------------------------------------
+
+1. This LICENSE AGREEMENT is between the Python Software Foundation
+("PSF"), and the Individual or Organization ("Licensee") accessing and
+otherwise using this software ("Python") in source or binary form and
+its associated documentation.
+
+2. Subject to the terms and conditions of this License Agreement, PSF hereby
+grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
+analyze, test, perform and/or display publicly, prepare derivative works,
+distribute, and otherwise use Python alone or in any derivative version,
+provided, however, that PSF's License Agreement and PSF's notice of copyright,
+i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
+Python Software Foundation; All Rights Reserved" are retained in Python alone or
+in any derivative version prepared by Licensee.
+
+3. In the event Licensee prepares a derivative work that is based on
+or incorporates Python or any part thereof, and wants to make
+the derivative work available to others as provided herein, then
+Licensee hereby agrees to include in any such work a brief summary of
+the changes made to Python.
+
+4. PSF is making Python available to Licensee on an "AS IS"
+basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
+IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
+DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
+FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
+INFRINGE ANY THIRD PARTY RIGHTS.
+
+5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
+FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
+A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
+OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+6. This License Agreement will automatically terminate upon a material
+breach of its terms and conditions.
+
+7. Nothing in this License Agreement shall be deemed to create any
+relationship of agency, partnership, or joint venture between PSF and
+Licensee. This License Agreement does not grant permission to use PSF
+trademarks or trade name in a trademark sense to endorse or promote
+products or services of Licensee, or any third party.
+
+8. By copying, installing or otherwise using Python, Licensee
+agrees to be bound by the terms and conditions of this License
+Agreement.
+
+
+BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
+-------------------------------------------
+
+BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
+
+1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
+office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
+Individual or Organization ("Licensee") accessing and otherwise using
+this software in source or binary form and its associated
+documentation ("the Software").
+
+2. Subject to the terms and conditions of this BeOpen Python License
+Agreement, BeOpen hereby grants Licensee a non-exclusive,
+royalty-free, world-wide license to reproduce, analyze, test, perform
+and/or display publicly, prepare derivative works, distribute, and
+otherwise use the Software alone or in any derivative version,
+provided, however, that the BeOpen Python License is retained in the
+Software, alone or in any derivative version prepared by Licensee.
+
+3. BeOpen is making the Software available to Licensee on an "AS IS"
+basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
+IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
+DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
+FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
+INFRINGE ANY THIRD PARTY RIGHTS.
+
+4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
+SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
+AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
+DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+5. This License Agreement will automatically terminate upon a material
+breach of its terms and conditions.
+
+6. This License Agreement shall be governed by and interpreted in all
+respects by the law of the State of California, excluding conflict of
+law provisions. Nothing in this License Agreement shall be deemed to
+create any relationship of agency, partnership, or joint venture
+between BeOpen and Licensee. This License Agreement does not grant
+permission to use BeOpen trademarks or trade names in a trademark
+sense to endorse or promote products or services of Licensee, or any
+third party. As an exception, the "BeOpen Python" logos available at
+http://www.pythonlabs.com/logos.html may be used according to the
+permissions granted on that web page.
+
+7. By copying, installing or otherwise using the software, Licensee
+agrees to be bound by the terms and conditions of this License
+Agreement.
+
+
+CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
+---------------------------------------
+
+1. This LICENSE AGREEMENT is between the Corporation for National
+Research Initiatives, having an office at 1895 Preston White Drive,
+Reston, VA 20191 ("CNRI"), and the Individual or Organization
+("Licensee") accessing and otherwise using Python 1.6.1 software in
+source or binary form and its associated documentation.
+
+2. Subject to the terms and conditions of this License Agreement, CNRI
+hereby grants Licensee a nonexclusive, royalty-free, world-wide
+license to reproduce, analyze, test, perform and/or display publicly,
+prepare derivative works, distribute, and otherwise use Python 1.6.1
+alone or in any derivative version, provided, however, that CNRI's
+License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
+1995-2001 Corporation for National Research Initiatives; All Rights
+Reserved" are retained in Python 1.6.1 alone or in any derivative
+version prepared by Licensee. Alternately, in lieu of CNRI's License
+Agreement, Licensee may substitute the following text (omitting the
+quotes): "Python 1.6.1 is made available subject to the terms and
+conditions in CNRI's License Agreement. This Agreement together with
+Python 1.6.1 may be located on the Internet using the following
+unique, persistent identifier (known as a handle): 1895.22/1013. This
+Agreement may also be obtained from a proxy server on the Internet
+using the following URL: http://hdl.handle.net/1895.22/1013".
+
+3. In the event Licensee prepares a derivative work that is based on
+or incorporates Python 1.6.1 or any part thereof, and wants to make
+the derivative work available to others as provided herein, then
+Licensee hereby agrees to include in any such work a brief summary of
+the changes made to Python 1.6.1.
+
+4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
+basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
+IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
+DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
+FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
+INFRINGE ANY THIRD PARTY RIGHTS.
+
+5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
+1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
+A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
+OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+6. This License Agreement will automatically terminate upon a material
+breach of its terms and conditions.
+
+7. This License Agreement shall be governed by the federal
+intellectual property law of the United States, including without
+limitation the federal copyright law, and, to the extent such
+U.S. federal law does not apply, by the law of the Commonwealth of
+Virginia, excluding Virginia's conflict of law provisions.
+Notwithstanding the foregoing, with regard to derivative works based
+on Python 1.6.1 that incorporate non-separable material that was
+previously distributed under the GNU General Public License (GPL), the
+law of the Commonwealth of Virginia shall govern this License
+Agreement only as to issues arising under or with respect to
+Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
+License Agreement shall be deemed to create any relationship of
+agency, partnership, or joint venture between CNRI and Licensee. This
+License Agreement does not grant permission to use CNRI trademarks or
+trade name in a trademark sense to endorse or promote products or
+services of Licensee, or any third party.
+
+8. By clicking on the "ACCEPT" button where indicated, or by copying,
+installing or otherwise using Python 1.6.1, Licensee agrees to be
+bound by the terms and conditions of this License Agreement.
+
+ ACCEPT
+
+
+CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
+--------------------------------------------------
+
+Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
+The Netherlands. All rights reserved.
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+provided that the above copyright notice appear in all copies and that
+both that copyright notice and this permission notice appear in
+supporting documentation, and that the name of Stichting Mathematisch
+Centrum or CWI not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
+THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
+FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Lib/BaseHTTPServer.py b/AppPkg/Applications/Python/Python-2.7.2/Lib/BaseHTTPServer.py
new file mode 100644
index 0000000000..120bd789d8
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Lib/BaseHTTPServer.py
@@ -0,0 +1,606 @@
+"""HTTP server base class.
+
+Note: the class in this module doesn't implement any HTTP request; see
+SimpleHTTPServer for simple implementations of GET, HEAD and POST
+(including CGI scripts). It does, however, optionally implement HTTP/1.1
+persistent connections, as of version 0.3.
+
+Contents:
+
+- BaseHTTPRequestHandler: HTTP request handler base class
+- test: test function
+
+XXX To do:
+
+- log requests even later (to capture byte count)
+- log user-agent header and other interesting goodies
+- send error log to separate file
+"""
+
+
+# See also:
+#
+# HTTP Working Group T. Berners-Lee
+# INTERNET-DRAFT R. T. Fielding
+# H. Frystyk Nielsen
+# Expires September 8, 1995 March 8, 1995
+#
+# URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
+#
+# and
+#
+# Network Working Group R. Fielding
+# Request for Comments: 2616 et al
+# Obsoletes: 2068 June 1999
+# Category: Standards Track
+#
+# URL: http://www.faqs.org/rfcs/rfc2616.html
+
+# Log files
+# ---------
+#
+# Here's a quote from the NCSA httpd docs about log file format.
+#
+# | The logfile format is as follows. Each line consists of:
+# |
+# | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb
+# |
+# | host: Either the DNS name or the IP number of the remote client
+# | rfc931: Any information returned by identd for this person,
+# | - otherwise.
+# | authuser: If user sent a userid for authentication, the user name,
+# | - otherwise.
+# | DD: Day
+# | Mon: Month (calendar name)
+# | YYYY: Year
+# | hh: hour (24-hour format, the machine's timezone)
+# | mm: minutes
+# | ss: seconds
+# | request: The first line of the HTTP request as sent by the client.
+# | ddd: the status code returned by the server, - if not available.
+# | bbbb: the total number of bytes sent,
+# | *not including the HTTP/1.0 header*, - if not available
+# |
+# | You can determine the name of the file accessed through request.
+#
+# (Actually, the latter is only true if you know the server configuration
+# at the time the request was made!)
+
+__version__ = "0.3"
+
+__all__ = ["HTTPServer", "BaseHTTPRequestHandler"]
+
+import sys
+import time
+import socket # For gethostbyaddr()
+from warnings import filterwarnings, catch_warnings
+with catch_warnings():
+ if sys.py3kwarning:
+ filterwarnings("ignore", ".*mimetools has been removed",
+ DeprecationWarning)
+ import mimetools
+import SocketServer
+
+# Default error message template
+DEFAULT_ERROR_MESSAGE = """\
+
+Error response
+
+
+
Error response
+
Error code %(code)d.
+
Message: %(message)s.
+
Error code explanation: %(code)s = %(explain)s.
+
+"""
+
+DEFAULT_ERROR_CONTENT_TYPE = "text/html"
+
+def _quote_html(html):
+ return html.replace("&", "&").replace("<", "<").replace(">", ">")
+
+class HTTPServer(SocketServer.TCPServer):
+
+ allow_reuse_address = 1 # Seems to make sense in testing environment
+
+ def server_bind(self):
+ """Override server_bind to store the server name."""
+ SocketServer.TCPServer.server_bind(self)
+ host, port = self.socket.getsockname()[:2]
+ self.server_name = socket.getfqdn(host)
+ self.server_port = port
+
+
+class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
+
+ """HTTP request handler base class.
+
+ The following explanation of HTTP serves to guide you through the
+ code as well as to expose any misunderstandings I may have about
+ HTTP (so you don't need to read the code to figure out I'm wrong
+ :-).
+
+ HTTP (HyperText Transfer Protocol) is an extensible protocol on
+ top of a reliable stream transport (e.g. TCP/IP). The protocol
+ recognizes three parts to a request:
+
+ 1. One line identifying the request type and path
+ 2. An optional set of RFC-822-style headers
+ 3. An optional data part
+
+ The headers and data are separated by a blank line.
+
+ The first line of the request has the form
+
+
+
+ where is a (case-sensitive) keyword such as GET or POST,
+ is a string containing path information for the request,
+ and should be the string "HTTP/1.0" or "HTTP/1.1".
+ is encoded using the URL encoding scheme (using %xx to signify
+ the ASCII character with hex code xx).
+
+ The specification specifies that lines are separated by CRLF but
+ for compatibility with the widest range of clients recommends
+ servers also handle LF. Similarly, whitespace in the request line
+ is treated sensibly (allowing multiple spaces between components
+ and allowing trailing whitespace).
+
+ Similarly, for output, lines ought to be separated by CRLF pairs
+ but most clients grok LF characters just fine.
+
+ If the first line of the request has the form
+
+
+
+ (i.e. is left out) then this is assumed to be an HTTP
+ 0.9 request; this form has no optional headers and data part and
+ the reply consists of just the data.
+
+ The reply form of the HTTP 1.x protocol again has three parts:
+
+ 1. One line giving the response code
+ 2. An optional set of RFC-822-style headers
+ 3. The data
+
+ Again, the headers and data are separated by a blank line.
+
+ The response code line has the form
+
+
+
+ where is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
+ is a 3-digit response code indicating success or
+ failure of the request, and is an optional
+ human-readable string explaining what the response code means.
+
+ This server parses the request and the headers, and then calls a
+ function specific to the request type (). Specifically,
+ a request SPAM will be handled by a method do_SPAM(). If no
+ such method exists the server sends an error response to the
+ client. If it exists, it is called with no arguments:
+
+ do_SPAM()
+
+ Note that the request name is case sensitive (i.e. SPAM and spam
+ are different requests).
+
+ The various request details are stored in instance variables:
+
+ - client_address is the client IP address in the form (host,
+ port);
+
+ - command, path and version are the broken-down request line;
+
+ - headers is an instance of mimetools.Message (or a derived
+ class) containing the header information;
+
+ - rfile is a file object open for reading positioned at the
+ start of the optional input data part;
+
+ - wfile is a file object open for writing.
+
+ IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
+
+ The first thing to be written must be the response line. Then
+ follow 0 or more header lines, then a blank line, and then the
+ actual data (if any). The meaning of the header lines depends on
+ the command executed by the server; in most cases, when data is
+ returned, there should be at least one header line of the form
+
+ Content-type: /
+
+ where and should be registered MIME types,
+ e.g. "text/html" or "text/plain".
+
+ """
+
+ # The Python system version, truncated to its first component.
+ sys_version = "Python/" + sys.version.split()[0]
+
+ # The server software version. You may want to override this.
+ # The format is multiple whitespace-separated strings,
+ # where each string is of the form name[/version].
+ server_version = "BaseHTTP/" + __version__
+
+ # The default request version. This only affects responses up until
+ # the point where the request line is parsed, so it mainly decides what
+ # the client gets back when sending a malformed request line.
+ # Most web servers default to HTTP 0.9, i.e. don't send a status line.
+ default_request_version = "HTTP/0.9"
+
+ def parse_request(self):
+ """Parse a request (internal).
+
+ The request should be stored in self.raw_requestline; the results
+ are in self.command, self.path, self.request_version and
+ self.headers.
+
+ Return True for success, False for failure; on failure, an
+ error is sent back.
+
+ """
+ self.command = None # set in case of error on the first line
+ self.request_version = version = self.default_request_version
+ self.close_connection = 1
+ requestline = self.raw_requestline
+ if requestline[-2:] == '\r\n':
+ requestline = requestline[:-2]
+ elif requestline[-1:] == '\n':
+ requestline = requestline[:-1]
+ self.requestline = requestline
+ words = requestline.split()
+ if len(words) == 3:
+ [command, path, version] = words
+ if version[:5] != 'HTTP/':
+ self.send_error(400, "Bad request version (%r)" % version)
+ return False
+ try:
+ base_version_number = version.split('/', 1)[1]
+ version_number = base_version_number.split(".")
+ # RFC 2145 section 3.1 says there can be only one "." and
+ # - major and minor numbers MUST be treated as
+ # separate integers;
+ # - HTTP/2.4 is a lower version than HTTP/2.13, which in
+ # turn is lower than HTTP/12.3;
+ # - Leading zeros MUST be ignored by recipients.
+ if len(version_number) != 2:
+ raise ValueError
+ version_number = int(version_number[0]), int(version_number[1])
+ except (ValueError, IndexError):
+ self.send_error(400, "Bad request version (%r)" % version)
+ return False
+ if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
+ self.close_connection = 0
+ if version_number >= (2, 0):
+ self.send_error(505,
+ "Invalid HTTP Version (%s)" % base_version_number)
+ return False
+ elif len(words) == 2:
+ [command, path] = words
+ self.close_connection = 1
+ if command != 'GET':
+ self.send_error(400,
+ "Bad HTTP/0.9 request type (%r)" % command)
+ return False
+ elif not words:
+ return False
+ else:
+ self.send_error(400, "Bad request syntax (%r)" % requestline)
+ return False
+ self.command, self.path, self.request_version = command, path, version
+
+ # Examine the headers and look for a Connection directive
+ self.headers = self.MessageClass(self.rfile, 0)
+
+ conntype = self.headers.get('Connection', "")
+ if conntype.lower() == 'close':
+ self.close_connection = 1
+ elif (conntype.lower() == 'keep-alive' and
+ self.protocol_version >= "HTTP/1.1"):
+ self.close_connection = 0
+ return True
+
+ def handle_one_request(self):
+ """Handle a single HTTP request.
+
+ You normally don't need to override this method; see the class
+ __doc__ string for information on how to handle specific HTTP
+ commands such as GET and POST.
+
+ """
+ try:
+ self.raw_requestline = self.rfile.readline(65537)
+ if len(self.raw_requestline) > 65536:
+ self.requestline = ''
+ self.request_version = ''
+ self.command = ''
+ self.send_error(414)
+ return
+ if not self.raw_requestline:
+ self.close_connection = 1
+ return
+ if not self.parse_request():
+ # An error code has been sent, just exit
+ return
+ mname = 'do_' + self.command
+ if not hasattr(self, mname):
+ self.send_error(501, "Unsupported method (%r)" % self.command)
+ return
+ method = getattr(self, mname)
+ method()
+ self.wfile.flush() #actually send the response if not already done.
+ except socket.timeout, e:
+ #a read or a write timed out. Discard this connection
+ self.log_error("Request timed out: %r", e)
+ self.close_connection = 1
+ return
+
+ def handle(self):
+ """Handle multiple requests if necessary."""
+ self.close_connection = 1
+
+ self.handle_one_request()
+ while not self.close_connection:
+ self.handle_one_request()
+
+ def send_error(self, code, message=None):
+ """Send and log an error reply.
+
+ Arguments are the error code, and a detailed message.
+ The detailed message defaults to the short entry matching the
+ response code.
+
+ This sends an error response (so it must be called before any
+ output has been generated), logs the error, and finally sends
+ a piece of HTML explaining the error to the user.
+
+ """
+
+ try:
+ short, long = self.responses[code]
+ except KeyError:
+ short, long = '???', '???'
+ if message is None:
+ message = short
+ explain = long
+ self.log_error("code %d, message %s", code, message)
+ # using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201)
+ content = (self.error_message_format %
+ {'code': code, 'message': _quote_html(message), 'explain': explain})
+ self.send_response(code, message)
+ self.send_header("Content-Type", self.error_content_type)
+ self.send_header('Connection', 'close')
+ self.end_headers()
+ if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
+ self.wfile.write(content)
+
+ error_message_format = DEFAULT_ERROR_MESSAGE
+ error_content_type = DEFAULT_ERROR_CONTENT_TYPE
+
+ def send_response(self, code, message=None):
+ """Send the response header and log the response code.
+
+ Also send two standard headers with the server software
+ version and the current date.
+
+ """
+ self.log_request(code)
+ if message is None:
+ if code in self.responses:
+ message = self.responses[code][0]
+ else:
+ message = ''
+ if self.request_version != 'HTTP/0.9':
+ self.wfile.write("%s %d %s\r\n" %
+ (self.protocol_version, code, message))
+ # print (self.protocol_version, code, message)
+ self.send_header('Server', self.version_string())
+ self.send_header('Date', self.date_time_string())
+
+ def send_header(self, keyword, value):
+ """Send a MIME header."""
+ if self.request_version != 'HTTP/0.9':
+ self.wfile.write("%s: %s\r\n" % (keyword, value))
+
+ if keyword.lower() == 'connection':
+ if value.lower() == 'close':
+ self.close_connection = 1
+ elif value.lower() == 'keep-alive':
+ self.close_connection = 0
+
+ def end_headers(self):
+ """Send the blank line ending the MIME headers."""
+ if self.request_version != 'HTTP/0.9':
+ self.wfile.write("\r\n")
+
+ def log_request(self, code='-', size='-'):
+ """Log an accepted request.
+
+ This is called by send_response().
+
+ """
+
+ self.log_message('"%s" %s %s',
+ self.requestline, str(code), str(size))
+
+ def log_error(self, format, *args):
+ """Log an error.
+
+ This is called when a request cannot be fulfilled. By
+ default it passes the message on to log_message().
+
+ Arguments are the same as for log_message().
+
+ XXX This should go to the separate error log.
+
+ """
+
+ self.log_message(format, *args)
+
+ def log_message(self, format, *args):
+ """Log an arbitrary message.
+
+ This is used by all other logging functions. Override
+ it if you have specific logging wishes.
+
+ The first argument, FORMAT, is a format string for the
+ message to be logged. If the format string contains
+ any % escapes requiring parameters, they should be
+ specified as subsequent arguments (it's just like
+ printf!).
+
+ The client host and current date/time are prefixed to
+ every message.
+
+ """
+
+ sys.stderr.write("%s - - [%s] %s\n" %
+ (self.address_string(),
+ self.log_date_time_string(),
+ format%args))
+
+ def version_string(self):
+ """Return the server software version string."""
+ return self.server_version + ' ' + self.sys_version
+
+ def date_time_string(self, timestamp=None):
+ """Return the current date and time formatted for a message header."""
+ if timestamp is None:
+ timestamp = time.time()
+ year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
+ s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
+ self.weekdayname[wd],
+ day, self.monthname[month], year,
+ hh, mm, ss)
+ return s
+
+ def log_date_time_string(self):
+ """Return the current time formatted for logging."""
+ now = time.time()
+ year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
+ s = "%02d/%3s/%04d %02d:%02d:%02d" % (
+ day, self.monthname[month], year, hh, mm, ss)
+ return s
+
+ weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
+
+ monthname = [None,
+ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
+
+ def address_string(self):
+ """Return the client address formatted for logging.
+
+ This version looks up the full hostname using gethostbyaddr(),
+ and tries to find a name that contains at least one dot.
+
+ """
+
+ host, port = self.client_address[:2]
+ return socket.getfqdn(host)
+
+ # Essentially static class variables
+
+ # The version of the HTTP protocol we support.
+ # Set this to HTTP/1.1 to enable automatic keepalive
+ protocol_version = "HTTP/1.0"
+
+ # The Message-like class used to parse headers
+ MessageClass = mimetools.Message
+
+ # Table mapping response codes to messages; entries have the
+ # form {code: (shortmessage, longmessage)}.
+ # See RFC 2616.
+ responses = {
+ 100: ('Continue', 'Request received, please continue'),
+ 101: ('Switching Protocols',
+ 'Switching to new protocol; obey Upgrade header'),
+
+ 200: ('OK', 'Request fulfilled, document follows'),
+ 201: ('Created', 'Document created, URL follows'),
+ 202: ('Accepted',
+ 'Request accepted, processing continues off-line'),
+ 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
+ 204: ('No Content', 'Request fulfilled, nothing follows'),
+ 205: ('Reset Content', 'Clear input form for further input.'),
+ 206: ('Partial Content', 'Partial content follows.'),
+
+ 300: ('Multiple Choices',
+ 'Object has several resources -- see URI list'),
+ 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
+ 302: ('Found', 'Object moved temporarily -- see URI list'),
+ 303: ('See Other', 'Object moved -- see Method and URL list'),
+ 304: ('Not Modified',
+ 'Document has not changed since given time'),
+ 305: ('Use Proxy',
+ 'You must use proxy specified in Location to access this '
+ 'resource.'),
+ 307: ('Temporary Redirect',
+ 'Object moved temporarily -- see URI list'),
+
+ 400: ('Bad Request',
+ 'Bad request syntax or unsupported method'),
+ 401: ('Unauthorized',
+ 'No permission -- see authorization schemes'),
+ 402: ('Payment Required',
+ 'No payment -- see charging schemes'),
+ 403: ('Forbidden',
+ 'Request forbidden -- authorization will not help'),
+ 404: ('Not Found', 'Nothing matches the given URI'),
+ 405: ('Method Not Allowed',
+ 'Specified method is invalid for this resource.'),
+ 406: ('Not Acceptable', 'URI not available in preferred format.'),
+ 407: ('Proxy Authentication Required', 'You must authenticate with '
+ 'this proxy before proceeding.'),
+ 408: ('Request Timeout', 'Request timed out; try again later.'),
+ 409: ('Conflict', 'Request conflict.'),
+ 410: ('Gone',
+ 'URI no longer exists and has been permanently removed.'),
+ 411: ('Length Required', 'Client must specify Content-Length.'),
+ 412: ('Precondition Failed', 'Precondition in headers is false.'),
+ 413: ('Request Entity Too Large', 'Entity is too large.'),
+ 414: ('Request-URI Too Long', 'URI is too long.'),
+ 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
+ 416: ('Requested Range Not Satisfiable',
+ 'Cannot satisfy request range.'),
+ 417: ('Expectation Failed',
+ 'Expect condition could not be satisfied.'),
+
+ 500: ('Internal Server Error', 'Server got itself in trouble'),
+ 501: ('Not Implemented',
+ 'Server does not support this operation'),
+ 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
+ 503: ('Service Unavailable',
+ 'The server cannot process the request due to a high load'),
+ 504: ('Gateway Timeout',
+ 'The gateway server did not receive a timely response'),
+ 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
+ }
+
+
+def test(HandlerClass = BaseHTTPRequestHandler,
+ ServerClass = HTTPServer, protocol="HTTP/1.0"):
+ """Test the HTTP request handler class.
+
+ This runs an HTTP server on port 8000 (or the first command line
+ argument).
+
+ """
+
+ if sys.argv[1:]:
+ port = int(sys.argv[1])
+ else:
+ port = 8000
+ server_address = ('', port)
+
+ HandlerClass.protocol_version = protocol
+ httpd = ServerClass(server_address, HandlerClass)
+
+ sa = httpd.socket.getsockname()
+ print "Serving HTTP on", sa[0], "port", sa[1], "..."
+ httpd.serve_forever()
+
+
+if __name__ == '__main__':
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Lib/Bastion.py b/AppPkg/Applications/Python/Python-2.7.2/Lib/Bastion.py
new file mode 100644
index 0000000000..9ab2f127bb
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Lib/Bastion.py
@@ -0,0 +1,180 @@
+"""Bastionification utility.
+
+A bastion (for another object -- the 'original') is an object that has
+the same methods as the original but does not give access to its
+instance variables. Bastions have a number of uses, but the most
+obvious one is to provide code executing in restricted mode with a
+safe interface to an object implemented in unrestricted mode.
+
+The bastionification routine has an optional second argument which is
+a filter function. Only those methods for which the filter method
+(called with the method name as argument) returns true are accessible.
+The default filter method returns true unless the method name begins
+with an underscore.
+
+There are a number of possible implementations of bastions. We use a
+'lazy' approach where the bastion's __getattr__() discipline does all
+the work for a particular method the first time it is used. This is
+usually fastest, especially if the user doesn't call all available
+methods. The retrieved methods are stored as instance variables of
+the bastion, so the overhead is only occurred on the first use of each
+method.
+
+Detail: the bastion class has a __repr__() discipline which includes
+the repr() of the original object. This is precomputed when the
+bastion is created.
+
+"""
+from warnings import warnpy3k
+warnpy3k("the Bastion module has been removed in Python 3.0", stacklevel=2)
+del warnpy3k
+
+__all__ = ["BastionClass", "Bastion"]
+
+from types import MethodType
+
+
+class BastionClass:
+
+ """Helper class used by the Bastion() function.
+
+ You could subclass this and pass the subclass as the bastionclass
+ argument to the Bastion() function, as long as the constructor has
+ the same signature (a get() function and a name for the object).
+
+ """
+
+ def __init__(self, get, name):
+ """Constructor.
+
+ Arguments:
+
+ get - a function that gets the attribute value (by name)
+ name - a human-readable name for the original object
+ (suggestion: use repr(object))
+
+ """
+ self._get_ = get
+ self._name_ = name
+
+ def __repr__(self):
+ """Return a representation string.
+
+ This includes the name passed in to the constructor, so that
+ if you print the bastion during debugging, at least you have
+ some idea of what it is.
+
+ """
+ return "" % self._name_
+
+ def __getattr__(self, name):
+ """Get an as-yet undefined attribute value.
+
+ This calls the get() function that was passed to the
+ constructor. The result is stored as an instance variable so
+ that the next time the same attribute is requested,
+ __getattr__() won't be invoked.
+
+ If the get() function raises an exception, this is simply
+ passed on -- exceptions are not cached.
+
+ """
+ attribute = self._get_(name)
+ self.__dict__[name] = attribute
+ return attribute
+
+
+def Bastion(object, filter = lambda name: name[:1] != '_',
+ name=None, bastionclass=BastionClass):
+ """Create a bastion for an object, using an optional filter.
+
+ See the Bastion module's documentation for background.
+
+ Arguments:
+
+ object - the original object
+ filter - a predicate that decides whether a function name is OK;
+ by default all names are OK that don't start with '_'
+ name - the name of the object; default repr(object)
+ bastionclass - class used to create the bastion; default BastionClass
+
+ """
+
+ raise RuntimeError, "This code is not secure in Python 2.2 and later"
+
+ # Note: we define *two* ad-hoc functions here, get1 and get2.
+ # Both are intended to be called in the same way: get(name).
+ # It is clear that the real work (getting the attribute
+ # from the object and calling the filter) is done in get1.
+ # Why can't we pass get1 to the bastion? Because the user
+ # would be able to override the filter argument! With get2,
+ # overriding the default argument is no security loophole:
+ # all it does is call it.
+ # Also notice that we can't place the object and filter as
+ # instance variables on the bastion object itself, since
+ # the user has full access to all instance variables!
+
+ def get1(name, object=object, filter=filter):
+ """Internal function for Bastion(). See source comments."""
+ if filter(name):
+ attribute = getattr(object, name)
+ if type(attribute) == MethodType:
+ return attribute
+ raise AttributeError, name
+
+ def get2(name, get1=get1):
+ """Internal function for Bastion(). See source comments."""
+ return get1(name)
+
+ if name is None:
+ name = repr(object)
+ return bastionclass(get2, name)
+
+
+def _test():
+ """Test the Bastion() function."""
+ class Original:
+ def __init__(self):
+ self.sum = 0
+ def add(self, n):
+ self._add(n)
+ def _add(self, n):
+ self.sum = self.sum + n
+ def total(self):
+ return self.sum
+ o = Original()
+ b = Bastion(o)
+ testcode = """if 1:
+ b.add(81)
+ b.add(18)
+ print "b.total() =", b.total()
+ try:
+ print "b.sum =", b.sum,
+ except:
+ print "inaccessible"
+ else:
+ print "accessible"
+ try:
+ print "b._add =", b._add,
+ except:
+ print "inaccessible"
+ else:
+ print "accessible"
+ try:
+ print "b._get_.func_defaults =", map(type, b._get_.func_defaults),
+ except:
+ print "inaccessible"
+ else:
+ print "accessible"
+ \n"""
+ exec testcode
+ print '='*20, "Using rexec:", '='*20
+ import rexec
+ r = rexec.RExec()
+ m = r.add_module('__main__')
+ m.b = b
+ r.r_exec(testcode)
+
+
+if __name__ == '__main__':
+ _test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Lib/CGIHTTPServer.py b/AppPkg/Applications/Python/Python-2.7.2/Lib/CGIHTTPServer.py
new file mode 100644
index 0000000000..9c7f9dfb61
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Lib/CGIHTTPServer.py
@@ -0,0 +1,374 @@
+"""CGI-savvy HTTP Server.
+
+This module builds on SimpleHTTPServer by implementing GET and POST
+requests to cgi-bin scripts.
+
+If the os.fork() function is not present (e.g. on Windows),
+os.popen2() is used as a fallback, with slightly altered semantics; if
+that function is not present either (e.g. on Macintosh), only Python
+scripts are supported, and they are executed by the current process.
+
+In all cases, the implementation is intentionally naive -- all
+requests are executed sychronously.
+
+SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL
+-- it may execute arbitrary Python code or external programs.
+
+Note that status code 200 is sent prior to execution of a CGI script, so
+scripts cannot send other status codes such as 302 (redirect).
+"""
+
+
+__version__ = "0.4"
+
+__all__ = ["CGIHTTPRequestHandler"]
+
+import os
+import sys
+import urllib
+import BaseHTTPServer
+import SimpleHTTPServer
+import select
+import copy
+
+
+class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
+
+ """Complete HTTP server with GET, HEAD and POST commands.
+
+ GET and HEAD also support running CGI scripts.
+
+ The POST command is *only* implemented for CGI scripts.
+
+ """
+
+ # Determine platform specifics
+ have_fork = hasattr(os, 'fork')
+ have_popen2 = hasattr(os, 'popen2')
+ have_popen3 = hasattr(os, 'popen3')
+
+ # Make rfile unbuffered -- we need to read one line and then pass
+ # the rest to a subprocess, so we can't use buffered input.
+ rbufsize = 0
+
+ def do_POST(self):
+ """Serve a POST request.
+
+ This is only implemented for CGI scripts.
+
+ """
+
+ if self.is_cgi():
+ self.run_cgi()
+ else:
+ self.send_error(501, "Can only POST to CGI scripts")
+
+ def send_head(self):
+ """Version of send_head that support CGI scripts"""
+ if self.is_cgi():
+ return self.run_cgi()
+ else:
+ return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self)
+
+ def is_cgi(self):
+ """Test whether self.path corresponds to a CGI script.
+
+ Returns True and updates the cgi_info attribute to the tuple
+ (dir, rest) if self.path requires running a CGI script.
+ Returns False otherwise.
+
+ If any exception is raised, the caller should assume that
+ self.path was rejected as invalid and act accordingly.
+
+ The default implementation tests whether the normalized url
+ path begins with one of the strings in self.cgi_directories
+ (and the next character is a '/' or the end of the string).
+ """
+ splitpath = _url_collapse_path_split(self.path)
+ if splitpath[0] in self.cgi_directories:
+ self.cgi_info = splitpath
+ return True
+ return False
+
+ cgi_directories = ['/cgi-bin', '/htbin']
+
+ def is_executable(self, path):
+ """Test whether argument path is an executable file."""
+ return executable(path)
+
+ def is_python(self, path):
+ """Test whether argument path is a Python script."""
+ head, tail = os.path.splitext(path)
+ return tail.lower() in (".py", ".pyw")
+
+ def run_cgi(self):
+ """Execute a CGI script."""
+ path = self.path
+ dir, rest = self.cgi_info
+
+ i = path.find('/', len(dir) + 1)
+ while i >= 0:
+ nextdir = path[:i]
+ nextrest = path[i+1:]
+
+ scriptdir = self.translate_path(nextdir)
+ if os.path.isdir(scriptdir):
+ dir, rest = nextdir, nextrest
+ i = path.find('/', len(dir) + 1)
+ else:
+ break
+
+ # find an explicit query string, if present.
+ i = rest.rfind('?')
+ if i >= 0:
+ rest, query = rest[:i], rest[i+1:]
+ else:
+ query = ''
+
+ # dissect the part after the directory name into a script name &
+ # a possible additional path, to be stored in PATH_INFO.
+ i = rest.find('/')
+ if i >= 0:
+ script, rest = rest[:i], rest[i:]
+ else:
+ script, rest = rest, ''
+
+ scriptname = dir + '/' + script
+ scriptfile = self.translate_path(scriptname)
+ if not os.path.exists(scriptfile):
+ self.send_error(404, "No such CGI script (%r)" % scriptname)
+ return
+ if not os.path.isfile(scriptfile):
+ self.send_error(403, "CGI script is not a plain file (%r)" %
+ scriptname)
+ return
+ ispy = self.is_python(scriptname)
+ if not ispy:
+ if not (self.have_fork or self.have_popen2 or self.have_popen3):
+ self.send_error(403, "CGI script is not a Python script (%r)" %
+ scriptname)
+ return
+ if not self.is_executable(scriptfile):
+ self.send_error(403, "CGI script is not executable (%r)" %
+ scriptname)
+ return
+
+ # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html
+ # XXX Much of the following could be prepared ahead of time!
+ env = copy.deepcopy(os.environ)
+ env['SERVER_SOFTWARE'] = self.version_string()
+ env['SERVER_NAME'] = self.server.server_name
+ env['GATEWAY_INTERFACE'] = 'CGI/1.1'
+ env['SERVER_PROTOCOL'] = self.protocol_version
+ env['SERVER_PORT'] = str(self.server.server_port)
+ env['REQUEST_METHOD'] = self.command
+ uqrest = urllib.unquote(rest)
+ env['PATH_INFO'] = uqrest
+ env['PATH_TRANSLATED'] = self.translate_path(uqrest)
+ env['SCRIPT_NAME'] = scriptname
+ if query:
+ env['QUERY_STRING'] = query
+ host = self.address_string()
+ if host != self.client_address[0]:
+ env['REMOTE_HOST'] = host
+ env['REMOTE_ADDR'] = self.client_address[0]
+ authorization = self.headers.getheader("authorization")
+ if authorization:
+ authorization = authorization.split()
+ if len(authorization) == 2:
+ import base64, binascii
+ env['AUTH_TYPE'] = authorization[0]
+ if authorization[0].lower() == "basic":
+ try:
+ authorization = base64.decodestring(authorization[1])
+ except binascii.Error:
+ pass
+ else:
+ authorization = authorization.split(':')
+ if len(authorization) == 2:
+ env['REMOTE_USER'] = authorization[0]
+ # XXX REMOTE_IDENT
+ if self.headers.typeheader is None:
+ env['CONTENT_TYPE'] = self.headers.type
+ else:
+ env['CONTENT_TYPE'] = self.headers.typeheader
+ length = self.headers.getheader('content-length')
+ if length:
+ env['CONTENT_LENGTH'] = length
+ referer = self.headers.getheader('referer')
+ if referer:
+ env['HTTP_REFERER'] = referer
+ accept = []
+ for line in self.headers.getallmatchingheaders('accept'):
+ if line[:1] in "\t\n\r ":
+ accept.append(line.strip())
+ else:
+ accept = accept + line[7:].split(',')
+ env['HTTP_ACCEPT'] = ','.join(accept)
+ ua = self.headers.getheader('user-agent')
+ if ua:
+ env['HTTP_USER_AGENT'] = ua
+ co = filter(None, self.headers.getheaders('cookie'))
+ if co:
+ env['HTTP_COOKIE'] = ', '.join(co)
+ # XXX Other HTTP_* headers
+ # Since we're setting the env in the parent, provide empty
+ # values to override previously set values
+ for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
+ 'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
+ env.setdefault(k, "")
+
+ self.send_response(200, "Script output follows")
+
+ decoded_query = query.replace('+', ' ')
+
+ if self.have_fork:
+ # Unix -- fork as we should
+ args = [script]
+ if '=' not in decoded_query:
+ args.append(decoded_query)
+ nobody = nobody_uid()
+ self.wfile.flush() # Always flush before forking
+ pid = os.fork()
+ if pid != 0:
+ # Parent
+ pid, sts = os.waitpid(pid, 0)
+ # throw away additional data [see bug #427345]
+ while select.select([self.rfile], [], [], 0)[0]:
+ if not self.rfile.read(1):
+ break
+ if sts:
+ self.log_error("CGI script exit status %#x", sts)
+ return
+ # Child
+ try:
+ try:
+ os.setuid(nobody)
+ except os.error:
+ pass
+ os.dup2(self.rfile.fileno(), 0)
+ os.dup2(self.wfile.fileno(), 1)
+ os.execve(scriptfile, args, env)
+ except:
+ self.server.handle_error(self.request, self.client_address)
+ os._exit(127)
+
+ else:
+ # Non Unix - use subprocess
+ import subprocess
+ cmdline = [scriptfile]
+ if self.is_python(scriptfile):
+ interp = sys.executable
+ if interp.lower().endswith("w.exe"):
+ # On Windows, use python.exe, not pythonw.exe
+ interp = interp[:-5] + interp[-4:]
+ cmdline = [interp, '-u'] + cmdline
+ if '=' not in query:
+ cmdline.append(query)
+
+ self.log_message("command: %s", subprocess.list2cmdline(cmdline))
+ try:
+ nbytes = int(length)
+ except (TypeError, ValueError):
+ nbytes = 0
+ p = subprocess.Popen(cmdline,
+ stdin = subprocess.PIPE,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ env = env
+ )
+ if self.command.lower() == "post" and nbytes > 0:
+ data = self.rfile.read(nbytes)
+ else:
+ data = None
+ # throw away additional data [see bug #427345]
+ while select.select([self.rfile._sock], [], [], 0)[0]:
+ if not self.rfile._sock.recv(1):
+ break
+ stdout, stderr = p.communicate(data)
+ self.wfile.write(stdout)
+ if stderr:
+ self.log_error('%s', stderr)
+ p.stderr.close()
+ p.stdout.close()
+ status = p.returncode
+ if status:
+ self.log_error("CGI script exit status %#x", status)
+ else:
+ self.log_message("CGI script exited OK")
+
+
+# TODO(gregory.p.smith): Move this into an appropriate library.
+def _url_collapse_path_split(path):
+ """
+ Given a URL path, remove extra '/'s and '.' path elements and collapse
+ any '..' references.
+
+ Implements something akin to RFC-2396 5.2 step 6 to parse relative paths.
+
+ Returns: A tuple of (head, tail) where tail is everything after the final /
+ and head is everything before it. Head will always start with a '/' and,
+ if it contains anything else, never have a trailing '/'.
+
+ Raises: IndexError if too many '..' occur within the path.
+ """
+ # Similar to os.path.split(os.path.normpath(path)) but specific to URL
+ # path semantics rather than local operating system semantics.
+ path_parts = []
+ for part in path.split('/'):
+ if part == '.':
+ path_parts.append('')
+ else:
+ path_parts.append(part)
+ # Filter out blank non trailing parts before consuming the '..'.
+ path_parts = [part for part in path_parts[:-1] if part] + path_parts[-1:]
+ if path_parts:
+ tail_part = path_parts.pop()
+ else:
+ tail_part = ''
+ head_parts = []
+ for part in path_parts:
+ if part == '..':
+ head_parts.pop()
+ else:
+ head_parts.append(part)
+ if tail_part and tail_part == '..':
+ head_parts.pop()
+ tail_part = ''
+ return ('/' + '/'.join(head_parts), tail_part)
+
+
+nobody = None
+
+def nobody_uid():
+ """Internal routine to get nobody's uid"""
+ global nobody
+ if nobody:
+ return nobody
+ try:
+ import pwd
+ except ImportError:
+ return -1
+ try:
+ nobody = pwd.getpwnam('nobody')[2]
+ except KeyError:
+ nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
+ return nobody
+
+
+def executable(path):
+ """Test for executable file."""
+ try:
+ st = os.stat(path)
+ except os.error:
+ return False
+ return st.st_mode & 0111 != 0
+
+
+def test(HandlerClass = CGIHTTPRequestHandler,
+ ServerClass = BaseHTTPServer.HTTPServer):
+ SimpleHTTPServer.test(HandlerClass, ServerClass)
+
+
+if __name__ == '__main__':
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Lib/ConfigParser.py b/AppPkg/Applications/Python/Python-2.7.2/Lib/ConfigParser.py
new file mode 100644
index 0000000000..033edda881
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Lib/ConfigParser.py
@@ -0,0 +1,745 @@
+"""Configuration file parser.
+
+A setup file consists of sections, lead by a "[section]" header,
+and followed by "name: value" entries, with continuations and such in
+the style of RFC 822.
+
+The option values can contain format strings which refer to other values in
+the same section, or values in a special [DEFAULT] section.
+
+For example:
+
+ something: %(dir)s/whatever
+
+would resolve the "%(dir)s" to the value of dir. All reference
+expansions are done late, on demand.
+
+Intrinsic defaults can be specified by passing them into the
+ConfigParser constructor as a dictionary.
+
+class:
+
+ConfigParser -- responsible for parsing a list of
+ configuration files, and managing the parsed database.
+
+ methods:
+
+ __init__(defaults=None)
+ create the parser and specify a dictionary of intrinsic defaults. The
+ keys must be strings, the values must be appropriate for %()s string
+ interpolation. Note that `__name__' is always an intrinsic default;
+ its value is the section's name.
+
+ sections()
+ return all the configuration section names, sans DEFAULT
+
+ has_section(section)
+ return whether the given section exists
+
+ has_option(section, option)
+ return whether the given option exists in the given section
+
+ options(section)
+ return list of configuration options for the named section
+
+ read(filenames)
+ read and parse the list of named configuration files, given by
+ name. A single filename is also allowed. Non-existing files
+ are ignored. Return list of successfully read files.
+
+ readfp(fp, filename=None)
+ read and parse one configuration file, given as a file object.
+ The filename defaults to fp.name; it is only used in error
+ messages (if fp has no `name' attribute, the string `??>' is used).
+
+ get(section, option, raw=False, vars=None)
+ return a string value for the named option. All % interpolations are
+ expanded in the return values, based on the defaults passed into the
+ constructor and the DEFAULT section. Additional substitutions may be
+ provided using the `vars' argument, which must be a dictionary whose
+ contents override any pre-existing defaults.
+
+ getint(section, options)
+ like get(), but convert value to an integer
+
+ getfloat(section, options)
+ like get(), but convert value to a float
+
+ getboolean(section, options)
+ like get(), but convert value to a boolean (currently case
+ insensitively defined as 0, false, no, off for False, and 1, true,
+ yes, on for True). Returns False or True.
+
+ items(section, raw=False, vars=None)
+ return a list of tuples with (name, value) for each option
+ in the section.
+
+ remove_section(section)
+ remove the given file section and all its options
+
+ remove_option(section, option)
+ remove the given option from the given section
+
+ set(section, option, value)
+ set the given option
+
+ write(fp)
+ write the configuration state in .ini format
+"""
+
+try:
+ from collections import OrderedDict as _default_dict
+except ImportError:
+ # fallback for setup.py which hasn't yet built _collections
+ _default_dict = dict
+
+import re
+
+__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
+ "InterpolationError", "InterpolationDepthError",
+ "InterpolationSyntaxError", "ParsingError",
+ "MissingSectionHeaderError",
+ "ConfigParser", "SafeConfigParser", "RawConfigParser",
+ "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
+
+DEFAULTSECT = "DEFAULT"
+
+MAX_INTERPOLATION_DEPTH = 10
+
+
+
+# exception classes
+class Error(Exception):
+ """Base class for ConfigParser exceptions."""
+
+ def _get_message(self):
+ """Getter for 'message'; needed only to override deprecation in
+ BaseException."""
+ return self.__message
+
+ def _set_message(self, value):
+ """Setter for 'message'; needed only to override deprecation in
+ BaseException."""
+ self.__message = value
+
+ # BaseException.message has been deprecated since Python 2.6. To prevent
+ # DeprecationWarning from popping up over this pre-existing attribute, use
+ # a new property that takes lookup precedence.
+ message = property(_get_message, _set_message)
+
+ def __init__(self, msg=''):
+ self.message = msg
+ Exception.__init__(self, msg)
+
+ def __repr__(self):
+ return self.message
+
+ __str__ = __repr__
+
+class NoSectionError(Error):
+ """Raised when no section matches a requested option."""
+
+ def __init__(self, section):
+ Error.__init__(self, 'No section: %r' % (section,))
+ self.section = section
+
+class DuplicateSectionError(Error):
+ """Raised when a section is multiply-created."""
+
+ def __init__(self, section):
+ Error.__init__(self, "Section %r already exists" % section)
+ self.section = section
+
+class NoOptionError(Error):
+ """A requested option was not found."""
+
+ def __init__(self, option, section):
+ Error.__init__(self, "No option %r in section: %r" %
+ (option, section))
+ self.option = option
+ self.section = section
+
+class InterpolationError(Error):
+ """Base class for interpolation-related exceptions."""
+
+ def __init__(self, option, section, msg):
+ Error.__init__(self, msg)
+ self.option = option
+ self.section = section
+
+class InterpolationMissingOptionError(InterpolationError):
+ """A string substitution required a setting which was not available."""
+
+ def __init__(self, option, section, rawval, reference):
+ msg = ("Bad value substitution:\n"
+ "\tsection: [%s]\n"
+ "\toption : %s\n"
+ "\tkey : %s\n"
+ "\trawval : %s\n"
+ % (section, option, reference, rawval))
+ InterpolationError.__init__(self, option, section, msg)
+ self.reference = reference
+
+class InterpolationSyntaxError(InterpolationError):
+ """Raised when the source text into which substitutions are made
+ does not conform to the required syntax."""
+
+class InterpolationDepthError(InterpolationError):
+ """Raised when substitutions are nested too deeply."""
+
+ def __init__(self, option, section, rawval):
+ msg = ("Value interpolation too deeply recursive:\n"
+ "\tsection: [%s]\n"
+ "\toption : %s\n"
+ "\trawval : %s\n"
+ % (section, option, rawval))
+ InterpolationError.__init__(self, option, section, msg)
+
+class ParsingError(Error):
+ """Raised when a configuration file does not follow legal syntax."""
+
+ def __init__(self, filename):
+ Error.__init__(self, 'File contains parsing errors: %s' % filename)
+ self.filename = filename
+ self.errors = []
+
+ def append(self, lineno, line):
+ self.errors.append((lineno, line))
+ self.message += '\n\t[line %2d]: %s' % (lineno, line)
+
+class MissingSectionHeaderError(ParsingError):
+ """Raised when a key-value pair is found before any section header."""
+
+ def __init__(self, filename, lineno, line):
+ Error.__init__(
+ self,
+ 'File contains no section headers.\nfile: %s, line: %d\n%r' %
+ (filename, lineno, line))
+ self.filename = filename
+ self.lineno = lineno
+ self.line = line
+
+
+class RawConfigParser:
+ def __init__(self, defaults=None, dict_type=_default_dict,
+ allow_no_value=False):
+ self._dict = dict_type
+ self._sections = self._dict()
+ self._defaults = self._dict()
+ if allow_no_value:
+ self._optcre = self.OPTCRE_NV
+ else:
+ self._optcre = self.OPTCRE
+ if defaults:
+ for key, value in defaults.items():
+ self._defaults[self.optionxform(key)] = value
+
+ def defaults(self):
+ return self._defaults
+
+ def sections(self):
+ """Return a list of section names, excluding [DEFAULT]"""
+ # self._sections will never have [DEFAULT] in it
+ return self._sections.keys()
+
+ def add_section(self, section):
+ """Create a new section in the configuration.
+
+ Raise DuplicateSectionError if a section by the specified name
+ already exists. Raise ValueError if name is DEFAULT or any of it's
+ case-insensitive variants.
+ """
+ if section.lower() == "default":
+ raise ValueError, 'Invalid section name: %s' % section
+
+ if section in self._sections:
+ raise DuplicateSectionError(section)
+ self._sections[section] = self._dict()
+
+ def has_section(self, section):
+ """Indicate whether the named section is present in the configuration.
+
+ The DEFAULT section is not acknowledged.
+ """
+ return section in self._sections
+
+ def options(self, section):
+ """Return a list of option names for the given section name."""
+ try:
+ opts = self._sections[section].copy()
+ except KeyError:
+ raise NoSectionError(section)
+ opts.update(self._defaults)
+ if '__name__' in opts:
+ del opts['__name__']
+ return opts.keys()
+
+ def read(self, filenames):
+ """Read and parse a filename or a list of filenames.
+
+ Files that cannot be opened are silently ignored; this is
+ designed so that you can specify a list of potential
+ configuration file locations (e.g. current directory, user's
+ home directory, systemwide directory), and all existing
+ configuration files in the list will be read. A single
+ filename may also be given.
+
+ Return list of successfully read files.
+ """
+ if isinstance(filenames, basestring):
+ filenames = [filenames]
+ read_ok = []
+ for filename in filenames:
+ try:
+ fp = open(filename)
+ except IOError:
+ continue
+ self._read(fp, filename)
+ fp.close()
+ read_ok.append(filename)
+ return read_ok
+
+ def readfp(self, fp, filename=None):
+ """Like read() but the argument must be a file-like object.
+
+ The `fp' argument must have a `readline' method. Optional
+ second argument is the `filename', which if not given, is
+ taken from fp.name. If fp has no `name' attribute, `??>' is
+ used.
+
+ """
+ if filename is None:
+ try:
+ filename = fp.name
+ except AttributeError:
+ filename = '??>'
+ self._read(fp, filename)
+
+ def get(self, section, option):
+ opt = self.optionxform(option)
+ if section not in self._sections:
+ if section != DEFAULTSECT:
+ raise NoSectionError(section)
+ if opt in self._defaults:
+ return self._defaults[opt]
+ else:
+ raise NoOptionError(option, section)
+ elif opt in self._sections[section]:
+ return self._sections[section][opt]
+ elif opt in self._defaults:
+ return self._defaults[opt]
+ else:
+ raise NoOptionError(option, section)
+
+ def items(self, section):
+ try:
+ d2 = self._sections[section]
+ except KeyError:
+ if section != DEFAULTSECT:
+ raise NoSectionError(section)
+ d2 = self._dict()
+ d = self._defaults.copy()
+ d.update(d2)
+ if "__name__" in d:
+ del d["__name__"]
+ return d.items()
+
+ def _get(self, section, conv, option):
+ return conv(self.get(section, option))
+
+ def getint(self, section, option):
+ return self._get(section, int, option)
+
+ def getfloat(self, section, option):
+ return self._get(section, float, option)
+
+ _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
+ '0': False, 'no': False, 'false': False, 'off': False}
+
+ def getboolean(self, section, option):
+ v = self.get(section, option)
+ if v.lower() not in self._boolean_states:
+ raise ValueError, 'Not a boolean: %s' % v
+ return self._boolean_states[v.lower()]
+
+ def optionxform(self, optionstr):
+ return optionstr.lower()
+
+ def has_option(self, section, option):
+ """Check for the existence of a given option in a given section."""
+ if not section or section == DEFAULTSECT:
+ option = self.optionxform(option)
+ return option in self._defaults
+ elif section not in self._sections:
+ return False
+ else:
+ option = self.optionxform(option)
+ return (option in self._sections[section]
+ or option in self._defaults)
+
+ def set(self, section, option, value=None):
+ """Set an option."""
+ if not section or section == DEFAULTSECT:
+ sectdict = self._defaults
+ else:
+ try:
+ sectdict = self._sections[section]
+ except KeyError:
+ raise NoSectionError(section)
+ sectdict[self.optionxform(option)] = value
+
+ def write(self, fp):
+ """Write an .ini-format representation of the configuration state."""
+ if self._defaults:
+ fp.write("[%s]\n" % DEFAULTSECT)
+ for (key, value) in self._defaults.items():
+ fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
+ fp.write("\n")
+ for section in self._sections:
+ fp.write("[%s]\n" % section)
+ for (key, value) in self._sections[section].items():
+ if key == "__name__":
+ continue
+ if (value is not None) or (self._optcre == self.OPTCRE):
+ key = " = ".join((key, str(value).replace('\n', '\n\t')))
+ fp.write("%s\n" % (key))
+ fp.write("\n")
+
+ def remove_option(self, section, option):
+ """Remove an option."""
+ if not section or section == DEFAULTSECT:
+ sectdict = self._defaults
+ else:
+ try:
+ sectdict = self._sections[section]
+ except KeyError:
+ raise NoSectionError(section)
+ option = self.optionxform(option)
+ existed = option in sectdict
+ if existed:
+ del sectdict[option]
+ return existed
+
+ def remove_section(self, section):
+ """Remove a file section."""
+ existed = section in self._sections
+ if existed:
+ del self._sections[section]
+ return existed
+
+ #
+ # Regular expressions for parsing section headers and options.
+ #
+ SECTCRE = re.compile(
+ r'\[' # [
+ r'(?P[^]]+)' # very permissive!
+ r'\]' # ]
+ )
+ OPTCRE = re.compile(
+ r'(?P