From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from mga05.intel.com (mga05.intel.com [192.55.52.43]) by mx.groups.io with SMTP id smtpd.web09.19194.1635602212911293022 for ; Sat, 30 Oct 2021 06:56:55 -0700 Authentication-Results: mx.groups.io; dkim=missing; spf=pass (domain: intel.com, ip: 192.55.52.43, mailfrom: n.jayaprakash@intel.com) X-IronPort-AV: E=McAfee;i="6200,9189,10152"; a="317018177" X-IronPort-AV: E=Sophos;i="5.87,195,1631602800"; d="scan'208";a="317018177" Received: from orsmga008.jf.intel.com ([10.7.209.65]) by fmsmga105.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 30 Oct 2021 06:56:29 -0700 X-IronPort-AV: E=Sophos;i="5.87,195,1631602800"; d="scan'208";a="499302307" Received: from ankitgo1-mobl.gar.corp.intel.com (HELO njayapra-MOBL1.gar.corp.intel.com) ([10.213.94.18]) by orsmga008-auth.jf.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 30 Oct 2021 06:53:04 -0700 From: "Jayaprakash, N" To: devel@edk2.groups.io Cc: Rebecca Cran , Michael D Kinney , Jayaprakash N Subject: [edk2-libc Patch v3 1/5] AppPkg/Applications/Python: To remove the py2.7.2 uefi port code Date: Sat, 30 Oct 2021 19:22:29 +0530 Message-Id: <20211030135233.1988-2-n.jayaprakash@intel.com> X-Mailer: git-send-email 2.32.0.windows.2 In-Reply-To: <20211030135233.1988-1-n.jayaprakash@intel.com> References: <20211030135233.1988-1-n.jayaprakash@intel.com> MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3589 This commit is to remove the UEFI port of py 2.7.2 code from the edk2-libc git repo. This is an outdated python version and is not supported anymore. Cc: Rebecca Cran Cc: Michael D Kinney Signed-off-by: Jayaprakash N --- AppPkg/AppPkg.dsc | 5 +- AppPkg/Applications/Python/Efi/config.c | 149 - AppPkg/Applications/Python/Efi/edk2module.c | 7414 ------- AppPkg/Applications/Python/Efi/getpath.c | 719 - AppPkg/Applications/Python/Ia32/pyconfig.h | 1256 -- .../Python/PyMod-2.7.2/Include/fileobject.h | 102 - .../Python/PyMod-2.7.2/Include/osdefs.h | 71 - .../Python/PyMod-2.7.2/Include/pyport.h | 918 - .../Python/PyMod-2.7.2/Lib/ntpath.py | 528 - .../Applications/Python/PyMod-2.7.2/Lib/os.py | 773 - .../Python/PyMod-2.7.2/Lib/pydoc.py | 2341 --- .../Python/PyMod-2.7.2/Lib/site.py | 537 - .../Python/PyMod-2.7.2/Modules/_sre.c | 3921 ---- .../Python/PyMod-2.7.2/Modules/addrinfo.h | 178 - .../Python/PyMod-2.7.2/Modules/errnomodule.c | 845 - .../Modules/expat/expat_external.h | 121 - .../PyMod-2.7.2/Modules/expat/xmlparse.c | 6279 ------ .../Python/PyMod-2.7.2/Modules/main.c | 678 - .../Python/PyMod-2.7.2/Modules/selectmodule.c | 1912 -- .../Python/PyMod-2.7.2/Modules/socketmodule.h | 250 - .../Python/PyMod-2.7.2/Modules/zlib/zutil.h | 277 - .../Python/PyMod-2.7.2/Objects/longobject.c | 4381 ---- .../Objects/stringlib/localeutil.h | 227 - .../Python/PyMod-2.7.2/Python/getcopyright.c | 36 - .../Python/PyMod-2.7.2/Python/import.c | 3398 --- .../Python/PyMod-2.7.2/Python/marshal.c | 1422 -- .../Python/Python-2.7.2/Demo/README | 40 - .../Python/Python-2.7.2/Demo/cgi/README | 11 - .../Python/Python-2.7.2/Demo/cgi/cgi0.sh | 8 - .../Python/Python-2.7.2/Demo/cgi/cgi1.py | 14 - .../Python/Python-2.7.2/Demo/cgi/cgi2.py | 22 - .../Python/Python-2.7.2/Demo/cgi/cgi3.py | 10 - .../Python/Python-2.7.2/Demo/cgi/wiki.py | 123 - .../Python-2.7.2/Demo/classes/Complex.py | 320 - .../Python/Python-2.7.2/Demo/classes/Dates.py | 227 - .../Python/Python-2.7.2/Demo/classes/Dbm.py | 66 - .../Python/Python-2.7.2/Demo/classes/README | 12 - .../Python/Python-2.7.2/Demo/classes/Range.py | 93 - .../Python/Python-2.7.2/Demo/classes/Rev.py | 95 - .../Python/Python-2.7.2/Demo/classes/Vec.py | 68 - .../Python-2.7.2/Demo/classes/bitvec.py | 333 - .../Python-2.7.2/Demo/comparisons/README | 60 - .../Python-2.7.2/Demo/comparisons/patterns | 4 - .../Demo/comparisons/regextest.py | 47 - .../Demo/comparisons/sortingtest.py | 45 - .../Demo/comparisons/systemtest.py | 74 - .../Python/Python-2.7.2/Demo/md5test/README | 10 - .../Python/Python-2.7.2/Demo/md5test/foo | 1 - .../Python-2.7.2/Demo/md5test/md5driver.py | 123 - .../Python-2.7.2/Demo/metaclasses/Eiffel.py | 113 - .../Python-2.7.2/Demo/metaclasses/Enum.py | 169 - .../Python-2.7.2/Demo/metaclasses/Meta.py | 118 - .../Python-2.7.2/Demo/metaclasses/Simple.py | 45 - .../Python-2.7.2/Demo/metaclasses/Synch.py | 256 - .../Python-2.7.2/Demo/metaclasses/Trace.py | 144 - .../Python-2.7.2/Demo/metaclasses/index.html | 605 - .../Demo/metaclasses/meta-vladimir.txt | 256 - .../Demo/newmetaclasses/Eiffel.py | 141 - .../Python-2.7.2/Demo/newmetaclasses/Enum.py | 177 - .../Python/Python-2.7.2/Demo/parser/FILES | 6 - .../Python/Python-2.7.2/Demo/parser/README | 32 - .../Python-2.7.2/Demo/parser/docstring.py | 2 - .../Python-2.7.2/Demo/parser/example.py | 190 - .../Python/Python-2.7.2/Demo/parser/simple.py | 1 - .../Python/Python-2.7.2/Demo/parser/source.py | 27 - .../Python-2.7.2/Demo/parser/test_parser.py | 48 - .../Python-2.7.2/Demo/parser/test_unparse.py | 213 - .../Python-2.7.2/Demo/parser/unparse.py | 606 - .../Python/Python-2.7.2/Demo/pdist/FSProxy.py | 301 - .../Python-2.7.2/Demo/pdist/RCSProxy.py | 198 - .../Python/Python-2.7.2/Demo/pdist/README | 121 - .../Python/Python-2.7.2/Demo/pdist/client.py | 157 - .../Python/Python-2.7.2/Demo/pdist/cmdfw.py | 144 - .../Python/Python-2.7.2/Demo/pdist/cmptree.py | 208 - .../Python/Python-2.7.2/Demo/pdist/cvslib.py | 364 - .../Python/Python-2.7.2/Demo/pdist/cvslock.py | 280 - .../Python/Python-2.7.2/Demo/pdist/mac.py | 19 - .../Python-2.7.2/Demo/pdist/makechangelog.py | 109 - .../Python/Python-2.7.2/Demo/pdist/rcsbump | 33 - .../Python-2.7.2/Demo/pdist/rcsclient.py | 71 - .../Python/Python-2.7.2/Demo/pdist/rcslib.py | 334 - .../Python/Python-2.7.2/Demo/pdist/rcvs | 8 - .../Python/Python-2.7.2/Demo/pdist/rcvs.py | 477 - .../Python/Python-2.7.2/Demo/pdist/rrcs | 8 - .../Python/Python-2.7.2/Demo/pdist/rrcs.py | 160 - .../Python-2.7.2/Demo/pdist/security.py | 33 - .../Python/Python-2.7.2/Demo/pdist/server.py | 145 - .../Python/Python-2.7.2/Demo/pdist/sumtree.py | 24 - .../Python/Python-2.7.2/Demo/scripts/README | 22 - .../Python/Python-2.7.2/Demo/scripts/beer.py | 20 - .../Python/Python-2.7.2/Demo/scripts/eqfix.py | 198 - .../Python/Python-2.7.2/Demo/scripts/fact.py | 49 - .../Python-2.7.2/Demo/scripts/find-uname.py | 40 - .../Python/Python-2.7.2/Demo/scripts/from.py | 35 - .../Python-2.7.2/Demo/scripts/lpwatch.py | 102 - .../Python-2.7.2/Demo/scripts/makedir.py | 21 - .../Python-2.7.2/Demo/scripts/markov.py | 121 - .../Python-2.7.2/Demo/scripts/mboxconvert.py | 124 - .../Python/Python-2.7.2/Demo/scripts/morse.py | 138 - .../Python-2.7.2/Demo/scripts/newslist.doc | 59 - .../Python-2.7.2/Demo/scripts/newslist.py | 362 - .../Python/Python-2.7.2/Demo/scripts/pi.py | 33 - .../Python/Python-2.7.2/Demo/scripts/pp.py | 129 - .../Python-2.7.2/Demo/scripts/primes.py | 30 - .../Python-2.7.2/Demo/scripts/queens.py | 85 - .../Python-2.7.2/Demo/scripts/script.py | 42 - .../Python-2.7.2/Demo/scripts/unbirthday.py | 104 - .../Python-2.7.2/Demo/scripts/update.py | 92 - .../Python/Python-2.7.2/Demo/sockets/README | 14 - .../Python-2.7.2/Demo/sockets/broadcast.py | 15 - .../Python-2.7.2/Demo/sockets/echosvr.py | 31 - .../Python-2.7.2/Demo/sockets/finger.py | 58 - .../Python/Python-2.7.2/Demo/sockets/ftp.py | 146 - .../Python-2.7.2/Demo/sockets/gopher.py | 347 - .../Python/Python-2.7.2/Demo/sockets/mcast.py | 80 - .../Python/Python-2.7.2/Demo/sockets/radio.py | 14 - .../Python-2.7.2/Demo/sockets/rpython.py | 35 - .../Python-2.7.2/Demo/sockets/rpythond.py | 52 - .../Python-2.7.2/Demo/sockets/telnet.py | 109 - .../Python-2.7.2/Demo/sockets/throughput.py | 93 - .../Python-2.7.2/Demo/sockets/udpecho.py | 63 - .../Python-2.7.2/Demo/sockets/unicast.py | 14 - .../Python-2.7.2/Demo/sockets/unixclient.py | 12 - .../Python-2.7.2/Demo/sockets/unixserver.py | 24 - .../Python-2.7.2/Demo/xml/elem_count.py | 42 - .../Python/Python-2.7.2/Demo/xml/roundtrip.py | 46 - .../Python/Python-2.7.2/Demo/xml/rss2html.py | 97 - .../Python/Python-2.7.2/Demo/zlib/minigzip.py | 133 - .../Python/Python-2.7.2/Demo/zlib/zlibdemo.py | 48 - .../Python/Python-2.7.2/Grammar/Grammar | 142 - .../Python/Python-2.7.2/Include/Python-ast.h | 535 - .../Python/Python-2.7.2/Include/Python.h | 178 - .../Python/Python-2.7.2/Include/abstract.h | 1396 -- .../Python/Python-2.7.2/Include/asdl.h | 45 - .../Python/Python-2.7.2/Include/ast.h | 13 - .../Python/Python-2.7.2/Include/bitset.h | 32 - .../Python/Python-2.7.2/Include/boolobject.h | 36 - .../Python-2.7.2/Include/bufferobject.h | 33 - .../Python-2.7.2/Include/bytearrayobject.h | 57 - .../Python-2.7.2/Include/bytes_methods.h | 75 - .../Python/Python-2.7.2/Include/bytesobject.h | 27 - .../Python/Python-2.7.2/Include/cStringIO.h | 73 - .../Python/Python-2.7.2/Include/cellobject.h | 28 - .../Python/Python-2.7.2/Include/ceval.h | 153 - .../Python/Python-2.7.2/Include/classobject.h | 83 - .../Python/Python-2.7.2/Include/cobject.h | 89 - .../Python/Python-2.7.2/Include/code.h | 107 - .../Python/Python-2.7.2/Include/codecs.h | 167 - .../Python/Python-2.7.2/Include/compile.h | 40 - .../Python-2.7.2/Include/complexobject.h | 66 - .../Python/Python-2.7.2/Include/datetime.h | 239 - .../Python/Python-2.7.2/Include/descrobject.h | 94 - .../Python/Python-2.7.2/Include/dictobject.h | 156 - .../Python/Python-2.7.2/Include/dtoa.h | 15 - .../Python/Python-2.7.2/Include/enumobject.h | 17 - .../Python/Python-2.7.2/Include/errcode.h | 36 - .../Python/Python-2.7.2/Include/eval.h | 25 - .../Python/Python-2.7.2/Include/fileobject.h | 102 - .../Python/Python-2.7.2/Include/floatobject.h | 140 - .../Python/Python-2.7.2/Include/frameobject.h | 89 - .../Python/Python-2.7.2/Include/funcobject.h | 76 - .../Python/Python-2.7.2/Include/genobject.h | 40 - .../Python/Python-2.7.2/Include/graminit.h | 87 - .../Python/Python-2.7.2/Include/grammar.h | 93 - .../Python/Python-2.7.2/Include/import.h | 71 - .../Python/Python-2.7.2/Include/intobject.h | 80 - .../Python/Python-2.7.2/Include/intrcheck.h | 15 - .../Python/Python-2.7.2/Include/iterobject.h | 23 - .../Python/Python-2.7.2/Include/listobject.h | 68 - .../Python/Python-2.7.2/Include/longintrepr.h | 103 - .../Python/Python-2.7.2/Include/longobject.h | 134 - .../Python/Python-2.7.2/Include/marshal.h | 25 - .../Python-2.7.2/Include/memoryobject.h | 74 - .../Python/Python-2.7.2/Include/metagrammar.h | 18 - .../Python-2.7.2/Include/methodobject.h | 93 - .../Python/Python-2.7.2/Include/modsupport.h | 134 - .../Python-2.7.2/Include/moduleobject.h | 24 - .../Python/Python-2.7.2/Include/node.h | 40 - .../Python/Python-2.7.2/Include/object.h | 986 - .../Python/Python-2.7.2/Include/objimpl.h | 354 - .../Python/Python-2.7.2/Include/opcode.h | 162 - .../Python/Python-2.7.2/Include/osdefs.h | 71 - .../Python/Python-2.7.2/Include/parsetok.h | 64 - .../Python/Python-2.7.2/Include/patchlevel.h | 43 - .../Python/Python-2.7.2/Include/pgen.h | 18 - .../Python/Python-2.7.2/Include/pgenheaders.h | 42 - .../Python/Python-2.7.2/Include/py_curses.h | 176 - .../Python/Python-2.7.2/Include/pyarena.h | 62 - .../Python/Python-2.7.2/Include/pycapsule.h | 56 - .../Python/Python-2.7.2/Include/pyctype.h | 31 - .../Python/Python-2.7.2/Include/pydebug.h | 40 - .../Python/Python-2.7.2/Include/pyerrors.h | 328 - .../Python/Python-2.7.2/Include/pyexpat.h | 48 - .../Python/Python-2.7.2/Include/pyfpe.h | 176 - .../Python/Python-2.7.2/Include/pygetopt.h | 17 - .../Python/Python-2.7.2/Include/pymacconfig.h | 102 - .../Python-2.7.2/Include/pymactoolbox.h | 217 - .../Python/Python-2.7.2/Include/pymath.h | 192 - .../Python/Python-2.7.2/Include/pymem.h | 122 - .../Python/Python-2.7.2/Include/pyport.h | 918 - .../Python/Python-2.7.2/Include/pystate.h | 198 - .../Python/Python-2.7.2/Include/pystrcmp.h | 23 - .../Python/Python-2.7.2/Include/pystrtod.h | 45 - .../Python/Python-2.7.2/Include/pythonrun.h | 178 - .../Python/Python-2.7.2/Include/pythread.h | 41 - .../Python/Python-2.7.2/Include/rangeobject.h | 28 - .../Python/Python-2.7.2/Include/setobject.h | 99 - .../Python/Python-2.7.2/Include/sliceobject.h | 44 - .../Python-2.7.2/Include/stringobject.h | 210 - .../Python-2.7.2/Include/structmember.h | 99 - .../Python/Python-2.7.2/Include/structseq.h | 41 - .../Python/Python-2.7.2/Include/symtable.h | 98 - .../Python/Python-2.7.2/Include/sysmodule.h | 32 - .../Python/Python-2.7.2/Include/timefuncs.h | 23 - .../Python/Python-2.7.2/Include/token.h | 85 - .../Python/Python-2.7.2/Include/traceback.h | 31 - .../Python/Python-2.7.2/Include/tupleobject.h | 61 - .../Python/Python-2.7.2/Include/ucnhash.h | 33 - .../Python-2.7.2/Include/unicodeobject.h | 1413 -- .../Python/Python-2.7.2/Include/warnings.h | 23 - .../Python-2.7.2/Include/weakrefobject.h | 75 - .../Applications/Python/Python-2.7.2/LICENSE | 279 - .../Python/Python-2.7.2/Lib/BaseHTTPServer.py | 606 - .../Python/Python-2.7.2/Lib/Bastion.py | 180 - .../Python/Python-2.7.2/Lib/CGIHTTPServer.py | 374 - .../Python/Python-2.7.2/Lib/ConfigParser.py | 745 - .../Python/Python-2.7.2/Lib/Cookie.py | 761 - .../Python-2.7.2/Lib/DocXMLRPCServer.py | 279 - .../Python/Python-2.7.2/Lib/HTMLParser.py | 393 - .../Python/Python-2.7.2/Lib/MimeWriter.py | 186 - .../Python/Python-2.7.2/Lib/Queue.py | 244 - .../Python-2.7.2/Lib/SimpleHTTPServer.py | 220 - .../Python-2.7.2/Lib/SimpleXMLRPCServer.py | 704 - .../Python/Python-2.7.2/Lib/SocketServer.py | 716 - .../Python/Python-2.7.2/Lib/StringIO.py | 324 - .../Python/Python-2.7.2/Lib/UserDict.py | 180 - .../Python/Python-2.7.2/Lib/UserList.py | 88 - .../Python/Python-2.7.2/Lib/UserString.py | 228 - .../Python/Python-2.7.2/Lib/_LWPCookieJar.py | 170 - .../Python-2.7.2/Lib/_MozillaCookieJar.py | 149 - .../Python/Python-2.7.2/Lib/__future__.py | 128 - .../Python/Python-2.7.2/Lib/__phello__.foo.py | 1 - .../Python/Python-2.7.2/Lib/_abcoll.py | 601 - .../Python/Python-2.7.2/Lib/_pyio.py | 2006 -- .../Python/Python-2.7.2/Lib/_strptime.py | 454 - .../Python/Python-2.7.2/Lib/_weakrefset.py | 216 - .../Python/Python-2.7.2/Lib/abc.py | 185 - .../Python/Python-2.7.2/Lib/aifc.py | 957 - .../Python/Python-2.7.2/Lib/antigravity.py | 4 - .../Python/Python-2.7.2/Lib/anydbm.py | 85 - .../Python/Python-2.7.2/Lib/argparse.py | 2347 --- .../Python/Python-2.7.2/Lib/ast.py | 311 - .../Python/Python-2.7.2/Lib/asynchat.py | 314 - .../Python/Python-2.7.2/Lib/asyncore.py | 655 - .../Python/Python-2.7.2/Lib/atexit.py | 65 - .../Python/Python-2.7.2/Lib/base64.py | 360 - .../Python/Python-2.7.2/Lib/bdb.py | 632 - .../Python/Python-2.7.2/Lib/binhex.py | 508 - .../Python/Python-2.7.2/Lib/bisect.py | 92 - .../Python/Python-2.7.2/Lib/cProfile.py | 199 - .../Python/Python-2.7.2/Lib/calendar.py | 708 - .../Python/Python-2.7.2/Lib/cgi.py | 1051 - .../Python/Python-2.7.2/Lib/cgitb.py | 318 - .../Python/Python-2.7.2/Lib/chunk.py | 167 - .../Python/Python-2.7.2/Lib/cmd.py | 401 - .../Python/Python-2.7.2/Lib/code.py | 310 - .../Python/Python-2.7.2/Lib/codecs.py | 1098 - .../Python/Python-2.7.2/Lib/codeop.py | 168 - .../Python/Python-2.7.2/Lib/collections.py | 667 - .../Python/Python-2.7.2/Lib/colorsys.py | 156 - .../Python/Python-2.7.2/Lib/commands.py | 90 - .../Python/Python-2.7.2/Lib/compileall.py | 214 - .../Python-2.7.2/Lib/compiler/__init__.py | 31 - .../Python/Python-2.7.2/Lib/compiler/ast.py | 1419 -- .../Python-2.7.2/Lib/compiler/consts.py | 23 - .../Python-2.7.2/Lib/compiler/future.py | 74 - .../Python/Python-2.7.2/Lib/compiler/misc.py | 73 - .../Python-2.7.2/Lib/compiler/pyassem.py | 763 - .../Python-2.7.2/Lib/compiler/pycodegen.py | 1555 -- .../Python-2.7.2/Lib/compiler/symbols.py | 462 - .../Python-2.7.2/Lib/compiler/syntax.py | 46 - .../Python-2.7.2/Lib/compiler/transformer.py | 1535 -- .../Python-2.7.2/Lib/compiler/visitor.py | 113 - .../Python/Python-2.7.2/Lib/contextlib.py | 154 - .../Python/Python-2.7.2/Lib/cookielib.py | 1794 -- .../Python/Python-2.7.2/Lib/copy.py | 433 - .../Python/Python-2.7.2/Lib/copy_reg.py | 201 - .../Python/Python-2.7.2/Lib/csv.py | 451 - .../Python/Python-2.7.2/Lib/dbhash.py | 18 - .../Python/Python-2.7.2/Lib/decimal.py | 6149 ------ .../Python/Python-2.7.2/Lib/difflib.py | 2059 -- .../Python/Python-2.7.2/Lib/dircache.py | 41 - .../Python/Python-2.7.2/Lib/dis.py | 224 - .../Python/Python-2.7.2/Lib/distutils/README | 13 - .../Python-2.7.2/Lib/distutils/__init__.py | 19 - .../Lib/distutils/archive_util.py | 243 - .../Lib/distutils/bcppcompiler.py | 394 - .../Python-2.7.2/Lib/distutils/ccompiler.py | 1145 - .../Python/Python-2.7.2/Lib/distutils/cmd.py | 457 - .../Lib/distutils/command/__init__.py | 33 - .../Lib/distutils/command/bdist.py | 146 - .../Lib/distutils/command/bdist_dumb.py | 132 - .../Lib/distutils/command/bdist_msi.py | 738 - .../Lib/distutils/command/bdist_rpm.py | 575 - .../Lib/distutils/command/bdist_wininst.py | 364 - .../Lib/distutils/command/build.py | 147 - .../Lib/distutils/command/build_clib.py | 209 - .../Lib/distutils/command/build_ext.py | 769 - .../Lib/distutils/command/build_py.py | 393 - .../Lib/distutils/command/build_scripts.py | 131 - .../Lib/distutils/command/check.py | 143 - .../Lib/distutils/command/clean.py | 80 - .../Lib/distutils/command/command_template | 45 - .../Lib/distutils/command/config.py | 357 - .../Lib/distutils/command/install.py | 672 - .../Lib/distutils/command/install_data.py | 81 - .../Lib/distutils/command/install_egg_info.py | 78 - .../Lib/distutils/command/install_headers.py | 51 - .../Lib/distutils/command/install_lib.py | 219 - .../Lib/distutils/command/install_scripts.py | 64 - .../Lib/distutils/command/register.py | 307 - .../Lib/distutils/command/sdist.py | 464 - .../Lib/distutils/command/upload.py | 194 - .../Lib/distutils/command/wininst-6.0.exe | Bin 61440 -> 0 bytes .../Lib/distutils/command/wininst-7.1.exe | Bin 65536 -> 0 bytes .../Lib/distutils/command/wininst-8.0.exe | Bin 61440 -> 0 bytes .../distutils/command/wininst-9.0-amd64.exe | Bin 223744 -> 0 bytes .../Lib/distutils/command/wininst-9.0.exe | Bin 196096 -> 0 bytes .../Python-2.7.2/Lib/distutils/config.py | 121 - .../Python/Python-2.7.2/Lib/distutils/core.py | 242 - .../Lib/distutils/cygwinccompiler.py | 449 - .../Python-2.7.2/Lib/distutils/debug.py | 7 - .../Python-2.7.2/Lib/distutils/dep_util.py | 88 - .../Python-2.7.2/Lib/distutils/dir_util.py | 212 - .../Python/Python-2.7.2/Lib/distutils/dist.py | 1248 -- .../Lib/distutils/emxccompiler.py | 319 - .../Python-2.7.2/Lib/distutils/errors.py | 88 - .../Python-2.7.2/Lib/distutils/extension.py | 255 - .../Lib/distutils/fancy_getopt.py | 484 - .../Python-2.7.2/Lib/distutils/file_util.py | 231 - .../Python-2.7.2/Lib/distutils/filelist.py | 336 - .../Python/Python-2.7.2/Lib/distutils/log.py | 71 - .../Lib/distutils/msvc9compiler.py | 764 - .../Lib/distutils/msvccompiler.py | 659 - .../Python-2.7.2/Lib/distutils/spawn.py | 173 - .../Python-2.7.2/Lib/distutils/sysconfig.py | 571 - .../Lib/distutils/tests/Setup.sample | 67 - .../Lib/distutils/tests/__init__.py | 36 - .../distutils/tests/setuptools_build_ext.py | 287 - .../distutils/tests/setuptools_extension.py | 51 - .../Lib/distutils/tests/support.py | 133 - .../Lib/distutils/tests/test_archive_util.py | 284 - .../Lib/distutils/tests/test_bdist.py | 45 - .../Lib/distutils/tests/test_bdist_dumb.py | 105 - .../Lib/distutils/tests/test_bdist_msi.py | 25 - .../Lib/distutils/tests/test_bdist_rpm.py | 127 - .../Lib/distutils/tests/test_bdist_wininst.py | 32 - .../Lib/distutils/tests/test_build.py | 55 - .../Lib/distutils/tests/test_build_clib.py | 145 - .../Lib/distutils/tests/test_build_ext.py | 491 - .../Lib/distutils/tests/test_build_py.py | 122 - .../Lib/distutils/tests/test_build_scripts.py | 112 - .../Lib/distutils/tests/test_ccompiler.py | 81 - .../Lib/distutils/tests/test_check.py | 99 - .../Lib/distutils/tests/test_clean.py | 51 - .../Lib/distutils/tests/test_cmd.py | 127 - .../Lib/distutils/tests/test_config.py | 123 - .../Lib/distutils/tests/test_config_cmd.py | 90 - .../Lib/distutils/tests/test_core.py | 108 - .../Lib/distutils/tests/test_dep_util.py | 81 - .../Lib/distutils/tests/test_dir_util.py | 116 - .../Lib/distutils/tests/test_dist.py | 436 - .../Lib/distutils/tests/test_file_util.py | 81 - .../Lib/distutils/tests/test_filelist.py | 85 - .../Lib/distutils/tests/test_install.py | 57 - .../Lib/distutils/tests/test_install_data.py | 77 - .../distutils/tests/test_install_headers.py | 41 - .../Lib/distutils/tests/test_install_lib.py | 107 - .../distutils/tests/test_install_scripts.py | 82 - .../Lib/distutils/tests/test_msvc9compiler.py | 141 - .../Lib/distutils/tests/test_register.py | 261 - .../Lib/distutils/tests/test_sdist.py | 429 - .../Lib/distutils/tests/test_spawn.py | 60 - .../Lib/distutils/tests/test_sysconfig.py | 82 - .../Lib/distutils/tests/test_text_file.py | 107 - .../Lib/distutils/tests/test_unixccompiler.py | 130 - .../Lib/distutils/tests/test_upload.py | 131 - .../Lib/distutils/tests/test_util.py | 25 - .../Lib/distutils/tests/test_version.py | 71 - .../distutils/tests/test_versionpredicate.py | 13 - .../Python-2.7.2/Lib/distutils/text_file.py | 304 - .../Lib/distutils/unixccompiler.py | 346 - .../Python/Python-2.7.2/Lib/distutils/util.py | 567 - .../Python-2.7.2/Lib/distutils/version.py | 299 - .../Lib/distutils/versionpredicate.py | 164 - .../Python/Python-2.7.2/Lib/doctest.py | 2731 --- .../Python/Python-2.7.2/Lib/dumbdbm.py | 250 - .../Python/Python-2.7.2/Lib/dummy_thread.py | 145 - .../Python-2.7.2/Lib/dummy_threading.py | 78 - .../Python/Python-2.7.2/Lib/email/__init__.py | 123 - .../Python-2.7.2/Lib/email/_parseaddr.py | 497 - .../Python-2.7.2/Lib/email/base64mime.py | 183 - .../Python/Python-2.7.2/Lib/email/charset.py | 397 - .../Python/Python-2.7.2/Lib/email/encoders.py | 82 - .../Python/Python-2.7.2/Lib/email/errors.py | 57 - .../Python-2.7.2/Lib/email/feedparser.py | 484 - .../Python-2.7.2/Lib/email/generator.py | 364 - .../Python/Python-2.7.2/Lib/email/header.py | 514 - .../Python-2.7.2/Lib/email/iterators.py | 73 - .../Python/Python-2.7.2/Lib/email/message.py | 797 - .../Python-2.7.2/Lib/email/mime/__init__.py | 0 .../Lib/email/mime/application.py | 36 - .../Python-2.7.2/Lib/email/mime/audio.py | 73 - .../Python-2.7.2/Lib/email/mime/base.py | 26 - .../Python-2.7.2/Lib/email/mime/image.py | 46 - .../Python-2.7.2/Lib/email/mime/message.py | 34 - .../Python-2.7.2/Lib/email/mime/multipart.py | 47 - .../Lib/email/mime/nonmultipart.py | 22 - .../Python-2.7.2/Lib/email/mime/text.py | 30 - .../Python/Python-2.7.2/Lib/email/parser.py | 91 - .../Python-2.7.2/Lib/email/quoprimime.py | 336 - .../Python-2.7.2/Lib/email/test/__init__.py | 0 .../Lib/email/test/data/PyBanner048.gif | Bin 954 -> 0 bytes .../Lib/email/test/data/audiotest.au | Bin 28144 -> 0 bytes .../Lib/email/test/data/msg_01.txt | 19 - .../Lib/email/test/data/msg_02.txt | 135 - .../Lib/email/test/data/msg_03.txt | 16 - .../Lib/email/test/data/msg_04.txt | 37 - .../Lib/email/test/data/msg_05.txt | 28 - .../Lib/email/test/data/msg_06.txt | 33 - .../Lib/email/test/data/msg_07.txt | 83 - .../Lib/email/test/data/msg_08.txt | 24 - .../Lib/email/test/data/msg_09.txt | 24 - .../Lib/email/test/data/msg_10.txt | 39 - .../Lib/email/test/data/msg_11.txt | 7 - .../Lib/email/test/data/msg_12.txt | 36 - .../Lib/email/test/data/msg_12a.txt | 38 - .../Lib/email/test/data/msg_13.txt | 94 - .../Lib/email/test/data/msg_14.txt | 23 - .../Lib/email/test/data/msg_15.txt | 52 - .../Lib/email/test/data/msg_16.txt | 123 - .../Lib/email/test/data/msg_17.txt | 12 - .../Lib/email/test/data/msg_18.txt | 6 - .../Lib/email/test/data/msg_19.txt | 43 - .../Lib/email/test/data/msg_20.txt | 22 - .../Lib/email/test/data/msg_21.txt | 20 - .../Lib/email/test/data/msg_22.txt | 46 - .../Lib/email/test/data/msg_23.txt | 8 - .../Lib/email/test/data/msg_24.txt | 10 - .../Lib/email/test/data/msg_25.txt | 117 - .../Lib/email/test/data/msg_26.txt | 45 - .../Lib/email/test/data/msg_27.txt | 15 - .../Lib/email/test/data/msg_28.txt | 25 - .../Lib/email/test/data/msg_29.txt | 22 - .../Lib/email/test/data/msg_30.txt | 23 - .../Lib/email/test/data/msg_31.txt | 15 - .../Lib/email/test/data/msg_32.txt | 14 - .../Lib/email/test/data/msg_33.txt | 29 - .../Lib/email/test/data/msg_34.txt | 19 - .../Lib/email/test/data/msg_35.txt | 4 - .../Lib/email/test/data/msg_36.txt | 40 - .../Lib/email/test/data/msg_37.txt | 22 - .../Lib/email/test/data/msg_38.txt | 101 - .../Lib/email/test/data/msg_39.txt | 83 - .../Lib/email/test/data/msg_40.txt | 10 - .../Lib/email/test/data/msg_41.txt | 8 - .../Lib/email/test/data/msg_42.txt | 20 - .../Lib/email/test/data/msg_43.txt | 217 - .../Lib/email/test/data/msg_44.txt | 33 - .../Lib/email/test/data/msg_45.txt | 33 - .../Lib/email/test/data/msg_46.txt | 23 - .../Python-2.7.2/Lib/email/test/test_email.py | 3529 ---- .../Lib/email/test/test_email_codecs.py | 77 - .../email/test/test_email_codecs_renamed.py | 77 - .../Lib/email/test/test_email_renamed.py | 3297 --- .../Lib/email/test/test_email_torture.py | 136 - .../Python/Python-2.7.2/Lib/email/utils.py | 324 - .../Python-2.7.2/Lib/encodings/__init__.py | 157 - .../Python-2.7.2/Lib/encodings/aliases.py | 527 - .../Python-2.7.2/Lib/encodings/ascii.py | 50 - .../Lib/encodings/base64_codec.py | 79 - .../Python/Python-2.7.2/Lib/encodings/big5.py | 39 - .../Python-2.7.2/Lib/encodings/big5hkscs.py | 39 - .../Python-2.7.2/Lib/encodings/bz2_codec.py | 102 - .../Python-2.7.2/Lib/encodings/charmap.py | 69 - .../Python-2.7.2/Lib/encodings/cp037.py | 307 - .../Python-2.7.2/Lib/encodings/cp1006.py | 307 - .../Python-2.7.2/Lib/encodings/cp1026.py | 307 - .../Python-2.7.2/Lib/encodings/cp1140.py | 307 - .../Python-2.7.2/Lib/encodings/cp1250.py | 307 - .../Python-2.7.2/Lib/encodings/cp1251.py | 307 - .../Python-2.7.2/Lib/encodings/cp1252.py | 307 - .../Python-2.7.2/Lib/encodings/cp1253.py | 307 - .../Python-2.7.2/Lib/encodings/cp1254.py | 307 - .../Python-2.7.2/Lib/encodings/cp1255.py | 307 - .../Python-2.7.2/Lib/encodings/cp1256.py | 307 - .../Python-2.7.2/Lib/encodings/cp1257.py | 307 - .../Python-2.7.2/Lib/encodings/cp1258.py | 307 - .../Python-2.7.2/Lib/encodings/cp424.py | 307 - .../Python-2.7.2/Lib/encodings/cp437.py | 698 - .../Python-2.7.2/Lib/encodings/cp500.py | 307 - .../Python-2.7.2/Lib/encodings/cp720.py | 309 - .../Python-2.7.2/Lib/encodings/cp737.py | 698 - .../Python-2.7.2/Lib/encodings/cp775.py | 697 - .../Python-2.7.2/Lib/encodings/cp850.py | 698 - .../Python-2.7.2/Lib/encodings/cp852.py | 698 - .../Python-2.7.2/Lib/encodings/cp855.py | 698 - .../Python-2.7.2/Lib/encodings/cp856.py | 307 - .../Python-2.7.2/Lib/encodings/cp857.py | 694 - .../Python-2.7.2/Lib/encodings/cp858.py | 698 - .../Python-2.7.2/Lib/encodings/cp860.py | 698 - .../Python-2.7.2/Lib/encodings/cp861.py | 698 - .../Python-2.7.2/Lib/encodings/cp862.py | 698 - .../Python-2.7.2/Lib/encodings/cp863.py | 698 - .../Python-2.7.2/Lib/encodings/cp864.py | 690 - .../Python-2.7.2/Lib/encodings/cp865.py | 698 - .../Python-2.7.2/Lib/encodings/cp866.py | 698 - .../Python-2.7.2/Lib/encodings/cp869.py | 689 - .../Python-2.7.2/Lib/encodings/cp874.py | 307 - .../Python-2.7.2/Lib/encodings/cp875.py | 307 - .../Python-2.7.2/Lib/encodings/cp932.py | 39 - .../Python-2.7.2/Lib/encodings/cp949.py | 39 - .../Python-2.7.2/Lib/encodings/cp950.py | 39 - .../Lib/encodings/euc_jis_2004.py | 39 - .../Lib/encodings/euc_jisx0213.py | 39 - .../Python-2.7.2/Lib/encodings/euc_jp.py | 39 - .../Python-2.7.2/Lib/encodings/euc_kr.py | 39 - .../Python-2.7.2/Lib/encodings/gb18030.py | 39 - .../Python-2.7.2/Lib/encodings/gb2312.py | 39 - .../Python/Python-2.7.2/Lib/encodings/gbk.py | 39 - .../Python-2.7.2/Lib/encodings/hex_codec.py | 79 - .../Python-2.7.2/Lib/encodings/hp_roman8.py | 152 - .../Python/Python-2.7.2/Lib/encodings/hz.py | 39 - .../Python/Python-2.7.2/Lib/encodings/idna.py | 288 - .../Python-2.7.2/Lib/encodings/iso2022_jp.py | 39 - .../Lib/encodings/iso2022_jp_1.py | 39 - .../Lib/encodings/iso2022_jp_2.py | 39 - .../Lib/encodings/iso2022_jp_2004.py | 39 - .../Lib/encodings/iso2022_jp_3.py | 39 - .../Lib/encodings/iso2022_jp_ext.py | 39 - .../Python-2.7.2/Lib/encodings/iso2022_kr.py | 39 - .../Python-2.7.2/Lib/encodings/iso8859_1.py | 307 - .../Python-2.7.2/Lib/encodings/iso8859_10.py | 307 - .../Python-2.7.2/Lib/encodings/iso8859_11.py | 307 - .../Python-2.7.2/Lib/encodings/iso8859_13.py | 307 - .../Python-2.7.2/Lib/encodings/iso8859_14.py | 307 - .../Python-2.7.2/Lib/encodings/iso8859_15.py | 307 - .../Python-2.7.2/Lib/encodings/iso8859_16.py | 307 - .../Python-2.7.2/Lib/encodings/iso8859_2.py | 307 - .../Python-2.7.2/Lib/encodings/iso8859_3.py | 307 - .../Python-2.7.2/Lib/encodings/iso8859_4.py | 307 - .../Python-2.7.2/Lib/encodings/iso8859_5.py | 307 - .../Python-2.7.2/Lib/encodings/iso8859_6.py | 307 - .../Python-2.7.2/Lib/encodings/iso8859_7.py | 307 - .../Python-2.7.2/Lib/encodings/iso8859_8.py | 307 - .../Python-2.7.2/Lib/encodings/iso8859_9.py | 307 - .../Python-2.7.2/Lib/encodings/johab.py | 39 - .../Python-2.7.2/Lib/encodings/koi8_r.py | 307 - .../Python-2.7.2/Lib/encodings/koi8_u.py | 307 - .../Python-2.7.2/Lib/encodings/latin_1.py | 50 - .../Python-2.7.2/Lib/encodings/mac_arabic.py | 698 - .../Lib/encodings/mac_centeuro.py | 307 - .../Lib/encodings/mac_croatian.py | 307 - .../Lib/encodings/mac_cyrillic.py | 307 - .../Python-2.7.2/Lib/encodings/mac_farsi.py | 307 - .../Python-2.7.2/Lib/encodings/mac_greek.py | 307 - .../Python-2.7.2/Lib/encodings/mac_iceland.py | 307 - .../Python-2.7.2/Lib/encodings/mac_latin2.py | 183 - .../Python-2.7.2/Lib/encodings/mac_roman.py | 307 - .../Lib/encodings/mac_romanian.py | 307 - .../Python-2.7.2/Lib/encodings/mac_turkish.py | 307 - .../Python/Python-2.7.2/Lib/encodings/mbcs.py | 47 - .../Python-2.7.2/Lib/encodings/palmos.py | 83 - .../Python-2.7.2/Lib/encodings/ptcp154.py | 175 - .../Python-2.7.2/Lib/encodings/punycode.py | 238 - .../Lib/encodings/quopri_codec.py | 75 - .../Lib/encodings/raw_unicode_escape.py | 45 - .../Python-2.7.2/Lib/encodings/rot_13.py | 118 - .../Python-2.7.2/Lib/encodings/shift_jis.py | 39 - .../Lib/encodings/shift_jis_2004.py | 39 - .../Lib/encodings/shift_jisx0213.py | 39 - .../Lib/encodings/string_escape.py | 38 - .../Python-2.7.2/Lib/encodings/tis_620.py | 307 - .../Python-2.7.2/Lib/encodings/undefined.py | 49 - .../Lib/encodings/unicode_escape.py | 45 - .../Lib/encodings/unicode_internal.py | 45 - .../Python-2.7.2/Lib/encodings/utf_16.py | 126 - .../Python-2.7.2/Lib/encodings/utf_16_be.py | 42 - .../Python-2.7.2/Lib/encodings/utf_16_le.py | 42 - .../Python-2.7.2/Lib/encodings/utf_32.py | 150 - .../Python-2.7.2/Lib/encodings/utf_32_be.py | 37 - .../Python-2.7.2/Lib/encodings/utf_32_le.py | 37 - .../Python-2.7.2/Lib/encodings/utf_7.py | 38 - .../Python-2.7.2/Lib/encodings/utf_8.py | 42 - .../Python-2.7.2/Lib/encodings/utf_8_sig.py | 117 - .../Python-2.7.2/Lib/encodings/uu_codec.py | 129 - .../Python-2.7.2/Lib/encodings/zlib_codec.py | 102 - .../Python/Python-2.7.2/Lib/filecmp.py | 295 - .../Python/Python-2.7.2/Lib/fileinput.py | 413 - .../Python/Python-2.7.2/Lib/fnmatch.py | 116 - .../Python/Python-2.7.2/Lib/formatter.py | 445 - .../Python/Python-2.7.2/Lib/fpformat.py | 145 - .../Python/Python-2.7.2/Lib/fractions.py | 605 - .../Python/Python-2.7.2/Lib/ftplib.py | 1036 - .../Python/Python-2.7.2/Lib/functools.py | 100 - .../Python/Python-2.7.2/Lib/genericpath.py | 105 - .../Python/Python-2.7.2/Lib/getopt.py | 210 - .../Python/Python-2.7.2/Lib/getpass.py | 179 - .../Python/Python-2.7.2/Lib/gettext.py | 591 - .../Python/Python-2.7.2/Lib/glob.py | 78 - .../Python/Python-2.7.2/Lib/gzip.py | 509 - .../Python/Python-2.7.2/Lib/hashlib.py | 146 - .../Python/Python-2.7.2/Lib/heapq.py | 442 - .../Python/Python-2.7.2/Lib/hmac.py | 133 - .../Python-2.7.2/Lib/hotshot/__init__.py | 78 - .../Python/Python-2.7.2/Lib/hotshot/log.py | 194 - .../Python/Python-2.7.2/Lib/hotshot/stats.py | 93 - .../Python/Python-2.7.2/Lib/hotshot/stones.py | 30 - .../Python/Python-2.7.2/Lib/htmlentitydefs.py | 273 - .../Python/Python-2.7.2/Lib/htmllib.py | 491 - .../Python/Python-2.7.2/Lib/httplib.py | 1392 -- .../Python/Python-2.7.2/Lib/ihooks.py | 554 - .../Python/Python-2.7.2/Lib/imaplib.py | 1518 -- .../Python/Python-2.7.2/Lib/imghdr.py | 161 - .../Python-2.7.2/Lib/importlib/__init__.py | 38 - .../Python/Python-2.7.2/Lib/imputil.py | 725 - .../Python/Python-2.7.2/Lib/inspect.py | 1056 - .../Python/Python-2.7.2/Lib/io.py | 98 - .../Python/Python-2.7.2/Lib/json/__init__.py | 339 - .../Python/Python-2.7.2/Lib/json/decoder.py | 385 - .../Python/Python-2.7.2/Lib/json/encoder.py | 442 - .../Python/Python-2.7.2/Lib/json/scanner.py | 67 - .../Python-2.7.2/Lib/json/tests/__init__.py | 73 - .../Lib/json/tests/test_check_circular.py | 34 - .../Lib/json/tests/test_decode.py | 50 - .../Lib/json/tests/test_default.py | 12 - .../Python-2.7.2/Lib/json/tests/test_dump.py | 23 - .../tests/test_encode_basestring_ascii.py | 41 - .../Python-2.7.2/Lib/json/tests/test_fail.py | 87 - .../Python-2.7.2/Lib/json/tests/test_float.py | 22 - .../Lib/json/tests/test_indent.py | 60 - .../Python-2.7.2/Lib/json/tests/test_pass1.py | 79 - .../Python-2.7.2/Lib/json/tests/test_pass2.py | 18 - .../Python-2.7.2/Lib/json/tests/test_pass3.py | 24 - .../Lib/json/tests/test_recursion.py | 108 - .../Lib/json/tests/test_scanstring.py | 109 - .../Lib/json/tests/test_separators.py | 44 - .../Lib/json/tests/test_speedups.py | 23 - .../Lib/json/tests/test_unicode.py | 85 - .../Python/Python-2.7.2/Lib/json/tool.py | 37 - .../Python/Python-2.7.2/Lib/keyword.py | 93 - .../Python-2.7.2/Lib/lib2to3/Grammar.txt | 158 - .../Lib/lib2to3/PatternGrammar.txt | 28 - .../Python-2.7.2/Lib/lib2to3/__init__.py | 1 - .../Python-2.7.2/Lib/lib2to3/__main__.py | 4 - .../Python-2.7.2/Lib/lib2to3/btm_matcher.py | 168 - .../Python-2.7.2/Lib/lib2to3/btm_utils.py | 283 - .../Python-2.7.2/Lib/lib2to3/fixer_base.py | 189 - .../Python-2.7.2/Lib/lib2to3/fixer_util.py | 432 - .../Lib/lib2to3/fixes/__init__.py | 1 - .../Lib/lib2to3/fixes/fix_apply.py | 59 - .../Lib/lib2to3/fixes/fix_basestring.py | 14 - .../Lib/lib2to3/fixes/fix_buffer.py | 22 - .../Lib/lib2to3/fixes/fix_callable.py | 37 - .../Lib/lib2to3/fixes/fix_dict.py | 107 - .../Lib/lib2to3/fixes/fix_except.py | 93 - .../Lib/lib2to3/fixes/fix_exec.py | 40 - .../Lib/lib2to3/fixes/fix_execfile.py | 52 - .../Lib/lib2to3/fixes/fix_exitfunc.py | 72 - .../Lib/lib2to3/fixes/fix_filter.py | 76 - .../Lib/lib2to3/fixes/fix_funcattrs.py | 21 - .../Lib/lib2to3/fixes/fix_future.py | 22 - .../Lib/lib2to3/fixes/fix_getcwdu.py | 19 - .../Lib/lib2to3/fixes/fix_has_key.py | 110 - .../Lib/lib2to3/fixes/fix_idioms.py | 152 - .../Lib/lib2to3/fixes/fix_import.py | 99 - .../Lib/lib2to3/fixes/fix_imports.py | 145 - .../Lib/lib2to3/fixes/fix_imports2.py | 16 - .../Lib/lib2to3/fixes/fix_input.py | 26 - .../Lib/lib2to3/fixes/fix_intern.py | 46 - .../Lib/lib2to3/fixes/fix_isinstance.py | 52 - .../Lib/lib2to3/fixes/fix_itertools.py | 43 - .../lib2to3/fixes/fix_itertools_imports.py | 57 - .../Lib/lib2to3/fixes/fix_long.py | 19 - .../Python-2.7.2/Lib/lib2to3/fixes/fix_map.py | 91 - .../Lib/lib2to3/fixes/fix_metaclass.py | 228 - .../Lib/lib2to3/fixes/fix_methodattrs.py | 24 - .../Python-2.7.2/Lib/lib2to3/fixes/fix_ne.py | 23 - .../Lib/lib2to3/fixes/fix_next.py | 103 - .../Lib/lib2to3/fixes/fix_nonzero.py | 21 - .../Lib/lib2to3/fixes/fix_numliterals.py | 28 - .../Lib/lib2to3/fixes/fix_operator.py | 96 - .../Lib/lib2to3/fixes/fix_paren.py | 44 - .../Lib/lib2to3/fixes/fix_print.py | 87 - .../Lib/lib2to3/fixes/fix_raise.py | 90 - .../Lib/lib2to3/fixes/fix_raw_input.py | 17 - .../Lib/lib2to3/fixes/fix_reduce.py | 35 - .../Lib/lib2to3/fixes/fix_renames.py | 70 - .../Lib/lib2to3/fixes/fix_repr.py | 23 - .../Lib/lib2to3/fixes/fix_set_literal.py | 53 - .../Lib/lib2to3/fixes/fix_standarderror.py | 18 - .../Lib/lib2to3/fixes/fix_sys_exc.py | 30 - .../Lib/lib2to3/fixes/fix_throw.py | 56 - .../Lib/lib2to3/fixes/fix_tuple_params.py | 175 - .../Lib/lib2to3/fixes/fix_types.py | 62 - .../Lib/lib2to3/fixes/fix_unicode.py | 25 - .../Lib/lib2to3/fixes/fix_urllib.py | 197 - .../Lib/lib2to3/fixes/fix_ws_comma.py | 39 - .../Lib/lib2to3/fixes/fix_xrange.py | 73 - .../Lib/lib2to3/fixes/fix_xreadlines.py | 25 - .../Python-2.7.2/Lib/lib2to3/fixes/fix_zip.py | 35 - .../Python/Python-2.7.2/Lib/lib2to3/main.py | 182 - .../Python-2.7.2/Lib/lib2to3/patcomp.py | 205 - .../Lib/lib2to3/pgen2/__init__.py | 4 - .../Python-2.7.2/Lib/lib2to3/pgen2/conv.py | 257 - .../Python-2.7.2/Lib/lib2to3/pgen2/driver.py | 140 - .../Python-2.7.2/Lib/lib2to3/pgen2/grammar.py | 184 - .../Lib/lib2to3/pgen2/literals.py | 60 - .../Python-2.7.2/Lib/lib2to3/pgen2/parse.py | 201 - .../Python-2.7.2/Lib/lib2to3/pgen2/pgen.py | 386 - .../Python-2.7.2/Lib/lib2to3/pgen2/token.py | 82 - .../Lib/lib2to3/pgen2/tokenize.py | 500 - .../Python/Python-2.7.2/Lib/lib2to3/pygram.py | 40 - .../Python/Python-2.7.2/Lib/lib2to3/pytree.py | 887 - .../Python-2.7.2/Lib/lib2to3/refactor.py | 741 - .../Lib/lib2to3/tests/__init__.py | 24 - .../Lib/lib2to3/tests/data/README | 6 - .../Lib/lib2to3/tests/data/bom.py | 2 - .../Lib/lib2to3/tests/data/crlf.py | 3 - .../lib2to3/tests/data/different_encoding.py | 6 - .../lib2to3/tests/data/fixers/bad_order.py | 5 - .../tests/data/fixers/myfixes/__init__.py | 0 .../tests/data/fixers/myfixes/fix_explicit.py | 6 - .../tests/data/fixers/myfixes/fix_first.py | 6 - .../tests/data/fixers/myfixes/fix_last.py | 7 - .../tests/data/fixers/myfixes/fix_parrot.py | 13 - .../tests/data/fixers/myfixes/fix_preorder.py | 6 - .../lib2to3/tests/data/fixers/no_fixer_cls.py | 1 - .../tests/data/fixers/parrot_example.py | 2 - .../lib2to3/tests/data/infinite_recursion.py | 2669 --- .../lib2to3/tests/data/py2_test_grammar.py | 974 - .../lib2to3/tests/data/py3_test_grammar.py | 923 - .../Lib/lib2to3/tests/pytree_idempotency.py | 92 - .../Python-2.7.2/Lib/lib2to3/tests/support.py | 54 - .../Lib/lib2to3/tests/test_all_fixers.py | 23 - .../Lib/lib2to3/tests/test_fixers.py | 4529 ---- .../Lib/lib2to3/tests/test_main.py | 41 - .../Lib/lib2to3/tests/test_parser.py | 227 - .../Lib/lib2to3/tests/test_pytree.py | 494 - .../Lib/lib2to3/tests/test_refactor.py | 281 - .../Lib/lib2to3/tests/test_util.py | 594 - .../Python/Python-2.7.2/Lib/linecache.py | 135 - .../Python/Python-2.7.2/Lib/locale.py | 1867 -- .../Python-2.7.2/Lib/logging/__init__.py | 1707 -- .../Python/Python-2.7.2/Lib/logging/config.py | 905 - .../Python-2.7.2/Lib/logging/handlers.py | 1158 -- .../Python/Python-2.7.2/Lib/mailbox.py | 2171 -- .../Python/Python-2.7.2/Lib/mailcap.py | 255 - .../Python/Python-2.7.2/Lib/markupbase.py | 392 - .../Python/Python-2.7.2/Lib/md5.py | 14 - .../Python/Python-2.7.2/Lib/mhlib.py | 1005 - .../Python/Python-2.7.2/Lib/mimetools.py | 250 - .../Python/Python-2.7.2/Lib/mimetypes.py | 591 - .../Python/Python-2.7.2/Lib/mimify.py | 468 - .../Python/Python-2.7.2/Lib/modulefinder.py | 671 - .../Python/Python-2.7.2/Lib/multifile.py | 162 - .../Python/Python-2.7.2/Lib/mutex.py | 55 - .../Python/Python-2.7.2/Lib/netrc.py | 122 - .../Python/Python-2.7.2/Lib/new.py | 17 - .../Python/Python-2.7.2/Lib/nntplib.py | 627 - .../Python/Python-2.7.2/Lib/ntpath.py | 523 - .../Python/Python-2.7.2/Lib/nturl2path.py | 66 - .../Python/Python-2.7.2/Lib/numbers.py | 391 - .../Python/Python-2.7.2/Lib/opcode.py | 192 - .../Python/Python-2.7.2/Lib/optparse.py | 1703 -- .../Python/Python-2.7.2/Lib/os.py | 759 - .../Python/Python-2.7.2/Lib/pdb.doc | 202 - .../Python/Python-2.7.2/Lib/pdb.py | 1338 -- .../Python/Python-2.7.2/Lib/pickle.py | 1391 -- .../Python/Python-2.7.2/Lib/pickletools.py | 2274 -- .../Python/Python-2.7.2/Lib/pipes.py | 280 - .../Python/Python-2.7.2/Lib/pkgutil.py | 583 - .../Python/Python-2.7.2/Lib/platform.py | 1614 -- .../Python/Python-2.7.2/Lib/plistlib.py | 474 - .../Python/Python-2.7.2/Lib/popen2.py | 201 - .../Python/Python-2.7.2/Lib/poplib.py | 417 - .../Python/Python-2.7.2/Lib/posixfile.py | 237 - .../Python/Python-2.7.2/Lib/posixpath.py | 415 - .../Python/Python-2.7.2/Lib/pprint.py | 350 - .../Python/Python-2.7.2/Lib/profile.py | 619 - .../Python/Python-2.7.2/Lib/pstats.py | 713 - .../Python/Python-2.7.2/Lib/pty.py | 174 - .../Python/Python-2.7.2/Lib/py_compile.py | 170 - .../Python/Python-2.7.2/Lib/pyclbr.py | 342 - .../Python/Python-2.7.2/Lib/pydoc.py | 2337 --- .../Python-2.7.2/Lib/pydoc_data/__init__.py | 0 .../Python-2.7.2/Lib/pydoc_data/topics.py | 83 - .../Python/Python-2.7.2/Lib/quopri.py | 237 - .../Python/Python-2.7.2/Lib/random.py | 908 - .../Python/Python-2.7.2/Lib/re.py | 326 - .../Python/Python-2.7.2/Lib/repr.py | 132 - .../Python/Python-2.7.2/Lib/rexec.py | 588 - .../Python/Python-2.7.2/Lib/rfc822.py | 1011 - .../Python/Python-2.7.2/Lib/rlcompleter.py | 170 - .../Python/Python-2.7.2/Lib/robotparser.py | 222 - .../Python/Python-2.7.2/Lib/runpy.py | 278 - .../Python/Python-2.7.2/Lib/sched.py | 134 - .../Python/Python-2.7.2/Lib/sets.py | 557 - .../Python/Python-2.7.2/Lib/sgmllib.py | 553 - .../Python/Python-2.7.2/Lib/sha.py | 15 - .../Python/Python-2.7.2/Lib/shelve.py | 239 - .../Python/Python-2.7.2/Lib/shlex.py | 292 - .../Python/Python-2.7.2/Lib/shutil.py | 552 - .../Python-2.7.2/Lib/site-packages/README | 2 - .../Python/Python-2.7.2/Lib/site.py | 615 - .../Python/Python-2.7.2/Lib/smtpd.py | 555 - .../Python/Python-2.7.2/Lib/smtplib.py | 848 - .../Python/Python-2.7.2/Lib/sndhdr.py | 228 - .../Python/Python-2.7.2/Lib/socket.py | 573 - .../Python/Python-2.7.2/Lib/sre.py | 13 - .../Python/Python-2.7.2/Lib/sre_compile.py | 524 - .../Python/Python-2.7.2/Lib/sre_constants.py | 261 - .../Python/Python-2.7.2/Lib/sre_parse.py | 790 - .../Python/Python-2.7.2/Lib/ssl.py | 464 - .../Python/Python-2.7.2/Lib/stat.py | 94 - .../Python/Python-2.7.2/Lib/statvfs.py | 18 - .../Python/Python-2.7.2/Lib/string.py | 642 - .../Python/Python-2.7.2/Lib/stringold.py | 432 - .../Python/Python-2.7.2/Lib/stringprep.py | 272 - .../Python/Python-2.7.2/Lib/struct.py | 3 - .../Python/Python-2.7.2/Lib/symbol.py | 114 - .../Python/Python-2.7.2/Lib/symtable.py | 242 - .../Python/Python-2.7.2/Lib/sysconfig.py | 687 - .../Python/Python-2.7.2/Lib/tabnanny.py | 329 - .../Python/Python-2.7.2/Lib/tarfile.py | 2594 --- .../Python/Python-2.7.2/Lib/telnetlib.py | 657 - .../Python/Python-2.7.2/Lib/tempfile.py | 606 - .../Python/Python-2.7.2/Lib/test/185test.db | Bin 16384 -> 0 bytes .../Lib/test/Sine-1000Hz-300ms.aif | Bin 61696 -> 0 bytes .../Python/Python-2.7.2/Lib/test/__init__.py | 1 - .../Python/Python-2.7.2/Lib/test/audiotest.au | Bin 28144 -> 0 bytes .../Python/Python-2.7.2/Lib/test/autotest.py | 6 - .../Python-2.7.2/Lib/test/bad_coding.py | 1 - .../Python-2.7.2/Lib/test/bad_coding2.py | 2 - .../Python/Python-2.7.2/Lib/test/badcert.pem | 36 - .../Python/Python-2.7.2/Lib/test/badkey.pem | 40 - .../Lib/test/badsyntax_future3.py | 10 - .../Lib/test/badsyntax_future4.py | 10 - .../Lib/test/badsyntax_future5.py | 12 - .../Lib/test/badsyntax_future6.py | 10 - .../Lib/test/badsyntax_future7.py | 11 - .../Lib/test/badsyntax_future8.py | 10 - .../Lib/test/badsyntax_future9.py | 10 - .../Lib/test/badsyntax_nocaret.py | 2 - .../Python-2.7.2/Lib/test/buffer_tests.py | 206 - .../Python/Python-2.7.2/Lib/test/cfgparser.1 | 2 - .../Python-2.7.2/Lib/test/check_soundcard.vbs | 13 - .../Lib/test/cjkencodings/big5-utf8.txt | 9 - .../Lib/test/cjkencodings/big5.txt | 9 - .../Lib/test/cjkencodings/big5hkscs-utf8.txt | 2 - .../Lib/test/cjkencodings/big5hkscs.txt | 2 - .../Lib/test/cjkencodings/cp949-utf8.txt | 9 - .../Lib/test/cjkencodings/cp949.txt | 9 - .../test/cjkencodings/euc_jisx0213-utf8.txt | 8 - .../Lib/test/cjkencodings/euc_jisx0213.txt | 8 - .../Lib/test/cjkencodings/euc_jp-utf8.txt | 7 - .../Lib/test/cjkencodings/euc_jp.txt | 7 - .../Lib/test/cjkencodings/euc_kr-utf8.txt | 7 - .../Lib/test/cjkencodings/euc_kr.txt | 7 - .../Lib/test/cjkencodings/gb18030-utf8.txt | 15 - .../Lib/test/cjkencodings/gb18030.txt | 15 - .../Lib/test/cjkencodings/gb2312-utf8.txt | 6 - .../Lib/test/cjkencodings/gb2312.txt | 6 - .../Lib/test/cjkencodings/gbk-utf8.txt | 14 - .../Lib/test/cjkencodings/gbk.txt | 14 - .../Lib/test/cjkencodings/hz-utf8.txt | 2 - .../Python-2.7.2/Lib/test/cjkencodings/hz.txt | 2 - .../Lib/test/cjkencodings/johab-utf8.txt | 9 - .../Lib/test/cjkencodings/johab.txt | 9 - .../Lib/test/cjkencodings/shift_jis-utf8.txt | 7 - .../Lib/test/cjkencodings/shift_jis.txt | 7 - .../test/cjkencodings/shift_jisx0213-utf8.txt | 8 - .../Lib/test/cjkencodings/shift_jisx0213.txt | 8 - .../Python-2.7.2/Lib/test/cmath_testcases.txt | 2365 --- .../Python-2.7.2/Lib/test/crashers/README | 16 - .../Lib/test/crashers/bogus_code_obj.py | 19 - .../Lib/test/crashers/borrowed_ref_1.py | 29 - .../Lib/test/crashers/borrowed_ref_2.py | 38 - .../Lib/test/crashers/compiler_recursion.py | 5 - .../Lib/test/crashers/gc_has_finalizer.py | 36 - .../Lib/test/crashers/gc_inspection.py | 32 - .../Lib/test/crashers/infinite_loop_re.py | 16 - .../Lib/test/crashers/loosing_mro_ref.py | 35 - .../test/crashers/mutation_inside_cyclegc.py | 31 - .../Lib/test/crashers/nasty_eq_vs_dict.py | 47 - .../test/crashers/recursion_limit_too_high.py | 16 - .../Lib/test/crashers/recursive_call.py | 15 - .../Python-2.7.2/Lib/test/curses_tests.py | 46 - .../Python/Python-2.7.2/Lib/test/data/README | 2 - .../Lib/test/decimaltestdata/abs.decTest | 161 - .../Lib/test/decimaltestdata/add.decTest | 2716 --- .../Lib/test/decimaltestdata/and.decTest | 338 - .../Lib/test/decimaltestdata/base.decTest | 1411 -- .../Lib/test/decimaltestdata/clamp.decTest | 211 - .../Lib/test/decimaltestdata/class.decTest | 131 - .../Lib/test/decimaltestdata/compare.decTest | 758 - .../test/decimaltestdata/comparetotal.decTest | 798 - .../decimaltestdata/comparetotmag.decTest | 790 - .../Lib/test/decimaltestdata/copy.decTest | 86 - .../Lib/test/decimaltestdata/copyabs.decTest | 86 - .../test/decimaltestdata/copynegate.decTest | 86 - .../Lib/test/decimaltestdata/copysign.decTest | 177 - .../Lib/test/decimaltestdata/ddAbs.decTest | 126 - .../Lib/test/decimaltestdata/ddAdd.decTest | 1328 -- .../Lib/test/decimaltestdata/ddAnd.decTest | 347 - .../Lib/test/decimaltestdata/ddBase.decTest | 1104 - .../test/decimaltestdata/ddCanonical.decTest | 357 - .../Lib/test/decimaltestdata/ddClass.decTest | 76 - .../test/decimaltestdata/ddCompare.decTest | 744 - .../test/decimaltestdata/ddCompareSig.decTest | 647 - .../decimaltestdata/ddCompareTotal.decTest | 706 - .../decimaltestdata/ddCompareTotalMag.decTest | 706 - .../Lib/test/decimaltestdata/ddCopy.decTest | 88 - .../test/decimaltestdata/ddCopyAbs.decTest | 88 - .../test/decimaltestdata/ddCopyNegate.decTest | 88 - .../test/decimaltestdata/ddCopySign.decTest | 175 - .../Lib/test/decimaltestdata/ddDivide.decTest | 863 - .../test/decimaltestdata/ddDivideInt.decTest | 449 - .../Lib/test/decimaltestdata/ddEncode.decTest | 495 - .../Lib/test/decimaltestdata/ddFMA.decTest | 1698 -- .../Lib/test/decimaltestdata/ddInvert.decTest | 202 - .../Lib/test/decimaltestdata/ddLogB.decTest | 159 - .../Lib/test/decimaltestdata/ddMax.decTest | 322 - .../Lib/test/decimaltestdata/ddMaxMag.decTest | 304 - .../Lib/test/decimaltestdata/ddMin.decTest | 309 - .../Lib/test/decimaltestdata/ddMinMag.decTest | 293 - .../Lib/test/decimaltestdata/ddMinus.decTest | 88 - .../test/decimaltestdata/ddMultiply.decTest | 553 - .../test/decimaltestdata/ddNextMinus.decTest | 126 - .../test/decimaltestdata/ddNextPlus.decTest | 124 - .../test/decimaltestdata/ddNextToward.decTest | 374 - .../Lib/test/decimaltestdata/ddOr.decTest | 292 - .../Lib/test/decimaltestdata/ddPlus.decTest | 88 - .../test/decimaltestdata/ddQuantize.decTest | 833 - .../Lib/test/decimaltestdata/ddReduce.decTest | 182 - .../test/decimaltestdata/ddRemainder.decTest | 600 - .../decimaltestdata/ddRemainderNear.decTest | 629 - .../Lib/test/decimaltestdata/ddRotate.decTest | 262 - .../decimaltestdata/ddSameQuantum.decTest | 389 - .../Lib/test/decimaltestdata/ddScaleB.decTest | 243 - .../Lib/test/decimaltestdata/ddShift.decTest | 262 - .../test/decimaltestdata/ddSubtract.decTest | 629 - .../test/decimaltestdata/ddToIntegral.decTest | 257 - .../Lib/test/decimaltestdata/ddXor.decTest | 337 - .../test/decimaltestdata/decDouble.decTest | 65 - .../Lib/test/decimaltestdata/decQuad.decTest | 65 - .../test/decimaltestdata/decSingle.decTest | 25 - .../Lib/test/decimaltestdata/divide.decTest | 854 - .../test/decimaltestdata/divideint.decTest | 486 - .../Lib/test/decimaltestdata/dqAbs.decTest | 126 - .../Lib/test/decimaltestdata/dqAdd.decTest | 1215 -- .../Lib/test/decimaltestdata/dqAnd.decTest | 420 - .../Lib/test/decimaltestdata/dqBase.decTest | 1081 - .../test/decimaltestdata/dqCanonical.decTest | 372 - .../Lib/test/decimaltestdata/dqClass.decTest | 77 - .../test/decimaltestdata/dqCompare.decTest | 753 - .../test/decimaltestdata/dqCompareSig.decTest | 647 - .../decimaltestdata/dqCompareTotal.decTest | 706 - .../decimaltestdata/dqCompareTotalMag.decTest | 706 - .../Lib/test/decimaltestdata/dqCopy.decTest | 88 - .../test/decimaltestdata/dqCopyAbs.decTest | 88 - .../test/decimaltestdata/dqCopyNegate.decTest | 88 - .../test/decimaltestdata/dqCopySign.decTest | 175 - .../Lib/test/decimaltestdata/dqDivide.decTest | 808 - .../test/decimaltestdata/dqDivideInt.decTest | 453 - .../Lib/test/decimaltestdata/dqEncode.decTest | 477 - .../Lib/test/decimaltestdata/dqFMA.decTest | 1786 -- .../Lib/test/decimaltestdata/dqInvert.decTest | 245 - .../Lib/test/decimaltestdata/dqLogB.decTest | 160 - .../Lib/test/decimaltestdata/dqMax.decTest | 322 - .../Lib/test/decimaltestdata/dqMaxMag.decTest | 304 - .../Lib/test/decimaltestdata/dqMin.decTest | 309 - .../Lib/test/decimaltestdata/dqMinMag.decTest | 293 - .../Lib/test/decimaltestdata/dqMinus.decTest | 88 - .../test/decimaltestdata/dqMultiply.decTest | 589 - .../test/decimaltestdata/dqNextMinus.decTest | 126 - .../test/decimaltestdata/dqNextPlus.decTest | 124 - .../test/decimaltestdata/dqNextToward.decTest | 375 - .../Lib/test/decimaltestdata/dqOr.decTest | 401 - .../Lib/test/decimaltestdata/dqPlus.decTest | 88 - .../test/decimaltestdata/dqQuantize.decTest | 836 - .../Lib/test/decimaltestdata/dqReduce.decTest | 183 - .../test/decimaltestdata/dqRemainder.decTest | 597 - .../decimaltestdata/dqRemainderNear.decTest | 631 - .../Lib/test/decimaltestdata/dqRotate.decTest | 298 - .../decimaltestdata/dqSameQuantum.decTest | 389 - .../Lib/test/decimaltestdata/dqScaleB.decTest | 260 - .../Lib/test/decimaltestdata/dqShift.decTest | 298 - .../test/decimaltestdata/dqSubtract.decTest | 635 - .../test/decimaltestdata/dqToIntegral.decTest | 257 - .../Lib/test/decimaltestdata/dqXor.decTest | 410 - .../Lib/test/decimaltestdata/dsBase.decTest | 1062 - .../Lib/test/decimaltestdata/dsEncode.decTest | 372 - .../Lib/test/decimaltestdata/exp.decTest | 674 - .../Lib/test/decimaltestdata/extra.decTest | 2817 --- .../Lib/test/decimaltestdata/fma.decTest | 3426 --- .../Lib/test/decimaltestdata/inexact.decTest | 215 - .../Lib/test/decimaltestdata/invert.decTest | 176 - .../Lib/test/decimaltestdata/ln.decTest | 611 - .../Lib/test/decimaltestdata/log10.decTest | 551 - .../Lib/test/decimaltestdata/logb.decTest | 188 - .../Lib/test/decimaltestdata/max.decTest | 424 - .../Lib/test/decimaltestdata/maxmag.decTest | 404 - .../Lib/test/decimaltestdata/min.decTest | 407 - .../Lib/test/decimaltestdata/minmag.decTest | 390 - .../Lib/test/decimaltestdata/minus.decTest | 182 - .../Lib/test/decimaltestdata/multiply.decTest | 731 - .../test/decimaltestdata/nextminus.decTest | 148 - .../Lib/test/decimaltestdata/nextplus.decTest | 150 - .../test/decimaltestdata/nexttoward.decTest | 426 - .../Lib/test/decimaltestdata/or.decTest | 334 - .../Lib/test/decimaltestdata/plus.decTest | 195 - .../Lib/test/decimaltestdata/power.decTest | 1624 -- .../test/decimaltestdata/powersqrt.decTest | 2970 --- .../Lib/test/decimaltestdata/quantize.decTest | 948 - .../decimaltestdata/randomBound32.decTest | 2443 --- .../Lib/test/decimaltestdata/randoms.decTest | 4030 ---- .../Lib/test/decimaltestdata/reduce.decTest | 234 - .../test/decimaltestdata/remainder.decTest | 640 - .../decimaltestdata/remainderNear.decTest | 572 - .../Lib/test/decimaltestdata/rescale.decTest | 764 - .../Lib/test/decimaltestdata/rotate.decTest | 247 - .../Lib/test/decimaltestdata/rounding.decTest | 1303 -- .../test/decimaltestdata/samequantum.decTest | 389 - .../Lib/test/decimaltestdata/scaleb.decTest | 209 - .../Lib/test/decimaltestdata/shift.decTest | 250 - .../test/decimaltestdata/squareroot.decTest | 3834 ---- .../Lib/test/decimaltestdata/subtract.decTest | 873 - .../Lib/test/decimaltestdata/testall.decTest | 87 - .../test/decimaltestdata/tointegral.decTest | 241 - .../test/decimaltestdata/tointegralx.decTest | 255 - .../Lib/test/decimaltestdata/xor.decTest | 335 - .../Python-2.7.2/Lib/test/doctest_aliases.py | 13 - .../Python-2.7.2/Lib/test/double_const.py | 30 - .../Python/Python-2.7.2/Lib/test/empty.vbs | 1 - .../Lib/test/exception_hierarchy.txt | 50 - .../Python-2.7.2/Lib/test/floating_points.txt | 1028 - .../Python/Python-2.7.2/Lib/test/fork_wait.py | 79 - .../Lib/test/formatfloat_testcases.txt | 380 - .../Python-2.7.2/Lib/test/gdb_sample.py | 12 - .../Python/Python-2.7.2/Lib/test/greyrgb.uue | 1547 -- .../Lib/test/https_svn_python_org_root.pem | 41 - .../Python/Python-2.7.2/Lib/test/ieee754.txt | 185 - .../Python-2.7.2/Lib/test/infinite_reload.py | 8 - .../Python-2.7.2/Lib/test/inspect_fodder.py | 56 - .../Python-2.7.2/Lib/test/inspect_fodder2.py | 99 - .../Python/Python-2.7.2/Lib/test/keycert.pem | 32 - .../Python-2.7.2/Lib/test/leakers/README.txt | 32 - .../Python-2.7.2/Lib/test/leakers/__init__.py | 0 .../Lib/test/leakers/test_ctypes.py | 16 - .../Lib/test/leakers/test_dictself.py | 12 - .../Lib/test/leakers/test_gestalt.py | 14 - .../Lib/test/leakers/test_selftype.py | 13 - .../Python-2.7.2/Lib/test/list_tests.py | 534 - .../Python-2.7.2/Lib/test/lock_tests.py | 546 - .../Python-2.7.2/Lib/test/mapping_tests.py | 682 - .../Python-2.7.2/Lib/test/math_testcases.txt | 447 - .../Python/Python-2.7.2/Lib/test/nullcert.pem | 0 .../Python-2.7.2/Lib/test/outstanding_bugs.py | 22 - .../Python-2.7.2/Lib/test/pickletester.py | 1259 -- .../Python/Python-2.7.2/Lib/test/profilee.py | 115 - .../Python-2.7.2/Lib/test/pyclbr_input.py | 33 - .../Python/Python-2.7.2/Lib/test/pydoc_mod.py | 27 - .../Python-2.7.2/Lib/test/pydocfodder.py | 216 - .../Python/Python-2.7.2/Lib/test/pystone.py | 270 - .../Python-2.7.2/Lib/test/randv2_32.pck | 633 - .../Python-2.7.2/Lib/test/randv2_64.pck | 633 - .../Python/Python-2.7.2/Lib/test/randv3.pck | 633 - .../Python/Python-2.7.2/Lib/test/re_tests.py | 674 - .../Python-2.7.2/Lib/test/regex_tests.py | 287 - .../Python/Python-2.7.2/Lib/test/regrtest.py | 1536 -- .../Python/Python-2.7.2/Lib/test/relimport.py | 1 - .../Python/Python-2.7.2/Lib/test/reperf.py | 23 - .../Python-2.7.2/Lib/test/sample_doctest.py | 76 - .../Python-2.7.2/Lib/test/script_helper.py | 164 - .../Python/Python-2.7.2/Lib/test/seq_tests.py | 392 - .../Python-2.7.2/Lib/test/sgml_input.html | 212 - .../Python/Python-2.7.2/Lib/test/sha256.pem | 129 - .../Python/Python-2.7.2/Lib/test/sortperf.py | 169 - .../Python/Python-2.7.2/Lib/test/ssl_cert.pem | 14 - .../Python/Python-2.7.2/Lib/test/ssl_key.pem | 9 - .../Python-2.7.2/Lib/test/string_tests.py | 1333 -- .../test/subprocessdata/sigchild_ignore.py | 6 - .../Lib/test/svn_python_org_https_cert.pem | 31 - .../Python-2.7.2/Lib/test/test_MimeWriter.py | 292 - .../Lib/test/test_SimpleHTTPServer.py | 41 - .../Python-2.7.2/Lib/test/test_StringIO.py | 150 - .../Python-2.7.2/Lib/test/test___all__.py | 123 - .../Python-2.7.2/Lib/test/test___future__.py | 66 - .../Python-2.7.2/Lib/test/test__locale.py | 137 - .../Python/Python-2.7.2/Lib/test/test_abc.py | 233 - .../Lib/test/test_abstract_numbers.py | 52 - .../Python-2.7.2/Lib/test/test_aepack.py | 90 - .../Python/Python-2.7.2/Lib/test/test_aifc.py | 115 - .../Python/Python-2.7.2/Lib/test/test_al.py | 25 - .../Python-2.7.2/Lib/test/test_anydbm.py | 97 - .../Python-2.7.2/Lib/test/test_applesingle.py | 71 - .../Python-2.7.2/Lib/test/test_argparse.py | 4646 ----- .../Python-2.7.2/Lib/test/test_array.py | 1095 - .../Lib/test/test_ascii_formatd.py | 58 - .../Python/Python-2.7.2/Lib/test/test_ast.py | 382 - .../Python-2.7.2/Lib/test/test_asynchat.py | 273 - .../Python-2.7.2/Lib/test/test_asyncore.py | 722 - .../Python-2.7.2/Lib/test/test_atexit.py | 82 - .../Python-2.7.2/Lib/test/test_audioop.py | 206 - .../Python-2.7.2/Lib/test/test_augassign.py | 331 - .../Python-2.7.2/Lib/test/test_base64.py | 190 - .../Python-2.7.2/Lib/test/test_bastion.py | 3 - .../Lib/test/test_bigaddrspace.py | 46 - .../Python-2.7.2/Lib/test/test_bigmem.py | 1073 - .../Python-2.7.2/Lib/test/test_binascii.py | 236 - .../Python-2.7.2/Lib/test/test_binhex.py | 49 - .../Python-2.7.2/Lib/test/test_binop.py | 331 - .../Python-2.7.2/Lib/test/test_bisect.py | 317 - .../Python/Python-2.7.2/Lib/test/test_bool.py | 371 - .../Python-2.7.2/Lib/test/test_bsddb.py | 357 - .../Python-2.7.2/Lib/test/test_bsddb185.py | 43 - .../Python-2.7.2/Lib/test/test_bsddb3.py | 81 - .../Python-2.7.2/Lib/test/test_buffer.py | 31 - .../Python-2.7.2/Lib/test/test_bufio.py | 79 - .../Python-2.7.2/Lib/test/test_builtin.py | 1708 -- .../Python-2.7.2/Lib/test/test_bytes.py | 1119 - .../Python/Python-2.7.2/Lib/test/test_bz2.py | 422 - .../Python-2.7.2/Lib/test/test_calendar.py | 457 - .../Python/Python-2.7.2/Lib/test/test_call.py | 134 - .../Python/Python-2.7.2/Lib/test/test_capi.py | 140 - .../Python/Python-2.7.2/Lib/test/test_cd.py | 30 - .../Python-2.7.2/Lib/test/test_cfgparser.py | 598 - .../Python/Python-2.7.2/Lib/test/test_cgi.py | 386 - .../Lib/test/test_charmapcodec.py | 56 - .../Python/Python-2.7.2/Lib/test/test_cl.py | 82 - .../Python-2.7.2/Lib/test/test_class.py | 626 - .../Python-2.7.2/Lib/test/test_cmath.py | 474 - .../Python/Python-2.7.2/Lib/test/test_cmd.py | 217 - .../Python-2.7.2/Lib/test/test_cmd_line.py | 95 - .../Lib/test/test_cmd_line_script.py | 213 - .../Python/Python-2.7.2/Lib/test/test_code.py | 147 - .../Lib/test/test_codeccallbacks.py | 804 - .../Lib/test/test_codecencodings_cn.py | 86 - .../Lib/test/test_codecencodings_hk.py | 27 - .../Lib/test/test_codecencodings_jp.py | 105 - .../Lib/test/test_codecencodings_kr.py | 69 - .../Lib/test/test_codecencodings_tw.py | 27 - .../Lib/test/test_codecmaps_cn.py | 33 - .../Lib/test/test_codecmaps_hk.py | 21 - .../Lib/test/test_codecmaps_jp.py | 67 - .../Lib/test/test_codecmaps_kr.py | 44 - .../Lib/test/test_codecmaps_tw.py | 31 - .../Python-2.7.2/Lib/test/test_codecs.py | 1614 -- .../Python-2.7.2/Lib/test/test_codeop.py | 304 - .../Python-2.7.2/Lib/test/test_coding.py | 37 - .../Python-2.7.2/Lib/test/test_coercion.py | 348 - .../Python-2.7.2/Lib/test/test_collections.py | 1042 - .../Python-2.7.2/Lib/test/test_colorsys.py | 76 - .../Python-2.7.2/Lib/test/test_commands.py | 74 - .../Python-2.7.2/Lib/test/test_compare.py | 58 - .../Python-2.7.2/Lib/test/test_compile.py | 498 - .../Python-2.7.2/Lib/test/test_compileall.py | 80 - .../Python-2.7.2/Lib/test/test_compiler.py | 317 - .../Python-2.7.2/Lib/test/test_complex.py | 651 - .../Lib/test/test_complex_args.py | 118 - .../Python-2.7.2/Lib/test/test_contains.py | 111 - .../Python-2.7.2/Lib/test/test_contextlib.py | 326 - .../Python-2.7.2/Lib/test/test_cookie.py | 98 - .../Python-2.7.2/Lib/test/test_cookielib.py | 1762 -- .../Python/Python-2.7.2/Lib/test/test_copy.py | 712 - .../Python-2.7.2/Lib/test/test_copy_reg.py | 121 - .../Python-2.7.2/Lib/test/test_cpickle.py | 139 - .../Python-2.7.2/Lib/test/test_cprofile.py | 127 - .../Python-2.7.2/Lib/test/test_crypt.py | 17 - .../Python/Python-2.7.2/Lib/test/test_csv.py | 1055 - .../Python-2.7.2/Lib/test/test_ctypes.py | 15 - .../Python-2.7.2/Lib/test/test_curses.py | 290 - .../Python-2.7.2/Lib/test/test_datetime.py | 3367 --- .../Python/Python-2.7.2/Lib/test/test_dbm.py | 42 - .../Python-2.7.2/Lib/test/test_decimal.py | 2339 --- .../Python-2.7.2/Lib/test/test_decorators.py | 309 - .../Python-2.7.2/Lib/test/test_defaultdict.py | 179 - .../Python-2.7.2/Lib/test/test_deque.py | 787 - .../Python-2.7.2/Lib/test/test_descr.py | 4659 ----- .../Python-2.7.2/Lib/test/test_descrtut.py | 497 - .../Python/Python-2.7.2/Lib/test/test_dict.py | 676 - .../Python-2.7.2/Lib/test/test_dictcomps.py | 54 - .../Python-2.7.2/Lib/test/test_dictviews.py | 154 - .../Python-2.7.2/Lib/test/test_difflib.py | 272 - .../Lib/test/test_difflib_expect.html | 526 - .../Python-2.7.2/Lib/test/test_dircache.py | 77 - .../Python/Python-2.7.2/Lib/test/test_dis.py | 150 - .../Python-2.7.2/Lib/test/test_distutils.py | 18 - .../Python/Python-2.7.2/Lib/test/test_dl.py | 39 - .../Python-2.7.2/Lib/test/test_doctest.py | 2615 --- .../Python-2.7.2/Lib/test/test_doctest.txt | 17 - .../Python-2.7.2/Lib/test/test_doctest2.py | 124 - .../Python-2.7.2/Lib/test/test_doctest2.txt | 14 - .../Python-2.7.2/Lib/test/test_doctest3.txt | 5 - .../Python-2.7.2/Lib/test/test_doctest4.txt | 17 - .../Python-2.7.2/Lib/test/test_docxmlrpc.py | 201 - .../Python-2.7.2/Lib/test/test_dumbdbm.py | 179 - .../Lib/test/test_dummy_thread.py | 182 - .../Lib/test/test_dummy_threading.py | 63 - .../Python-2.7.2/Lib/test/test_email.py | 12 - .../Lib/test/test_email_codecs.py | 15 - .../Lib/test/test_email_renamed.py | 12 - .../Python-2.7.2/Lib/test/test_enumerate.py | 255 - .../Python/Python-2.7.2/Lib/test/test_eof.py | 32 - .../Python-2.7.2/Lib/test/test_epoll.py | 221 - .../Python-2.7.2/Lib/test/test_errno.py | 40 - .../Lib/test/test_exception_variations.py | 180 - .../Python-2.7.2/Lib/test/test_exceptions.py | 620 - .../Python-2.7.2/Lib/test/test_extcall.py | 319 - .../Python-2.7.2/Lib/test/test_fcntl.py | 108 - .../Python/Python-2.7.2/Lib/test/test_file.py | 347 - .../Python-2.7.2/Lib/test/test_file2k.py | 680 - .../Python-2.7.2/Lib/test/test_filecmp.py | 134 - .../Python-2.7.2/Lib/test/test_fileinput.py | 225 - .../Python-2.7.2/Lib/test/test_fileio.py | 434 - .../Python-2.7.2/Lib/test/test_float.py | 1396 -- .../Python-2.7.2/Lib/test/test_fnmatch.py | 72 - .../Python-2.7.2/Lib/test/test_fork1.py | 71 - .../Python-2.7.2/Lib/test/test_format.py | 297 - .../Python-2.7.2/Lib/test/test_fpformat.py | 76 - .../Python-2.7.2/Lib/test/test_fractions.py | 587 - .../Python-2.7.2/Lib/test/test_frozen.py | 47 - .../Python-2.7.2/Lib/test/test_ftplib.py | 778 - .../Python-2.7.2/Lib/test/test_funcattrs.py | 353 - .../Python-2.7.2/Lib/test/test_functools.py | 478 - .../Python-2.7.2/Lib/test/test_future.py | 119 - .../Python-2.7.2/Lib/test/test_future1.py | 11 - .../Python-2.7.2/Lib/test/test_future2.py | 10 - .../Python-2.7.2/Lib/test/test_future3.py | 30 - .../Python-2.7.2/Lib/test/test_future4.py | 47 - .../Python-2.7.2/Lib/test/test_future5.py | 21 - .../Lib/test/test_future_builtins.py | 38 - .../Python/Python-2.7.2/Lib/test/test_gc.py | 639 - .../Python/Python-2.7.2/Lib/test/test_gdb.py | 702 - .../Python/Python-2.7.2/Lib/test/test_gdbm.py | 82 - .../Python-2.7.2/Lib/test/test_generators.py | 1906 -- .../Python-2.7.2/Lib/test/test_genericpath.py | 256 - .../Python-2.7.2/Lib/test/test_genexps.py | 282 - .../Python-2.7.2/Lib/test/test_getargs.py | 31 - .../Python-2.7.2/Lib/test/test_getargs2.py | 335 - .../Python-2.7.2/Lib/test/test_getopt.py | 187 - .../Python-2.7.2/Lib/test/test_gettext.py | 467 - .../Python/Python-2.7.2/Lib/test/test_gl.py | 155 - .../Python/Python-2.7.2/Lib/test/test_glob.py | 114 - .../Python-2.7.2/Lib/test/test_global.py | 52 - .../Python-2.7.2/Lib/test/test_grammar.py | 999 - .../Python/Python-2.7.2/Lib/test/test_grp.py | 97 - .../Python/Python-2.7.2/Lib/test/test_gzip.py | 281 - .../Python/Python-2.7.2/Lib/test/test_hash.py | 144 - .../Python-2.7.2/Lib/test/test_hashlib.py | 361 - .../Python-2.7.2/Lib/test/test_heapq.py | 393 - .../Python/Python-2.7.2/Lib/test/test_hmac.py | 314 - .../Python-2.7.2/Lib/test/test_hotshot.py | 158 - .../Python-2.7.2/Lib/test/test_htmllib.py | 69 - .../Python-2.7.2/Lib/test/test_htmlparser.py | 351 - .../Python-2.7.2/Lib/test/test_httplib.py | 447 - .../Python-2.7.2/Lib/test/test_httpservers.py | 529 - .../Python-2.7.2/Lib/test/test_imageop.py | 211 - .../Python-2.7.2/Lib/test/test_imaplib.py | 240 - .../Python-2.7.2/Lib/test/test_imgfile.py | 119 - .../Python/Python-2.7.2/Lib/test/test_imp.py | 81 - .../Python-2.7.2/Lib/test/test_import.py | 460 - .../Python-2.7.2/Lib/test/test_importhooks.py | 255 - .../Python-2.7.2/Lib/test/test_importlib.py | 176 - .../Python-2.7.2/Lib/test/test_index.py | 323 - .../Python-2.7.2/Lib/test/test_inspect.py | 752 - .../Python/Python-2.7.2/Lib/test/test_int.py | 406 - .../Python-2.7.2/Lib/test/test_int_literal.py | 188 - .../Python/Python-2.7.2/Lib/test/test_io.py | 2782 --- .../Python-2.7.2/Lib/test/test_ioctl.py | 93 - .../Python-2.7.2/Lib/test/test_isinstance.py | 277 - .../Python/Python-2.7.2/Lib/test/test_iter.py | 917 - .../Python-2.7.2/Lib/test/test_iterlen.py | 257 - .../Python-2.7.2/Lib/test/test_itertools.py | 1650 -- .../Python/Python-2.7.2/Lib/test/test_json.py | 17 - .../Python-2.7.2/Lib/test/test_kqueue.py | 196 - .../Python-2.7.2/Lib/test/test_largefile.py | 200 - .../Python-2.7.2/Lib/test/test_lib2to3.py | 21 - .../Python-2.7.2/Lib/test/test_linecache.py | 131 - .../Lib/test/test_linuxaudiodev.py | 99 - .../Python/Python-2.7.2/Lib/test/test_list.py | 78 - .../Python-2.7.2/Lib/test/test_locale.py | 420 - .../Python-2.7.2/Lib/test/test_logging.py | 1886 -- .../Python/Python-2.7.2/Lib/test/test_long.py | 914 - .../Python-2.7.2/Lib/test/test_long_future.py | 221 - .../Python-2.7.2/Lib/test/test_longexp.py | 14 - .../Python-2.7.2/Lib/test/test_macos.py | 98 - .../Python-2.7.2/Lib/test/test_macostools.py | 88 - .../Python-2.7.2/Lib/test/test_macpath.py | 57 - .../Python-2.7.2/Lib/test/test_mailbox.py | 1970 -- .../Python-2.7.2/Lib/test/test_marshal.py | 283 - .../Python/Python-2.7.2/Lib/test/test_math.py | 1030 - .../Python/Python-2.7.2/Lib/test/test_md5.py | 61 - .../Python-2.7.2/Lib/test/test_memoryio.py | 707 - .../Python-2.7.2/Lib/test/test_memoryview.py | 361 - .../Python-2.7.2/Lib/test/test_mhlib.py | 348 - .../Python-2.7.2/Lib/test/test_mimetools.py | 53 - .../Python-2.7.2/Lib/test/test_mimetypes.py | 94 - .../Python-2.7.2/Lib/test/test_minidom.py | 1477 -- .../Python/Python-2.7.2/Lib/test/test_mmap.py | 704 - .../Python-2.7.2/Lib/test/test_module.py | 85 - .../Lib/test/test_modulefinder.py | 286 - .../Python-2.7.2/Lib/test/test_msilib.py | 46 - .../Lib/test/test_multibytecodec.py | 274 - .../Lib/test/test_multibytecodec_support.py | 338 - .../Python-2.7.2/Lib/test/test_multifile.py | 67 - .../Lib/test/test_multiprocessing.py | 2110 -- .../Python-2.7.2/Lib/test/test_mutants.py | 292 - .../Python-2.7.2/Lib/test/test_mutex.py | 35 - .../Python-2.7.2/Lib/test/test_netrc.py | 110 - .../Python/Python-2.7.2/Lib/test/test_new.py | 163 - .../Python/Python-2.7.2/Lib/test/test_nis.py | 44 - .../Lib/test/test_normalization.py | 102 - .../Python-2.7.2/Lib/test/test_ntpath.py | 203 - .../Python-2.7.2/Lib/test/test_old_mailbox.py | 152 - .../Python-2.7.2/Lib/test/test_opcodes.py | 121 - .../Python-2.7.2/Lib/test/test_openpty.py | 23 - .../Python-2.7.2/Lib/test/test_operator.py | 532 - .../Python-2.7.2/Lib/test/test_optparse.py | 1619 -- .../Python/Python-2.7.2/Lib/test/test_os.py | 824 - .../Python-2.7.2/Lib/test/test_ossaudiodev.py | 174 - .../Python-2.7.2/Lib/test/test_parser.py | 596 - .../Python/Python-2.7.2/Lib/test/test_pdb.py | 287 - .../Python-2.7.2/Lib/test/test_peepholer.py | 243 - .../Python-2.7.2/Lib/test/test_pep247.py | 74 - .../Python-2.7.2/Lib/test/test_pep263.py | 48 - .../Python-2.7.2/Lib/test/test_pep277.py | 210 - .../Python-2.7.2/Lib/test/test_pep292.py | 193 - .../Python-2.7.2/Lib/test/test_pep352.py | 239 - .../Python-2.7.2/Lib/test/test_pickle.py | 80 - .../Python-2.7.2/Lib/test/test_pickletools.py | 24 - .../Python-2.7.2/Lib/test/test_pipes.py | 204 - .../Python/Python-2.7.2/Lib/test/test_pkg.py | 292 - .../Python-2.7.2/Lib/test/test_pkgimport.py | 83 - .../Python-2.7.2/Lib/test/test_pkgutil.py | 130 - .../Python-2.7.2/Lib/test/test_platform.py | 254 - .../Python-2.7.2/Lib/test/test_plistlib.py | 192 - .../Python/Python-2.7.2/Lib/test/test_poll.py | 157 - .../Python-2.7.2/Lib/test/test_popen.py | 52 - .../Python-2.7.2/Lib/test/test_popen2.py | 130 - .../Python-2.7.2/Lib/test/test_poplib.py | 343 - .../Python-2.7.2/Lib/test/test_posix.py | 429 - .../Python-2.7.2/Lib/test/test_posixpath.py | 348 - .../Python/Python-2.7.2/Lib/test/test_pow.py | 129 - .../Python-2.7.2/Lib/test/test_pprint.py | 432 - .../Python-2.7.2/Lib/test/test_print.py | 141 - .../Python-2.7.2/Lib/test/test_profile.py | 186 - .../Python-2.7.2/Lib/test/test_property.py | 231 - .../Python-2.7.2/Lib/test/test_pstats.py | 32 - .../Python/Python-2.7.2/Lib/test/test_pty.py | 200 - .../Python/Python-2.7.2/Lib/test/test_pwd.py | 100 - .../Python-2.7.2/Lib/test/test_py3kwarn.py | 426 - .../Python-2.7.2/Lib/test/test_pyclbr.py | 197 - .../Python-2.7.2/Lib/test/test_pydoc.py | 367 - .../Python-2.7.2/Lib/test/test_pyexpat.py | 604 - .../Python-2.7.2/Lib/test/test_queue.py | 322 - .../Python-2.7.2/Lib/test/test_quopri.py | 201 - .../Python-2.7.2/Lib/test/test_random.py | 572 - .../Python/Python-2.7.2/Lib/test/test_re.py | 889 - .../Python-2.7.2/Lib/test/test_readline.py | 43 - .../Python/Python-2.7.2/Lib/test/test_repr.py | 327 - .../Python-2.7.2/Lib/test/test_resource.py | 110 - .../Python-2.7.2/Lib/test/test_rfc822.py | 257 - .../Python-2.7.2/Lib/test/test_richcmp.py | 338 - .../Python-2.7.2/Lib/test/test_rlcompleter.py | 73 - .../Python-2.7.2/Lib/test/test_robotparser.py | 261 - .../Python-2.7.2/Lib/test/test_runpy.py | 402 - .../Python/Python-2.7.2/Lib/test/test_sax.py | 753 - .../Python-2.7.2/Lib/test/test_scope.py | 664 - .../Lib/test/test_scriptpackages.py | 51 - .../Python-2.7.2/Lib/test/test_select.py | 58 - .../Python/Python-2.7.2/Lib/test/test_set.py | 1781 -- .../Python-2.7.2/Lib/test/test_setcomps.py | 151 - .../Python/Python-2.7.2/Lib/test/test_sets.py | 862 - .../Python-2.7.2/Lib/test/test_sgmllib.py | 439 - .../Python/Python-2.7.2/Lib/test/test_sha.py | 56 - .../Python-2.7.2/Lib/test/test_shelve.py | 163 - .../Python-2.7.2/Lib/test/test_shlex.py | 191 - .../Python-2.7.2/Lib/test/test_shutil.py | 831 - .../Python-2.7.2/Lib/test/test_signal.py | 493 - .../Python/Python-2.7.2/Lib/test/test_site.py | 392 - .../Python-2.7.2/Lib/test/test_slice.py | 134 - .../Python-2.7.2/Lib/test/test_smtplib.py | 518 - .../Python-2.7.2/Lib/test/test_smtpnet.py | 31 - .../Python-2.7.2/Lib/test/test_socket.py | 1618 -- .../Lib/test/test_socketserver.py | 284 - .../Python-2.7.2/Lib/test/test_softspace.py | 23 - .../Python/Python-2.7.2/Lib/test/test_sort.py | 292 - .../Python-2.7.2/Lib/test/test_sqlite.py | 16 - .../Python/Python-2.7.2/Lib/test/test_ssl.py | 1360 -- .../Python-2.7.2/Lib/test/test_startfile.py | 45 - .../Python/Python-2.7.2/Lib/test/test_str.py | 434 - .../Python-2.7.2/Lib/test/test_strftime.py | 185 - .../Python-2.7.2/Lib/test/test_string.py | 217 - .../Python-2.7.2/Lib/test/test_stringprep.py | 96 - .../Python-2.7.2/Lib/test/test_strop.py | 153 - .../Python-2.7.2/Lib/test/test_strptime.py | 562 - .../Python-2.7.2/Lib/test/test_strtod.py | 399 - .../Python-2.7.2/Lib/test/test_struct.py | 551 - .../Lib/test/test_structmembers.py | 108 - .../Python-2.7.2/Lib/test/test_structseq.py | 120 - .../Python-2.7.2/Lib/test/test_subprocess.py | 1053 - .../Python-2.7.2/Lib/test/test_sunaudiodev.py | 33 - .../Python-2.7.2/Lib/test/test_sundry.py | 96 - .../Python-2.7.2/Lib/test/test_support.py | 1233 -- .../Python-2.7.2/Lib/test/test_symtable.py | 184 - .../Python-2.7.2/Lib/test/test_syntax.py | 572 - .../Python/Python-2.7.2/Lib/test/test_sys.py | 794 - .../Lib/test/test_sys_setprofile.py | 386 - .../Lib/test/test_sys_settrace.py | 789 - .../Python-2.7.2/Lib/test/test_sysconfig.py | 316 - .../Python-2.7.2/Lib/test/test_tarfile.py | 1637 -- .../Python/Python-2.7.2/Lib/test/test_tcl.py | 160 - .../Python-2.7.2/Lib/test/test_telnetlib.py | 372 - .../Python-2.7.2/Lib/test/test_tempfile.py | 856 - .../Python-2.7.2/Lib/test/test_textwrap.py | 610 - .../Python-2.7.2/Lib/test/test_thread.py | 242 - .../Lib/test/test_threaded_import.py | 76 - .../Lib/test/test_threadedtempfile.py | 78 - .../Python-2.7.2/Lib/test/test_threading.py | 734 - .../Lib/test/test_threading_local.py | 234 - .../Lib/test/test_threadsignals.py | 85 - .../Python/Python-2.7.2/Lib/test/test_time.py | 250 - .../Python-2.7.2/Lib/test/test_timeout.py | 202 - .../Python/Python-2.7.2/Lib/test/test_tk.py | 35 - .../Python-2.7.2/Lib/test/test_tokenize.py | 596 - .../Python-2.7.2/Lib/test/test_trace.py | 341 - .../Python-2.7.2/Lib/test/test_traceback.py | 204 - .../Python-2.7.2/Lib/test/test_transformer.py | 38 - .../Python-2.7.2/Lib/test/test_ttk_guionly.py | 40 - .../Lib/test/test_ttk_textonly.py | 19 - .../Python-2.7.2/Lib/test/test_tuple.py | 161 - .../Python-2.7.2/Lib/test/test_typechecks.py | 93 - .../Python-2.7.2/Lib/test/test_types.py | 756 - .../Python/Python-2.7.2/Lib/test/test_ucn.py | 144 - .../Python-2.7.2/Lib/test/test_unary.py | 59 - .../Lib/test/test_undocumented_details.py | 39 - .../Python-2.7.2/Lib/test/test_unicode.py | 1404 -- .../Lib/test/test_unicode_file.py | 200 - .../Python-2.7.2/Lib/test/test_unicodedata.py | 317 - .../Python-2.7.2/Lib/test/test_unittest.py | 12 - .../Lib/test/test_univnewlines.py | 135 - .../Lib/test/test_univnewlines2k.py | 130 - .../Python-2.7.2/Lib/test/test_unpack.py | 130 - .../Python-2.7.2/Lib/test/test_urllib.py | 786 - .../Python-2.7.2/Lib/test/test_urllib2.py | 1327 -- .../Lib/test/test_urllib2_localnet.py | 539 - .../Python-2.7.2/Lib/test/test_urllib2net.py | 319 - .../Python-2.7.2/Lib/test/test_urllibnet.py | 205 - .../Python-2.7.2/Lib/test/test_urlparse.py | 513 - .../Python-2.7.2/Lib/test/test_userdict.py | 350 - .../Python-2.7.2/Lib/test/test_userlist.py | 61 - .../Python-2.7.2/Lib/test/test_userstring.py | 147 - .../Python/Python-2.7.2/Lib/test/test_uu.py | 201 - .../Python/Python-2.7.2/Lib/test/test_uuid.py | 482 - .../Python-2.7.2/Lib/test/test_wait3.py | 39 - .../Python-2.7.2/Lib/test/test_wait4.py | 32 - .../Python-2.7.2/Lib/test/test_warnings.py | 749 - .../Python/Python-2.7.2/Lib/test/test_wave.py | 45 - .../Python-2.7.2/Lib/test/test_weakref.py | 1256 -- .../Python-2.7.2/Lib/test/test_weakset.py | 377 - .../Python-2.7.2/Lib/test/test_whichdb.py | 68 - .../Python-2.7.2/Lib/test/test_winreg.py | 416 - .../Python-2.7.2/Lib/test/test_winsound.py | 255 - .../Python/Python-2.7.2/Lib/test/test_with.py | 750 - .../Python-2.7.2/Lib/test/test_wsgiref.py | 630 - .../Python-2.7.2/Lib/test/test_xdrlib.py | 58 - .../Python-2.7.2/Lib/test/test_xml_etree.py | 1886 -- .../Python-2.7.2/Lib/test/test_xml_etree_c.py | 55 - .../Python-2.7.2/Lib/test/test_xmllib.py | 48 - .../Python-2.7.2/Lib/test/test_xmlrpc.py | 1018 - .../Python-2.7.2/Lib/test/test_xpickle.py | 260 - .../Python-2.7.2/Lib/test/test_xrange.py | 143 - .../Python-2.7.2/Lib/test/test_zipfile.py | 1362 -- .../Python-2.7.2/Lib/test/test_zipfile64.py | 124 - .../Python-2.7.2/Lib/test/test_zipimport.py | 472 - .../Lib/test/test_zipimport_support.py | 238 - .../Python/Python-2.7.2/Lib/test/test_zlib.py | 572 - .../Python/Python-2.7.2/Lib/test/testall.py | 10 - .../Python/Python-2.7.2/Lib/test/testcodec.py | 48 - .../Python/Python-2.7.2/Lib/test/testimg.uue | 1170 -- .../Python/Python-2.7.2/Lib/test/testimgr.uue | 1170 -- .../Python/Python-2.7.2/Lib/test/testrgb.uue | 971 - .../Python/Python-2.7.2/Lib/test/testtar.tar | Bin 281088 -> 0 bytes .../Python-2.7.2/Lib/test/tf_inherit_check.py | 25 - .../Lib/test/threaded_import_hangers.py | 42 - .../Python-2.7.2/Lib/test/time_hashlib.py | 87 - .../Python-2.7.2/Lib/test/tokenize_tests.txt | 178 - .../Lib/test/tracedmodules/__init__.py | 4 - .../Lib/test/tracedmodules/testmod.py | 9 - .../Python-2.7.2/Lib/test/warning_tests.py | 9 - .../Lib/test/win_console_handler.py | 49 - .../Python-2.7.2/Lib/test/wrongcert.pem | 32 - .../Lib/test/xmltestdata/simple-ns.xml | 7 - .../Lib/test/xmltestdata/simple.xml | 6 - .../Lib/test/xmltestdata/test.xml | 115 - .../Lib/test/xmltestdata/test.xml.out | 115 - .../Python/Python-2.7.2/Lib/test/xmltests.py | 21 - .../Python/Python-2.7.2/Lib/test/zipdir.zip | Bin 374 -> 0 bytes .../Python/Python-2.7.2/Lib/textwrap.py | 417 - .../Python/Python-2.7.2/Lib/this.py | 28 - .../Python/Python-2.7.2/Lib/timeit.py | 328 - .../Python/Python-2.7.2/Lib/toaiff.py | 110 - .../Python/Python-2.7.2/Lib/token.py | 142 - .../Python/Python-2.7.2/Lib/tokenize.py | 424 - .../Python/Python-2.7.2/Lib/trace.py | 827 - .../Python/Python-2.7.2/Lib/traceback.py | 319 - .../Python/Python-2.7.2/Lib/tty.py | 36 - .../Python/Python-2.7.2/Lib/types.py | 84 - .../Python-2.7.2/Lib/unittest/__init__.py | 69 - .../Python-2.7.2/Lib/unittest/__main__.py | 12 - .../Python/Python-2.7.2/Lib/unittest/case.py | 1070 - .../Python-2.7.2/Lib/unittest/loader.py | 314 - .../Python/Python-2.7.2/Lib/unittest/main.py | 233 - .../Python-2.7.2/Lib/unittest/result.py | 193 - .../Python-2.7.2/Lib/unittest/runner.py | 196 - .../Python-2.7.2/Lib/unittest/signals.py | 57 - .../Python/Python-2.7.2/Lib/unittest/suite.py | 303 - .../Lib/unittest/test/__init__.py | 21 - .../Python-2.7.2/Lib/unittest/test/dummy.py | 1 - .../Python-2.7.2/Lib/unittest/test/support.py | 119 - .../Lib/unittest/test/test_assertions.py | 286 - .../Lib/unittest/test/test_break.py | 252 - .../Lib/unittest/test/test_case.py | 1109 - .../Lib/unittest/test/test_discovery.py | 362 - .../unittest/test/test_functiontestcase.py | 148 - .../Lib/unittest/test/test_loader.py | 1286 -- .../Lib/unittest/test/test_program.py | 255 - .../Lib/unittest/test/test_result.py | 567 - .../Lib/unittest/test/test_runner.py | 253 - .../Lib/unittest/test/test_setups.py | 508 - .../Lib/unittest/test/test_skipping.py | 138 - .../Lib/unittest/test/test_suite.py | 367 - .../Python/Python-2.7.2/Lib/unittest/util.py | 156 - .../Python/Python-2.7.2/Lib/urllib.py | 1646 -- .../Python/Python-2.7.2/Lib/urllib2.py | 1448 -- .../Python/Python-2.7.2/Lib/urlparse.py | 397 - .../Python/Python-2.7.2/Lib/user.py | 48 - .../Python/Python-2.7.2/Lib/uu.py | 196 - .../Python/Python-2.7.2/Lib/uuid.py | 560 - .../Python/Python-2.7.2/Lib/warnings.py | 400 - .../Python/Python-2.7.2/Lib/wave.py | 504 - .../Python/Python-2.7.2/Lib/weakref.py | 379 - .../Python/Python-2.7.2/Lib/webbrowser.py | 673 - .../Python/Python-2.7.2/Lib/whichdb.py | 117 - .../Python/Python-2.7.2/Lib/wsgiref.egg-info | 8 - .../Python-2.7.2/Lib/wsgiref/__init__.py | 23 - .../Python-2.7.2/Lib/wsgiref/handlers.py | 448 - .../Python-2.7.2/Lib/wsgiref/headers.py | 169 - .../Python-2.7.2/Lib/wsgiref/simple_server.py | 155 - .../Python/Python-2.7.2/Lib/wsgiref/util.py | 165 - .../Python-2.7.2/Lib/wsgiref/validate.py | 432 - .../Python/Python-2.7.2/Lib/xdrlib.py | 231 - .../Python/Python-2.7.2/Lib/xml/__init__.py | 41 - .../Python-2.7.2/Lib/xml/dom/NodeFilter.py | 27 - .../Python-2.7.2/Lib/xml/dom/__init__.py | 139 - .../Python/Python-2.7.2/Lib/xml/dom/domreg.py | 99 - .../Python-2.7.2/Lib/xml/dom/expatbuilder.py | 983 - .../Python-2.7.2/Lib/xml/dom/minicompat.py | 110 - .../Python-2.7.2/Lib/xml/dom/minidom.py | 1937 -- .../Python-2.7.2/Lib/xml/dom/pulldom.py | 351 - .../Python-2.7.2/Lib/xml/dom/xmlbuilder.py | 386 - .../Lib/xml/etree/ElementInclude.py | 143 - .../Python-2.7.2/Lib/xml/etree/ElementPath.py | 303 - .../Python-2.7.2/Lib/xml/etree/ElementTree.py | 1649 -- .../Python-2.7.2/Lib/xml/etree/__init__.py | 33 - .../Lib/xml/etree/cElementTree.py | 3 - .../Python-2.7.2/Lib/xml/parsers/__init__.py | 8 - .../Python-2.7.2/Lib/xml/parsers/expat.py | 4 - .../Python-2.7.2/Lib/xml/sax/__init__.py | 108 - .../Python-2.7.2/Lib/xml/sax/_exceptions.py | 131 - .../Python-2.7.2/Lib/xml/sax/expatreader.py | 414 - .../Python-2.7.2/Lib/xml/sax/handler.py | 342 - .../Python-2.7.2/Lib/xml/sax/saxutils.py | 308 - .../Python-2.7.2/Lib/xml/sax/xmlreader.py | 381 - .../Python/Python-2.7.2/Lib/xmllib.py | 930 - .../Python/Python-2.7.2/Lib/xmlrpclib.py | 1636 -- .../Python/Python-2.7.2/Lib/zipfile.py | 1437 -- .../Python-2.7.2/Modules/_bisectmodule.c | 241 - .../Python-2.7.2/Modules/_codecsmodule.c | 1116 - .../Python-2.7.2/Modules/_collectionsmodule.c | 1634 -- .../Python/Python-2.7.2/Modules/_csv.c | 1611 -- .../Python-2.7.2/Modules/_elementtree.c | 3079 --- .../Python-2.7.2/Modules/_functoolsmodule.c | 402 - .../Python-2.7.2/Modules/_hashopenssl.c | 597 - .../Python-2.7.2/Modules/_heapqmodule.c | 697 - .../Python/Python-2.7.2/Modules/_hotshot.c | 1643 -- .../Python-2.7.2/Modules/_io/_iomodule.c | 768 - .../Python-2.7.2/Modules/_io/_iomodule.h | 165 - .../Python-2.7.2/Modules/_io/bufferedio.c | 2389 --- .../Python/Python-2.7.2/Modules/_io/bytesio.c | 887 - .../Python/Python-2.7.2/Modules/_io/fileio.c | 1095 - .../Python/Python-2.7.2/Modules/_io/iobase.c | 893 - .../Python-2.7.2/Modules/_io/stringio.c | 882 - .../Python/Python-2.7.2/Modules/_io/textio.c | 2617 --- .../Python/Python-2.7.2/Modules/_json.c | 2421 --- .../Python-2.7.2/Modules/_localemodule.c | 758 - .../Python/Python-2.7.2/Modules/_lsprof.c | 892 - .../Python/Python-2.7.2/Modules/_math.c | 232 - .../Python/Python-2.7.2/Modules/_math.h | 45 - .../Python-2.7.2/Modules/_randommodule.c | 580 - .../Python-2.7.2/Modules/_sqlite/cache.c | 375 - .../Python-2.7.2/Modules/_sqlite/cache.h | 73 - .../Python-2.7.2/Modules/_sqlite/connection.c | 1664 -- .../Python-2.7.2/Modules/_sqlite/connection.h | 138 - .../Python-2.7.2/Modules/_sqlite/cursor.c | 1126 - .../Python-2.7.2/Modules/_sqlite/cursor.h | 74 - .../Modules/_sqlite/microprotocols.c | 142 - .../Modules/_sqlite/microprotocols.h | 55 - .../Python-2.7.2/Modules/_sqlite/module.c | 457 - .../Python-2.7.2/Modules/_sqlite/module.h | 58 - .../Modules/_sqlite/prepare_protocol.c | 84 - .../Modules/_sqlite/prepare_protocol.h | 41 - .../Python/Python-2.7.2/Modules/_sqlite/row.c | 256 - .../Python/Python-2.7.2/Modules/_sqlite/row.h | 39 - .../Modules/_sqlite/sqlitecompat.h | 63 - .../Python-2.7.2/Modules/_sqlite/statement.c | 543 - .../Python-2.7.2/Modules/_sqlite/statement.h | 59 - .../Python-2.7.2/Modules/_sqlite/util.c | 106 - .../Python-2.7.2/Modules/_sqlite/util.h | 38 - .../Python/Python-2.7.2/Modules/_sre.c | 3921 ---- .../Python/Python-2.7.2/Modules/_ssl.c | 1751 -- .../Python/Python-2.7.2/Modules/_struct.c | 2048 -- .../Python-2.7.2/Modules/_testcapimodule.c | 1897 -- .../Python/Python-2.7.2/Modules/_weakref.c | 112 - .../Python/Python-2.7.2/Modules/addrinfo.h | 178 - .../Python/Python-2.7.2/Modules/arraymodule.c | 2246 -- .../Python/Python-2.7.2/Modules/binascii.c | 1531 -- .../Python/Python-2.7.2/Modules/bz2module.c | 2344 --- .../Python/Python-2.7.2/Modules/cPickle.c | 6023 ------ .../Python/Python-2.7.2/Modules/cStringIO.c | 752 - .../Python-2.7.2/Modules/cjkcodecs/README | 79 - .../Modules/cjkcodecs/_codecs_cn.c | 444 - .../Modules/cjkcodecs/_codecs_hk.c | 183 - .../Modules/cjkcodecs/_codecs_iso2022.c | 1131 - .../Modules/cjkcodecs/_codecs_jp.c | 731 - .../Modules/cjkcodecs/_codecs_kr.c | 452 - .../Modules/cjkcodecs/_codecs_tw.c | 132 - .../Modules/cjkcodecs/alg_jisx0201.h | 24 - .../Modules/cjkcodecs/cjkcodecs.h | 398 - .../Modules/cjkcodecs/emu_jisx0213_2000.h | 43 - .../Modules/cjkcodecs/mappings_cn.h | 4103 ---- .../Modules/cjkcodecs/mappings_hk.h | 2378 --- .../cjkcodecs/mappings_jisx0213_pair.h | 59 - .../Modules/cjkcodecs/mappings_jp.h | 4765 ----- .../Modules/cjkcodecs/mappings_kr.h | 3251 --- .../Modules/cjkcodecs/mappings_tw.h | 2633 --- .../Modules/cjkcodecs/multibytecodec.c | 1829 -- .../Modules/cjkcodecs/multibytecodec.h | 141 - .../Python/Python-2.7.2/Modules/cmathmodule.c | 1210 -- .../Python/Python-2.7.2/Modules/cryptmodule.c | 49 - .../Python-2.7.2/Modules/datetimemodule.c | 5117 ----- .../Python/Python-2.7.2/Modules/errnomodule.c | 845 - .../Python/Python-2.7.2/Modules/expat/COPYING | 21 - .../Python-2.7.2/Modules/expat/amigaconfig.h | 96 - .../Python/Python-2.7.2/Modules/expat/ascii.h | 85 - .../Python-2.7.2/Modules/expat/asciitab.h | 36 - .../Python/Python-2.7.2/Modules/expat/expat.h | 1013 - .../Python-2.7.2/Modules/expat/expat_config.h | 19 - .../Modules/expat/expat_external.h | 121 - .../Python-2.7.2/Modules/expat/iasciitab.h | 37 - .../Python-2.7.2/Modules/expat/internal.h | 73 - .../Python-2.7.2/Modules/expat/latin1tab.h | 36 - .../Python-2.7.2/Modules/expat/macconfig.h | 53 - .../Python-2.7.2/Modules/expat/nametab.h | 150 - .../Python-2.7.2/Modules/expat/pyexpatns.h | 124 - .../Python-2.7.2/Modules/expat/utf8tab.h | 37 - .../Python-2.7.2/Modules/expat/winconfig.h | 30 - .../Python-2.7.2/Modules/expat/xmlparse.c | 6279 ------ .../Python-2.7.2/Modules/expat/xmlrole.c | 1330 -- .../Python-2.7.2/Modules/expat/xmlrole.h | 114 - .../Python-2.7.2/Modules/expat/xmltok.c | 1639 -- .../Python-2.7.2/Modules/expat/xmltok.h | 316 - .../Python-2.7.2/Modules/expat/xmltok_impl.c | 1779 -- .../Python-2.7.2/Modules/expat/xmltok_impl.h | 46 - .../Python-2.7.2/Modules/expat/xmltok_ns.c | 106 - .../Python/Python-2.7.2/Modules/fcntlmodule.c | 620 - .../Python/Python-2.7.2/Modules/flmodule.c | 2144 -- .../Python/Python-2.7.2/Modules/fmmodule.c | 269 - .../Python-2.7.2/Modules/fpectlmodule.c | 303 - .../Python-2.7.2/Modules/fpetestmodule.c | 186 - .../Python-2.7.2/Modules/future_builtins.c | 105 - .../Python-2.7.2/Modules/gc_weakref.txt | 219 - .../Python/Python-2.7.2/Modules/gcmodule.c | 1516 -- .../Python/Python-2.7.2/Modules/getaddrinfo.c | 638 - .../Python-2.7.2/Modules/getbuildinfo.c | 85 - .../Python/Python-2.7.2/Modules/getnameinfo.c | 222 - .../Python/Python-2.7.2/Modules/getpath.c | 698 - .../Python/Python-2.7.2/Modules/imageop.c | 794 - .../Python-2.7.2/Modules/itertoolsmodule.c | 4097 ---- .../Python/Python-2.7.2/Modules/main.c | 663 - .../Python/Python-2.7.2/Modules/mathmodule.c | 1624 -- .../Python/Python-2.7.2/Modules/md5.c | 394 - .../Python/Python-2.7.2/Modules/md5.h | 91 - .../Python/Python-2.7.2/Modules/md5module.c | 315 - .../Python/Python-2.7.2/Modules/operator.c | 802 - .../Python-2.7.2/Modules/parsermodule.c | 3464 ---- .../Python/Python-2.7.2/Modules/posixmodule.c | 9396 --------- .../Python/Python-2.7.2/Modules/puremodule.c | 992 - .../Python/Python-2.7.2/Modules/pwdmodule.c | 200 - .../Python/Python-2.7.2/Modules/pyexpat.c | 2123 -- .../Python/Python-2.7.2/Modules/python.c | 24 - .../Python/Python-2.7.2/Modules/readline.c | 1144 - .../Python/Python-2.7.2/Modules/resource.c | 329 - .../Python-2.7.2/Modules/rotatingtree.c | 121 - .../Python-2.7.2/Modules/rotatingtree.h | 27 - .../Python-2.7.2/Modules/selectmodule.c | 1912 -- .../Python-2.7.2/Modules/sha256module.c | 706 - .../Python-2.7.2/Modules/sha512module.c | 774 - .../Python/Python-2.7.2/Modules/shamodule.c | 597 - .../Python-2.7.2/Modules/signalmodule.c | 986 - .../Python-2.7.2/Modules/socketmodule.c | 5454 ----- .../Python-2.7.2/Modules/socketmodule.h | 250 - .../Python/Python-2.7.2/Modules/sre.h | 94 - .../Python-2.7.2/Modules/sre_constants.h | 86 - .../Python/Python-2.7.2/Modules/stropmodule.c | 1270 -- .../Python-2.7.2/Modules/symtablemodule.c | 83 - .../Python-2.7.2/Modules/testcapi_long.h | 182 - .../Python-2.7.2/Modules/threadmodule.c | 931 - .../Python/Python-2.7.2/Modules/timemodule.c | 1054 - .../Python/Python-2.7.2/Modules/timing.h | 64 - .../Python-2.7.2/Modules/timingmodule.c | 62 - .../Python/Python-2.7.2/Modules/unicodedata.c | 1280 -- .../Python-2.7.2/Modules/unicodedata_db.h | 6202 ------ .../Python-2.7.2/Modules/unicodename_db.h | 17259 ---------------- .../Python/Python-2.7.2/Modules/xxmodule.c | 379 - .../Python/Python-2.7.2/Modules/xxsubtype.c | 297 - .../Python/Python-2.7.2/Modules/yuv.h | 99 - .../Python/Python-2.7.2/Modules/yuvconvert.c | 118 - .../Python/Python-2.7.2/Modules/zipimport.c | 1229 -- .../Python-2.7.2/Modules/zlib/ChangeLog | 855 - .../Python/Python-2.7.2/Modules/zlib/FAQ | 339 - .../Python/Python-2.7.2/Modules/zlib/INDEX | 51 - .../Python/Python-2.7.2/Modules/zlib/Makefile | 154 - .../Python-2.7.2/Modules/zlib/Makefile.in | 154 - .../Python/Python-2.7.2/Modules/zlib/README | 125 - .../Python-2.7.2/Modules/zlib/adler32.c | 149 - .../Python-2.7.2/Modules/zlib/algorithm.txt | 209 - .../Python-2.7.2/Modules/zlib/compress.c | 79 - .../Python-2.7.2/Modules/zlib/configure | 459 - .../Python/Python-2.7.2/Modules/zlib/crc32.c | 423 - .../Python/Python-2.7.2/Modules/zlib/crc32.h | 441 - .../Python-2.7.2/Modules/zlib/deflate.c | 1736 -- .../Python-2.7.2/Modules/zlib/deflate.h | 331 - .../Python-2.7.2/Modules/zlib/example.c | 565 - .../Python/Python-2.7.2/Modules/zlib/gzio.c | 1026 - .../Python-2.7.2/Modules/zlib/infback.c | 623 - .../Python-2.7.2/Modules/zlib/inffast.c | 318 - .../Python-2.7.2/Modules/zlib/inffast.h | 11 - .../Python-2.7.2/Modules/zlib/inffixed.h | 94 - .../Python-2.7.2/Modules/zlib/inflate.c | 1368 -- .../Python-2.7.2/Modules/zlib/inflate.h | 115 - .../Python-2.7.2/Modules/zlib/inftrees.c | 329 - .../Python-2.7.2/Modules/zlib/inftrees.h | 55 - .../Python-2.7.2/Modules/zlib/make_vms.com | 461 - .../Python-2.7.2/Modules/zlib/minigzip.c | 322 - .../Python/Python-2.7.2/Modules/zlib/trees.c | 1219 -- .../Python/Python-2.7.2/Modules/zlib/trees.h | 128 - .../Python-2.7.2/Modules/zlib/uncompr.c | 61 - .../Python/Python-2.7.2/Modules/zlib/zconf.h | 332 - .../Python-2.7.2/Modules/zlib/zconf.in.h | 332 - .../Python/Python-2.7.2/Modules/zlib/zlib.3 | 159 - .../Python/Python-2.7.2/Modules/zlib/zlib.h | 1357 -- .../Python/Python-2.7.2/Modules/zlib/zutil.c | 318 - .../Python/Python-2.7.2/Modules/zlib/zutil.h | 277 - .../Python/Python-2.7.2/Modules/zlibmodule.c | 1058 - .../Python/Python-2.7.2/Objects/abstract.c | 3113 --- .../Python/Python-2.7.2/Objects/boolobject.c | 202 - .../Python-2.7.2/Objects/bufferobject.c | 857 - .../Python-2.7.2/Objects/bytearrayobject.c | 3044 --- .../Python-2.7.2/Objects/bytes_methods.c | 398 - .../Python/Python-2.7.2/Objects/capsule.c | 324 - .../Python/Python-2.7.2/Objects/cellobject.c | 145 - .../Python/Python-2.7.2/Objects/classobject.c | 2672 --- .../Python/Python-2.7.2/Objects/cobject.c | 172 - .../Python/Python-2.7.2/Objects/codeobject.c | 581 - .../Python-2.7.2/Objects/complexobject.c | 1353 -- .../Python/Python-2.7.2/Objects/descrobject.c | 1385 -- .../Python/Python-2.7.2/Objects/dictnotes.txt | 270 - .../Python/Python-2.7.2/Objects/dictobject.c | 3210 --- .../Python/Python-2.7.2/Objects/enumobject.c | 381 - .../Python/Python-2.7.2/Objects/exceptions.c | 2215 -- .../Python/Python-2.7.2/Objects/fileobject.c | 2822 --- .../Python/Python-2.7.2/Objects/floatobject.c | 2693 --- .../Python/Python-2.7.2/Objects/frameobject.c | 982 - .../Python/Python-2.7.2/Objects/funcobject.c | 897 - .../Python/Python-2.7.2/Objects/genobject.c | 414 - .../Python/Python-2.7.2/Objects/intobject.c | 1550 -- .../Python/Python-2.7.2/Objects/iterobject.c | 230 - .../Python/Python-2.7.2/Objects/listobject.c | 3044 --- .../Python/Python-2.7.2/Objects/listsort.txt | 677 - .../Python-2.7.2/Objects/lnotab_notes.txt | 124 - .../Python/Python-2.7.2/Objects/longobject.c | 4381 ---- .../Python-2.7.2/Objects/memoryobject.c | 842 - .../Python-2.7.2/Objects/methodobject.c | 427 - .../Python-2.7.2/Objects/moduleobject.c | 260 - .../Python/Python-2.7.2/Objects/object.c | 2455 --- .../Python/Python-2.7.2/Objects/obmalloc.c | 1888 -- .../Python/Python-2.7.2/Objects/rangeobject.c | 322 - .../Python/Python-2.7.2/Objects/setobject.c | 2518 --- .../Python/Python-2.7.2/Objects/sliceobject.c | 361 - .../Python-2.7.2/Objects/stringlib/README.txt | 40 - .../Python-2.7.2/Objects/stringlib/count.h | 30 - .../Python-2.7.2/Objects/stringlib/ctype.h | 109 - .../Objects/stringlib/fastsearch.h | 160 - .../Python-2.7.2/Objects/stringlib/find.h | 175 - .../Objects/stringlib/formatter.h | 1531 -- .../Objects/stringlib/localeutil.h | 227 - .../Objects/stringlib/partition.h | 110 - .../Python-2.7.2/Objects/stringlib/split.h | 394 - .../Objects/stringlib/string_format.h | 1364 -- .../Objects/stringlib/stringdefs.h | 33 - .../Objects/stringlib/transmogrify.h | 264 - .../Objects/stringlib/unicodedefs.h | 37 - .../Python-2.7.2/Objects/stringobject.c | 4824 ----- .../Python/Python-2.7.2/Objects/structseq.c | 539 - .../Python/Python-2.7.2/Objects/tupleobject.c | 1052 - .../Python/Python-2.7.2/Objects/typeobject.c | 6712 ------ .../Python-2.7.2/Objects/unicodectype.c | 215 - .../Python-2.7.2/Objects/unicodeobject.c | 8888 -------- .../Python-2.7.2/Objects/unicodetype_db.h | 3337 --- .../Python-2.7.2/Objects/weakrefobject.c | 975 - .../Python/Python-2.7.2/Parser/Python.asdl | 115 - .../Python/Python-2.7.2/Parser/acceler.c | 125 - .../Python/Python-2.7.2/Parser/asdl.py | 413 - .../Python/Python-2.7.2/Parser/asdl_c.py | 1220 -- .../Python/Python-2.7.2/Parser/bitset.c | 66 - .../Python/Python-2.7.2/Parser/firstsets.c | 113 - .../Python/Python-2.7.2/Parser/grammar.c | 254 - .../Python/Python-2.7.2/Parser/grammar1.c | 57 - .../Python/Python-2.7.2/Parser/intrcheck.c | 178 - .../Python/Python-2.7.2/Parser/listnode.c | 66 - .../Python/Python-2.7.2/Parser/metagrammar.c | 159 - .../Python/Python-2.7.2/Parser/myreadline.c | 221 - .../Python/Python-2.7.2/Parser/node.c | 138 - .../Python/Python-2.7.2/Parser/parser.c | 436 - .../Python/Python-2.7.2/Parser/parser.h | 42 - .../Python/Python-2.7.2/Parser/parsetok.c | 295 - .../Python/Python-2.7.2/Parser/pgen.c | 708 - .../Python/Python-2.7.2/Parser/pgenmain.c | 173 - .../Python/Python-2.7.2/Parser/printgrammar.c | 117 - .../Python/Python-2.7.2/Parser/spark.py | 839 - .../Python/Python-2.7.2/Parser/tokenizer.c | 1726 -- .../Python/Python-2.7.2/Parser/tokenizer.h | 70 - .../Python-2.7.2/Parser/tokenizer_pgen.c | 2 - .../Python/Python-2.7.2/Python/Python-ast.c | 6763 ------ .../Python/Python-2.7.2/Python/_warnings.c | 909 - .../Python/Python-2.7.2/Python/asdl.c | 64 - .../Python/Python-2.7.2/Python/ast.c | 3558 ---- .../Python/Python-2.7.2/Python/atof.c | 50 - .../Python/Python-2.7.2/Python/bltinmodule.c | 3043 --- .../Python/Python-2.7.2/Python/ceval.c | 4895 ----- .../Python/Python-2.7.2/Python/codecs.c | 872 - .../Python/Python-2.7.2/Python/compile.c | 3979 ---- .../Python/Python-2.7.2/Python/dtoa.c | 2918 --- .../Python/Python-2.7.2/Python/dup2.c | 31 - .../Python/Python-2.7.2/Python/dynload_aix.c | 183 - .../Python-2.7.2/Python/dynload_atheos.c | 47 - .../Python/Python-2.7.2/Python/dynload_beos.c | 254 - .../Python/Python-2.7.2/Python/dynload_dl.c | 26 - .../Python/Python-2.7.2/Python/dynload_hpux.c | 58 - .../Python/Python-2.7.2/Python/dynload_next.c | 114 - .../Python/Python-2.7.2/Python/dynload_os2.c | 46 - .../Python-2.7.2/Python/dynload_shlib.c | 143 - .../Python/Python-2.7.2/Python/dynload_stub.c | 11 - .../Python/Python-2.7.2/Python/dynload_win.c | 274 - .../Python/Python-2.7.2/Python/errors.c | 805 - .../Python-2.7.2/Python/formatter_string.c | 17 - .../Python-2.7.2/Python/formatter_unicode.c | 18 - .../Python/Python-2.7.2/Python/frozen.c | 38 - .../Python/Python-2.7.2/Python/frozenmain.c | 68 - .../Python/Python-2.7.2/Python/future.c | 142 - .../Python/Python-2.7.2/Python/getargs.c | 1907 -- .../Python/Python-2.7.2/Python/getcompiler.c | 28 - .../Python/Python-2.7.2/Python/getcopyright.c | 36 - .../Python/Python-2.7.2/Python/getcwd.c | 82 - .../Python/Python-2.7.2/Python/getopt.c | 126 - .../Python/Python-2.7.2/Python/getplatform.c | 12 - .../Python/Python-2.7.2/Python/getversion.c | 15 - .../Python/Python-2.7.2/Python/graminit.c | 2177 -- .../Python/Python-2.7.2/Python/import.c | 3398 --- .../Python/Python-2.7.2/Python/importdl.c | 78 - .../Python/Python-2.7.2/Python/importdl.h | 53 - .../Python-2.7.2/Python/mactoolboxglue.c | 474 - .../Python/Python-2.7.2/Python/marshal.c | 1422 -- .../Python/Python-2.7.2/Python/modsupport.c | 644 - .../Python/Python-2.7.2/Python/mysnprintf.c | 105 - .../Python/Python-2.7.2/Python/mystrtoul.c | 285 - .../Python/Python-2.7.2/Python/peephole.c | 680 - .../Python/Python-2.7.2/Python/pyarena.c | 220 - .../Python/Python-2.7.2/Python/pyctype.c | 214 - .../Python/Python-2.7.2/Python/pyfpe.c | 23 - .../Python/Python-2.7.2/Python/pymath.c | 79 - .../Python/Python-2.7.2/Python/pystate.c | 680 - .../Python/Python-2.7.2/Python/pystrcmp.c | 26 - .../Python/Python-2.7.2/Python/pystrtod.c | 1249 -- .../Python/Python-2.7.2/Python/pythonrun.c | 2004 -- .../Python/Python-2.7.2/Python/sigcheck.c | 19 - .../Python/Python-2.7.2/Python/strdup.c | 14 - .../Python/Python-2.7.2/Python/strtod.c | 159 - .../Python/Python-2.7.2/Python/structmember.c | 363 - .../Python/Python-2.7.2/Python/symtable.c | 1554 -- .../Python/Python-2.7.2/Python/sysmodule.c | 1779 -- .../Python/Python-2.7.2/Python/thread.c | 421 - .../Python-2.7.2/Python/thread_atheos.h | 259 - .../Python/Python-2.7.2/Python/thread_beos.h | 248 - .../Python-2.7.2/Python/thread_cthread.h | 112 - .../Python-2.7.2/Python/thread_foobar.h | 75 - .../Python/Python-2.7.2/Python/thread_lwp.h | 113 - .../Python/Python-2.7.2/Python/thread_nt.h | 359 - .../Python/Python-2.7.2/Python/thread_os2.h | 267 - .../Python/Python-2.7.2/Python/thread_pth.h | 178 - .../Python-2.7.2/Python/thread_pthread.h | 505 - .../Python/Python-2.7.2/Python/thread_sgi.h | 259 - .../Python-2.7.2/Python/thread_solaris.h | 130 - .../Python/Python-2.7.2/Python/thread_wince.h | 136 - .../Python/Python-2.7.2/Python/traceback.c | 283 - .../Applications/Python/Python-2.7.2/README | 1229 -- .../Python/Python-2.7.2/Tools/README | 41 - .../Python/Python-2.7.2/Tools/bgen/README | 9 - .../Python-2.7.2/Tools/bgen/bgen/bgen.py | 12 - .../Tools/bgen/bgen/bgenBuffer.py | 301 - .../Tools/bgen/bgen/bgenGenerator.py | 302 - .../Tools/bgen/bgen/bgenGeneratorGroup.py | 40 - .../Tools/bgen/bgen/bgenHeapBuffer.py | 145 - .../Tools/bgen/bgen/bgenModule.py | 94 - .../Tools/bgen/bgen/bgenObjectDefinition.py | 512 - .../Tools/bgen/bgen/bgenOutput.py | 219 - .../Tools/bgen/bgen/bgenStackBuffer.py | 62 - .../Tools/bgen/bgen/bgenStringBuffer.py | 67 - .../Python-2.7.2/Tools/bgen/bgen/bgenType.py | 328 - .../Tools/bgen/bgen/bgenVariable.py | 112 - .../Tools/bgen/bgen/macsupport.py | 197 - .../Python-2.7.2/Tools/bgen/bgen/scantools.py | 849 - .../Tools/buildbot/README.tcltk-AMD64 | 36 - .../Tools/buildbot/build-amd64.bat | 6 - .../Python-2.7.2/Tools/buildbot/build.bat | 7 - .../Python-2.7.2/Tools/buildbot/buildmsi.bat | 20 - .../Tools/buildbot/clean-amd64.bat | 10 - .../Python-2.7.2/Tools/buildbot/clean.bat | 10 - .../Tools/buildbot/external-amd64.bat | 20 - .../Tools/buildbot/external-common.bat | 45 - .../Python-2.7.2/Tools/buildbot/external.bat | 21 - .../Tools/buildbot/test-amd64.bat | 3 - .../Python-2.7.2/Tools/buildbot/test.bat | 3 - .../Python-2.7.2/Tools/ccbench/ccbench.py | 609 - .../Python/Python-2.7.2/Tools/compiler/ACKS | 8 - .../Python/Python-2.7.2/Tools/compiler/README | 18 - .../Python-2.7.2/Tools/compiler/ast.txt | 104 - .../Python-2.7.2/Tools/compiler/astgen.py | 294 - .../Python-2.7.2/Tools/compiler/compile.py | 51 - .../Python-2.7.2/Tools/compiler/demo.py | 38 - .../Python-2.7.2/Tools/compiler/dumppyc.py | 46 - .../Python-2.7.2/Tools/compiler/regrtest.py | 78 - .../Python-2.7.2/Tools/compiler/stacktest.py | 43 - .../Python/Python-2.7.2/Tools/faqwiz/README | 114 - .../Python-2.7.2/Tools/faqwiz/faqconf.py | 577 - .../Python-2.7.2/Tools/faqwiz/faqcust.py | 1 - .../Python/Python-2.7.2/Tools/faqwiz/faqw.py | 33 - .../Python-2.7.2/Tools/faqwiz/faqwiz.py | 841 - .../Python-2.7.2/Tools/faqwiz/move-faqwiz.sh | 55 - .../Python-2.7.2/Tools/framer/README.txt | 8 - .../Python/Python-2.7.2/Tools/framer/TODO.txt | 6 - .../Python-2.7.2/Tools/framer/example.py | 126 - .../Tools/framer/framer/__init__.py | 6 - .../Python-2.7.2/Tools/framer/framer/bases.py | 220 - .../Tools/framer/framer/function.py | 173 - .../Tools/framer/framer/member.py | 73 - .../Python-2.7.2/Tools/framer/framer/slots.py | 64 - .../Tools/framer/framer/struct.py | 52 - .../Tools/framer/framer/structparse.py | 46 - .../Tools/framer/framer/template.py | 102 - .../Python-2.7.2/Tools/framer/framer/util.py | 35 - .../Python/Python-2.7.2/Tools/freeze/README | 296 - .../Python-2.7.2/Tools/freeze/bkfile.py | 47 - .../Tools/freeze/checkextensions.py | 90 - .../Tools/freeze/checkextensions_win32.py | 188 - .../Tools/freeze/extensions_win32.ini | 171 - .../Python-2.7.2/Tools/freeze/freeze.py | 497 - .../Python/Python-2.7.2/Tools/freeze/hello.py | 1 - .../Python-2.7.2/Tools/freeze/makeconfig.py | 60 - .../Python-2.7.2/Tools/freeze/makefreeze.py | 90 - .../Python-2.7.2/Tools/freeze/makemakefile.py | 29 - .../Python-2.7.2/Tools/freeze/parsesetup.py | 112 - .../Python-2.7.2/Tools/freeze/win32.html | 119 - .../Tools/freeze/winmakemakefile.py | 147 - .../Python-2.7.2/Tools/gdb/libpython.py | 1447 -- .../Tools/i18n/makelocalealias.py | 73 - .../Python/Python-2.7.2/Tools/i18n/msgfmt.py | 226 - .../Python-2.7.2/Tools/i18n/pygettext.py | 669 - .../Python-2.7.2/Tools/iobench/iobench.py | 539 - .../Python/Python-2.7.2/Tools/msi/README.txt | 25 - .../Python-2.7.2/Tools/msi/crtlicense.txt | 44 - .../Python/Python-2.7.2/Tools/msi/msi.py | 1398 -- .../Python/Python-2.7.2/Tools/msi/msilib.py | 692 - .../Python-2.7.2/Tools/msi/msisupport.c | 93 - .../Python-2.7.2/Tools/msi/msisupport.mak | 9 - .../Python/Python-2.7.2/Tools/msi/schema.py | 1007 - .../Python/Python-2.7.2/Tools/msi/sequence.py | 126 - .../Python/Python-2.7.2/Tools/msi/uisample.py | 1400 -- .../Python/Python-2.7.2/Tools/msi/uuids.py | 58 - .../Python-2.7.2/Tools/pybench/Arithmetic.py | 777 - .../Python-2.7.2/Tools/pybench/Calls.py | 560 - .../Python-2.7.2/Tools/pybench/CommandLine.py | 634 - .../Python-2.7.2/Tools/pybench/Constructs.py | 564 - .../Python/Python-2.7.2/Tools/pybench/Dict.py | 504 - .../Python-2.7.2/Tools/pybench/Exceptions.py | 699 - .../Python-2.7.2/Tools/pybench/Imports.py | 138 - .../Python-2.7.2/Tools/pybench/Instances.py | 66 - .../Python/Python-2.7.2/Tools/pybench/LICENSE | 25 - .../Python-2.7.2/Tools/pybench/Lists.py | 350 - .../Python-2.7.2/Tools/pybench/Lookups.py | 945 - .../Tools/pybench/NewInstances.py | 75 - .../Python-2.7.2/Tools/pybench/Numbers.py | 784 - .../Python/Python-2.7.2/Tools/pybench/README | 368 - .../Python-2.7.2/Tools/pybench/Setup.py | 43 - .../Python-2.7.2/Tools/pybench/Strings.py | 562 - .../Python-2.7.2/Tools/pybench/Tuples.py | 360 - .../Python-2.7.2/Tools/pybench/Unicode.py | 542 - .../Python/Python-2.7.2/Tools/pybench/With.py | 190 - .../Python-2.7.2/Tools/pybench/clockres.py | 43 - .../Tools/pybench/package/__init__.py | 0 .../Tools/pybench/package/submodule.py | 0 .../Python-2.7.2/Tools/pybench/pybench.py | 961 - .../Python-2.7.2/Tools/pybench/systimes.py | 211 - .../Python/Python-2.7.2/Tools/scripts/2to3 | 5 - .../Python/Python-2.7.2/Tools/scripts/README | 69 - .../Python-2.7.2/Tools/scripts/analyze_dxp.py | 129 - .../Python-2.7.2/Tools/scripts/byext.py | 131 - .../Python-2.7.2/Tools/scripts/byteyears.py | 61 - .../Python-2.7.2/Tools/scripts/checkappend.py | 167 - .../Python-2.7.2/Tools/scripts/checkpyc.py | 66 - .../Python-2.7.2/Tools/scripts/classfix.py | 190 - .../Python-2.7.2/Tools/scripts/cleanfuture.py | 276 - .../Python-2.7.2/Tools/scripts/combinerefs.py | 127 - .../Python-2.7.2/Tools/scripts/copytime.py | 26 - .../Python/Python-2.7.2/Tools/scripts/crlf.py | 23 - .../Python-2.7.2/Tools/scripts/cvsfiles.py | 72 - .../Python-2.7.2/Tools/scripts/db2pickle.py | 135 - .../Python/Python-2.7.2/Tools/scripts/diff.py | 49 - .../Python-2.7.2/Tools/scripts/dutree.doc | 54 - .../Python-2.7.2/Tools/scripts/dutree.py | 60 - .../Python-2.7.2/Tools/scripts/eptags.py | 56 - .../Tools/scripts/find_recursionlimit.py | 117 - .../Python-2.7.2/Tools/scripts/finddiv.py | 89 - .../Python-2.7.2/Tools/scripts/findlinksto.py | 43 - .../Tools/scripts/findnocoding.py | 104 - .../Python-2.7.2/Tools/scripts/fixcid.py | 314 - .../Python-2.7.2/Tools/scripts/fixdiv.py | 380 - .../Python-2.7.2/Tools/scripts/fixheader.py | 49 - .../Python-2.7.2/Tools/scripts/fixnotice.py | 113 - .../Python-2.7.2/Tools/scripts/fixps.py | 33 - .../Python-2.7.2/Tools/scripts/ftpmirror.py | 400 - .../Python-2.7.2/Tools/scripts/google.py | 23 - .../Python-2.7.2/Tools/scripts/gprof2html.py | 79 - .../Python/Python-2.7.2/Tools/scripts/h2py.py | 175 - .../Python-2.7.2/Tools/scripts/hotshotmain.py | 55 - .../Python/Python-2.7.2/Tools/scripts/idle | 5 - .../Python-2.7.2/Tools/scripts/ifdef.py | 112 - .../Python/Python-2.7.2/Tools/scripts/lfcr.py | 24 - .../Python-2.7.2/Tools/scripts/linktree.py | 80 - .../Python/Python-2.7.2/Tools/scripts/lll.py | 28 - .../Python-2.7.2/Tools/scripts/logmerge.py | 185 - .../Tools/scripts/mailerdaemon.py | 237 - .../Python-2.7.2/Tools/scripts/md5sum.py | 90 - .../Python-2.7.2/Tools/scripts/methfix.py | 171 - .../Python-2.7.2/Tools/scripts/mkreal.py | 66 - .../Python-2.7.2/Tools/scripts/ndiff.py | 133 - .../Python-2.7.2/Tools/scripts/nm2def.py | 103 - .../Python-2.7.2/Tools/scripts/objgraph.py | 215 - .../Tools/scripts/parseentities.py | 64 - .../Python-2.7.2/Tools/scripts/patchcheck.py | 158 - .../Python-2.7.2/Tools/scripts/pathfix.py | 149 - .../Python-2.7.2/Tools/scripts/pdeps.py | 167 - .../Python-2.7.2/Tools/scripts/pickle2db.py | 147 - .../Python-2.7.2/Tools/scripts/pindent.py | 542 - .../Python-2.7.2/Tools/scripts/ptags.py | 53 - .../Python/Python-2.7.2/Tools/scripts/pydoc | 5 - .../Python-2.7.2/Tools/scripts/pydocgui.pyw | 7 - .../Python-2.7.2/Tools/scripts/pysource.py | 130 - .../Python-2.7.2/Tools/scripts/redemo.py | 171 - .../Tools/scripts/reindent-rst.py | 14 - .../Python-2.7.2/Tools/scripts/reindent.py | 304 - .../Python-2.7.2/Tools/scripts/rgrep.py | 64 - .../Python-2.7.2/Tools/scripts/serve.py | 35 - .../Python-2.7.2/Tools/scripts/setup.py | 20 - .../Python/Python-2.7.2/Tools/scripts/suff.py | 30 - .../Python-2.7.2/Tools/scripts/svneol.py | 91 - .../Python-2.7.2/Tools/scripts/texcheck.py | 233 - .../Python-2.7.2/Tools/scripts/texi2html.py | 2078 -- .../Python-2.7.2/Tools/scripts/treesync.py | 205 - .../Python-2.7.2/Tools/scripts/untabify.py | 52 - .../Python-2.7.2/Tools/scripts/which.py | 60 - .../Tools/scripts/win_add2path.py | 57 - .../Python/Python-2.7.2/Tools/scripts/xxci.py | 116 - .../Tools/ssl/get-remote-certificate.py | 79 - .../Python-2.7.2/Tools/unicode/Makefile | 84 - .../Tools/unicode/comparecodecs.py | 53 - .../Tools/unicode/gencjkcodecs.py | 68 - .../Python-2.7.2/Tools/unicode/gencodec.py | 423 - .../Python-2.7.2/Tools/unicode/genwincodec.py | 61 - .../Tools/unicode/genwincodecs.bat | 7 - .../Python-2.7.2/Tools/unicode/listcodecs.py | 41 - .../Tools/unicode/makeunicodedata.py | 1135 - .../Tools/unicode/mkstringprep.py | 425 - .../Tools/unicode/python-mappings/CP1140.TXT | 291 - .../Tools/unicode/python-mappings/KOI8-U.TXT | 298 - .../Tools/unicode/python-mappings/TIS-620.TXT | 284 - .../Python-2.7.2/Tools/versioncheck/README | 41 - .../Tools/versioncheck/_checkversion.py | 16 - .../Tools/versioncheck/checkversions.py | 52 - .../Tools/versioncheck/pyversioncheck.py | 98 - .../Python-2.7.2/Tools/webchecker/README | 23 - .../Python-2.7.2/Tools/webchecker/tktools.py | 366 - .../Python-2.7.2/Tools/webchecker/wcgui.py | 456 - .../Python-2.7.2/Tools/webchecker/wcmac.py | 7 - .../Tools/webchecker/webchecker.py | 892 - .../Tools/webchecker/websucker.py | 123 - .../Python-2.7.2/Tools/webchecker/wsgui.py | 240 - .../Python/Python-2.7.2/Tools/world/README | 85 - .../Python/Python-2.7.2/Tools/world/world | 551 - AppPkg/Applications/Python/PythonCore.inf | 248 - AppPkg/Applications/Python/X64/pyconfig.h | 1301 -- 2134 files changed, 1 insertion(+), 911901 deletions(-) delete mode 100644 AppPkg/Applications/Python/Efi/config.c delete mode 100644 AppPkg/Applications/Python/Efi/edk2module.c delete mode 100644 AppPkg/Applications/Python/Efi/getpath.c delete mode 100644 AppPkg/Applications/Python/Ia32/pyconfig.h delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Include/fileobject.h delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Include/osdefs.h delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Include/pyport.h delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Lib/ntpath.py delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Lib/os.py delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Lib/pydoc.py delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Lib/site.py delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Modules/_sre.c delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Modules/addrinfo.h delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Modules/errnomodule.c delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/expat_external.h delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/xmlparse.c delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Modules/main.c delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Modules/selectmodule.c delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Modules/socketmodule.h delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Modules/zlib/zutil.h delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Objects/longobject.c delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Objects/stringlib/localeutil.h delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Python/getcopyright.c delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Python/import.c delete mode 100644 AppPkg/Applications/Python/PyMod-2.7.2/Python/marshal.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi0.sh delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi1.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi3.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/wiki.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Complex.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Dates.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Dbm.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/classes/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Range.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Rev.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Vec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/classes/bitvec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/patterns delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/regextest.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/sortingtest.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/systemtest.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/foo delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/md5driver.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Eiffel.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Enum.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Meta.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Simple.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Synch.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Trace.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/index.html delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/meta-vladimir.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/newmetaclasses/Eiffel.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/newmetaclasses/Enum.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/parser/FILES delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/parser/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/parser/docstring.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/parser/example.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/parser/simple.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/parser/source.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/parser/test_parser.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/parser/test_unparse.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/parser/unparse.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/FSProxy.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/RCSProxy.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/client.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cmdfw.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cmptree.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cvslib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cvslock.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/mac.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/makechangelog.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcsbump delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcsclient.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcslib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcvs delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcvs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rrcs delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rrcs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/security.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/server.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/sumtree.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/beer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/eqfix.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/fact.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/find-uname.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/from.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/lpwatch.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/makedir.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/markov.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/mboxconvert.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/morse.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/newslist.doc delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/newslist.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/pi.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/pp.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/primes.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/queens.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/script.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/unbirthday.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/update.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/broadcast.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/echosvr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/finger.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/ftp.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/gopher.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/mcast.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/radio.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/rpython.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/rpythond.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/telnet.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/throughput.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/udpecho.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/unicast.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/unixclient.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/unixserver.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/xml/elem_count.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/xml/roundtrip.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/xml/rss2html.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/zlib/minigzip.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Demo/zlib/zlibdemo.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Grammar/Grammar delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/Python-ast.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/Python.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/abstract.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/asdl.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/ast.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/bitset.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/boolobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/bufferobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/bytearrayobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/bytes_methods.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/bytesobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/cStringIO.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/cellobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/ceval.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/classobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/cobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/code.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/codecs.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/compile.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/complexobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/datetime.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/descrobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/dictobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/dtoa.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/enumobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/errcode.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/eval.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/fileobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/floatobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/frameobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/funcobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/genobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/graminit.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/grammar.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/import.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/intobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/intrcheck.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/iterobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/listobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/longintrepr.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/longobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/marshal.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/memoryobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/metagrammar.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/methodobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/modsupport.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/moduleobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/node.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/object.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/objimpl.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/opcode.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/osdefs.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/parsetok.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/patchlevel.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pgen.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pgenheaders.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/py_curses.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pyarena.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pycapsule.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pyctype.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pydebug.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pyerrors.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pyexpat.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pyfpe.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pygetopt.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pymacconfig.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pymactoolbox.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pymath.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pymem.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pyport.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pystate.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pystrcmp.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pystrtod.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pythonrun.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/pythread.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/rangeobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/setobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/sliceobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/stringobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/structmember.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/structseq.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/symtable.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/sysmodule.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/timefuncs.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/token.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/traceback.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/tupleobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/ucnhash.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/unicodeobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/warnings.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Include/weakrefobject.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/LICENSE delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/BaseHTTPServer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/Bastion.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/CGIHTTPServer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/ConfigParser.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/Cookie.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/DocXMLRPCServer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/HTMLParser.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/MimeWriter.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/Queue.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/SimpleHTTPServer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/SimpleXMLRPCServer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/SocketServer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/StringIO.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/UserDict.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/UserList.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/UserString.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/_LWPCookieJar.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/_MozillaCookieJar.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/__future__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/__phello__.foo.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/_abcoll.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/_pyio.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/_strptime.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/_weakrefset.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/abc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/aifc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/antigravity.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/anydbm.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/argparse.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/ast.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/asynchat.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/asyncore.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/atexit.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/base64.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/bdb.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/binhex.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/bisect.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/cProfile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/calendar.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/cgi.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/cgitb.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/chunk.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/cmd.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/code.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/codecs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/codeop.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/collections.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/colorsys.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/commands.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/compileall.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/compiler/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/compiler/ast.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/compiler/consts.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/compiler/future.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/compiler/misc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/compiler/pyassem.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/compiler/pycodegen.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/compiler/symbols.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/compiler/syntax.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/compiler/transformer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/compiler/visitor.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/contextlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/cookielib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/copy.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/copy_reg.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/csv.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/dbhash.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/decimal.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/difflib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/dircache.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/dis.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/archive_util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/bcppcompiler.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/ccompiler.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/cmd.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/bdist.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/bdist_dumb.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/bdist_msi.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/bdist_rpm.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/bdist_wininst.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/build.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/build_clib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/build_ext.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/build_py.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/build_scripts.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/check.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/clean.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/command_template delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/config.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/install.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/install_data.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/install_egg_info.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/install_headers.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/install_lib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/install_scripts.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/register.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/sdist.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/upload.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/wininst-6.0.exe delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/wininst-7.1.exe delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/wininst-8.0.exe delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/wininst-9.0-amd64.exe delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/command/wininst-9.0.exe delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/config.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/core.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/cygwinccompiler.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/debug.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/dep_util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/dir_util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/dist.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/emxccompiler.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/errors.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/extension.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/fancy_getopt.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/file_util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/filelist.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/log.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/msvc9compiler.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/msvccompiler.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/spawn.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/sysconfig.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/Setup.sample delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/setuptools_build_ext.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/setuptools_extension.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/support.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_archive_util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_bdist.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_bdist_dumb.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_bdist_msi.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_bdist_rpm.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_bdist_wininst.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_build.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_build_clib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_build_ext.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_build_py.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_build_scripts.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_ccompiler.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_check.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_clean.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_cmd.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_config.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_config_cmd.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_core.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_dep_util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_dir_util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_dist.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_file_util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_filelist.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_install.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_install_data.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_install_headers.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_install_lib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_install_scripts.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_msvc9compiler.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_register.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_sdist.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_spawn.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_sysconfig.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_text_file.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_unixccompiler.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_upload.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_version.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/tests/test_versionpredicate.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/text_file.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/unixccompiler.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/version.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/versionpredicate.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/doctest.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/dumbdbm.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/dummy_thread.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/dummy_threading.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/_parseaddr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/base64mime.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/charset.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/encoders.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/errors.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/feedparser.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/generator.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/header.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/iterators.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/message.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/mime/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/mime/application.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/mime/audio.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/mime/base.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/mime/image.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/mime/message.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/mime/multipart.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/mime/nonmultipart.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/mime/text.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/parser.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/quoprimime.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/PyBanner048.gif delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/audiotest.au delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_01.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_02.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_03.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_04.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_05.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_06.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_07.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_08.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_09.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_10.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_11.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_12.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_12a.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_13.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_14.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_15.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_16.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_17.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_18.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_19.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_20.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_21.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_22.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_23.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_24.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_25.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_26.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_27.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_28.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_29.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_30.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_31.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_32.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_33.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_34.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_35.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_36.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_37.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_38.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_39.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_40.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_41.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_42.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_43.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_44.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_45.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/data/msg_46.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/test_email.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/test_email_codecs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/test_email_codecs_renamed.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/test_email_renamed.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/test/test_email_torture.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/email/utils.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/aliases.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/ascii.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/base64_codec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/big5.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/big5hkscs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/bz2_codec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/charmap.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp037.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp1006.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp1026.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp1140.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp1250.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp1251.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp1252.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp1253.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp1254.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp1255.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp1256.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp1257.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp1258.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp424.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp437.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp500.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp720.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp737.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp775.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp850.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp852.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp855.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp856.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp857.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp858.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp860.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp861.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp862.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp863.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp864.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp865.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp866.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp869.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp874.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp875.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp932.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp949.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/cp950.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/euc_jis_2004.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/euc_jisx0213.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/euc_jp.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/euc_kr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/gb18030.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/gb2312.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/gbk.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/hex_codec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/hp_roman8.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/hz.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/idna.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso2022_jp.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso2022_jp_1.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso2022_jp_2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso2022_jp_2004.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso2022_jp_3.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso2022_jp_ext.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso2022_kr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_1.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_10.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_11.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_13.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_14.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_15.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_16.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_3.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_4.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_5.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_6.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_7.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_8.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/iso8859_9.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/johab.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/koi8_r.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/koi8_u.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/latin_1.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/mac_arabic.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/mac_centeuro.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/mac_croatian.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/mac_cyrillic.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/mac_farsi.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/mac_greek.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/mac_iceland.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/mac_latin2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/mac_roman.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/mac_romanian.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/mac_turkish.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/mbcs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/palmos.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/ptcp154.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/punycode.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/quopri_codec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/raw_unicode_escape.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/rot_13.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/shift_jis.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/shift_jis_2004.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/shift_jisx0213.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/string_escape.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/tis_620.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/undefined.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/unicode_escape.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/unicode_internal.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/utf_16.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/utf_16_be.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/utf_16_le.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/utf_32.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/utf_32_be.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/utf_32_le.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/utf_7.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/utf_8.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/utf_8_sig.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/uu_codec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/encodings/zlib_codec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/filecmp.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/fileinput.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/fnmatch.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/formatter.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/fpformat.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/fractions.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/ftplib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/functools.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/genericpath.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/getopt.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/getpass.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/gettext.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/glob.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/gzip.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/hashlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/heapq.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/hmac.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/hotshot/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/hotshot/log.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/hotshot/stats.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/hotshot/stones.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/htmlentitydefs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/htmllib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/httplib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/ihooks.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/imaplib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/imghdr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/importlib/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/imputil.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/inspect.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/io.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/decoder.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/encoder.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/scanner.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_check_circular.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_decode.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_default.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_dump.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_encode_basestring_ascii.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_fail.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_float.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_indent.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_pass1.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_pass2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_pass3.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_recursion.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_scanstring.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_separators.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_speedups.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tests/test_unicode.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/json/tool.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/keyword.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/Grammar.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/PatternGrammar.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/__main__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/btm_matcher.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/btm_utils.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixer_base.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixer_util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_apply.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_basestring.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_buffer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_callable.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_dict.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_except.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_exec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_execfile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_exitfunc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_filter.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_funcattrs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_future.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_getcwdu.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_has_key.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_idioms.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_import.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_imports.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_imports2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_input.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_intern.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_isinstance.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_itertools.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_itertools_imports.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_long.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_map.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_metaclass.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_methodattrs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_ne.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_next.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_nonzero.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_numliterals.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_operator.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_paren.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_print.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_raise.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_raw_input.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_reduce.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_renames.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_repr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_set_literal.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_standarderror.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_sys_exc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_throw.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_tuple_params.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_types.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_unicode.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_urllib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_ws_comma.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_xrange.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_xreadlines.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/fixes/fix_zip.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/main.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/patcomp.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/pgen2/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/pgen2/conv.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/pgen2/driver.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/pgen2/grammar.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/pgen2/literals.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/pgen2/parse.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/pgen2/pgen.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/pgen2/token.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/pgen2/tokenize.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/pygram.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/pytree.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/refactor.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/bom.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/crlf.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/different_encoding.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/fixers/bad_order.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/fixers/myfixes/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/fixers/myfixes/fix_explicit.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/fixers/myfixes/fix_first.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/fixers/myfixes/fix_last.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/fixers/myfixes/fix_parrot.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/fixers/myfixes/fix_preorder.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/fixers/no_fixer_cls.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/fixers/parrot_example.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/infinite_recursion.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/py2_test_grammar.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/data/py3_test_grammar.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/pytree_idempotency.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/support.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/test_all_fixers.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/test_fixers.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/test_main.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/test_parser.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/test_pytree.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/test_refactor.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/lib2to3/tests/test_util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/linecache.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/locale.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/logging/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/logging/config.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/logging/handlers.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/mailbox.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/mailcap.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/markupbase.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/md5.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/mhlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/mimetools.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/mimetypes.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/mimify.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/modulefinder.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/multifile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/mutex.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/netrc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/new.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/nntplib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/ntpath.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/nturl2path.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/numbers.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/opcode.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/optparse.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/os.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/pdb.doc delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/pdb.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/pickle.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/pickletools.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/pipes.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/pkgutil.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/platform.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/plistlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/popen2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/poplib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/posixfile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/posixpath.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/pprint.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/profile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/pstats.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/pty.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/py_compile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/pyclbr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/pydoc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/pydoc_data/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/pydoc_data/topics.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/quopri.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/random.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/re.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/repr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/rexec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/rfc822.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/rlcompleter.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/robotparser.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/runpy.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/sched.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/sets.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/sgmllib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/sha.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/shelve.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/shlex.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/shutil.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/site-packages/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/site.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/smtpd.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/smtplib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/sndhdr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/socket.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/sre.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/sre_compile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/sre_constants.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/sre_parse.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/ssl.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/stat.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/statvfs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/string.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/stringold.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/stringprep.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/struct.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/symbol.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/symtable.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/sysconfig.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/tabnanny.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/tarfile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/telnetlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/tempfile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/185test.db delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/Sine-1000Hz-300ms.aif delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/audiotest.au delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/autotest.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/bad_coding.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/bad_coding2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/badcert.pem delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/badkey.pem delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/badsyntax_future3.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/badsyntax_future4.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/badsyntax_future5.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/badsyntax_future6.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/badsyntax_future7.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/badsyntax_future8.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/badsyntax_future9.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/badsyntax_nocaret.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/buffer_tests.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cfgparser.1 delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/check_soundcard.vbs delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/big5-utf8.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/big5.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/big5hkscs-utf8.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/big5hkscs.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/cp949-utf8.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/cp949.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/euc_jisx0213-utf8.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/euc_jisx0213.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/euc_jp-utf8.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/euc_jp.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/euc_kr-utf8.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/euc_kr.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/gb18030-utf8.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/gb18030.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/gb2312-utf8.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/gb2312.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/gbk-utf8.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/gbk.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/hz-utf8.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/hz.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/johab-utf8.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/johab.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/shift_jis-utf8.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/shift_jis.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/shift_jisx0213-utf8.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cjkencodings/shift_jisx0213.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/cmath_testcases.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/crashers/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/crashers/bogus_code_obj.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/crashers/borrowed_ref_1.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/crashers/borrowed_ref_2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/crashers/compiler_recursion.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/crashers/gc_has_finalizer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/crashers/gc_inspection.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/crashers/infinite_loop_re.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/crashers/loosing_mro_ref.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/crashers/mutation_inside_cyclegc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/crashers/nasty_eq_vs_dict.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/crashers/recursion_limit_too_high.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/crashers/recursive_call.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/curses_tests.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/data/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/abs.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/add.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/and.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/base.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/clamp.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/class.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/compare.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/comparetotal.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/comparetotmag.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/copy.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/copyabs.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/copynegate.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/copysign.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddAbs.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddAdd.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddAnd.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddBase.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddCanonical.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddClass.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddCompare.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddCompareSig.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddCompareTotal.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddCompareTotalMag.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddCopy.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddCopyAbs.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddCopyNegate.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddCopySign.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddDivide.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddDivideInt.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddEncode.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddFMA.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddInvert.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddLogB.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddMax.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddMaxMag.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddMin.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddMinMag.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddMinus.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddMultiply.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddNextMinus.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddNextPlus.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddNextToward.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddOr.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddPlus.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddQuantize.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddReduce.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddRemainder.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddRemainderNear.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddRotate.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddSameQuantum.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddScaleB.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddShift.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddSubtract.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddToIntegral.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ddXor.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/decDouble.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/decQuad.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/decSingle.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/divide.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/divideint.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqAbs.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqAdd.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqAnd.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqBase.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqCanonical.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqClass.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqCompare.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqCompareSig.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqCompareTotal.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqCompareTotalMag.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqCopy.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqCopyAbs.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqCopyNegate.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqCopySign.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqDivide.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqDivideInt.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqEncode.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqFMA.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqInvert.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqLogB.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqMax.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqMaxMag.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqMin.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqMinMag.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqMinus.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqMultiply.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqNextMinus.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqNextPlus.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqNextToward.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqOr.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqPlus.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqQuantize.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqReduce.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqRemainder.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqRemainderNear.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqRotate.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqSameQuantum.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqScaleB.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqShift.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqSubtract.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqToIntegral.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dqXor.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dsBase.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/dsEncode.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/exp.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/extra.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/fma.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/inexact.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/invert.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/ln.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/log10.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/logb.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/max.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/maxmag.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/min.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/minmag.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/minus.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/multiply.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/nextminus.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/nextplus.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/nexttoward.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/or.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/plus.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/power.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/powersqrt.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/quantize.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/randomBound32.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/randoms.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/reduce.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/remainder.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/remainderNear.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/rescale.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/rotate.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/rounding.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/samequantum.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/scaleb.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/shift.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/squareroot.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/subtract.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/testall.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/tointegral.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/tointegralx.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/decimaltestdata/xor.decTest delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/doctest_aliases.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/double_const.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/empty.vbs delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/exception_hierarchy.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/floating_points.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/fork_wait.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/formatfloat_testcases.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/gdb_sample.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/greyrgb.uue delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/https_svn_python_org_root.pem delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/ieee754.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/infinite_reload.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/inspect_fodder.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/inspect_fodder2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/keycert.pem delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/leakers/README.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/leakers/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/leakers/test_ctypes.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/leakers/test_dictself.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/leakers/test_gestalt.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/leakers/test_selftype.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/list_tests.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/lock_tests.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/mapping_tests.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/math_testcases.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/nullcert.pem delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/outstanding_bugs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/pickletester.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/profilee.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/pyclbr_input.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/pydoc_mod.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/pydocfodder.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/pystone.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/randv2_32.pck delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/randv2_64.pck delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/randv3.pck delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/re_tests.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/regex_tests.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/regrtest.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/relimport.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/reperf.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/sample_doctest.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/script_helper.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/seq_tests.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/sgml_input.html delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/sha256.pem delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/sortperf.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/ssl_cert.pem delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/ssl_key.pem delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/string_tests.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/subprocessdata/sigchild_ignore.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/svn_python_org_https_cert.pem delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_MimeWriter.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_SimpleHTTPServer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_StringIO.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test___all__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test___future__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test__locale.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_abc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_abstract_numbers.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_aepack.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_aifc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_al.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_anydbm.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_applesingle.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_argparse.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_array.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_ascii_formatd.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_ast.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_asynchat.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_asyncore.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_atexit.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_audioop.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_augassign.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_base64.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_bastion.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_bigaddrspace.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_bigmem.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_binascii.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_binhex.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_binop.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_bisect.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_bool.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_bsddb.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_bsddb185.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_bsddb3.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_buffer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_bufio.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_builtin.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_bytes.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_bz2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_calendar.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_call.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_capi.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_cd.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_cfgparser.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_cgi.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_charmapcodec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_cl.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_class.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_cmath.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_cmd.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_cmd_line.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_cmd_line_script.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_code.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_codeccallbacks.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_codecencodings_cn.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_codecencodings_hk.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_codecencodings_jp.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_codecencodings_kr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_codecencodings_tw.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_codecmaps_cn.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_codecmaps_hk.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_codecmaps_jp.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_codecmaps_kr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_codecmaps_tw.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_codecs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_codeop.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_coding.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_coercion.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_collections.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_colorsys.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_commands.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_compare.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_compile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_compileall.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_compiler.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_complex.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_complex_args.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_contains.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_contextlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_cookie.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_cookielib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_copy.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_copy_reg.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_cpickle.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_cprofile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_crypt.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_csv.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_ctypes.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_curses.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_datetime.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_dbm.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_decimal.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_decorators.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_defaultdict.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_deque.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_descr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_descrtut.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_dict.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_dictcomps.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_dictviews.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_difflib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_difflib_expect.html delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_dircache.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_dis.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_distutils.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_dl.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_doctest.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_doctest.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_doctest2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_doctest2.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_doctest3.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_doctest4.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_docxmlrpc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_dumbdbm.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_dummy_thread.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_dummy_threading.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_email.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_email_codecs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_email_renamed.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_enumerate.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_eof.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_epoll.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_errno.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_exception_variations.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_exceptions.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_extcall.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_fcntl.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_file.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_file2k.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_filecmp.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_fileinput.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_fileio.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_float.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_fnmatch.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_fork1.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_format.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_fpformat.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_fractions.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_frozen.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_ftplib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_funcattrs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_functools.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_future.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_future1.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_future2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_future3.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_future4.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_future5.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_future_builtins.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_gc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_gdb.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_gdbm.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_generators.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_genericpath.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_genexps.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_getargs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_getargs2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_getopt.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_gettext.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_gl.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_glob.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_global.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_grammar.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_grp.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_gzip.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_hash.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_hashlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_heapq.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_hmac.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_hotshot.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_htmllib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_htmlparser.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_httplib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_httpservers.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_imageop.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_imaplib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_imgfile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_imp.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_import.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_importhooks.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_importlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_index.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_inspect.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_int.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_int_literal.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_io.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_ioctl.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_isinstance.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_iter.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_iterlen.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_itertools.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_json.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_kqueue.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_largefile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_lib2to3.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_linecache.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_linuxaudiodev.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_list.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_locale.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_logging.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_long.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_long_future.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_longexp.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_macos.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_macostools.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_macpath.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_mailbox.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_marshal.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_math.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_md5.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_memoryio.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_memoryview.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_mhlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_mimetools.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_mimetypes.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_minidom.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_mmap.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_module.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_modulefinder.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_msilib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_multibytecodec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_multibytecodec_support.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_multifile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_multiprocessing.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_mutants.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_mutex.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_netrc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_new.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_nis.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_normalization.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_ntpath.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_old_mailbox.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_opcodes.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_openpty.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_operator.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_optparse.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_os.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_ossaudiodev.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_parser.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pdb.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_peepholer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pep247.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pep263.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pep277.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pep292.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pep352.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pickle.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pickletools.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pipes.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pkg.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pkgimport.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pkgutil.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_platform.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_plistlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_poll.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_popen.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_popen2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_poplib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_posix.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_posixpath.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pow.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pprint.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_print.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_profile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_property.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pstats.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pty.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pwd.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_py3kwarn.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pyclbr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pydoc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pyexpat.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_queue.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_quopri.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_random.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_re.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_readline.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_repr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_resource.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_rfc822.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_richcmp.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_rlcompleter.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_robotparser.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_runpy.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_sax.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_scope.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_scriptpackages.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_select.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_set.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_setcomps.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_sets.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_sgmllib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_sha.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_shelve.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_shlex.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_shutil.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_signal.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_site.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_slice.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_smtplib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_smtpnet.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_socket.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_socketserver.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_softspace.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_sort.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_sqlite.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_ssl.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_startfile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_str.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_strftime.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_string.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_stringprep.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_strop.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_strptime.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_strtod.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_struct.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_structmembers.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_structseq.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_subprocess.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_sunaudiodev.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_sundry.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_support.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_symtable.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_syntax.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_sys.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_sys_setprofile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_sys_settrace.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_sysconfig.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_tarfile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_tcl.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_telnetlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_tempfile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_textwrap.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_thread.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_threaded_import.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_threadedtempfile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_threading.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_threading_local.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_threadsignals.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_time.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_timeout.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_tk.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_tokenize.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_trace.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_traceback.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_transformer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_ttk_guionly.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_ttk_textonly.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_tuple.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_typechecks.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_types.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_ucn.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_unary.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_undocumented_details.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_unicode.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_unicode_file.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_unicodedata.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_unittest.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_univnewlines.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_univnewlines2k.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_unpack.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_urllib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_urllib2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_urllib2_localnet.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_urllib2net.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_urllibnet.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_urlparse.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_userdict.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_userlist.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_userstring.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_uu.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_uuid.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_wait3.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_wait4.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_warnings.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_wave.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_weakref.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_weakset.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_whichdb.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_winreg.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_winsound.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_with.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_wsgiref.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_xdrlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_xml_etree.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_xml_etree_c.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_xmllib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_xmlrpc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_xpickle.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_xrange.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_zipfile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_zipfile64.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_zipimport.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_zipimport_support.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_zlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/testall.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/testcodec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/testimg.uue delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/testimgr.uue delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/testrgb.uue delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/testtar.tar delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/tf_inherit_check.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/threaded_import_hangers.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/time_hashlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/tokenize_tests.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/tracedmodules/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/tracedmodules/testmod.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/warning_tests.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/win_console_handler.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/wrongcert.pem delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/xmltestdata/simple-ns.xml delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/xmltestdata/simple.xml delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/xmltestdata/test.xml delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/xmltestdata/test.xml.out delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/xmltests.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/test/zipdir.zip delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/textwrap.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/this.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/timeit.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/toaiff.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/token.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/tokenize.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/trace.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/traceback.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/tty.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/types.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/__main__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/case.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/loader.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/main.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/result.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/runner.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/signals.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/suite.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/dummy.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/support.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/test_assertions.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/test_break.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/test_case.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/test_discovery.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/test_functiontestcase.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/test_loader.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/test_program.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/test_result.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/test_runner.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/test_setups.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/test_skipping.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/test/test_suite.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/unittest/util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/urllib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/urllib2.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/urlparse.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/user.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/uu.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/uuid.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/warnings.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/wave.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/weakref.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/webbrowser.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/whichdb.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/wsgiref.egg-info delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/wsgiref/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/wsgiref/handlers.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/wsgiref/headers.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/wsgiref/simple_server.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/wsgiref/util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/wsgiref/validate.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xdrlib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/dom/NodeFilter.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/dom/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/dom/domreg.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/dom/expatbuilder.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/dom/minicompat.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/dom/minidom.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/dom/pulldom.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/dom/xmlbuilder.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/etree/ElementInclude.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/etree/ElementPath.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/etree/ElementTree.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/etree/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/etree/cElementTree.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/parsers/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/parsers/expat.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/sax/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/sax/_exceptions.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/sax/expatreader.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/sax/handler.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/sax/saxutils.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xml/sax/xmlreader.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xmllib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/xmlrpclib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Lib/zipfile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_bisectmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_codecsmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_collectionsmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_csv.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_elementtree.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_functoolsmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_hashopenssl.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_heapqmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_hotshot.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_io/_iomodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_io/_iomodule.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_io/bufferedio.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_io/bytesio.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_io/fileio.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_io/iobase.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_io/stringio.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_io/textio.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_json.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_localemodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_lsprof.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_math.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_math.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_randommodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/cache.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/cache.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/connection.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/connection.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/cursor.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/cursor.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/microprotocols.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/microprotocols.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/module.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/module.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/prepare_protocol.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/prepare_protocol.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/row.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/row.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/sqlitecompat.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/statement.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/statement.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/util.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sqlite/util.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_sre.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_ssl.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_struct.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_testcapimodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/_weakref.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/addrinfo.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/arraymodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/binascii.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/bz2module.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cPickle.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cStringIO.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/_codecs_cn.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/_codecs_hk.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/_codecs_iso2022.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/_codecs_jp.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/_codecs_kr.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/_codecs_tw.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/alg_jisx0201.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/cjkcodecs.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/emu_jisx0213_2000.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/mappings_cn.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/mappings_hk.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/mappings_jisx0213_pair.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/mappings_jp.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/mappings_kr.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/mappings_tw.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/multibytecodec.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cjkcodecs/multibytecodec.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cmathmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/cryptmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/datetimemodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/errnomodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/COPYING delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/amigaconfig.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/ascii.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/asciitab.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/expat.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/expat_config.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/expat_external.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/iasciitab.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/internal.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/latin1tab.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/macconfig.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/nametab.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/pyexpatns.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/utf8tab.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/winconfig.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/xmlparse.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/xmlrole.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/xmlrole.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/xmltok.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/xmltok.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/xmltok_impl.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/xmltok_impl.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/expat/xmltok_ns.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/fcntlmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/flmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/fmmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/fpectlmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/fpetestmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/future_builtins.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/gc_weakref.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/gcmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/getaddrinfo.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/getbuildinfo.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/getnameinfo.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/getpath.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/imageop.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/itertoolsmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/main.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/mathmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/md5.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/md5.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/md5module.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/operator.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/parsermodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/posixmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/puremodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/pwdmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/pyexpat.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/python.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/readline.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/resource.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/rotatingtree.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/rotatingtree.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/selectmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/sha256module.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/sha512module.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/shamodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/signalmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/socketmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/socketmodule.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/sre.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/sre_constants.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/stropmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/symtablemodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/testcapi_long.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/threadmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/timemodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/timing.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/timingmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/unicodedata.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/unicodedata_db.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/unicodename_db.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/xxmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/xxsubtype.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/yuv.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/yuvconvert.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zipimport.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/ChangeLog delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/FAQ delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/INDEX delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/Makefile delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/Makefile.in delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/adler32.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/algorithm.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/compress.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/configure delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/crc32.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/crc32.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/deflate.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/deflate.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/example.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/gzio.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/infback.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/inffast.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/inffast.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/inffixed.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/inflate.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/inflate.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/inftrees.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/inftrees.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/make_vms.com delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/minigzip.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/trees.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/trees.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/uncompr.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/zconf.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/zconf.in.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/zlib.3 delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/zlib.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/zutil.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlib/zutil.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Modules/zlibmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/abstract.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/boolobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/bufferobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/bytearrayobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/bytes_methods.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/capsule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/cellobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/classobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/cobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/codeobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/complexobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/descrobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/dictnotes.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/dictobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/enumobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/exceptions.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/fileobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/floatobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/frameobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/funcobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/genobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/intobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/iterobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/listobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/listsort.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/lnotab_notes.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/longobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/memoryobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/methodobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/moduleobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/object.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/obmalloc.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/rangeobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/setobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/sliceobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/stringlib/README.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/stringlib/count.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/stringlib/ctype.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/stringlib/fastsearch.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/stringlib/find.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/stringlib/formatter.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/stringlib/localeutil.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/stringlib/partition.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/stringlib/split.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/stringlib/string_format.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/stringlib/stringdefs.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/stringlib/transmogrify.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/stringlib/unicodedefs.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/stringobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/structseq.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/tupleobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/typeobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/unicodectype.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/unicodeobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/unicodetype_db.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Objects/weakrefobject.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/Python.asdl delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/acceler.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/asdl.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/asdl_c.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/bitset.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/firstsets.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/grammar.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/grammar1.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/intrcheck.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/listnode.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/metagrammar.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/myreadline.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/node.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/parser.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/parser.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/parsetok.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/pgen.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/pgenmain.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/printgrammar.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/spark.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/tokenizer.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/tokenizer.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Parser/tokenizer_pgen.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/Python-ast.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/_warnings.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/asdl.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/ast.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/atof.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/bltinmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/ceval.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/codecs.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/compile.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/dtoa.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/dup2.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/dynload_aix.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/dynload_atheos.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/dynload_beos.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/dynload_dl.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/dynload_hpux.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/dynload_next.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/dynload_os2.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/dynload_shlib.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/dynload_stub.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/dynload_win.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/errors.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/formatter_string.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/formatter_unicode.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/frozen.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/frozenmain.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/future.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/getargs.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/getcompiler.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/getcopyright.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/getcwd.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/getopt.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/getplatform.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/getversion.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/graminit.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/import.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/importdl.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/importdl.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/mactoolboxglue.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/marshal.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/modsupport.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/mysnprintf.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/mystrtoul.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/peephole.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/pyarena.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/pyctype.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/pyfpe.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/pymath.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/pystate.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/pystrcmp.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/pystrtod.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/pythonrun.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/sigcheck.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/strdup.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/strtod.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/structmember.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/symtable.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/sysmodule.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/thread.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/thread_atheos.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/thread_beos.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/thread_cthread.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/thread_foobar.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/thread_lwp.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/thread_nt.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/thread_os2.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/thread_pth.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/thread_pthread.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/thread_sgi.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/thread_solaris.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/thread_wince.h delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Python/traceback.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgen.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenBuffer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenGenerator.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenGeneratorGroup.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenHeapBuffer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenModule.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenObjectDefinition.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenOutput.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenStackBuffer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenStringBuffer.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenType.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenVariable.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/macsupport.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/scantools.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/README.tcltk-AMD64 delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/build-amd64.bat delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/build.bat delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/buildmsi.bat delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/clean-amd64.bat delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/clean.bat delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external-amd64.bat delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external-common.bat delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external.bat delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/test-amd64.bat delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/test.bat delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/ccbench/ccbench.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/ACKS delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/ast.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/astgen.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/compile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/demo.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/dumppyc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/regrtest.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/stacktest.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqconf.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqcust.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqw.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqwiz.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/move-faqwiz.sh delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/framer/README.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/framer/TODO.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/framer/example.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/bases.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/function.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/member.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/slots.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/struct.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/structparse.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/template.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/util.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/bkfile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/checkextensions.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/checkextensions_win32.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/extensions_win32.ini delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/freeze.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/hello.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makeconfig.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makefreeze.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makemakefile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/parsesetup.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/win32.html delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/winmakemakefile.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/gdb/libpython.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/makelocalealias.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/msgfmt.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/pygettext.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/iobench/iobench.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/msi/README.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/msi/crtlicense.txt delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msi.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msilib.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msisupport.c delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msisupport.mak delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/msi/schema.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/msi/sequence.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/msi/uisample.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/msi/uuids.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Arithmetic.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Calls.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/CommandLine.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Constructs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Dict.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Exceptions.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Imports.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Instances.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/LICENSE delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Lists.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Lookups.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/NewInstances.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Numbers.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Setup.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Strings.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Tuples.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Unicode.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/With.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/clockres.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/package/__init__.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/package/submodule.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/pybench.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/systimes.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/2to3 delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/analyze_dxp.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/byext.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/byteyears.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/checkappend.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/checkpyc.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/classfix.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/cleanfuture.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/combinerefs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/copytime.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/crlf.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/cvsfiles.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/db2pickle.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/diff.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/dutree.doc delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/dutree.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/eptags.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/find_recursionlimit.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/finddiv.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/findlinksto.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/findnocoding.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixcid.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixdiv.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixheader.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixnotice.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixps.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ftpmirror.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/google.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/gprof2html.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/h2py.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/hotshotmain.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/idle delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ifdef.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/lfcr.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/linktree.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/lll.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/logmerge.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/mailerdaemon.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/md5sum.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/methfix.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/mkreal.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ndiff.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/nm2def.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/objgraph.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/parseentities.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/patchcheck.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pathfix.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pdeps.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pickle2db.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pindent.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ptags.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pydoc delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pydocgui.pyw delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pysource.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/redemo.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/reindent-rst.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/reindent.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/rgrep.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/serve.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/setup.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/suff.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/svneol.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/texcheck.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/texi2html.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/treesync.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/untabify.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/which.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/win_add2path.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/xxci.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/ssl/get-remote-certificate.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/Makefile delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/comparecodecs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/gencjkcodecs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/gencodec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/genwincodec.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/genwincodecs.bat delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/listcodecs.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/makeunicodedata.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/mkstringprep.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/CP1140.TXT delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/KOI8-U.TXT delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/TIS-620.TXT delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/_checkversion.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/checkversions.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/pyversioncheck.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/tktools.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wcgui.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wcmac.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/webchecker.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/websucker.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wsgui.py delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/world/README delete mode 100644 AppPkg/Applications/Python/Python-2.7.2/Tools/world/world delete mode 100644 AppPkg/Applications/Python/PythonCore.inf delete mode 100644 AppPkg/Applications/Python/X64/pyconfig.h diff --git a/AppPkg/AppPkg.dsc b/AppPkg/AppPkg.dsc index 5938789..eb02539 100644 --- a/AppPkg/AppPkg.dsc +++ b/AppPkg/AppPkg.dsc @@ -7,7 +7,7 @@ # for important information about configuring this package for your # environment. # -# Copyright (c) 2010 - 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2010 - 2021, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent ## @@ -120,9 +120,6 @@ gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x80400040 } -#### Un-comment the following line to build Python 2.7.2. -# AppPkg/Applications/Python/PythonCore.inf - #### Un-comment the following line to build Python 2.7.10. # AppPkg/Applications/Python/Python-2.7.10/Python2710.inf diff --git a/AppPkg/Applications/Python/Efi/config.c b/AppPkg/Applications/Python/Efi/config.c deleted file mode 100644 index 5ca95e8..0000000 --- a/AppPkg/Applications/Python/Efi/config.c +++ /dev/null @@ -1,149 +0,0 @@ -/** @file - Python Module configuration. - - Copyright (c) 2011-2012, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent -**/ - -/* This file contains the table of built-in modules. - See init_builtin() in import.c. */ - -#include "Python.h" - -extern void initarray(void); -extern void init_ast(void); -extern void initbinascii(void); -extern void init_bisect(void); -extern void initcmath(void); -extern void init_codecs(void); -extern void init_collections(void); -extern void initcPickle(void); -extern void initcStringIO(void); -extern void init_csv(void); -extern void init_ctypes(void); -extern void initdatetime(void); -extern void initedk2(void); -extern void initerrno(void); -extern void init_functools(void); -extern void initfuture_builtins(void); -extern void initgc(void); -extern void init_heapq(void); -extern void init_hotshot(void); -extern void initimp(void); -extern void init_io(void); -extern void inititertools(void); -extern void init_json(void); -extern void init_lsprof(void); -extern void initmath(void); -extern void init_md5(void); -extern void initmmap(void); -extern void initoperator(void); -extern void initparser(void); -extern void initpyexpat(void); -extern void init_random(void); -extern void initselect(void); -extern void init_sha(void); -extern void init_sha256(void); -extern void init_sha512(void); -extern void initsignal(void); -extern void init_socket(void); -extern void init_sre(void); -extern void initstrop(void); -extern void init_struct(void); -extern void init_subprocess(void); -extern void init_symtable(void); -extern void initthread(void); -extern void inittime(void); -extern void initunicodedata(void); -extern void init_weakref(void); -extern void init_winreg(void); -extern void initxxsubtype(void); -extern void initzipimport(void); -extern void initzlib(void); - -extern void PyMarshal_Init(void); -extern void _PyWarnings_Init(void); - -extern void init_multibytecodec(void); -extern void init_codecs_cn(void); -extern void init_codecs_hk(void); -extern void init_codecs_iso2022(void); -extern void init_codecs_jp(void); -extern void init_codecs_kr(void); -extern void init_codecs_tw(void); - -struct _inittab _PyImport_Inittab[] = { - - //{"_ast", init_ast}, - //{"_bisect", init_bisect}, /* A fast version of bisect.py */ - //{"_csv", init_csv}, - //{"_heapq", init_heapq}, /* A fast version of heapq.py */ - //{"_io", init_io}, - //{"_json", init_json}, - //{"_md5", init_md5}, - //{"_sha", init_sha}, - //{"_sha256", init_sha256}, - //{"_sha512", init_sha512}, - //{"_socket", init_socket}, - //{"_symtable", init_symtable}, - - //{"array", initarray}, - //{"cmath", initcmath}, - //{"cPickle", initcPickle}, - //{"datetime", initdatetime}, - //{"future_builtins", initfuture_builtins}, - //{"parser", initparser}, - //{"pyexpat", initpyexpat}, - //{"select", initselect}, - //{"signal", initsignal}, - //{"strop", initstrop}, /* redefines some string operations that are 100-1000 times faster */ - //{"unicodedata", initunicodedata}, - //{"xxsubtype", initxxsubtype}, - //{"zipimport", initzipimport}, - //{"zlib", initzlib}, - - /* CJK codecs */ - //{"_multibytecodec", init_multibytecodec}, - //{"_codecs_cn", init_codecs_cn}, - //{"_codecs_hk", init_codecs_hk}, - //{"_codecs_iso2022", init_codecs_iso2022}, - //{"_codecs_jp", init_codecs_jp}, - //{"_codecs_kr", init_codecs_kr}, - //{"_codecs_tw", init_codecs_tw}, - -#ifdef WITH_THREAD - {"thread", initthread}, -#endif - - /* These modules are required for the full built-in help() facility provided by pydoc. */ - {"_codecs", init_codecs}, - {"_collections", init_collections}, - {"_functools", init_functools}, - {"_random", init_random}, - {"_sre", init_sre}, - {"_struct", init_struct}, /* Required by the logging package. */ - {"_weakref", init_weakref}, - {"binascii", initbinascii}, - {"cStringIO", initcStringIO}, /* Required by several modules, such as logging. */ - {"gc", initgc}, - {"itertools", inititertools}, - {"math", initmath}, - {"operator", initoperator}, - {"time", inittime}, - - /* These four modules should always be built in. */ - {"edk2", initedk2}, - {"errno", initerrno}, - {"imp", initimp}, /* We get this for free from Python/import.c */ - {"marshal", PyMarshal_Init}, /* We get this for free from Python/marshal.c */ - - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"__builtin__", NULL}, - {"sys", NULL}, - {"exceptions", NULL}, - {"_warnings", _PyWarnings_Init}, - - /* Sentinel */ - {0, 0} -}; diff --git a/AppPkg/Applications/Python/Efi/edk2module.c b/AppPkg/Applications/Python/Efi/edk2module.c deleted file mode 100644 index 0f1c7fe..0000000 --- a/AppPkg/Applications/Python/Efi/edk2module.c +++ /dev/null @@ -1,7414 +0,0 @@ -/** @file - OS-specific module implementation for EDK II and UEFI. - Derived from posixmodule.c in Python 2.7.2. - - Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent -**/ -#define PY_SSIZE_T_CLEAN - -#include "Python.h" -#include "structseq.h" - -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -PyDoc_STRVAR(edk2__doc__, - "This module provides access to UEFI firmware functionality that is\n\ - standardized by the C Standard and the POSIX standard (a thinly\n\ - disguised Unix interface). Refer to the library manual and\n\ - corresponding UEFI Specification entries for more information on calls."); - -#ifndef Py_USING_UNICODE - /* This is used in signatures of functions. */ - #define Py_UNICODE void -#endif - -#ifdef HAVE_SYS_TYPES_H - #include -#endif /* HAVE_SYS_TYPES_H */ - -#ifdef HAVE_SYS_STAT_H - #include -#endif /* HAVE_SYS_STAT_H */ - -#ifdef HAVE_SYS_WAIT_H - #include /* For WNOHANG */ -#endif - -#ifdef HAVE_SIGNAL_H - #include -#endif - -#ifdef HAVE_FCNTL_H - #include -#endif /* HAVE_FCNTL_H */ - -#ifdef HAVE_GRP_H - #include -#endif - -#ifdef HAVE_SYSEXITS_H - #include -#endif /* HAVE_SYSEXITS_H */ - -#ifdef HAVE_SYS_LOADAVG_H - #include -#endif - -#ifdef HAVE_UTIME_H - #include -#endif /* HAVE_UTIME_H */ - -#ifdef HAVE_SYS_UTIME_H - #include - #define HAVE_UTIME_H /* pretend we do for the rest of this file */ -#endif /* HAVE_SYS_UTIME_H */ - -#ifdef HAVE_SYS_TIMES_H - #include -#endif /* HAVE_SYS_TIMES_H */ - -#ifdef HAVE_SYS_PARAM_H - #include -#endif /* HAVE_SYS_PARAM_H */ - -#ifdef HAVE_SYS_UTSNAME_H - #include -#endif /* HAVE_SYS_UTSNAME_H */ - -#ifdef HAVE_DIRENT_H - #include - #define NAMLEN(dirent) wcslen((dirent)->FileName) -#else - #define dirent direct - #define NAMLEN(dirent) (dirent)->d_namlen - #ifdef HAVE_SYS_NDIR_H - #include - #endif - #ifdef HAVE_SYS_DIR_H - #include - #endif - #ifdef HAVE_NDIR_H - #include - #endif -#endif - -#ifndef MAXPATHLEN - #if defined(PATH_MAX) && PATH_MAX > 1024 - #define MAXPATHLEN PATH_MAX - #else - #define MAXPATHLEN 1024 - #endif -#endif /* MAXPATHLEN */ - -#define WAIT_TYPE int -#define WAIT_STATUS_INT(s) (s) - -/* Issue #1983: pid_t can be longer than a C long on some systems */ -#if !defined(SIZEOF_PID_T) || SIZEOF_PID_T == SIZEOF_INT - #define PARSE_PID "i" - #define PyLong_FromPid PyInt_FromLong - #define PyLong_AsPid PyInt_AsLong -#elif SIZEOF_PID_T == SIZEOF_LONG - #define PARSE_PID "l" - #define PyLong_FromPid PyInt_FromLong - #define PyLong_AsPid PyInt_AsLong -#elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG - #define PARSE_PID "L" - #define PyLong_FromPid PyLong_FromLongLong - #define PyLong_AsPid PyInt_AsLongLong -#else - #error "sizeof(pid_t) is neither sizeof(int), sizeof(long) or sizeof(long long)" -#endif /* SIZEOF_PID_T */ - -/* Don't use the "_r" form if we don't need it (also, won't have a - prototype for it, at least on Solaris -- maybe others as well?). */ -#if defined(HAVE_CTERMID_R) && defined(WITH_THREAD) - #define USE_CTERMID_R -#endif - -#if defined(HAVE_TMPNAM_R) && defined(WITH_THREAD) - #define USE_TMPNAM_R -#endif - -/* choose the appropriate stat and fstat functions and return structs */ -#undef STAT -#undef FSTAT -#undef STRUCT_STAT -#define STAT stat -#define FSTAT fstat -#define STRUCT_STAT struct stat - -/* dummy version. _PyVerify_fd() is already defined in fileobject.h */ -#define _PyVerify_fd_dup2(A, B) (1) - -#ifndef UEFI_C_SOURCE -/* Return a dictionary corresponding to the POSIX environment table */ -extern char **environ; - -static PyObject * -convertenviron(void) -{ - PyObject *d; - char **e; - d = PyDict_New(); - if (d == NULL) - return NULL; - if (environ == NULL) - return d; - /* This part ignores errors */ - for (e = environ; *e != NULL; e++) { - PyObject *k; - PyObject *v; - char *p = strchr(*e, '='); - if (p == NULL) - continue; - k = PyString_FromStringAndSize(*e, (int)(p-*e)); - if (k == NULL) { - PyErr_Clear(); - continue; - } - v = PyString_FromString(p+1); - if (v == NULL) { - PyErr_Clear(); - Py_DECREF(k); - continue; - } - if (PyDict_GetItem(d, k) == NULL) { - if (PyDict_SetItem(d, k, v) != 0) - PyErr_Clear(); - } - Py_DECREF(k); - Py_DECREF(v); - } - return d; -} -#endif /* UEFI_C_SOURCE */ - -/* Set a POSIX-specific error from errno, and return NULL */ - -static PyObject * -posix_error(void) -{ - return PyErr_SetFromErrno(PyExc_OSError); -} -static PyObject * -posix_error_with_filename(char* name) -{ - return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); -} - - -static PyObject * -posix_error_with_allocated_filename(char* name) -{ - PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); - PyMem_Free(name); - return rc; -} - -/* POSIX generic methods */ - -#ifndef UEFI_C_SOURCE - static PyObject * - posix_fildes(PyObject *fdobj, int (*func)(int)) - { - int fd; - int res; - fd = PyObject_AsFileDescriptor(fdobj); - if (fd < 0) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = (*func)(fd); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; - } -#endif /* UEFI_C_SOURCE */ - -static PyObject * -posix_1str(PyObject *args, char *format, int (*func)(const char*)) -{ - char *path1 = NULL; - int res; - if (!PyArg_ParseTuple(args, format, - Py_FileSystemDefaultEncoding, &path1)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = (*func)(path1); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path1); - PyMem_Free(path1); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -posix_2str(PyObject *args, - char *format, - int (*func)(const char *, const char *)) -{ - char *path1 = NULL, *path2 = NULL; - int res; - if (!PyArg_ParseTuple(args, format, - Py_FileSystemDefaultEncoding, &path1, - Py_FileSystemDefaultEncoding, &path2)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = (*func)(path1, path2); - Py_END_ALLOW_THREADS - PyMem_Free(path1); - PyMem_Free(path2); - if (res != 0) - /* XXX how to report both path1 and path2??? */ - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} - -PyDoc_STRVAR(stat_result__doc__, -"stat_result: Result from stat or lstat.\n\n\ -This object may be accessed either as a tuple of\n\ - (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\ -or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\ -\n\ -Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\ -or st_flags, they are available as attributes only.\n\ -\n\ -See os.stat for more information."); - -static PyStructSequence_Field stat_result_fields[] = { - {"st_mode", "protection bits"}, - //{"st_ino", "inode"}, - //{"st_dev", "device"}, - //{"st_nlink", "number of hard links"}, - //{"st_uid", "user ID of owner"}, - //{"st_gid", "group ID of owner"}, - {"st_size", "total size, in bytes"}, - /* The NULL is replaced with PyStructSequence_UnnamedField later. */ - {NULL, "integer time of last access"}, - {NULL, "integer time of last modification"}, - {NULL, "integer time of last change"}, - {"st_atime", "time of last access"}, - {"st_mtime", "time of last modification"}, - {"st_ctime", "time of last change"}, -#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE - {"st_blksize", "blocksize for filesystem I/O"}, -#endif -#ifdef HAVE_STRUCT_STAT_ST_BLOCKS - {"st_blocks", "number of blocks allocated"}, -#endif -#ifdef HAVE_STRUCT_STAT_ST_RDEV - {"st_rdev", "device type (if inode device)"}, -#endif -#ifdef HAVE_STRUCT_STAT_ST_FLAGS - {"st_flags", "user defined flags for file"}, -#endif -#ifdef HAVE_STRUCT_STAT_ST_GEN - {"st_gen", "generation number"}, -#endif -#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME - {"st_birthtime", "time of creation"}, -#endif - {0} -}; - -#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE -#define ST_BLKSIZE_IDX 8 -#else -#define ST_BLKSIZE_IDX 12 -#endif - -#ifdef HAVE_STRUCT_STAT_ST_BLOCKS -#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1) -#else -#define ST_BLOCKS_IDX ST_BLKSIZE_IDX -#endif - -#ifdef HAVE_STRUCT_STAT_ST_RDEV -#define ST_RDEV_IDX (ST_BLOCKS_IDX+1) -#else -#define ST_RDEV_IDX ST_BLOCKS_IDX -#endif - -#ifdef HAVE_STRUCT_STAT_ST_FLAGS -#define ST_FLAGS_IDX (ST_RDEV_IDX+1) -#else -#define ST_FLAGS_IDX ST_RDEV_IDX -#endif - -#ifdef HAVE_STRUCT_STAT_ST_GEN -#define ST_GEN_IDX (ST_FLAGS_IDX+1) -#else -#define ST_GEN_IDX ST_FLAGS_IDX -#endif - -#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME -#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1) -#else -#define ST_BIRTHTIME_IDX ST_GEN_IDX -#endif - -static PyStructSequence_Desc stat_result_desc = { - "stat_result", /* name */ - stat_result__doc__, /* doc */ - stat_result_fields, - 10 -}; - -#ifndef UEFI_C_SOURCE /* Not in UEFI */ -PyDoc_STRVAR(statvfs_result__doc__, -"statvfs_result: Result from statvfs or fstatvfs.\n\n\ -This object may be accessed either as a tuple of\n\ - (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\ -or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\ -\n\ -See os.statvfs for more information."); - -static PyStructSequence_Field statvfs_result_fields[] = { - {"f_bsize", }, - {"f_frsize", }, - {"f_blocks", }, - {"f_bfree", }, - {"f_bavail", }, - {"f_files", }, - {"f_ffree", }, - {"f_favail", }, - {"f_flag", }, - {"f_namemax",}, - {0} -}; - -static PyStructSequence_Desc statvfs_result_desc = { - "statvfs_result", /* name */ - statvfs_result__doc__, /* doc */ - statvfs_result_fields, - 10 -}; - -static PyTypeObject StatVFSResultType; -#endif - -static int initialized; -static PyTypeObject StatResultType; -static newfunc structseq_new; - -static PyObject * -statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds) -{ - PyStructSequence *result; - int i; - - result = (PyStructSequence*)structseq_new(type, args, kwds); - if (!result) - return NULL; - /* If we have been initialized from a tuple, - st_?time might be set to None. Initialize it - from the int slots. */ - for (i = 7; i <= 9; i++) { - if (result->ob_item[i+3] == Py_None) { - Py_DECREF(Py_None); - Py_INCREF(result->ob_item[i]); - result->ob_item[i+3] = result->ob_item[i]; - } - } - return (PyObject*)result; -} - - - -/* If true, st_?time is float. */ -#if defined(UEFI_C_SOURCE) - static int _stat_float_times = 0; -#else - static int _stat_float_times = 1; - -PyDoc_STRVAR(stat_float_times__doc__, -"stat_float_times([newval]) -> oldval\n\n\ -Determine whether os.[lf]stat represents time stamps as float objects.\n\ -If newval is True, future calls to stat() return floats, if it is False,\n\ -future calls return ints. \n\ -If newval is omitted, return the current setting.\n"); - -static PyObject* -stat_float_times(PyObject* self, PyObject *args) -{ - int newval = -1; - - if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval)) - return NULL; - if (newval == -1) - /* Return old value */ - return PyBool_FromLong(_stat_float_times); - _stat_float_times = newval; - Py_INCREF(Py_None); - return Py_None; -} -#endif /* UEFI_C_SOURCE */ - -static void -fill_time(PyObject *v, int index, time_t sec, unsigned long nsec) -{ - PyObject *fval,*ival; -#if SIZEOF_TIME_T > SIZEOF_LONG - ival = PyLong_FromLongLong((PY_LONG_LONG)sec); -#else - ival = PyInt_FromLong((long)sec); -#endif - if (!ival) - return; - if (_stat_float_times) { - fval = PyFloat_FromDouble(sec + 1e-9*nsec); - } else { - fval = ival; - Py_INCREF(fval); - } - PyStructSequence_SET_ITEM(v, index, ival); - PyStructSequence_SET_ITEM(v, index+3, fval); -} - -/* pack a system stat C structure into the Python stat tuple - (used by posix_stat() and posix_fstat()) */ -static PyObject* -_pystat_fromstructstat(STRUCT_STAT *st) -{ - unsigned long ansec, mnsec, cnsec; - PyObject *v = PyStructSequence_New(&StatResultType); - if (v == NULL) - return NULL; - - PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long)st->st_mode)); - PyStructSequence_SET_ITEM(v, 1, - PyLong_FromLongLong((PY_LONG_LONG)st->st_size)); - - ansec = mnsec = cnsec = 0; - /* The index used by fill_time is the index of the integer time. - fill_time will add 3 to the index to get the floating time index. - */ - fill_time(v, 2, st->st_atime, ansec); - fill_time(v, 3, st->st_mtime, mnsec); - fill_time(v, 4, st->st_mtime, cnsec); - -#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE - PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX, - PyInt_FromLong((long)st->st_blksize)); -#endif -#ifdef HAVE_STRUCT_STAT_ST_BLOCKS - PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX, - PyInt_FromLong((long)st->st_blocks)); -#endif -#ifdef HAVE_STRUCT_STAT_ST_RDEV - PyStructSequence_SET_ITEM(v, ST_RDEV_IDX, - PyInt_FromLong((long)st->st_rdev)); -#endif -#ifdef HAVE_STRUCT_STAT_ST_GEN - PyStructSequence_SET_ITEM(v, ST_GEN_IDX, - PyInt_FromLong((long)st->st_gen)); -#endif -#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME - { - PyObject *val; - unsigned long bsec,bnsec; - bsec = (long)st->st_birthtime; -#ifdef HAVE_STAT_TV_NSEC2 - bnsec = st->st_birthtimespec.tv_nsec; -#else - bnsec = 0; -#endif - if (_stat_float_times) { - val = PyFloat_FromDouble(bsec + 1e-9*bnsec); - } else { - val = PyInt_FromLong((long)bsec); - } - PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX, - val); - } -#endif -#ifdef HAVE_STRUCT_STAT_ST_FLAGS - PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX, - PyInt_FromLong((long)st->st_flags)); -#endif - - if (PyErr_Occurred()) { - Py_DECREF(v); - return NULL; - } - - return v; -} - -static PyObject * -posix_do_stat(PyObject *self, PyObject *args, - char *format, - int (*statfunc)(const char *, STRUCT_STAT *), - char *wformat, - int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *)) -{ - STRUCT_STAT st; - char *path = NULL; /* pass this to stat; do not free() it */ - char *pathfree = NULL; /* this memory must be free'd */ - int res; - PyObject *result; - - if (!PyArg_ParseTuple(args, format, - Py_FileSystemDefaultEncoding, &path)) - return NULL; - pathfree = path; - - Py_BEGIN_ALLOW_THREADS - res = (*statfunc)(path, &st); - Py_END_ALLOW_THREADS - - if (res != 0) { - result = posix_error_with_filename(pathfree); - } - else - result = _pystat_fromstructstat(&st); - - PyMem_Free(pathfree); - return result; -} - -/* POSIX methods */ - -PyDoc_STRVAR(posix_access__doc__, -"access(path, mode) -> True if granted, False otherwise\n\n\ -Use the real uid/gid to test for access to a path. Note that most\n\ -operations will use the effective uid/gid, therefore this routine can\n\ -be used in a suid/sgid environment to test if the invoking user has the\n\ -specified access to the path. The mode argument can be F_OK to test\n\ -existence, or the inclusive-OR of R_OK, W_OK, and X_OK."); - -static PyObject * -posix_access(PyObject *self, PyObject *args) -{ - char *path; - int mode; - - int res; - if (!PyArg_ParseTuple(args, "eti:access", - Py_FileSystemDefaultEncoding, &path, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = access(path, mode); - Py_END_ALLOW_THREADS - PyMem_Free(path); - return PyBool_FromLong(res == 0); -} - -#ifndef F_OK - #define F_OK 0 -#endif -#ifndef R_OK - #define R_OK 4 -#endif -#ifndef W_OK - #define W_OK 2 -#endif -#ifndef X_OK - #define X_OK 1 -#endif - -PyDoc_STRVAR(posix_chdir__doc__, -"chdir(path)\n\n\ -Change the current working directory to the specified path."); - -static PyObject * -posix_chdir(PyObject *self, PyObject *args) -{ - return posix_1str(args, "et:chdir", chdir); -} - -PyDoc_STRVAR(posix_chmod__doc__, -"chmod(path, mode)\n\n\ -Change the access permissions of a file."); - -static PyObject * -posix_chmod(PyObject *self, PyObject *args) -{ - char *path = NULL; - int i; - int res; - if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding, - &path, &i)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = chmod(path, i); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; -} - -#ifdef HAVE_FCHMOD -PyDoc_STRVAR(posix_fchmod__doc__, -"fchmod(fd, mode)\n\n\ -Change the access permissions of the file given by file\n\ -descriptor fd."); - -static PyObject * -posix_fchmod(PyObject *self, PyObject *args) -{ - int fd, mode, res; - if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fchmod(fd, mode); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_RETURN_NONE; -} -#endif /* HAVE_FCHMOD */ - -#ifdef HAVE_LCHMOD -PyDoc_STRVAR(posix_lchmod__doc__, -"lchmod(path, mode)\n\n\ -Change the access permissions of a file. If path is a symlink, this\n\ -affects the link itself rather than the target."); - -static PyObject * -posix_lchmod(PyObject *self, PyObject *args) -{ - char *path = NULL; - int i; - int res; - if (!PyArg_ParseTuple(args, "eti:lchmod", Py_FileSystemDefaultEncoding, - &path, &i)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = lchmod(path, i); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_RETURN_NONE; -} -#endif /* HAVE_LCHMOD */ - - -#ifdef HAVE_CHFLAGS -PyDoc_STRVAR(posix_chflags__doc__, -"chflags(path, flags)\n\n\ -Set file flags."); - -static PyObject * -posix_chflags(PyObject *self, PyObject *args) -{ - char *path; - unsigned long flags; - int res; - if (!PyArg_ParseTuple(args, "etk:chflags", - Py_FileSystemDefaultEncoding, &path, &flags)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = chflags(path, flags); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; -} -#endif /* HAVE_CHFLAGS */ - -#ifdef HAVE_LCHFLAGS -PyDoc_STRVAR(posix_lchflags__doc__, -"lchflags(path, flags)\n\n\ -Set file flags.\n\ -This function will not follow symbolic links."); - -static PyObject * -posix_lchflags(PyObject *self, PyObject *args) -{ - char *path; - unsigned long flags; - int res; - if (!PyArg_ParseTuple(args, "etk:lchflags", - Py_FileSystemDefaultEncoding, &path, &flags)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = lchflags(path, flags); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; -} -#endif /* HAVE_LCHFLAGS */ - -#ifdef HAVE_CHROOT -PyDoc_STRVAR(posix_chroot__doc__, -"chroot(path)\n\n\ -Change root directory to path."); - -static PyObject * -posix_chroot(PyObject *self, PyObject *args) -{ - return posix_1str(args, "et:chroot", chroot); -} -#endif - -#ifdef HAVE_FSYNC -PyDoc_STRVAR(posix_fsync__doc__, -"fsync(fildes)\n\n\ -force write of file with filedescriptor to disk."); - -static PyObject * -posix_fsync(PyObject *self, PyObject *fdobj) -{ - return posix_fildes(fdobj, fsync); -} -#endif /* HAVE_FSYNC */ - -#ifdef HAVE_FDATASYNC - -#ifdef __hpux -extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */ -#endif - -PyDoc_STRVAR(posix_fdatasync__doc__, -"fdatasync(fildes)\n\n\ -force write of file with filedescriptor to disk.\n\ - does not force update of metadata."); - -static PyObject * -posix_fdatasync(PyObject *self, PyObject *fdobj) -{ - return posix_fildes(fdobj, fdatasync); -} -#endif /* HAVE_FDATASYNC */ - - -#ifdef HAVE_CHOWN -PyDoc_STRVAR(posix_chown__doc__, -"chown(path, uid, gid)\n\n\ -Change the owner and group id of path to the numeric uid and gid."); - -static PyObject * -posix_chown(PyObject *self, PyObject *args) -{ - char *path = NULL; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "etll:chown", - Py_FileSystemDefaultEncoding, &path, - &uid, &gid)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = chown(path, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; -} -#endif /* HAVE_CHOWN */ - -#ifdef HAVE_FCHOWN -PyDoc_STRVAR(posix_fchown__doc__, -"fchown(fd, uid, gid)\n\n\ -Change the owner and group id of the file given by file descriptor\n\ -fd to the numeric uid and gid."); - -static PyObject * -posix_fchown(PyObject *self, PyObject *args) -{ - int fd; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "ill:chown", &fd, &uid, &gid)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fchown(fd, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_RETURN_NONE; -} -#endif /* HAVE_FCHOWN */ - -#ifdef HAVE_LCHOWN -PyDoc_STRVAR(posix_lchown__doc__, -"lchown(path, uid, gid)\n\n\ -Change the owner and group id of path to the numeric uid and gid.\n\ -This function will not follow symbolic links."); - -static PyObject * -posix_lchown(PyObject *self, PyObject *args) -{ - char *path = NULL; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "etll:lchown", - Py_FileSystemDefaultEncoding, &path, - &uid, &gid)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = lchown(path, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; -} -#endif /* HAVE_LCHOWN */ - - -#ifdef HAVE_GETCWD -PyDoc_STRVAR(posix_getcwd__doc__, -"getcwd() -> path\n\n\ -Return a string representing the current working directory."); - -static PyObject * -posix_getcwd(PyObject *self, PyObject *noargs) -{ - int bufsize_incr = 1024; - int bufsize = 0; - char *tmpbuf = NULL; - char *res = NULL; - PyObject *dynamic_return; - - Py_BEGIN_ALLOW_THREADS - do { - bufsize = bufsize + bufsize_incr; - tmpbuf = malloc(bufsize); - if (tmpbuf == NULL) { - break; - } - res = getcwd(tmpbuf, bufsize); - if (res == NULL) { - free(tmpbuf); - } - } while ((res == NULL) && (errno == ERANGE)); - Py_END_ALLOW_THREADS - - if (res == NULL) - return posix_error(); - - dynamic_return = PyString_FromString(tmpbuf); - free(tmpbuf); - - return dynamic_return; -} - -#ifdef Py_USING_UNICODE -PyDoc_STRVAR(posix_getcwdu__doc__, -"getcwdu() -> path\n\n\ -Return a unicode string representing the current working directory."); - -static PyObject * -posix_getcwdu(PyObject *self, PyObject *noargs) -{ - char buf[1026]; - char *res; - - Py_BEGIN_ALLOW_THREADS - res = getcwd(buf, sizeof buf); - Py_END_ALLOW_THREADS - if (res == NULL) - return posix_error(); - return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"strict"); -} -#endif /* Py_USING_UNICODE */ -#endif /* HAVE_GETCWD */ - - -PyDoc_STRVAR(posix_listdir__doc__, -"listdir(path) -> list_of_strings\n\n\ -Return a list containing the names of the entries in the directory.\n\ -\n\ - path: path of directory to list\n\ -\n\ -The list is in arbitrary order. It does not include the special\n\ -entries '.' and '..' even if they are present in the directory."); - -static PyObject * -posix_listdir(PyObject *self, PyObject *args) -{ - /* XXX Should redo this putting the (now four) versions of opendir - in separate files instead of having them all here... */ - - char *name = NULL; - char *MBname; - PyObject *d, *v; - DIR *dirp; - struct dirent *ep; - int arg_is_unicode = 1; - - errno = 0; - if (!PyArg_ParseTuple(args, "U:listdir", &v)) { - arg_is_unicode = 0; - PyErr_Clear(); - } - if (!PyArg_ParseTuple(args, "et:listdir", Py_FileSystemDefaultEncoding, &name)) - return NULL; - Py_BEGIN_ALLOW_THREADS - dirp = opendir(name); - Py_END_ALLOW_THREADS - if (dirp == NULL) { - return posix_error_with_allocated_filename(name); - } - if ((d = PyList_New(0)) == NULL) { - Py_BEGIN_ALLOW_THREADS - closedir(dirp); - Py_END_ALLOW_THREADS - PyMem_Free(name); - return NULL; - } - if((MBname = malloc(NAME_MAX)) == NULL) { - Py_BEGIN_ALLOW_THREADS - closedir(dirp); - Py_END_ALLOW_THREADS - Py_DECREF(d); - PyMem_Free(name); - return NULL; - } - for (;;) { - errno = 0; - Py_BEGIN_ALLOW_THREADS - ep = readdir(dirp); - Py_END_ALLOW_THREADS - if (ep == NULL) { - if ((errno == 0) || (errno == EISDIR)) { - break; - } else { - Py_BEGIN_ALLOW_THREADS - closedir(dirp); - Py_END_ALLOW_THREADS - Py_DECREF(d); - return posix_error_with_allocated_filename(name); - } - } - if (ep->FileName[0] == L'.' && - (NAMLEN(ep) == 1 || - (ep->FileName[1] == L'.' && NAMLEN(ep) == 2))) - continue; - if(wcstombs(MBname, ep->FileName, NAME_MAX) == -1) { - free(MBname); - Py_BEGIN_ALLOW_THREADS - closedir(dirp); - Py_END_ALLOW_THREADS - Py_DECREF(d); - PyMem_Free(name); - return NULL; - } - v = PyString_FromStringAndSize(MBname, strlen(MBname)); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } -#ifdef Py_USING_UNICODE - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "strict"); - if (w != NULL) { - Py_DECREF(v); - v = w; - } - else { - /* fall back to the original byte string, as - discussed in patch #683592 */ - PyErr_Clear(); - } - } -#endif - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - Py_BEGIN_ALLOW_THREADS - closedir(dirp); - Py_END_ALLOW_THREADS - PyMem_Free(name); - if(MBname != NULL) { - free(MBname); - } - - return d; - -} /* end of posix_listdir */ - -#ifdef MS_WINDOWS -/* A helper function for abspath on win32 */ -static PyObject * -posix__getfullpathname(PyObject *self, PyObject *args) -{ - /* assume encoded strings won't more than double no of chars */ - char inbuf[MAX_PATH*2]; - char *inbufp = inbuf; - Py_ssize_t insize = sizeof(inbuf); - char outbuf[MAX_PATH*2]; - char *temp; - - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) { - Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); - Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf; - Py_UNICODE *wtemp; - DWORD result; - PyObject *v; - result = GetFullPathNameW(wpath, - sizeof(woutbuf)/sizeof(woutbuf[0]), - woutbuf, &wtemp); - if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) { - woutbufp = malloc(result * sizeof(Py_UNICODE)); - if (!woutbufp) - return PyErr_NoMemory(); - result = GetFullPathNameW(wpath, result, woutbufp, &wtemp); - } - if (result) - v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp)); - else - v = win32_error_unicode("GetFullPathNameW", wpath); - if (woutbufp != woutbuf) - free(woutbufp); - return v; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - - if (!PyArg_ParseTuple (args, "et#:_getfullpathname", - Py_FileSystemDefaultEncoding, &inbufp, - &insize)) - return NULL; - if (!GetFullPathName(inbuf, sizeof(outbuf)/sizeof(outbuf[0]), - outbuf, &temp)) - return win32_error("GetFullPathName", inbuf); - if (PyUnicode_Check(PyTuple_GetItem(args, 0))) { - return PyUnicode_Decode(outbuf, strlen(outbuf), - Py_FileSystemDefaultEncoding, NULL); - } - return PyString_FromString(outbuf); -} /* end of posix__getfullpathname */ -#endif /* MS_WINDOWS */ - -PyDoc_STRVAR(posix_mkdir__doc__, -"mkdir(path [, mode=0777])\n\n\ -Create a directory."); - -static PyObject * -posix_mkdir(PyObject *self, PyObject *args) -{ - int res; - char *path = NULL; - int mode = 0777; - - if (!PyArg_ParseTuple(args, "et|i:mkdir", - Py_FileSystemDefaultEncoding, &path, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = mkdir(path, mode); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; -} - - -/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */ -#if defined(HAVE_SYS_RESOURCE_H) -#include -#endif - - -#ifdef HAVE_NICE -PyDoc_STRVAR(posix_nice__doc__, -"nice(inc) -> new_priority\n\n\ -Decrease the priority of process by inc and return the new priority."); - -static PyObject * -posix_nice(PyObject *self, PyObject *args) -{ - int increment, value; - - if (!PyArg_ParseTuple(args, "i:nice", &increment)) - return NULL; - - /* There are two flavours of 'nice': one that returns the new - priority (as required by almost all standards out there) and the - Linux/FreeBSD/BSDI one, which returns '0' on success and advices - the use of getpriority() to get the new priority. - - If we are of the nice family that returns the new priority, we - need to clear errno before the call, and check if errno is filled - before calling posix_error() on a returnvalue of -1, because the - -1 may be the actual new priority! */ - - errno = 0; - value = nice(increment); -#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY) - if (value == 0) - value = getpriority(PRIO_PROCESS, 0); -#endif - if (value == -1 && errno != 0) - /* either nice() or getpriority() returned an error */ - return posix_error(); - return PyInt_FromLong((long) value); -} -#endif /* HAVE_NICE */ - -PyDoc_STRVAR(posix_rename__doc__, -"rename(old, new)\n\n\ -Rename a file or directory."); - -static PyObject * -posix_rename(PyObject *self, PyObject *args) -{ - return posix_2str(args, "etet:rename", rename); -} - - -PyDoc_STRVAR(posix_rmdir__doc__, -"rmdir(path)\n\n\ -Remove a directory."); - -static PyObject * -posix_rmdir(PyObject *self, PyObject *args) -{ - return posix_1str(args, "et:rmdir", rmdir); -} - - -PyDoc_STRVAR(posix_stat__doc__, -"stat(path) -> stat result\n\n\ -Perform a stat system call on the given path."); - -static PyObject * -posix_stat(PyObject *self, PyObject *args) -{ - return posix_do_stat(self, args, "et:stat", STAT, NULL, NULL); -} - - -#ifdef HAVE_SYSTEM -PyDoc_STRVAR(posix_system__doc__, -"system(command) -> exit_status\n\n\ -Execute the command (a string) in a subshell."); - -static PyObject * -posix_system(PyObject *self, PyObject *args) -{ - char *command; - long sts; - if (!PyArg_ParseTuple(args, "s:system", &command)) - return NULL; - Py_BEGIN_ALLOW_THREADS - sts = system(command); - Py_END_ALLOW_THREADS - return PyInt_FromLong(sts); -} -#endif - - -PyDoc_STRVAR(posix_umask__doc__, -"umask(new_mask) -> old_mask\n\n\ -Set the current numeric umask and return the previous umask."); - -static PyObject * -posix_umask(PyObject *self, PyObject *args) -{ - int i; - if (!PyArg_ParseTuple(args, "i:umask", &i)) - return NULL; - i = (int)umask(i); - if (i < 0) - return posix_error(); - return PyInt_FromLong((long)i); -} - - -PyDoc_STRVAR(posix_unlink__doc__, -"unlink(path)\n\n\ -Remove a file (same as remove(path))."); - -PyDoc_STRVAR(posix_remove__doc__, -"remove(path)\n\n\ -Remove a file (same as unlink(path))."); - -static PyObject * -posix_unlink(PyObject *self, PyObject *args) -{ - return posix_1str(args, "et:remove", unlink); -} - - -static int -extract_time(PyObject *t, time_t* sec, long* usec) -{ - time_t intval; - if (PyFloat_Check(t)) { - double tval = PyFloat_AsDouble(t); - PyObject *intobj = PyNumber_Long(t); - if (!intobj) - return -1; -#if SIZEOF_TIME_T > SIZEOF_LONG - intval = PyInt_AsUnsignedLongLongMask(intobj); -#else - intval = PyInt_AsLong(intobj); -#endif - Py_DECREF(intobj); - if (intval == -1 && PyErr_Occurred()) - return -1; - *sec = intval; - *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */ - if (*usec < 0) - /* If rounding gave us a negative number, - truncate. */ - *usec = 0; - return 0; - } -#if SIZEOF_TIME_T > SIZEOF_LONG - intval = PyInt_AsUnsignedLongLongMask(t); -#else - intval = PyInt_AsLong(t); -#endif - if (intval == -1 && PyErr_Occurred()) - return -1; - *sec = intval; - *usec = 0; - return 0; -} - -PyDoc_STRVAR(posix_utime__doc__, -"utime(path, (atime, mtime))\n\ -utime(path, None)\n\n\ -Set the access and modified time of the file to the given values. If the\n\ -second form is used, set the access and modified times to the current time."); - -static PyObject * -posix_utime(PyObject *self, PyObject *args) -{ - char *path = NULL; - time_t atime, mtime; - long ausec, musec; - int res; - PyObject* arg; - -#if defined(HAVE_UTIMES) - struct timeval buf[2]; -#define ATIME buf[0].tv_sec -#define MTIME buf[1].tv_sec -#elif defined(HAVE_UTIME_H) -/* XXX should define struct utimbuf instead, above */ - struct utimbuf buf; -#define ATIME buf.actime -#define MTIME buf.modtime -#define UTIME_ARG &buf -#else /* HAVE_UTIMES */ - time_t buf[2]; -#define ATIME buf[0] -#define MTIME buf[1] -#define UTIME_ARG buf -#endif /* HAVE_UTIMES */ - - - if (!PyArg_ParseTuple(args, "etO:utime", - Py_FileSystemDefaultEncoding, &path, &arg)) - return NULL; - if (arg == Py_None) { - /* optional time values not given */ - Py_BEGIN_ALLOW_THREADS - res = utime(path, NULL); - Py_END_ALLOW_THREADS - } - else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { - PyErr_SetString(PyExc_TypeError, - "utime() arg 2 must be a tuple (atime, mtime)"); - PyMem_Free(path); - return NULL; - } - else { - if (extract_time(PyTuple_GET_ITEM(arg, 0), - &atime, &ausec) == -1) { - PyMem_Free(path); - return NULL; - } - if (extract_time(PyTuple_GET_ITEM(arg, 1), - &mtime, &musec) == -1) { - PyMem_Free(path); - return NULL; - } - ATIME = atime; - MTIME = mtime; -#ifdef HAVE_UTIMES - buf[0].tv_usec = ausec; - buf[1].tv_usec = musec; - Py_BEGIN_ALLOW_THREADS - res = utimes(path, buf); - Py_END_ALLOW_THREADS -#else - Py_BEGIN_ALLOW_THREADS - res = utime(path, UTIME_ARG); - Py_END_ALLOW_THREADS -#endif /* HAVE_UTIMES */ - } - if (res < 0) { - return posix_error_with_allocated_filename(path); - } - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; -#undef UTIME_ARG -#undef ATIME -#undef MTIME -} - - -/* Process operations */ - -PyDoc_STRVAR(posix__exit__doc__, -"_exit(status)\n\n\ -Exit to the system with specified status, without normal exit processing."); - -static PyObject * -posix__exit(PyObject *self, PyObject *args) -{ - int sts; - if (!PyArg_ParseTuple(args, "i:_exit", &sts)) - return NULL; - _Exit(sts); - return NULL; /* Make gcc -Wall happy */ -} - -#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) -static void -free_string_array(char **array, Py_ssize_t count) -{ - Py_ssize_t i; - for (i = 0; i < count; i++) - PyMem_Free(array[i]); - PyMem_DEL(array); -} -#endif - - -#ifdef HAVE_EXECV -PyDoc_STRVAR(posix_execv__doc__, -"execv(path, args)\n\n\ -Execute an executable path with arguments, replacing current process.\n\ -\n\ - path: path of executable file\n\ - args: tuple or list of strings"); - -static PyObject * -posix_execv(PyObject *self, PyObject *args) -{ - char *path; - PyObject *argv; - char **argvlist; - Py_ssize_t i, argc; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* execv has two arguments: (path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "etO:execv", - Py_FileSystemDefaultEncoding, - &path, &argv)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list"); - PyMem_Free(path); - return NULL; - } - if (argc < 1) { - PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty"); - PyMem_Free(path); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyMem_Free(path); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), "et", - Py_FileSystemDefaultEncoding, - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString(PyExc_TypeError, - "execv() arg 2 must contain only strings"); - PyMem_Free(path); - return NULL; - - } - } - argvlist[argc] = NULL; - - execv(path, argvlist); - - /* If we get here it's definitely an error */ - - free_string_array(argvlist, argc); - PyMem_Free(path); - return posix_error(); -} - - -PyDoc_STRVAR(posix_execve__doc__, -"execve(path, args, env)\n\n\ -Execute a path with arguments and environment, replacing current process.\n\ -\n\ - path: path of executable file\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); - -static PyObject * -posix_execve(PyObject *self, PyObject *args) -{ - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *key, *val, *keys=NULL, *vals=NULL; - Py_ssize_t i, pos, argc, envc; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - Py_ssize_t lastarg = 0; - - /* execve has three arguments: (path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "etOO:execve", - Py_FileSystemDefaultEncoding, - &path, &argv, &env)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "execve() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "execve() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), - "et;execve() arg 2 must contain only strings", - Py_FileSystemDefaultEncoding, - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - i = PyMapping_Size(env); - if (i < 0) - goto fail_1; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); - goto fail_1; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto fail_2; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_SetString(PyExc_TypeError, - "execve(): env.keys() or env.values() is not a list"); - goto fail_2; - } - - for (pos = 0; pos < i; pos++) { - char *p, *k, *v; - size_t len; - - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto fail_2; - - if (!PyArg_Parse( - key, - "s;execve() arg 3 contains a non-string key", - &k) || - !PyArg_Parse( - val, - "s;execve() arg 3 contains a non-string value", - &v)) - { - goto fail_2; - } - -#if defined(PYOS_OS2) - /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */ - if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) { -#endif - len = PyString_Size(key) + PyString_Size(val) + 2; - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - goto fail_2; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; -#if defined(PYOS_OS2) - } -#endif - } - envlist[envc] = 0; - - execve(path, argvlist, envlist); - - /* If we get here it's definitely an error */ - - (void) posix_error(); - - fail_2: - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); - fail_1: - free_string_array(argvlist, lastarg); - Py_XDECREF(vals); - Py_XDECREF(keys); - fail_0: - PyMem_Free(path); - return NULL; -} -#endif /* HAVE_EXECV */ - - -#ifdef HAVE_SPAWNV -PyDoc_STRVAR(posix_spawnv__doc__, -"spawnv(mode, path, args)\n\n\ -Execute the program 'path' in a new process.\n\ -\n\ - mode: mode of process creation\n\ - path: path of executable file\n\ - args: tuple or list of strings"); - -static PyObject * -posix_spawnv(PyObject *self, PyObject *args) -{ - char *path; - PyObject *argv; - char **argvlist; - int mode, i; - Py_ssize_t argc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* spawnv has three arguments: (mode, path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "ietO:spawnv", &mode, - Py_FileSystemDefaultEncoding, - &path, &argv)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnv() arg 2 must be a tuple or list"); - PyMem_Free(path); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyMem_Free(path); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), "et", - Py_FileSystemDefaultEncoding, - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString( - PyExc_TypeError, - "spawnv() arg 2 must contain only strings"); - PyMem_Free(path); - return NULL; - } - } - argvlist[argc] = NULL; - -#if defined(PYOS_OS2) && defined(PYCC_GCC) - Py_BEGIN_ALLOW_THREADS - spawnval = spawnv(mode, path, argvlist); - Py_END_ALLOW_THREADS -#else - if (mode == _OLD_P_OVERLAY) - mode = _P_OVERLAY; - - Py_BEGIN_ALLOW_THREADS - spawnval = _spawnv(mode, path, argvlist); - Py_END_ALLOW_THREADS -#endif - - free_string_array(argvlist, argc); - PyMem_Free(path); - - if (spawnval == -1) - return posix_error(); - else -#if SIZEOF_LONG == SIZEOF_VOID_P - return Py_BuildValue("l", (long) spawnval); -#else - return Py_BuildValue("L", (PY_LONG_LONG) spawnval); -#endif -} - - -PyDoc_STRVAR(posix_spawnve__doc__, -"spawnve(mode, path, args, env)\n\n\ -Execute the program 'path' in a new process.\n\ -\n\ - mode: mode of process creation\n\ - path: path of executable file\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); - -static PyObject * -posix_spawnve(PyObject *self, PyObject *args) -{ - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL; - int mode, pos, envc; - Py_ssize_t argc, i; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - Py_ssize_t lastarg = 0; - - /* spawnve has four arguments: (mode, path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "ietOO:spawnve", &mode, - Py_FileSystemDefaultEncoding, - &path, &argv, &env)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnve() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "spawnve() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), - "et;spawnve() arg 2 must contain only strings", - Py_FileSystemDefaultEncoding, - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - i = PyMapping_Size(env); - if (i < 0) - goto fail_1; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); - goto fail_1; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto fail_2; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_SetString(PyExc_TypeError, - "spawnve(): env.keys() or env.values() is not a list"); - goto fail_2; - } - - for (pos = 0; pos < i; pos++) { - char *p, *k, *v; - size_t len; - - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto fail_2; - - if (!PyArg_Parse( - key, - "s;spawnve() arg 3 contains a non-string key", - &k) || - !PyArg_Parse( - val, - "s;spawnve() arg 3 contains a non-string value", - &v)) - { - goto fail_2; - } - len = PyString_Size(key) + PyString_Size(val) + 2; - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - goto fail_2; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; - } - envlist[envc] = 0; - -#if defined(PYOS_OS2) && defined(PYCC_GCC) - Py_BEGIN_ALLOW_THREADS - spawnval = spawnve(mode, path, argvlist, envlist); - Py_END_ALLOW_THREADS -#else - if (mode == _OLD_P_OVERLAY) - mode = _P_OVERLAY; - - Py_BEGIN_ALLOW_THREADS - spawnval = _spawnve(mode, path, argvlist, envlist); - Py_END_ALLOW_THREADS -#endif - - if (spawnval == -1) - (void) posix_error(); - else -#if SIZEOF_LONG == SIZEOF_VOID_P - res = Py_BuildValue("l", (long) spawnval); -#else - res = Py_BuildValue("L", (PY_LONG_LONG) spawnval); -#endif - - fail_2: - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); - fail_1: - free_string_array(argvlist, lastarg); - Py_XDECREF(vals); - Py_XDECREF(keys); - fail_0: - PyMem_Free(path); - return res; -} - -/* OS/2 supports spawnvp & spawnvpe natively */ -#if defined(PYOS_OS2) -PyDoc_STRVAR(posix_spawnvp__doc__, -"spawnvp(mode, file, args)\n\n\ -Execute the program 'file' in a new process, using the environment\n\ -search path to find the file.\n\ -\n\ - mode: mode of process creation\n\ - file: executable file name\n\ - args: tuple or list of strings"); - -static PyObject * -posix_spawnvp(PyObject *self, PyObject *args) -{ - char *path; - PyObject *argv; - char **argvlist; - int mode, i, argc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* spawnvp has three arguments: (mode, path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "ietO:spawnvp", &mode, - Py_FileSystemDefaultEncoding, - &path, &argv)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnvp() arg 2 must be a tuple or list"); - PyMem_Free(path); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyMem_Free(path); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), "et", - Py_FileSystemDefaultEncoding, - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString( - PyExc_TypeError, - "spawnvp() arg 2 must contain only strings"); - PyMem_Free(path); - return NULL; - } - } - argvlist[argc] = NULL; - - Py_BEGIN_ALLOW_THREADS -#if defined(PYCC_GCC) - spawnval = spawnvp(mode, path, argvlist); -#else - spawnval = _spawnvp(mode, path, argvlist); -#endif - Py_END_ALLOW_THREADS - - free_string_array(argvlist, argc); - PyMem_Free(path); - - if (spawnval == -1) - return posix_error(); - else - return Py_BuildValue("l", (long) spawnval); -} - - -PyDoc_STRVAR(posix_spawnvpe__doc__, -"spawnvpe(mode, file, args, env)\n\n\ -Execute the program 'file' in a new process, using the environment\n\ -search path to find the file.\n\ -\n\ - mode: mode of process creation\n\ - file: executable file name\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); - -static PyObject * -posix_spawnvpe(PyObject *self, PyObject *args) -{ - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL; - int mode, i, pos, argc, envc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - int lastarg = 0; - - /* spawnvpe has four arguments: (mode, path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode, - Py_FileSystemDefaultEncoding, - &path, &argv, &env)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnvpe() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "spawnvpe() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), - "et;spawnvpe() arg 2 must contain only strings", - Py_FileSystemDefaultEncoding, - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - i = PyMapping_Size(env); - if (i < 0) - goto fail_1; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); - goto fail_1; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto fail_2; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_SetString(PyExc_TypeError, - "spawnvpe(): env.keys() or env.values() is not a list"); - goto fail_2; - } - - for (pos = 0; pos < i; pos++) { - char *p, *k, *v; - size_t len; - - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto fail_2; - - if (!PyArg_Parse( - key, - "s;spawnvpe() arg 3 contains a non-string key", - &k) || - !PyArg_Parse( - val, - "s;spawnvpe() arg 3 contains a non-string value", - &v)) - { - goto fail_2; - } - len = PyString_Size(key) + PyString_Size(val) + 2; - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - goto fail_2; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; - } - envlist[envc] = 0; - - Py_BEGIN_ALLOW_THREADS -#if defined(PYCC_GCC) - spawnval = spawnvpe(mode, path, argvlist, envlist); -#else - spawnval = _spawnvpe(mode, path, argvlist, envlist); -#endif - Py_END_ALLOW_THREADS - - if (spawnval == -1) - (void) posix_error(); - else - res = Py_BuildValue("l", (long) spawnval); - - fail_2: - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); - fail_1: - free_string_array(argvlist, lastarg); - Py_XDECREF(vals); - Py_XDECREF(keys); - fail_0: - PyMem_Free(path); - return res; -} -#endif /* PYOS_OS2 */ -#endif /* HAVE_SPAWNV */ - - -#ifdef HAVE_FORK1 -PyDoc_STRVAR(posix_fork1__doc__, -"fork1() -> pid\n\n\ -Fork a child process with a single multiplexed (i.e., not bound) thread.\n\ -\n\ -Return 0 to child process and PID of child to parent process."); - -static PyObject * -posix_fork1(PyObject *self, PyObject *noargs) -{ - pid_t pid; - int result = 0; - _PyImport_AcquireLock(); - pid = fork1(); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return PyLong_FromPid(pid); -} -#endif - - -#ifdef HAVE_FORK -PyDoc_STRVAR(posix_fork__doc__, -"fork() -> pid\n\n\ -Fork a child process.\n\ -Return 0 to child process and PID of child to parent process."); - -static PyObject * -posix_fork(PyObject *self, PyObject *noargs) -{ - pid_t pid; - int result = 0; - _PyImport_AcquireLock(); - pid = fork(); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return PyLong_FromPid(pid); -} -#endif - -/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */ -/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */ -#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX) -#define DEV_PTY_FILE "/dev/ptc" -#define HAVE_DEV_PTMX -#else -#define DEV_PTY_FILE "/dev/ptmx" -#endif - -#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) -#ifdef HAVE_PTY_H -#include -#else -#ifdef HAVE_LIBUTIL_H -#include -#else -#ifdef HAVE_UTIL_H -#include -#endif /* HAVE_UTIL_H */ -#endif /* HAVE_LIBUTIL_H */ -#endif /* HAVE_PTY_H */ -#ifdef HAVE_STROPTS_H -#include -#endif -#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX */ - -#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) -PyDoc_STRVAR(posix_openpty__doc__, -"openpty() -> (master_fd, slave_fd)\n\n\ -Open a pseudo-terminal, returning open fd's for both master and slave end.\n"); - -static PyObject * -posix_openpty(PyObject *self, PyObject *noargs) -{ - int master_fd, slave_fd; -#ifndef HAVE_OPENPTY - char * slave_name; -#endif -#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY) - PyOS_sighandler_t sig_saved; -#ifdef sun - extern char *ptsname(int fildes); -#endif -#endif - -#ifdef HAVE_OPENPTY - if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0) - return posix_error(); -#elif defined(HAVE__GETPTY) - slave_name = _getpty(&master_fd, O_RDWR, 0666, 0); - if (slave_name == NULL) - return posix_error(); - - slave_fd = open(slave_name, O_RDWR); - if (slave_fd < 0) - return posix_error(); -#else - master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */ - if (master_fd < 0) - return posix_error(); - sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL); - /* change permission of slave */ - if (grantpt(master_fd) < 0) { - PyOS_setsig(SIGCHLD, sig_saved); - return posix_error(); - } - /* unlock slave */ - if (unlockpt(master_fd) < 0) { - PyOS_setsig(SIGCHLD, sig_saved); - return posix_error(); - } - PyOS_setsig(SIGCHLD, sig_saved); - slave_name = ptsname(master_fd); /* get name of slave */ - if (slave_name == NULL) - return posix_error(); - slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */ - if (slave_fd < 0) - return posix_error(); -#if !defined(__CYGWIN__) && !defined(HAVE_DEV_PTC) - ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */ - ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */ -#ifndef __hpux - ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */ -#endif /* __hpux */ -#endif /* HAVE_CYGWIN */ -#endif /* HAVE_OPENPTY */ - - return Py_BuildValue("(ii)", master_fd, slave_fd); - -} -#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */ - -#ifdef HAVE_FORKPTY -PyDoc_STRVAR(posix_forkpty__doc__, -"forkpty() -> (pid, master_fd)\n\n\ -Fork a new process with a new pseudo-terminal as controlling tty.\n\n\ -Like fork(), return 0 as pid to child process, and PID of child to parent.\n\ -To both, return fd of newly opened pseudo-terminal.\n"); - -static PyObject * -posix_forkpty(PyObject *self, PyObject *noargs) -{ - int master_fd = -1, result = 0; - pid_t pid; - - _PyImport_AcquireLock(); - pid = forkpty(&master_fd, NULL, NULL, NULL); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd); -} -#endif - -#ifdef HAVE_GETEGID -PyDoc_STRVAR(posix_getegid__doc__, -"getegid() -> egid\n\n\ -Return the current process's effective group id."); - -static PyObject * -posix_getegid(PyObject *self, PyObject *noargs) -{ - return PyInt_FromLong((long)getegid()); -} -#endif - - -#ifdef HAVE_GETEUID -PyDoc_STRVAR(posix_geteuid__doc__, -"geteuid() -> euid\n\n\ -Return the current process's effective user id."); - -static PyObject * -posix_geteuid(PyObject *self, PyObject *noargs) -{ - return PyInt_FromLong((long)geteuid()); -} -#endif - - -#ifdef HAVE_GETGID -PyDoc_STRVAR(posix_getgid__doc__, -"getgid() -> gid\n\n\ -Return the current process's group id."); - -static PyObject * -posix_getgid(PyObject *self, PyObject *noargs) -{ - return PyInt_FromLong((long)getgid()); -} -#endif - - -PyDoc_STRVAR(posix_getpid__doc__, -"getpid() -> pid\n\n\ -Return the current process id"); - -static PyObject * -posix_getpid(PyObject *self, PyObject *noargs) -{ - return PyLong_FromPid(getpid()); -} - - -#ifdef HAVE_GETGROUPS -PyDoc_STRVAR(posix_getgroups__doc__, -"getgroups() -> list of group IDs\n\n\ -Return list of supplemental group IDs for the process."); - -static PyObject * -posix_getgroups(PyObject *self, PyObject *noargs) -{ - PyObject *result = NULL; - -#ifdef NGROUPS_MAX -#define MAX_GROUPS NGROUPS_MAX -#else - /* defined to be 16 on Solaris7, so this should be a small number */ -#define MAX_GROUPS 64 -#endif - gid_t grouplist[MAX_GROUPS]; - - /* On MacOSX getgroups(2) can return more than MAX_GROUPS results - * This is a helper variable to store the intermediate result when - * that happens. - * - * To keep the code readable the OSX behaviour is unconditional, - * according to the POSIX spec this should be safe on all unix-y - * systems. - */ - gid_t* alt_grouplist = grouplist; - int n; - - n = getgroups(MAX_GROUPS, grouplist); - if (n < 0) { - if (errno == EINVAL) { - n = getgroups(0, NULL); - if (n == -1) { - return posix_error(); - } - if (n == 0) { - /* Avoid malloc(0) */ - alt_grouplist = grouplist; - } else { - alt_grouplist = PyMem_Malloc(n * sizeof(gid_t)); - if (alt_grouplist == NULL) { - errno = EINVAL; - return posix_error(); - } - n = getgroups(n, alt_grouplist); - if (n == -1) { - PyMem_Free(alt_grouplist); - return posix_error(); - } - } - } else { - return posix_error(); - } - } - result = PyList_New(n); - if (result != NULL) { - int i; - for (i = 0; i < n; ++i) { - PyObject *o = PyInt_FromLong((long)alt_grouplist[i]); - if (o == NULL) { - Py_DECREF(result); - result = NULL; - break; - } - PyList_SET_ITEM(result, i, o); - } - } - - if (alt_grouplist != grouplist) { - PyMem_Free(alt_grouplist); - } - - return result; -} -#endif - -#ifdef HAVE_INITGROUPS -PyDoc_STRVAR(posix_initgroups__doc__, -"initgroups(username, gid) -> None\n\n\ -Call the system initgroups() to initialize the group access list with all of\n\ -the groups of which the specified username is a member, plus the specified\n\ -group id."); - -static PyObject * -posix_initgroups(PyObject *self, PyObject *args) -{ - char *username; - long gid; - - if (!PyArg_ParseTuple(args, "sl:initgroups", &username, &gid)) - return NULL; - - if (initgroups(username, (gid_t) gid) == -1) - return PyErr_SetFromErrno(PyExc_OSError); - - Py_INCREF(Py_None); - return Py_None; -} -#endif - -#ifdef HAVE_GETPGID -PyDoc_STRVAR(posix_getpgid__doc__, -"getpgid(pid) -> pgid\n\n\ -Call the system call getpgid()."); - -static PyObject * -posix_getpgid(PyObject *self, PyObject *args) -{ - pid_t pid, pgid; - if (!PyArg_ParseTuple(args, PARSE_PID ":getpgid", &pid)) - return NULL; - pgid = getpgid(pid); - if (pgid < 0) - return posix_error(); - return PyLong_FromPid(pgid); -} -#endif /* HAVE_GETPGID */ - - -#ifdef HAVE_GETPGRP -PyDoc_STRVAR(posix_getpgrp__doc__, -"getpgrp() -> pgrp\n\n\ -Return the current process group id."); - -static PyObject * -posix_getpgrp(PyObject *self, PyObject *noargs) -{ -#ifdef GETPGRP_HAVE_ARG - return PyLong_FromPid(getpgrp(0)); -#else /* GETPGRP_HAVE_ARG */ - return PyLong_FromPid(getpgrp()); -#endif /* GETPGRP_HAVE_ARG */ -} -#endif /* HAVE_GETPGRP */ - - -#ifdef HAVE_SETPGRP -PyDoc_STRVAR(posix_setpgrp__doc__, -"setpgrp()\n\n\ -Make this process the process group leader."); - -static PyObject * -posix_setpgrp(PyObject *self, PyObject *noargs) -{ -#ifdef SETPGRP_HAVE_ARG - if (setpgrp(0, 0) < 0) -#else /* SETPGRP_HAVE_ARG */ - if (setpgrp() < 0) -#endif /* SETPGRP_HAVE_ARG */ - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} - -#endif /* HAVE_SETPGRP */ - -#ifdef HAVE_GETPPID -PyDoc_STRVAR(posix_getppid__doc__, -"getppid() -> ppid\n\n\ -Return the parent's process id."); - -static PyObject * -posix_getppid(PyObject *self, PyObject *noargs) -{ - return PyLong_FromPid(getppid()); -} -#endif - - -#ifdef HAVE_GETLOGIN -PyDoc_STRVAR(posix_getlogin__doc__, -"getlogin() -> string\n\n\ -Return the actual login name."); - -static PyObject * -posix_getlogin(PyObject *self, PyObject *noargs) -{ - PyObject *result = NULL; - char *name; - int old_errno = errno; - - errno = 0; - name = getlogin(); - if (name == NULL) { - if (errno) - posix_error(); - else - PyErr_SetString(PyExc_OSError, - "unable to determine login name"); - } - else - result = PyString_FromString(name); - errno = old_errno; - - return result; -} -#endif - -#ifndef UEFI_C_SOURCE -PyDoc_STRVAR(posix_getuid__doc__, -"getuid() -> uid\n\n\ -Return the current process's user id."); - -static PyObject * -posix_getuid(PyObject *self, PyObject *noargs) -{ - return PyInt_FromLong((long)getuid()); -} -#endif /* UEFI_C_SOURCE */ - -#ifdef HAVE_KILL -PyDoc_STRVAR(posix_kill__doc__, -"kill(pid, sig)\n\n\ -Kill a process with a signal."); - -static PyObject * -posix_kill(PyObject *self, PyObject *args) -{ - pid_t pid; - int sig; - if (!PyArg_ParseTuple(args, PARSE_PID "i:kill", &pid, &sig)) - return NULL; -#if defined(PYOS_OS2) && !defined(PYCC_GCC) - if (sig == XCPT_SIGNAL_INTR || sig == XCPT_SIGNAL_BREAK) { - APIRET rc; - if ((rc = DosSendSignalException(pid, sig)) != NO_ERROR) - return os2_error(rc); - - } else if (sig == XCPT_SIGNAL_KILLPROC) { - APIRET rc; - if ((rc = DosKillProcess(DKP_PROCESS, pid)) != NO_ERROR) - return os2_error(rc); - - } else - return NULL; /* Unrecognized Signal Requested */ -#else - if (kill(pid, sig) == -1) - return posix_error(); -#endif - Py_INCREF(Py_None); - return Py_None; -} -#endif - -#ifdef HAVE_KILLPG -PyDoc_STRVAR(posix_killpg__doc__, -"killpg(pgid, sig)\n\n\ -Kill a process group with a signal."); - -static PyObject * -posix_killpg(PyObject *self, PyObject *args) -{ - int sig; - pid_t pgid; - /* XXX some man pages make the `pgid` parameter an int, others - a pid_t. Since getpgrp() returns a pid_t, we assume killpg should - take the same type. Moreover, pid_t is always at least as wide as - int (else compilation of this module fails), which is safe. */ - if (!PyArg_ParseTuple(args, PARSE_PID "i:killpg", &pgid, &sig)) - return NULL; - if (killpg(pgid, sig) == -1) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} -#endif - -#ifdef HAVE_PLOCK - -#ifdef HAVE_SYS_LOCK_H -#include -#endif - -PyDoc_STRVAR(posix_plock__doc__, -"plock(op)\n\n\ -Lock program segments into memory."); - -static PyObject * -posix_plock(PyObject *self, PyObject *args) -{ - int op; - if (!PyArg_ParseTuple(args, "i:plock", &op)) - return NULL; - if (plock(op) == -1) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} -#endif - - -#ifdef HAVE_POPEN -PyDoc_STRVAR(posix_popen__doc__, -"popen(command [, mode='r' [, bufsize]]) -> pipe\n\n\ -Open a pipe to/from a command returning a file object."); - -#if defined(PYOS_OS2) -#if defined(PYCC_VACPP) -static int -async_system(const char *command) -{ - char errormsg[256], args[1024]; - RESULTCODES rcodes; - APIRET rc; - - char *shell = getenv("COMSPEC"); - if (!shell) - shell = "cmd"; - - /* avoid overflowing the argument buffer */ - if (strlen(shell) + 3 + strlen(command) >= 1024) - return ERROR_NOT_ENOUGH_MEMORY - - args[0] = '\0'; - strcat(args, shell); - strcat(args, "/c "); - strcat(args, command); - - /* execute asynchronously, inheriting the environment */ - rc = DosExecPgm(errormsg, - sizeof(errormsg), - EXEC_ASYNC, - args, - NULL, - &rcodes, - shell); - return rc; -} - -static FILE * -popen(const char *command, const char *mode, int pipesize, int *err) -{ - int oldfd, tgtfd; - HFILE pipeh[2]; - APIRET rc; - - /* mode determines which of stdin or stdout is reconnected to - * the pipe to the child - */ - if (strchr(mode, 'r') != NULL) { - tgt_fd = 1; /* stdout */ - } else if (strchr(mode, 'w')) { - tgt_fd = 0; /* stdin */ - } else { - *err = ERROR_INVALID_ACCESS; - return NULL; - } - - /* setup the pipe */ - if ((rc = DosCreatePipe(&pipeh[0], &pipeh[1], pipesize)) != NO_ERROR) { - *err = rc; - return NULL; - } - - /* prevent other threads accessing stdio */ - DosEnterCritSec(); - - /* reconnect stdio and execute child */ - oldfd = dup(tgtfd); - close(tgtfd); - if (dup2(pipeh[tgtfd], tgtfd) == 0) { - DosClose(pipeh[tgtfd]); - rc = async_system(command); - } - - /* restore stdio */ - dup2(oldfd, tgtfd); - close(oldfd); - - /* allow other threads access to stdio */ - DosExitCritSec(); - - /* if execution of child was successful return file stream */ - if (rc == NO_ERROR) - return fdopen(pipeh[1 - tgtfd], mode); - else { - DosClose(pipeh[1 - tgtfd]); - *err = rc; - return NULL; - } -} - -static PyObject * -posix_popen(PyObject *self, PyObject *args) -{ - char *name; - char *mode = "r"; - int err, bufsize = -1; - FILE *fp; - PyObject *f; - if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) - return NULL; - Py_BEGIN_ALLOW_THREADS - fp = popen(name, mode, (bufsize > 0) ? bufsize : 4096, &err); - Py_END_ALLOW_THREADS - if (fp == NULL) - return os2_error(err); - - f = PyFile_FromFile(fp, name, mode, fclose); - if (f != NULL) - PyFile_SetBufSize(f, bufsize); - return f; -} - -#elif defined(PYCC_GCC) - -/* standard posix version of popen() support */ -static PyObject * -posix_popen(PyObject *self, PyObject *args) -{ - char *name; - char *mode = "r"; - int bufsize = -1; - FILE *fp; - PyObject *f; - if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) - return NULL; - Py_BEGIN_ALLOW_THREADS - fp = popen(name, mode); - Py_END_ALLOW_THREADS - if (fp == NULL) - return posix_error(); - f = PyFile_FromFile(fp, name, mode, pclose); - if (f != NULL) - PyFile_SetBufSize(f, bufsize); - return f; -} - -/* fork() under OS/2 has lots'o'warts - * EMX supports pipe() and spawn*() so we can synthesize popen[234]() - * most of this code is a ripoff of the win32 code, but using the - * capabilities of EMX's C library routines - */ - -/* These tell _PyPopen() whether to return 1, 2, or 3 file objects. */ -#define POPEN_1 1 -#define POPEN_2 2 -#define POPEN_3 3 -#define POPEN_4 4 - -static PyObject *_PyPopen(char *, int, int, int); -static int _PyPclose(FILE *file); - -/* - * Internal dictionary mapping popen* file pointers to process handles, - * for use when retrieving the process exit code. See _PyPclose() below - * for more information on this dictionary's use. - */ -static PyObject *_PyPopenProcs = NULL; - -/* os2emx version of popen2() - * - * The result of this function is a pipe (file) connected to the - * process's stdin, and a pipe connected to the process's stdout. - */ - -static PyObject * -os2emx_popen2(PyObject *self, PyObject *args) -{ - PyObject *f; - int tm=0; - - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); - return NULL; - } else - tm = O_BINARY; - - f = _PyPopen(cmdstring, tm, POPEN_2, bufsize); - - return f; -} - -/* - * Variation on os2emx.popen2 - * - * The result of this function is 3 pipes - the process's stdin, - * stdout and stderr - */ - -static PyObject * -os2emx_popen3(PyObject *self, PyObject *args) -{ - PyObject *f; - int tm = 0; - - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); - return NULL; - } else - tm = O_BINARY; - - f = _PyPopen(cmdstring, tm, POPEN_3, bufsize); - - return f; -} - -/* - * Variation on os2emx.popen2 - * - * The result of this function is 2 pipes - the processes stdin, - * and stdout+stderr combined as a single pipe. - */ - -static PyObject * -os2emx_popen4(PyObject *self, PyObject *args) -{ - PyObject *f; - int tm = 0; - - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); - return NULL; - } else - tm = O_BINARY; - - f = _PyPopen(cmdstring, tm, POPEN_4, bufsize); - - return f; -} - -/* a couple of structures for convenient handling of multiple - * file handles and pipes - */ -struct file_ref -{ - int handle; - int flags; -}; - -struct pipe_ref -{ - int rd; - int wr; -}; - -/* The following code is derived from the win32 code */ - -static PyObject * -_PyPopen(char *cmdstring, int mode, int n, int bufsize) -{ - struct file_ref stdio[3]; - struct pipe_ref p_fd[3]; - FILE *p_s[3]; - int file_count, i, pipe_err; - pid_t pipe_pid; - char *shell, *sh_name, *opt, *rd_mode, *wr_mode; - PyObject *f, *p_f[3]; - - /* file modes for subsequent fdopen's on pipe handles */ - if (mode == O_TEXT) - { - rd_mode = "rt"; - wr_mode = "wt"; - } - else - { - rd_mode = "rb"; - wr_mode = "wb"; - } - - /* prepare shell references */ - if ((shell = getenv("EMXSHELL")) == NULL) - if ((shell = getenv("COMSPEC")) == NULL) - { - errno = ENOENT; - return posix_error(); - } - - sh_name = _getname(shell); - if (stricmp(sh_name, "cmd.exe") == 0 || stricmp(sh_name, "4os2.exe") == 0) - opt = "/c"; - else - opt = "-c"; - - /* save current stdio fds + their flags, and set not inheritable */ - i = pipe_err = 0; - while (pipe_err >= 0 && i < 3) - { - pipe_err = stdio[i].handle = dup(i); - stdio[i].flags = fcntl(i, F_GETFD, 0); - fcntl(stdio[i].handle, F_SETFD, stdio[i].flags | FD_CLOEXEC); - i++; - } - if (pipe_err < 0) - { - /* didn't get them all saved - clean up and bail out */ - int saved_err = errno; - while (i-- > 0) - { - close(stdio[i].handle); - } - errno = saved_err; - return posix_error(); - } - - /* create pipe ends */ - file_count = 2; - if (n == POPEN_3) - file_count = 3; - i = pipe_err = 0; - while ((pipe_err == 0) && (i < file_count)) - pipe_err = pipe((int *)&p_fd[i++]); - if (pipe_err < 0) - { - /* didn't get them all made - clean up and bail out */ - while (i-- > 0) - { - close(p_fd[i].wr); - close(p_fd[i].rd); - } - errno = EPIPE; - return posix_error(); - } - - /* change the actual standard IO streams over temporarily, - * making the retained pipe ends non-inheritable - */ - pipe_err = 0; - - /* - stdin */ - if (dup2(p_fd[0].rd, 0) == 0) - { - close(p_fd[0].rd); - i = fcntl(p_fd[0].wr, F_GETFD, 0); - fcntl(p_fd[0].wr, F_SETFD, i | FD_CLOEXEC); - if ((p_s[0] = fdopen(p_fd[0].wr, wr_mode)) == NULL) - { - close(p_fd[0].wr); - pipe_err = -1; - } - } - else - { - pipe_err = -1; - } - - /* - stdout */ - if (pipe_err == 0) - { - if (dup2(p_fd[1].wr, 1) == 1) - { - close(p_fd[1].wr); - i = fcntl(p_fd[1].rd, F_GETFD, 0); - fcntl(p_fd[1].rd, F_SETFD, i | FD_CLOEXEC); - if ((p_s[1] = fdopen(p_fd[1].rd, rd_mode)) == NULL) - { - close(p_fd[1].rd); - pipe_err = -1; - } - } - else - { - pipe_err = -1; - } - } - - /* - stderr, as required */ - if (pipe_err == 0) - switch (n) - { - case POPEN_3: - { - if (dup2(p_fd[2].wr, 2) == 2) - { - close(p_fd[2].wr); - i = fcntl(p_fd[2].rd, F_GETFD, 0); - fcntl(p_fd[2].rd, F_SETFD, i | FD_CLOEXEC); - if ((p_s[2] = fdopen(p_fd[2].rd, rd_mode)) == NULL) - { - close(p_fd[2].rd); - pipe_err = -1; - } - } - else - { - pipe_err = -1; - } - break; - } - - case POPEN_4: - { - if (dup2(1, 2) != 2) - { - pipe_err = -1; - } - break; - } - } - - /* spawn the child process */ - if (pipe_err == 0) - { - pipe_pid = spawnlp(P_NOWAIT, shell, shell, opt, cmdstring, (char *)0); - if (pipe_pid == -1) - { - pipe_err = -1; - } - else - { - /* save the PID into the FILE structure - * NOTE: this implementation doesn't actually - * take advantage of this, but do it for - * completeness - AIM Apr01 - */ - for (i = 0; i < file_count; i++) - p_s[i]->_pid = pipe_pid; - } - } - - /* reset standard IO to normal */ - for (i = 0; i < 3; i++) - { - dup2(stdio[i].handle, i); - fcntl(i, F_SETFD, stdio[i].flags); - close(stdio[i].handle); - } - - /* if any remnant problems, clean up and bail out */ - if (pipe_err < 0) - { - for (i = 0; i < 3; i++) - { - close(p_fd[i].rd); - close(p_fd[i].wr); - } - errno = EPIPE; - return posix_error_with_filename(cmdstring); - } - - /* build tuple of file objects to return */ - if ((p_f[0] = PyFile_FromFile(p_s[0], cmdstring, wr_mode, _PyPclose)) != NULL) - PyFile_SetBufSize(p_f[0], bufsize); - if ((p_f[1] = PyFile_FromFile(p_s[1], cmdstring, rd_mode, _PyPclose)) != NULL) - PyFile_SetBufSize(p_f[1], bufsize); - if (n == POPEN_3) - { - if ((p_f[2] = PyFile_FromFile(p_s[2], cmdstring, rd_mode, _PyPclose)) != NULL) - PyFile_SetBufSize(p_f[0], bufsize); - f = PyTuple_Pack(3, p_f[0], p_f[1], p_f[2]); - } - else - f = PyTuple_Pack(2, p_f[0], p_f[1]); - - /* - * Insert the files we've created into the process dictionary - * all referencing the list with the process handle and the - * initial number of files (see description below in _PyPclose). - * Since if _PyPclose later tried to wait on a process when all - * handles weren't closed, it could create a deadlock with the - * child, we spend some energy here to try to ensure that we - * either insert all file handles into the dictionary or none - * at all. It's a little clumsy with the various popen modes - * and variable number of files involved. - */ - if (!_PyPopenProcs) - { - _PyPopenProcs = PyDict_New(); - } - - if (_PyPopenProcs) - { - PyObject *procObj, *pidObj, *intObj, *fileObj[3]; - int ins_rc[3]; - - fileObj[0] = fileObj[1] = fileObj[2] = NULL; - ins_rc[0] = ins_rc[1] = ins_rc[2] = 0; - - procObj = PyList_New(2); - pidObj = PyLong_FromPid(pipe_pid); - intObj = PyInt_FromLong((long) file_count); - - if (procObj && pidObj && intObj) - { - PyList_SetItem(procObj, 0, pidObj); - PyList_SetItem(procObj, 1, intObj); - - fileObj[0] = PyLong_FromVoidPtr(p_s[0]); - if (fileObj[0]) - { - ins_rc[0] = PyDict_SetItem(_PyPopenProcs, - fileObj[0], - procObj); - } - fileObj[1] = PyLong_FromVoidPtr(p_s[1]); - if (fileObj[1]) - { - ins_rc[1] = PyDict_SetItem(_PyPopenProcs, - fileObj[1], - procObj); - } - if (file_count >= 3) - { - fileObj[2] = PyLong_FromVoidPtr(p_s[2]); - if (fileObj[2]) - { - ins_rc[2] = PyDict_SetItem(_PyPopenProcs, - fileObj[2], - procObj); - } - } - - if (ins_rc[0] < 0 || !fileObj[0] || - ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) || - ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) - { - /* Something failed - remove any dictionary - * entries that did make it. - */ - if (!ins_rc[0] && fileObj[0]) - { - PyDict_DelItem(_PyPopenProcs, - fileObj[0]); - } - if (!ins_rc[1] && fileObj[1]) - { - PyDict_DelItem(_PyPopenProcs, - fileObj[1]); - } - if (!ins_rc[2] && fileObj[2]) - { - PyDict_DelItem(_PyPopenProcs, - fileObj[2]); - } - } - } - - /* - * Clean up our localized references for the dictionary keys - * and value since PyDict_SetItem will Py_INCREF any copies - * that got placed in the dictionary. - */ - Py_XDECREF(procObj); - Py_XDECREF(fileObj[0]); - Py_XDECREF(fileObj[1]); - Py_XDECREF(fileObj[2]); - } - - /* Child is launched. */ - return f; -} - -/* - * Wrapper for fclose() to use for popen* files, so we can retrieve the - * exit code for the child process and return as a result of the close. - * - * This function uses the _PyPopenProcs dictionary in order to map the - * input file pointer to information about the process that was - * originally created by the popen* call that created the file pointer. - * The dictionary uses the file pointer as a key (with one entry - * inserted for each file returned by the original popen* call) and a - * single list object as the value for all files from a single call. - * The list object contains the Win32 process handle at [0], and a file - * count at [1], which is initialized to the total number of file - * handles using that list. - * - * This function closes whichever handle it is passed, and decrements - * the file count in the dictionary for the process handle pointed to - * by this file. On the last close (when the file count reaches zero), - * this function will wait for the child process and then return its - * exit code as the result of the close() operation. This permits the - * files to be closed in any order - it is always the close() of the - * final handle that will return the exit code. - * - * NOTE: This function is currently called with the GIL released. - * hence we use the GILState API to manage our state. - */ - -static int _PyPclose(FILE *file) -{ - int result; - int exit_code; - pid_t pipe_pid; - PyObject *procObj, *pidObj, *intObj, *fileObj; - int file_count; -#ifdef WITH_THREAD - PyGILState_STATE state; -#endif - - /* Close the file handle first, to ensure it can't block the - * child from exiting if it's the last handle. - */ - result = fclose(file); - -#ifdef WITH_THREAD - state = PyGILState_Ensure(); -#endif - if (_PyPopenProcs) - { - if ((fileObj = PyLong_FromVoidPtr(file)) != NULL && - (procObj = PyDict_GetItem(_PyPopenProcs, - fileObj)) != NULL && - (pidObj = PyList_GetItem(procObj,0)) != NULL && - (intObj = PyList_GetItem(procObj,1)) != NULL) - { - pipe_pid = (pid_t) PyLong_AsPid(pidObj); - file_count = (int) PyInt_AsLong(intObj); - - if (file_count > 1) - { - /* Still other files referencing process */ - file_count--; - PyList_SetItem(procObj,1, - PyInt_FromLong((long) file_count)); - } - else - { - /* Last file for this process */ - if (result != EOF && - waitpid(pipe_pid, &exit_code, 0) == pipe_pid) - { - /* extract exit status */ - if (WIFEXITED(exit_code)) - { - result = WEXITSTATUS(exit_code); - } - else - { - errno = EPIPE; - result = -1; - } - } - else - { - /* Indicate failure - this will cause the file object - * to raise an I/O error and translate the last - * error code from errno. We do have a problem with - * last errors that overlap the normal errno table, - * but that's a consistent problem with the file object. - */ - result = -1; - } - } - - /* Remove this file pointer from dictionary */ - PyDict_DelItem(_PyPopenProcs, fileObj); - - if (PyDict_Size(_PyPopenProcs) == 0) - { - Py_DECREF(_PyPopenProcs); - _PyPopenProcs = NULL; - } - - } /* if object retrieval ok */ - - Py_XDECREF(fileObj); - } /* if _PyPopenProcs */ - -#ifdef WITH_THREAD - PyGILState_Release(state); -#endif - return result; -} - -#endif /* PYCC_??? */ - -#elif defined(MS_WINDOWS) - -/* - * Portable 'popen' replacement for Win32. - * - * Written by Bill Tutt . Minor tweaks - * and 2.0 integration by Fredrik Lundh - * Return code handling by David Bolen . - */ - -#include -#include -#include - -/* These tell _PyPopen() wether to return 1, 2, or 3 file objects. */ -#define POPEN_1 1 -#define POPEN_2 2 -#define POPEN_3 3 -#define POPEN_4 4 - -static PyObject *_PyPopen(char *, int, int); -static int _PyPclose(FILE *file); - -/* - * Internal dictionary mapping popen* file pointers to process handles, - * for use when retrieving the process exit code. See _PyPclose() below - * for more information on this dictionary's use. - */ -static PyObject *_PyPopenProcs = NULL; - - -/* popen that works from a GUI. - * - * The result of this function is a pipe (file) connected to the - * processes stdin or stdout, depending on the requested mode. - */ - -static PyObject * -posix_popen(PyObject *self, PyObject *args) -{ - PyObject *f; - int tm = 0; - - char *cmdstring; - char *mode = "r"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 'r') - tm = _O_RDONLY; - else if (*mode != 'w') { - PyErr_SetString(PyExc_ValueError, "popen() arg 2 must be 'r' or 'w'"); - return NULL; - } else - tm = _O_WRONLY; - - if (bufsize != -1) { - PyErr_SetString(PyExc_ValueError, "popen() arg 3 must be -1"); - return NULL; - } - - if (*(mode+1) == 't') - f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1); - else if (*(mode+1) == 'b') - f = _PyPopen(cmdstring, tm | _O_BINARY, POPEN_1); - else - f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1); - - return f; -} - -/* Variation on win32pipe.popen - * - * The result of this function is a pipe (file) connected to the - * process's stdin, and a pipe connected to the process's stdout. - */ - -static PyObject * -win32_popen2(PyObject *self, PyObject *args) -{ - PyObject *f; - int tm=0; - - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = _O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "popen2() arg 2 must be 't' or 'b'"); - return NULL; - } else - tm = _O_BINARY; - - if (bufsize != -1) { - PyErr_SetString(PyExc_ValueError, "popen2() arg 3 must be -1"); - return NULL; - } - - f = _PyPopen(cmdstring, tm, POPEN_2); - - return f; -} - -/* - * Variation on - * - * The result of this function is 3 pipes - the process's stdin, - * stdout and stderr - */ - -static PyObject * -win32_popen3(PyObject *self, PyObject *args) -{ - PyObject *f; - int tm = 0; - - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = _O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "popen3() arg 2 must be 't' or 'b'"); - return NULL; - } else - tm = _O_BINARY; - - if (bufsize != -1) { - PyErr_SetString(PyExc_ValueError, "popen3() arg 3 must be -1"); - return NULL; - } - - f = _PyPopen(cmdstring, tm, POPEN_3); - - return f; -} - -/* - * Variation on win32pipe.popen - * - * The result of this function is 2 pipes - the processes stdin, - * and stdout+stderr combined as a single pipe. - */ - -static PyObject * -win32_popen4(PyObject *self, PyObject *args) -{ - PyObject *f; - int tm = 0; - - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = _O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "popen4() arg 2 must be 't' or 'b'"); - return NULL; - } else - tm = _O_BINARY; - - if (bufsize != -1) { - PyErr_SetString(PyExc_ValueError, "popen4() arg 3 must be -1"); - return NULL; - } - - f = _PyPopen(cmdstring, tm, POPEN_4); - - return f; -} - -static BOOL -_PyPopenCreateProcess(char *cmdstring, - HANDLE hStdin, - HANDLE hStdout, - HANDLE hStderr, - HANDLE *hProcess) -{ - PROCESS_INFORMATION piProcInfo; - STARTUPINFO siStartInfo; - DWORD dwProcessFlags = 0; /* no NEW_CONSOLE by default for Ctrl+C handling */ - char *s1,*s2, *s3 = " /c "; - const char *szConsoleSpawn = "w9xpopen.exe"; - int i; - Py_ssize_t x; - - if (i = GetEnvironmentVariable("COMSPEC",NULL,0)) { - char *comshell; - - s1 = (char *)alloca(i); - if (!(x = GetEnvironmentVariable("COMSPEC", s1, i))) - /* x < i, so x fits into an integer */ - return (int)x; - - /* Explicitly check if we are using COMMAND.COM. If we are - * then use the w9xpopen hack. - */ - comshell = s1 + x; - while (comshell >= s1 && *comshell != '\\') - --comshell; - ++comshell; - - if (GetVersion() < 0x80000000 && - _stricmp(comshell, "command.com") != 0) { - /* NT/2000 and not using command.com. */ - x = i + strlen(s3) + strlen(cmdstring) + 1; - s2 = (char *)alloca(x); - ZeroMemory(s2, x); - PyOS_snprintf(s2, x, "%s%s%s", s1, s3, cmdstring); - } - else { - /* - * Oh gag, we're on Win9x or using COMMAND.COM. Use - * the workaround listed in KB: Q150956 - */ - char modulepath[_MAX_PATH]; - struct stat statinfo; - GetModuleFileName(NULL, modulepath, sizeof(modulepath)); - for (x = i = 0; modulepath[i]; i++) - if (modulepath[i] == SEP) - x = i+1; - modulepath[x] = '\0'; - /* Create the full-name to w9xpopen, so we can test it exists */ - strncat(modulepath, - szConsoleSpawn, - (sizeof(modulepath)/sizeof(modulepath[0])) - -strlen(modulepath)); - if (stat(modulepath, &statinfo) != 0) { - size_t mplen = sizeof(modulepath)/sizeof(modulepath[0]); - /* Eeek - file-not-found - possibly an embedding - situation - see if we can locate it in sys.prefix - */ - strncpy(modulepath, - Py_GetExecPrefix(), - mplen); - modulepath[mplen-1] = '\0'; - if (modulepath[strlen(modulepath)-1] != '\\') - strcat(modulepath, "\\"); - strncat(modulepath, - szConsoleSpawn, - mplen-strlen(modulepath)); - /* No where else to look - raise an easily identifiable - error, rather than leaving Windows to report - "file not found" - as the user is probably blissfully - unaware this shim EXE is used, and it will confuse them. - (well, it confused me for a while ;-) - */ - if (stat(modulepath, &statinfo) != 0) { - PyErr_Format(PyExc_RuntimeError, - "Can not locate '%s' which is needed " - "for popen to work with your shell " - "or platform.", - szConsoleSpawn); - return FALSE; - } - } - x = i + strlen(s3) + strlen(cmdstring) + 1 + - strlen(modulepath) + - strlen(szConsoleSpawn) + 1; - - s2 = (char *)alloca(x); - ZeroMemory(s2, x); - /* To maintain correct argument passing semantics, - we pass the command-line as it stands, and allow - quoting to be applied. w9xpopen.exe will then - use its argv vector, and re-quote the necessary - args for the ultimate child process. - */ - PyOS_snprintf( - s2, x, - "\"%s\" %s%s%s", - modulepath, - s1, - s3, - cmdstring); - /* Not passing CREATE_NEW_CONSOLE has been known to - cause random failures on win9x. Specifically a - dialog: - "Your program accessed mem currently in use at xxx" - and a hopeful warning about the stability of your - system. - Cost is Ctrl+C won't kill children, but anyone - who cares can have a go! - */ - dwProcessFlags |= CREATE_NEW_CONSOLE; - } - } - - /* Could be an else here to try cmd.exe / command.com in the path - Now we'll just error out.. */ - else { - PyErr_SetString(PyExc_RuntimeError, - "Cannot locate a COMSPEC environment variable to " - "use as the shell"); - return FALSE; - } - - ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); - siStartInfo.cb = sizeof(STARTUPINFO); - siStartInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; - siStartInfo.hStdInput = hStdin; - siStartInfo.hStdOutput = hStdout; - siStartInfo.hStdError = hStderr; - siStartInfo.wShowWindow = SW_HIDE; - - if (CreateProcess(NULL, - s2, - NULL, - NULL, - TRUE, - dwProcessFlags, - NULL, - NULL, - &siStartInfo, - &piProcInfo) ) { - /* Close the handles now so anyone waiting is woken. */ - CloseHandle(piProcInfo.hThread); - - /* Return process handle */ - *hProcess = piProcInfo.hProcess; - return TRUE; - } - win32_error("CreateProcess", s2); - return FALSE; -} - -/* The following code is based off of KB: Q190351 */ - -static PyObject * -_PyPopen(char *cmdstring, int mode, int n) -{ - HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr, - hChildStderrRd, hChildStderrWr, hChildStdinWrDup, hChildStdoutRdDup, - hChildStderrRdDup, hProcess; /* hChildStdoutWrDup; */ - - SECURITY_ATTRIBUTES saAttr; - BOOL fSuccess; - int fd1, fd2, fd3; - FILE *f1, *f2, *f3; - long file_count; - PyObject *f; - - saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); - saAttr.bInheritHandle = TRUE; - saAttr.lpSecurityDescriptor = NULL; - - if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) - return win32_error("CreatePipe", NULL); - - /* Create new output read handle and the input write handle. Set - * the inheritance properties to FALSE. Otherwise, the child inherits - * these handles; resulting in non-closeable handles to the pipes - * being created. */ - fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr, - GetCurrentProcess(), &hChildStdinWrDup, 0, - FALSE, - DUPLICATE_SAME_ACCESS); - if (!fSuccess) - return win32_error("DuplicateHandle", NULL); - - /* Close the inheritable version of ChildStdin - that we're using. */ - CloseHandle(hChildStdinWr); - - if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) - return win32_error("CreatePipe", NULL); - - fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd, - GetCurrentProcess(), &hChildStdoutRdDup, 0, - FALSE, DUPLICATE_SAME_ACCESS); - if (!fSuccess) - return win32_error("DuplicateHandle", NULL); - - /* Close the inheritable version of ChildStdout - that we're using. */ - CloseHandle(hChildStdoutRd); - - if (n != POPEN_4) { - if (!CreatePipe(&hChildStderrRd, &hChildStderrWr, &saAttr, 0)) - return win32_error("CreatePipe", NULL); - fSuccess = DuplicateHandle(GetCurrentProcess(), - hChildStderrRd, - GetCurrentProcess(), - &hChildStderrRdDup, 0, - FALSE, DUPLICATE_SAME_ACCESS); - if (!fSuccess) - return win32_error("DuplicateHandle", NULL); - /* Close the inheritable version of ChildStdErr that we're using. */ - CloseHandle(hChildStderrRd); - } - - switch (n) { - case POPEN_1: - switch (mode & (_O_RDONLY | _O_TEXT | _O_BINARY | _O_WRONLY)) { - case _O_WRONLY | _O_TEXT: - /* Case for writing to child Stdin in text mode. */ - fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); - f1 = _fdopen(fd1, "w"); - f = PyFile_FromFile(f1, cmdstring, "w", _PyPclose); - PyFile_SetBufSize(f, 0); - /* We don't care about these pipes anymore, so close them. */ - CloseHandle(hChildStdoutRdDup); - CloseHandle(hChildStderrRdDup); - break; - - case _O_RDONLY | _O_TEXT: - /* Case for reading from child Stdout in text mode. */ - fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); - f1 = _fdopen(fd1, "r"); - f = PyFile_FromFile(f1, cmdstring, "r", _PyPclose); - PyFile_SetBufSize(f, 0); - /* We don't care about these pipes anymore, so close them. */ - CloseHandle(hChildStdinWrDup); - CloseHandle(hChildStderrRdDup); - break; - - case _O_RDONLY | _O_BINARY: - /* Case for readinig from child Stdout in binary mode. */ - fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); - f1 = _fdopen(fd1, "rb"); - f = PyFile_FromFile(f1, cmdstring, "rb", _PyPclose); - PyFile_SetBufSize(f, 0); - /* We don't care about these pipes anymore, so close them. */ - CloseHandle(hChildStdinWrDup); - CloseHandle(hChildStderrRdDup); - break; - - case _O_WRONLY | _O_BINARY: - /* Case for writing to child Stdin in binary mode. */ - fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); - f1 = _fdopen(fd1, "wb"); - f = PyFile_FromFile(f1, cmdstring, "wb", _PyPclose); - PyFile_SetBufSize(f, 0); - /* We don't care about these pipes anymore, so close them. */ - CloseHandle(hChildStdoutRdDup); - CloseHandle(hChildStderrRdDup); - break; - } - file_count = 1; - break; - - case POPEN_2: - case POPEN_4: - { - char *m1, *m2; - PyObject *p1, *p2; - - if (mode & _O_TEXT) { - m1 = "r"; - m2 = "w"; - } else { - m1 = "rb"; - m2 = "wb"; - } - - fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); - f1 = _fdopen(fd1, m2); - fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); - f2 = _fdopen(fd2, m1); - p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose); - PyFile_SetBufSize(p1, 0); - p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose); - PyFile_SetBufSize(p2, 0); - - if (n != 4) - CloseHandle(hChildStderrRdDup); - - f = PyTuple_Pack(2,p1,p2); - Py_XDECREF(p1); - Py_XDECREF(p2); - file_count = 2; - break; - } - - case POPEN_3: - { - char *m1, *m2; - PyObject *p1, *p2, *p3; - - if (mode & _O_TEXT) { - m1 = "r"; - m2 = "w"; - } else { - m1 = "rb"; - m2 = "wb"; - } - - fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); - f1 = _fdopen(fd1, m2); - fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); - f2 = _fdopen(fd2, m1); - fd3 = _open_osfhandle((Py_intptr_t)hChildStderrRdDup, mode); - f3 = _fdopen(fd3, m1); - p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose); - p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose); - p3 = PyFile_FromFile(f3, cmdstring, m1, _PyPclose); - PyFile_SetBufSize(p1, 0); - PyFile_SetBufSize(p2, 0); - PyFile_SetBufSize(p3, 0); - f = PyTuple_Pack(3,p1,p2,p3); - Py_XDECREF(p1); - Py_XDECREF(p2); - Py_XDECREF(p3); - file_count = 3; - break; - } - } - - if (n == POPEN_4) { - if (!_PyPopenCreateProcess(cmdstring, - hChildStdinRd, - hChildStdoutWr, - hChildStdoutWr, - &hProcess)) - return NULL; - } - else { - if (!_PyPopenCreateProcess(cmdstring, - hChildStdinRd, - hChildStdoutWr, - hChildStderrWr, - &hProcess)) - return NULL; - } - - /* - * Insert the files we've created into the process dictionary - * all referencing the list with the process handle and the - * initial number of files (see description below in _PyPclose). - * Since if _PyPclose later tried to wait on a process when all - * handles weren't closed, it could create a deadlock with the - * child, we spend some energy here to try to ensure that we - * either insert all file handles into the dictionary or none - * at all. It's a little clumsy with the various popen modes - * and variable number of files involved. - */ - if (!_PyPopenProcs) { - _PyPopenProcs = PyDict_New(); - } - - if (_PyPopenProcs) { - PyObject *procObj, *hProcessObj, *intObj, *fileObj[3]; - int ins_rc[3]; - - fileObj[0] = fileObj[1] = fileObj[2] = NULL; - ins_rc[0] = ins_rc[1] = ins_rc[2] = 0; - - procObj = PyList_New(2); - hProcessObj = PyLong_FromVoidPtr(hProcess); - intObj = PyInt_FromLong(file_count); - - if (procObj && hProcessObj && intObj) { - PyList_SetItem(procObj,0,hProcessObj); - PyList_SetItem(procObj,1,intObj); - - fileObj[0] = PyLong_FromVoidPtr(f1); - if (fileObj[0]) { - ins_rc[0] = PyDict_SetItem(_PyPopenProcs, - fileObj[0], - procObj); - } - if (file_count >= 2) { - fileObj[1] = PyLong_FromVoidPtr(f2); - if (fileObj[1]) { - ins_rc[1] = PyDict_SetItem(_PyPopenProcs, - fileObj[1], - procObj); - } - } - if (file_count >= 3) { - fileObj[2] = PyLong_FromVoidPtr(f3); - if (fileObj[2]) { - ins_rc[2] = PyDict_SetItem(_PyPopenProcs, - fileObj[2], - procObj); - } - } - - if (ins_rc[0] < 0 || !fileObj[0] || - ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) || - ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) { - /* Something failed - remove any dictionary - * entries that did make it. - */ - if (!ins_rc[0] && fileObj[0]) { - PyDict_DelItem(_PyPopenProcs, - fileObj[0]); - } - if (!ins_rc[1] && fileObj[1]) { - PyDict_DelItem(_PyPopenProcs, - fileObj[1]); - } - if (!ins_rc[2] && fileObj[2]) { - PyDict_DelItem(_PyPopenProcs, - fileObj[2]); - } - } - } - - /* - * Clean up our localized references for the dictionary keys - * and value since PyDict_SetItem will Py_INCREF any copies - * that got placed in the dictionary. - */ - Py_XDECREF(procObj); - Py_XDECREF(fileObj[0]); - Py_XDECREF(fileObj[1]); - Py_XDECREF(fileObj[2]); - } - - /* Child is launched. Close the parents copy of those pipe - * handles that only the child should have open. You need to - * make sure that no handles to the write end of the output pipe - * are maintained in this process or else the pipe will not close - * when the child process exits and the ReadFile will hang. */ - - if (!CloseHandle(hChildStdinRd)) - return win32_error("CloseHandle", NULL); - - if (!CloseHandle(hChildStdoutWr)) - return win32_error("CloseHandle", NULL); - - if ((n != 4) && (!CloseHandle(hChildStderrWr))) - return win32_error("CloseHandle", NULL); - - return f; -} - -/* - * Wrapper for fclose() to use for popen* files, so we can retrieve the - * exit code for the child process and return as a result of the close. - * - * This function uses the _PyPopenProcs dictionary in order to map the - * input file pointer to information about the process that was - * originally created by the popen* call that created the file pointer. - * The dictionary uses the file pointer as a key (with one entry - * inserted for each file returned by the original popen* call) and a - * single list object as the value for all files from a single call. - * The list object contains the Win32 process handle at [0], and a file - * count at [1], which is initialized to the total number of file - * handles using that list. - * - * This function closes whichever handle it is passed, and decrements - * the file count in the dictionary for the process handle pointed to - * by this file. On the last close (when the file count reaches zero), - * this function will wait for the child process and then return its - * exit code as the result of the close() operation. This permits the - * files to be closed in any order - it is always the close() of the - * final handle that will return the exit code. - * - * NOTE: This function is currently called with the GIL released. - * hence we use the GILState API to manage our state. - */ - -static int _PyPclose(FILE *file) -{ - int result; - DWORD exit_code; - HANDLE hProcess; - PyObject *procObj, *hProcessObj, *intObj, *fileObj; - long file_count; -#ifdef WITH_THREAD - PyGILState_STATE state; -#endif - - /* Close the file handle first, to ensure it can't block the - * child from exiting if it's the last handle. - */ - result = fclose(file); -#ifdef WITH_THREAD - state = PyGILState_Ensure(); -#endif - if (_PyPopenProcs) { - if ((fileObj = PyLong_FromVoidPtr(file)) != NULL && - (procObj = PyDict_GetItem(_PyPopenProcs, - fileObj)) != NULL && - (hProcessObj = PyList_GetItem(procObj,0)) != NULL && - (intObj = PyList_GetItem(procObj,1)) != NULL) { - - hProcess = PyLong_AsVoidPtr(hProcessObj); - file_count = PyInt_AsLong(intObj); - - if (file_count > 1) { - /* Still other files referencing process */ - file_count--; - PyList_SetItem(procObj,1, - PyInt_FromLong(file_count)); - } else { - /* Last file for this process */ - if (result != EOF && - WaitForSingleObject(hProcess, INFINITE) != WAIT_FAILED && - GetExitCodeProcess(hProcess, &exit_code)) { - /* Possible truncation here in 16-bit environments, but - * real exit codes are just the lower byte in any event. - */ - result = exit_code; - } else { - /* Indicate failure - this will cause the file object - * to raise an I/O error and translate the last Win32 - * error code from errno. We do have a problem with - * last errors that overlap the normal errno table, - * but that's a consistent problem with the file object. - */ - if (result != EOF) { - /* If the error wasn't from the fclose(), then - * set errno for the file object error handling. - */ - errno = GetLastError(); - } - result = -1; - } - - /* Free up the native handle at this point */ - CloseHandle(hProcess); - } - - /* Remove this file pointer from dictionary */ - PyDict_DelItem(_PyPopenProcs, fileObj); - - if (PyDict_Size(_PyPopenProcs) == 0) { - Py_DECREF(_PyPopenProcs); - _PyPopenProcs = NULL; - } - - } /* if object retrieval ok */ - - Py_XDECREF(fileObj); - } /* if _PyPopenProcs */ - -#ifdef WITH_THREAD - PyGILState_Release(state); -#endif - return result; -} - -#else /* which OS? */ -static PyObject * -posix_popen(PyObject *self, PyObject *args) -{ - char *name; - char *mode = "r"; - int bufsize = -1; - FILE *fp; - PyObject *f; - if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) - return NULL; - /* Strip mode of binary or text modifiers */ - if (strcmp(mode, "rb") == 0 || strcmp(mode, "rt") == 0) - mode = "r"; - else if (strcmp(mode, "wb") == 0 || strcmp(mode, "wt") == 0) - mode = "w"; - Py_BEGIN_ALLOW_THREADS - fp = popen(name, mode); - Py_END_ALLOW_THREADS - if (fp == NULL) - return posix_error(); - f = PyFile_FromFile(fp, name, mode, pclose); - if (f != NULL) - PyFile_SetBufSize(f, bufsize); - return f; -} - -#endif /* PYOS_??? */ -#endif /* HAVE_POPEN */ - - -#ifdef HAVE_SETUID -PyDoc_STRVAR(posix_setuid__doc__, -"setuid(uid)\n\n\ -Set the current process's user id."); - -static PyObject * -posix_setuid(PyObject *self, PyObject *args) -{ - long uid_arg; - uid_t uid; - if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg)) - return NULL; - uid = uid_arg; - if (uid != uid_arg) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (setuid(uid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} -#endif /* HAVE_SETUID */ - - -#ifdef HAVE_SETEUID -PyDoc_STRVAR(posix_seteuid__doc__, -"seteuid(uid)\n\n\ -Set the current process's effective user id."); - -static PyObject * -posix_seteuid (PyObject *self, PyObject *args) -{ - long euid_arg; - uid_t euid; - if (!PyArg_ParseTuple(args, "l", &euid_arg)) - return NULL; - euid = euid_arg; - if (euid != euid_arg) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (seteuid(euid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } -} -#endif /* HAVE_SETEUID */ - -#ifdef HAVE_SETEGID -PyDoc_STRVAR(posix_setegid__doc__, -"setegid(gid)\n\n\ -Set the current process's effective group id."); - -static PyObject * -posix_setegid (PyObject *self, PyObject *args) -{ - long egid_arg; - gid_t egid; - if (!PyArg_ParseTuple(args, "l", &egid_arg)) - return NULL; - egid = egid_arg; - if (egid != egid_arg) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setegid(egid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } -} -#endif /* HAVE_SETEGID */ - -#ifdef HAVE_SETREUID -PyDoc_STRVAR(posix_setreuid__doc__, -"setreuid(ruid, euid)\n\n\ -Set the current process's real and effective user ids."); - -static PyObject * -posix_setreuid (PyObject *self, PyObject *args) -{ - long ruid_arg, euid_arg; - uid_t ruid, euid; - if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg)) - return NULL; - if (ruid_arg == -1) - ruid = (uid_t)-1; /* let the compiler choose how -1 fits */ - else - ruid = ruid_arg; /* otherwise, assign from our long */ - if (euid_arg == -1) - euid = (uid_t)-1; - else - euid = euid_arg; - if ((euid_arg != -1 && euid != euid_arg) || - (ruid_arg != -1 && ruid != ruid_arg)) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (setreuid(ruid, euid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } -} -#endif /* HAVE_SETREUID */ - -#ifdef HAVE_SETREGID -PyDoc_STRVAR(posix_setregid__doc__, -"setregid(rgid, egid)\n\n\ -Set the current process's real and effective group ids."); - -static PyObject * -posix_setregid (PyObject *self, PyObject *args) -{ - long rgid_arg, egid_arg; - gid_t rgid, egid; - if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg)) - return NULL; - if (rgid_arg == -1) - rgid = (gid_t)-1; /* let the compiler choose how -1 fits */ - else - rgid = rgid_arg; /* otherwise, assign from our long */ - if (egid_arg == -1) - egid = (gid_t)-1; - else - egid = egid_arg; - if ((egid_arg != -1 && egid != egid_arg) || - (rgid_arg != -1 && rgid != rgid_arg)) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setregid(rgid, egid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } -} -#endif /* HAVE_SETREGID */ - -#ifdef HAVE_SETGID -PyDoc_STRVAR(posix_setgid__doc__, -"setgid(gid)\n\n\ -Set the current process's group id."); - -static PyObject * -posix_setgid(PyObject *self, PyObject *args) -{ - long gid_arg; - gid_t gid; - if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg)) - return NULL; - gid = gid_arg; - if (gid != gid_arg) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setgid(gid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} -#endif /* HAVE_SETGID */ - -#ifdef HAVE_SETGROUPS -PyDoc_STRVAR(posix_setgroups__doc__, -"setgroups(list)\n\n\ -Set the groups of the current process to list."); - -static PyObject * -posix_setgroups(PyObject *self, PyObject *groups) -{ - int i, len; - gid_t grouplist[MAX_GROUPS]; - - if (!PySequence_Check(groups)) { - PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence"); - return NULL; - } - len = PySequence_Size(groups); - if (len > MAX_GROUPS) { - PyErr_SetString(PyExc_ValueError, "too many groups"); - return NULL; - } - for(i = 0; i < len; i++) { - PyObject *elem; - elem = PySequence_GetItem(groups, i); - if (!elem) - return NULL; - if (!PyInt_Check(elem)) { - if (!PyLong_Check(elem)) { - PyErr_SetString(PyExc_TypeError, - "groups must be integers"); - Py_DECREF(elem); - return NULL; - } else { - unsigned long x = PyLong_AsUnsignedLong(elem); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - grouplist[i] = x; - /* read back to see if it fits in gid_t */ - if (grouplist[i] != x) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - } - } else { - long x = PyInt_AsLong(elem); - grouplist[i] = x; - if (grouplist[i] != x) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - } - Py_DECREF(elem); - } - - if (setgroups(len, grouplist) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} -#endif /* HAVE_SETGROUPS */ - -#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4) -static PyObject * -wait_helper(pid_t pid, int status, struct rusage *ru) -{ - PyObject *result; - static PyObject *struct_rusage; - - if (pid == -1) - return posix_error(); - - if (struct_rusage == NULL) { - PyObject *m = PyImport_ImportModuleNoBlock("resource"); - if (m == NULL) - return NULL; - struct_rusage = PyObject_GetAttrString(m, "struct_rusage"); - Py_DECREF(m); - if (struct_rusage == NULL) - return NULL; - } - - /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */ - result = PyStructSequence_New((PyTypeObject*) struct_rusage); - if (!result) - return NULL; - -#ifndef doubletime -#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001) -#endif - - PyStructSequence_SET_ITEM(result, 0, - PyFloat_FromDouble(doubletime(ru->ru_utime))); - PyStructSequence_SET_ITEM(result, 1, - PyFloat_FromDouble(doubletime(ru->ru_stime))); -#define SET_INT(result, index, value)\ - PyStructSequence_SET_ITEM(result, index, PyInt_FromLong(value)) - SET_INT(result, 2, ru->ru_maxrss); - SET_INT(result, 3, ru->ru_ixrss); - SET_INT(result, 4, ru->ru_idrss); - SET_INT(result, 5, ru->ru_isrss); - SET_INT(result, 6, ru->ru_minflt); - SET_INT(result, 7, ru->ru_majflt); - SET_INT(result, 8, ru->ru_nswap); - SET_INT(result, 9, ru->ru_inblock); - SET_INT(result, 10, ru->ru_oublock); - SET_INT(result, 11, ru->ru_msgsnd); - SET_INT(result, 12, ru->ru_msgrcv); - SET_INT(result, 13, ru->ru_nsignals); - SET_INT(result, 14, ru->ru_nvcsw); - SET_INT(result, 15, ru->ru_nivcsw); -#undef SET_INT - - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } - - return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result); -} -#endif /* HAVE_WAIT3 || HAVE_WAIT4 */ - -#ifdef HAVE_WAIT3 -PyDoc_STRVAR(posix_wait3__doc__, -"wait3(options) -> (pid, status, rusage)\n\n\ -Wait for completion of a child process."); - -static PyObject * -posix_wait3(PyObject *self, PyObject *args) -{ - pid_t pid; - int options; - struct rusage ru; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, "i:wait3", &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - pid = wait3(&status, options, &ru); - Py_END_ALLOW_THREADS - - return wait_helper(pid, WAIT_STATUS_INT(status), &ru); -} -#endif /* HAVE_WAIT3 */ - -#ifdef HAVE_WAIT4 -PyDoc_STRVAR(posix_wait4__doc__, -"wait4(pid, options) -> (pid, status, rusage)\n\n\ -Wait for completion of a given child process."); - -static PyObject * -posix_wait4(PyObject *self, PyObject *args) -{ - pid_t pid; - int options; - struct rusage ru; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, PARSE_PID "i:wait4", &pid, &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - pid = wait4(pid, &status, options, &ru); - Py_END_ALLOW_THREADS - - return wait_helper(pid, WAIT_STATUS_INT(status), &ru); -} -#endif /* HAVE_WAIT4 */ - -#ifdef HAVE_WAITPID -PyDoc_STRVAR(posix_waitpid__doc__, -"waitpid(pid, options) -> (pid, status)\n\n\ -Wait for completion of a given child process."); - -static PyObject * -posix_waitpid(PyObject *self, PyObject *args) -{ - pid_t pid; - int options; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options)) - return NULL; - Py_BEGIN_ALLOW_THREADS - pid = waitpid(pid, &status, options); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); - - return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); -} - -#elif defined(HAVE_CWAIT) - -/* MS C has a variant of waitpid() that's usable for most purposes. */ -PyDoc_STRVAR(posix_waitpid__doc__, -"waitpid(pid, options) -> (pid, status << 8)\n\n" -"Wait for completion of a given process. options is ignored on Windows."); - -static PyObject * -posix_waitpid(PyObject *self, PyObject *args) -{ - Py_intptr_t pid; - int status, options; - - if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options)) - return NULL; - Py_BEGIN_ALLOW_THREADS - pid = _cwait(&status, pid, options); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); - - /* shift the status left a byte so this is more like the POSIX waitpid */ - return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8); -} -#endif /* HAVE_WAITPID || HAVE_CWAIT */ - -#ifdef HAVE_WAIT -PyDoc_STRVAR(posix_wait__doc__, -"wait() -> (pid, status)\n\n\ -Wait for completion of a child process."); - -static PyObject * -posix_wait(PyObject *self, PyObject *noargs) -{ - pid_t pid; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - Py_BEGIN_ALLOW_THREADS - pid = wait(&status); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); - - return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); -} -#endif - - -PyDoc_STRVAR(posix_lstat__doc__, -"lstat(path) -> stat result\n\n\ -Like stat(path), but do not follow symbolic links."); - -static PyObject * -posix_lstat(PyObject *self, PyObject *args) -{ -#ifdef HAVE_LSTAT - return posix_do_stat(self, args, "et:lstat", lstat, NULL, NULL); -#else /* !HAVE_LSTAT */ - return posix_do_stat(self, args, "et:lstat", STAT, NULL, NULL); -#endif /* !HAVE_LSTAT */ -} - - -#ifdef HAVE_READLINK -PyDoc_STRVAR(posix_readlink__doc__, -"readlink(path) -> path\n\n\ -Return a string representing the path to which the symbolic link points."); - -static PyObject * -posix_readlink(PyObject *self, PyObject *args) -{ - PyObject* v; - char buf[MAXPATHLEN]; - char *path; - int n; -#ifdef Py_USING_UNICODE - int arg_is_unicode = 0; -#endif - - if (!PyArg_ParseTuple(args, "et:readlink", - Py_FileSystemDefaultEncoding, &path)) - return NULL; -#ifdef Py_USING_UNICODE - v = PySequence_GetItem(args, 0); - if (v == NULL) { - PyMem_Free(path); - return NULL; - } - - if (PyUnicode_Check(v)) { - arg_is_unicode = 1; - } - Py_DECREF(v); -#endif - - Py_BEGIN_ALLOW_THREADS - n = readlink(path, buf, (int) sizeof buf); - Py_END_ALLOW_THREADS - if (n < 0) - return posix_error_with_allocated_filename(path); - - PyMem_Free(path); - v = PyString_FromStringAndSize(buf, n); -#ifdef Py_USING_UNICODE - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "strict"); - if (w != NULL) { - Py_DECREF(v); - v = w; - } - else { - /* fall back to the original byte string, as - discussed in patch #683592 */ - PyErr_Clear(); - } - } -#endif - return v; -} -#endif /* HAVE_READLINK */ - - -#ifdef HAVE_SYMLINK -PyDoc_STRVAR(posix_symlink__doc__, -"symlink(src, dst)\n\n\ -Create a symbolic link pointing to src named dst."); - -static PyObject * -posix_symlink(PyObject *self, PyObject *args) -{ - return posix_2str(args, "etet:symlink", symlink); -} -#endif /* HAVE_SYMLINK */ - - -#ifdef HAVE_TIMES -#if defined(PYCC_VACPP) && defined(PYOS_OS2) -static long -system_uptime(void) -{ - ULONG value = 0; - - Py_BEGIN_ALLOW_THREADS - DosQuerySysInfo(QSV_MS_COUNT, QSV_MS_COUNT, &value, sizeof(value)); - Py_END_ALLOW_THREADS - - return value; -} - -static PyObject * -posix_times(PyObject *self, PyObject *noargs) -{ - /* Currently Only Uptime is Provided -- Others Later */ - return Py_BuildValue("ddddd", - (double)0 /* t.tms_utime / HZ */, - (double)0 /* t.tms_stime / HZ */, - (double)0 /* t.tms_cutime / HZ */, - (double)0 /* t.tms_cstime / HZ */, - (double)system_uptime() / 1000); -} -#else /* not OS2 */ -#define NEED_TICKS_PER_SECOND -static long ticks_per_second = -1; -static PyObject * -posix_times(PyObject *self, PyObject *noargs) -{ - struct tms t; - clock_t c; - errno = 0; - c = times(&t); - if (c == (clock_t) -1) - return posix_error(); - return Py_BuildValue("ddddd", - (double)t.tms_utime / ticks_per_second, - (double)t.tms_stime / ticks_per_second, - (double)t.tms_cutime / ticks_per_second, - (double)t.tms_cstime / ticks_per_second, - (double)c / ticks_per_second); -} -#endif /* not OS2 */ -#endif /* HAVE_TIMES */ - - -#ifdef HAVE_TIMES -PyDoc_STRVAR(posix_times__doc__, -"times() -> (utime, stime, cutime, cstime, elapsed_time)\n\n\ -Return a tuple of floating point numbers indicating process times."); -#endif - - -#ifdef HAVE_GETSID -PyDoc_STRVAR(posix_getsid__doc__, -"getsid(pid) -> sid\n\n\ -Call the system call getsid()."); - -static PyObject * -posix_getsid(PyObject *self, PyObject *args) -{ - pid_t pid; - int sid; - if (!PyArg_ParseTuple(args, PARSE_PID ":getsid", &pid)) - return NULL; - sid = getsid(pid); - if (sid < 0) - return posix_error(); - return PyInt_FromLong((long)sid); -} -#endif /* HAVE_GETSID */ - - -#ifdef HAVE_SETSID -PyDoc_STRVAR(posix_setsid__doc__, -"setsid()\n\n\ -Call the system call setsid()."); - -static PyObject * -posix_setsid(PyObject *self, PyObject *noargs) -{ - if (setsid() < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} -#endif /* HAVE_SETSID */ - -#ifdef HAVE_SETPGID -PyDoc_STRVAR(posix_setpgid__doc__, -"setpgid(pid, pgrp)\n\n\ -Call the system call setpgid()."); - -static PyObject * -posix_setpgid(PyObject *self, PyObject *args) -{ - pid_t pid; - int pgrp; - if (!PyArg_ParseTuple(args, PARSE_PID "i:setpgid", &pid, &pgrp)) - return NULL; - if (setpgid(pid, pgrp) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} -#endif /* HAVE_SETPGID */ - - -#ifdef HAVE_TCGETPGRP -PyDoc_STRVAR(posix_tcgetpgrp__doc__, -"tcgetpgrp(fd) -> pgid\n\n\ -Return the process group associated with the terminal given by a fd."); - -static PyObject * -posix_tcgetpgrp(PyObject *self, PyObject *args) -{ - int fd; - pid_t pgid; - if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd)) - return NULL; - pgid = tcgetpgrp(fd); - if (pgid < 0) - return posix_error(); - return PyLong_FromPid(pgid); -} -#endif /* HAVE_TCGETPGRP */ - - -#ifdef HAVE_TCSETPGRP -PyDoc_STRVAR(posix_tcsetpgrp__doc__, -"tcsetpgrp(fd, pgid)\n\n\ -Set the process group associated with the terminal given by a fd."); - -static PyObject * -posix_tcsetpgrp(PyObject *self, PyObject *args) -{ - int fd; - pid_t pgid; - if (!PyArg_ParseTuple(args, "i" PARSE_PID ":tcsetpgrp", &fd, &pgid)) - return NULL; - if (tcsetpgrp(fd, pgid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} -#endif /* HAVE_TCSETPGRP */ - -/* Functions acting on file descriptors */ - -PyDoc_STRVAR(posix_open__doc__, -"open(filename, flag [, mode=0777]) -> fd\n\n\ -Open a file (for low level IO)."); - -static PyObject * -posix_open(PyObject *self, PyObject *args) -{ - char *file = NULL; - int flag; - int mode = 0777; - int fd; - - if (!PyArg_ParseTuple(args, "eti|i", - Py_FileSystemDefaultEncoding, &file, - &flag, &mode)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - fd = open(file, flag, mode); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error_with_allocated_filename(file); - PyMem_Free(file); - return PyInt_FromLong((long)fd); -} - - -PyDoc_STRVAR(posix_close__doc__, -"close(fd)\n\n\ -Close a file descriptor (for low level IO)."); - -static PyObject * -posix_close(PyObject *self, PyObject *args) -{ - int fd, res; - if (!PyArg_ParseTuple(args, "i:close", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = close(fd); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} - - -PyDoc_STRVAR(posix_closerange__doc__, -"closerange(fd_low, fd_high)\n\n\ -Closes all file descriptors in [fd_low, fd_high), ignoring errors."); - -static PyObject * -posix_closerange(PyObject *self, PyObject *args) -{ - int fd_from, fd_to, i; - if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to)) - return NULL; - Py_BEGIN_ALLOW_THREADS - for (i = fd_from; i < fd_to; i++) - if (_PyVerify_fd(i)) - close(i); - Py_END_ALLOW_THREADS - Py_RETURN_NONE; -} - - -PyDoc_STRVAR(posix_dup__doc__, -"dup(fd) -> fd2\n\n\ -Return a duplicate of a file descriptor."); - -static PyObject * -posix_dup(PyObject *self, PyObject *args) -{ - int fd; - if (!PyArg_ParseTuple(args, "i:dup", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - fd = dup(fd); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error(); - return PyInt_FromLong((long)fd); -} - - -PyDoc_STRVAR(posix_dup2__doc__, -"dup2(old_fd, new_fd)\n\n\ -Duplicate file descriptor."); - -static PyObject * -posix_dup2(PyObject *self, PyObject *args) -{ - int fd, fd2, res; - if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2)) - return NULL; - if (!_PyVerify_fd_dup2(fd, fd2)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = dup2(fd, fd2); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} - - -PyDoc_STRVAR(posix_lseek__doc__, -"lseek(fd, pos, how) -> newpos\n\n\ -Set the current position of a file descriptor."); - -static PyObject * -posix_lseek(PyObject *self, PyObject *args) -{ - int fd, how; - off_t pos, res; - PyObject *posobj; - if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how)) - return NULL; -#ifdef SEEK_SET - /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ - switch (how) { - case 0: how = SEEK_SET; break; - case 1: how = SEEK_CUR; break; - case 2: how = SEEK_END; break; - } -#endif /* SEEK_END */ - -#if !defined(HAVE_LARGEFILE_SUPPORT) - pos = PyInt_AsLong(posobj); -#else - pos = PyLong_Check(posobj) ? - PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj); -#endif - if (PyErr_Occurred()) - return NULL; - - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = lseek(fd, pos, how); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - -#if !defined(HAVE_LARGEFILE_SUPPORT) - return PyInt_FromLong(res); -#else - return PyLong_FromLongLong(res); -#endif -} - - -PyDoc_STRVAR(posix_read__doc__, -"read(fd, buffersize) -> string\n\n\ -Read a file descriptor."); - -static PyObject * -posix_read(PyObject *self, PyObject *args) -{ - int fd, size, n; - PyObject *buffer; - if (!PyArg_ParseTuple(args, "ii:read", &fd, &size)) - return NULL; - if (size < 0) { - errno = EINVAL; - return posix_error(); - } - buffer = PyString_FromStringAndSize((char *)NULL, size); - if (buffer == NULL) - return NULL; - if (!_PyVerify_fd(fd)) { - Py_DECREF(buffer); - return posix_error(); - } - Py_BEGIN_ALLOW_THREADS - n = read(fd, PyString_AsString(buffer), size); - Py_END_ALLOW_THREADS - if (n < 0) { - Py_DECREF(buffer); - return posix_error(); - } - if (n != size) - _PyString_Resize(&buffer, n); - return buffer; -} - - -PyDoc_STRVAR(posix_write__doc__, -"write(fd, string) -> byteswritten\n\n\ -Write a string to a file descriptor."); - -static PyObject * -posix_write(PyObject *self, PyObject *args) -{ - Py_buffer pbuf; - int fd; - Py_ssize_t size; - - if (!PyArg_ParseTuple(args, "is*:write", &fd, &pbuf)) - return NULL; - if (!_PyVerify_fd(fd)) { - PyBuffer_Release(&pbuf); - return posix_error(); - } - Py_BEGIN_ALLOW_THREADS - size = write(fd, pbuf.buf, (size_t)pbuf.len); - Py_END_ALLOW_THREADS - PyBuffer_Release(&pbuf); - if (size < 0) - return posix_error(); - return PyInt_FromSsize_t(size); -} - - -PyDoc_STRVAR(posix_fstat__doc__, -"fstat(fd) -> stat result\n\n\ -Like stat(), but for an open file descriptor."); - -static PyObject * -posix_fstat(PyObject *self, PyObject *args) -{ - int fd; - STRUCT_STAT st; - int res; - if (!PyArg_ParseTuple(args, "i:fstat", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = FSTAT(fd, &st); - Py_END_ALLOW_THREADS - if (res != 0) { - return posix_error(); - } - - return _pystat_fromstructstat(&st); -} - - -PyDoc_STRVAR(posix_fdopen__doc__, -"fdopen(fd [, mode='r' [, bufsize]]) -> file_object\n\n\ -Return an open file object connected to a file descriptor."); - -static PyObject * -posix_fdopen(PyObject *self, PyObject *args) -{ - int fd; - char *orgmode = "r"; - int bufsize = -1; - FILE *fp; - PyObject *f; - char *mode; - if (!PyArg_ParseTuple(args, "i|si", &fd, &orgmode, &bufsize)) - return NULL; - - /* Sanitize mode. See fileobject.c */ - mode = PyMem_MALLOC(strlen(orgmode)+3); - if (!mode) { - PyErr_NoMemory(); - return NULL; - } - strcpy(mode, orgmode); - if (_PyFile_SanitizeMode(mode)) { - PyMem_FREE(mode); - return NULL; - } - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS -#if !defined(MS_WINDOWS) && defined(HAVE_FCNTL_H) - if (mode[0] == 'a') { - /* try to make sure the O_APPEND flag is set */ - int flags; - flags = fcntl(fd, F_GETFL); - if (flags != -1) - fcntl(fd, F_SETFL, flags | O_APPEND); - fp = fdopen(fd, mode); - if (fp == NULL && flags != -1) - /* restore old mode if fdopen failed */ - fcntl(fd, F_SETFL, flags); - } else { - fp = fdopen(fd, mode); - } -#else - fp = fdopen(fd, mode); -#endif - Py_END_ALLOW_THREADS - PyMem_FREE(mode); - if (fp == NULL) - return posix_error(); - f = PyFile_FromFile(fp, "", orgmode, fclose); - if (f != NULL) - PyFile_SetBufSize(f, bufsize); - return f; -} - -PyDoc_STRVAR(posix_isatty__doc__, -"isatty(fd) -> bool\n\n\ -Return True if the file descriptor 'fd' is an open file descriptor\n\ -connected to the slave end of a terminal."); - -static PyObject * -posix_isatty(PyObject *self, PyObject *args) -{ - int fd; - if (!PyArg_ParseTuple(args, "i:isatty", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return PyBool_FromLong(0); - return PyBool_FromLong(isatty(fd)); -} - -#ifdef HAVE_PIPE -PyDoc_STRVAR(posix_pipe__doc__, -"pipe() -> (read_end, write_end)\n\n\ -Create a pipe."); - -static PyObject * -posix_pipe(PyObject *self, PyObject *noargs) -{ -#if defined(PYOS_OS2) - HFILE read, write; - APIRET rc; - - Py_BEGIN_ALLOW_THREADS - rc = DosCreatePipe( &read, &write, 4096); - Py_END_ALLOW_THREADS - if (rc != NO_ERROR) - return os2_error(rc); - - return Py_BuildValue("(ii)", read, write); -#else -#if !defined(MS_WINDOWS) - int fds[2]; - int res; - Py_BEGIN_ALLOW_THREADS - res = pipe(fds); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error(); - return Py_BuildValue("(ii)", fds[0], fds[1]); -#else /* MS_WINDOWS */ - HANDLE read, write; - int read_fd, write_fd; - BOOL ok; - Py_BEGIN_ALLOW_THREADS - ok = CreatePipe(&read, &write, NULL, 0); - Py_END_ALLOW_THREADS - if (!ok) - return win32_error("CreatePipe", NULL); - read_fd = _open_osfhandle((Py_intptr_t)read, 0); - write_fd = _open_osfhandle((Py_intptr_t)write, 1); - return Py_BuildValue("(ii)", read_fd, write_fd); -#endif /* MS_WINDOWS */ -#endif -} -#endif /* HAVE_PIPE */ - - -#ifdef HAVE_MKFIFO -PyDoc_STRVAR(posix_mkfifo__doc__, -"mkfifo(filename [, mode=0666])\n\n\ -Create a FIFO (a POSIX named pipe)."); - -static PyObject * -posix_mkfifo(PyObject *self, PyObject *args) -{ - char *filename; - int mode = 0666; - int res; - if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = mkfifo(filename, mode); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} -#endif - - -#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) -PyDoc_STRVAR(posix_mknod__doc__, -"mknod(filename [, mode=0600, device])\n\n\ -Create a filesystem node (file, device special file or named pipe)\n\ -named filename. mode specifies both the permissions to use and the\n\ -type of node to be created, being combined (bitwise OR) with one of\n\ -S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. For S_IFCHR and S_IFBLK,\n\ -device defines the newly created device special file (probably using\n\ -os.makedev()), otherwise it is ignored."); - - -static PyObject * -posix_mknod(PyObject *self, PyObject *args) -{ - char *filename; - int mode = 0600; - int device = 0; - int res; - if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = mknod(filename, mode, device); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} -#endif - -#ifdef HAVE_DEVICE_MACROS -PyDoc_STRVAR(posix_major__doc__, -"major(device) -> major number\n\ -Extracts a device major number from a raw device number."); - -static PyObject * -posix_major(PyObject *self, PyObject *args) -{ - int device; - if (!PyArg_ParseTuple(args, "i:major", &device)) - return NULL; - return PyInt_FromLong((long)major(device)); -} - -PyDoc_STRVAR(posix_minor__doc__, -"minor(device) -> minor number\n\ -Extracts a device minor number from a raw device number."); - -static PyObject * -posix_minor(PyObject *self, PyObject *args) -{ - int device; - if (!PyArg_ParseTuple(args, "i:minor", &device)) - return NULL; - return PyInt_FromLong((long)minor(device)); -} - -PyDoc_STRVAR(posix_makedev__doc__, -"makedev(major, minor) -> device number\n\ -Composes a raw device number from the major and minor device numbers."); - -static PyObject * -posix_makedev(PyObject *self, PyObject *args) -{ - int major, minor; - if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor)) - return NULL; - return PyInt_FromLong((long)makedev(major, minor)); -} -#endif /* device macros */ - - -#ifdef HAVE_FTRUNCATE -PyDoc_STRVAR(posix_ftruncate__doc__, -"ftruncate(fd, length)\n\n\ -Truncate a file to a specified length."); - -static PyObject * -posix_ftruncate(PyObject *self, PyObject *args) -{ - int fd; - off_t length; - int res; - PyObject *lenobj; - - if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj)) - return NULL; - -#if !defined(HAVE_LARGEFILE_SUPPORT) - length = PyInt_AsLong(lenobj); -#else - length = PyLong_Check(lenobj) ? - PyLong_AsLongLong(lenobj) : PyInt_AsLong(lenobj); -#endif - if (PyErr_Occurred()) - return NULL; - - Py_BEGIN_ALLOW_THREADS - res = ftruncate(fd, length); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; -} -#endif - -#ifdef HAVE_PUTENV -PyDoc_STRVAR(posix_putenv__doc__, -"putenv(key, value)\n\n\ -Change or add an environment variable."); - -/* Save putenv() parameters as values here, so we can collect them when they - * get re-set with another call for the same key. */ -static PyObject *posix_putenv_garbage; - -static PyObject * -posix_putenv(PyObject *self, PyObject *args) -{ - char *s1, *s2; - char *newenv; - PyObject *newstr; - size_t len; - - if (!PyArg_ParseTuple(args, "ss:putenv", &s1, &s2)) - return NULL; - -#if defined(PYOS_OS2) - if (stricmp(s1, "BEGINLIBPATH") == 0) { - APIRET rc; - - rc = DosSetExtLIBPATH(s2, BEGIN_LIBPATH); - if (rc != NO_ERROR) - return os2_error(rc); - - } else if (stricmp(s1, "ENDLIBPATH") == 0) { - APIRET rc; - - rc = DosSetExtLIBPATH(s2, END_LIBPATH); - if (rc != NO_ERROR) - return os2_error(rc); - } else { -#endif - - /* XXX This can leak memory -- not easy to fix :-( */ - len = strlen(s1) + strlen(s2) + 2; - /* len includes space for a trailing \0; the size arg to - PyString_FromStringAndSize does not count that */ - newstr = PyString_FromStringAndSize(NULL, (int)len - 1); - if (newstr == NULL) - return PyErr_NoMemory(); - newenv = PyString_AS_STRING(newstr); - PyOS_snprintf(newenv, len, "%s=%s", s1, s2); - if (putenv(newenv)) { - Py_DECREF(newstr); - posix_error(); - return NULL; - } - /* Install the first arg and newstr in posix_putenv_garbage; - * this will cause previous value to be collected. This has to - * happen after the real putenv() call because the old value - * was still accessible until then. */ - if (PyDict_SetItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0), newstr)) { - /* really not much we can do; just leak */ - PyErr_Clear(); - } - else { - Py_DECREF(newstr); - } - -#if defined(PYOS_OS2) - } -#endif - Py_INCREF(Py_None); - return Py_None; -} -#endif /* putenv */ - -#ifdef HAVE_UNSETENV -PyDoc_STRVAR(posix_unsetenv__doc__, -"unsetenv(key)\n\n\ -Delete an environment variable."); - -static PyObject * -posix_unsetenv(PyObject *self, PyObject *args) -{ - char *s1; - - if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) - return NULL; - - unsetenv(s1); - - /* Remove the key from posix_putenv_garbage; - * this will cause it to be collected. This has to - * happen after the real unsetenv() call because the - * old value was still accessible until then. - */ - if (PyDict_DelItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0))) { - /* really not much we can do; just leak */ - PyErr_Clear(); - } - - Py_INCREF(Py_None); - return Py_None; -} -#endif /* unsetenv */ - -PyDoc_STRVAR(posix_strerror__doc__, -"strerror(code) -> string\n\n\ -Translate an error code to a message string."); - -static PyObject * -posix_strerror(PyObject *self, PyObject *args) -{ - int code; - char *message; - if (!PyArg_ParseTuple(args, "i:strerror", &code)) - return NULL; - message = strerror(code); - if (message == NULL) { - PyErr_SetString(PyExc_ValueError, - "strerror() argument out of range"); - return NULL; - } - return PyString_FromString(message); -} - - -#ifdef HAVE_SYS_WAIT_H - -#ifdef WCOREDUMP -PyDoc_STRVAR(posix_WCOREDUMP__doc__, -"WCOREDUMP(status) -> bool\n\n\ -Return True if the process returning 'status' was dumped to a core file."); - -static PyObject * -posix_WCOREDUMP(PyObject *self, PyObject *args) -{ - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status))) - return NULL; - - return PyBool_FromLong(WCOREDUMP(status)); -} -#endif /* WCOREDUMP */ - -#ifdef WIFCONTINUED -PyDoc_STRVAR(posix_WIFCONTINUED__doc__, -"WIFCONTINUED(status) -> bool\n\n\ -Return True if the process returning 'status' was continued from a\n\ -job control stop."); - -static PyObject * -posix_WIFCONTINUED(PyObject *self, PyObject *args) -{ - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status))) - return NULL; - - return PyBool_FromLong(WIFCONTINUED(status)); -} -#endif /* WIFCONTINUED */ - -#ifdef WIFSTOPPED -PyDoc_STRVAR(posix_WIFSTOPPED__doc__, -"WIFSTOPPED(status) -> bool\n\n\ -Return True if the process returning 'status' was stopped."); - -static PyObject * -posix_WIFSTOPPED(PyObject *self, PyObject *args) -{ - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status))) - return NULL; - - return PyBool_FromLong(WIFSTOPPED(status)); -} -#endif /* WIFSTOPPED */ - -#ifdef WIFSIGNALED -PyDoc_STRVAR(posix_WIFSIGNALED__doc__, -"WIFSIGNALED(status) -> bool\n\n\ -Return True if the process returning 'status' was terminated by a signal."); - -static PyObject * -posix_WIFSIGNALED(PyObject *self, PyObject *args) -{ - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status))) - return NULL; - - return PyBool_FromLong(WIFSIGNALED(status)); -} -#endif /* WIFSIGNALED */ - -#ifdef WIFEXITED -PyDoc_STRVAR(posix_WIFEXITED__doc__, -"WIFEXITED(status) -> bool\n\n\ -Return true if the process returning 'status' exited using the exit()\n\ -system call."); - -static PyObject * -posix_WIFEXITED(PyObject *self, PyObject *args) -{ - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status))) - return NULL; - - return PyBool_FromLong(WIFEXITED(status)); -} -#endif /* WIFEXITED */ - -#ifdef WEXITSTATUS -PyDoc_STRVAR(posix_WEXITSTATUS__doc__, -"WEXITSTATUS(status) -> integer\n\n\ -Return the process return code from 'status'."); - -static PyObject * -posix_WEXITSTATUS(PyObject *self, PyObject *args) -{ - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status))) - return NULL; - - return Py_BuildValue("i", WEXITSTATUS(status)); -} -#endif /* WEXITSTATUS */ - -#ifdef WTERMSIG -PyDoc_STRVAR(posix_WTERMSIG__doc__, -"WTERMSIG(status) -> integer\n\n\ -Return the signal that terminated the process that provided the 'status'\n\ -value."); - -static PyObject * -posix_WTERMSIG(PyObject *self, PyObject *args) -{ - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status))) - return NULL; - - return Py_BuildValue("i", WTERMSIG(status)); -} -#endif /* WTERMSIG */ - -#ifdef WSTOPSIG -PyDoc_STRVAR(posix_WSTOPSIG__doc__, -"WSTOPSIG(status) -> integer\n\n\ -Return the signal that stopped the process that provided\n\ -the 'status' value."); - -static PyObject * -posix_WSTOPSIG(PyObject *self, PyObject *args) -{ - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status))) - return NULL; - - return Py_BuildValue("i", WSTOPSIG(status)); -} -#endif /* WSTOPSIG */ - -#endif /* HAVE_SYS_WAIT_H */ - - -#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) -#ifdef _SCO_DS -/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the - needed definitions in sys/statvfs.h */ -#define _SVID3 -#endif -#include - -static PyObject* -_pystatvfs_fromstructstatvfs(struct statvfs st) { - PyObject *v = PyStructSequence_New(&StatVFSResultType); - if (v == NULL) - return NULL; - -#if !defined(HAVE_LARGEFILE_SUPPORT) - PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize)); - PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize)); - PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long) st.f_blocks)); - PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long) st.f_bfree)); - PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long) st.f_bavail)); - PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long) st.f_files)); - PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong((long) st.f_ffree)); - PyStructSequence_SET_ITEM(v, 7, PyInt_FromLong((long) st.f_favail)); - PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag)); - PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax)); -#else - PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize)); - PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize)); - PyStructSequence_SET_ITEM(v, 2, - PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks)); - PyStructSequence_SET_ITEM(v, 3, - PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree)); - PyStructSequence_SET_ITEM(v, 4, - PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail)); - PyStructSequence_SET_ITEM(v, 5, - PyLong_FromLongLong((PY_LONG_LONG) st.f_files)); - PyStructSequence_SET_ITEM(v, 6, - PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree)); - PyStructSequence_SET_ITEM(v, 7, - PyLong_FromLongLong((PY_LONG_LONG) st.f_favail)); - PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag)); - PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax)); -#endif - - return v; -} - -PyDoc_STRVAR(posix_fstatvfs__doc__, -"fstatvfs(fd) -> statvfs result\n\n\ -Perform an fstatvfs system call on the given fd."); - -static PyObject * -posix_fstatvfs(PyObject *self, PyObject *args) -{ - int fd, res; - struct statvfs st; - - if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fstatvfs(fd, &st); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error(); - - return _pystatvfs_fromstructstatvfs(st); -} -#endif /* HAVE_FSTATVFS && HAVE_SYS_STATVFS_H */ - - -#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) -#include - -PyDoc_STRVAR(posix_statvfs__doc__, -"statvfs(path) -> statvfs result\n\n\ -Perform a statvfs system call on the given path."); - -static PyObject * -posix_statvfs(PyObject *self, PyObject *args) -{ - char *path; - int res; - struct statvfs st; - if (!PyArg_ParseTuple(args, "s:statvfs", &path)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = statvfs(path, &st); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error_with_filename(path); - - return _pystatvfs_fromstructstatvfs(st); -} -#endif /* HAVE_STATVFS */ - - -#ifdef HAVE_TEMPNAM -PyDoc_STRVAR(posix_tempnam__doc__, -"tempnam([dir[, prefix]]) -> string\n\n\ -Return a unique name for a temporary file.\n\ -The directory and a prefix may be specified as strings; they may be omitted\n\ -or None if not needed."); - -static PyObject * -posix_tempnam(PyObject *self, PyObject *args) -{ - PyObject *result = NULL; - char *dir = NULL; - char *pfx = NULL; - char *name; - - if (!PyArg_ParseTuple(args, "|zz:tempnam", &dir, &pfx)) - return NULL; - - if (PyErr_Warn(PyExc_RuntimeWarning, - "tempnam is a potential security risk to your program") < 0) - return NULL; - - if (PyErr_WarnPy3k("tempnam has been removed in 3.x; " - "use the tempfile module", 1) < 0) - return NULL; - - name = tempnam(dir, pfx); - if (name == NULL) - return PyErr_NoMemory(); - result = PyString_FromString(name); - free(name); - return result; -} -#endif - - -#ifdef HAVE_TMPFILE -PyDoc_STRVAR(posix_tmpfile__doc__, -"tmpfile() -> file object\n\n\ -Create a temporary file with no directory entries."); - -static PyObject * -posix_tmpfile(PyObject *self, PyObject *noargs) -{ - FILE *fp; - - if (PyErr_WarnPy3k("tmpfile has been removed in 3.x; " - "use the tempfile module", 1) < 0) - return NULL; - - fp = tmpfile(); - if (fp == NULL) - return posix_error(); - return PyFile_FromFile(fp, "", "w+b", fclose); -} -#endif - - -#ifdef HAVE_TMPNAM -PyDoc_STRVAR(posix_tmpnam__doc__, -"tmpnam() -> string\n\n\ -Return a unique name for a temporary file."); - -static PyObject * -posix_tmpnam(PyObject *self, PyObject *noargs) -{ - char buffer[L_tmpnam]; - char *name; - - if (PyErr_Warn(PyExc_RuntimeWarning, - "tmpnam is a potential security risk to your program") < 0) - return NULL; - - if (PyErr_WarnPy3k("tmpnam has been removed in 3.x; " - "use the tempfile module", 1) < 0) - return NULL; - -#ifdef USE_TMPNAM_R - name = tmpnam_r(buffer); -#else - name = tmpnam(buffer); -#endif - if (name == NULL) { - PyObject *err = Py_BuildValue("is", 0, -#ifdef USE_TMPNAM_R - "unexpected NULL from tmpnam_r" -#else - "unexpected NULL from tmpnam" -#endif - ); - PyErr_SetObject(PyExc_OSError, err); - Py_XDECREF(err); - return NULL; - } - return PyString_FromString(buffer); -} -#endif - - -/* This is used for fpathconf(), pathconf(), confstr() and sysconf(). - * It maps strings representing configuration variable names to - * integer values, allowing those functions to be called with the - * magic names instead of polluting the module's namespace with tons of - * rarely-used constants. There are three separate tables that use - * these definitions. - * - * This code is always included, even if none of the interfaces that - * need it are included. The #if hackery needed to avoid it would be - * sufficiently pervasive that it's not worth the loss of readability. - */ -struct constdef { - char *name; - long value; -}; - -#ifndef UEFI_C_SOURCE -static int -conv_confname(PyObject *arg, int *valuep, struct constdef *table, - size_t tablesize) -{ - if (PyInt_Check(arg)) { - *valuep = PyInt_AS_LONG(arg); - return 1; - } - if (PyString_Check(arg)) { - /* look up the value in the table using a binary search */ - size_t lo = 0; - size_t mid; - size_t hi = tablesize; - int cmp; - char *confname = PyString_AS_STRING(arg); - while (lo < hi) { - mid = (lo + hi) / 2; - cmp = strcmp(confname, table[mid].name); - if (cmp < 0) - hi = mid; - else if (cmp > 0) - lo = mid + 1; - else { - *valuep = table[mid].value; - return 1; - } - } - PyErr_SetString(PyExc_ValueError, "unrecognized configuration name"); - } - else - PyErr_SetString(PyExc_TypeError, - "configuration names must be strings or integers"); - return 0; -} -#endif /* UEFI_C_SOURCE */ - -#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF) -static struct constdef posix_constants_pathconf[] = { -#ifdef _PC_ABI_AIO_XFER_MAX - {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX}, -#endif -#ifdef _PC_ABI_ASYNC_IO - {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO}, -#endif -#ifdef _PC_ASYNC_IO - {"PC_ASYNC_IO", _PC_ASYNC_IO}, -#endif -#ifdef _PC_CHOWN_RESTRICTED - {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED}, -#endif -#ifdef _PC_FILESIZEBITS - {"PC_FILESIZEBITS", _PC_FILESIZEBITS}, -#endif -#ifdef _PC_LAST - {"PC_LAST", _PC_LAST}, -#endif -#ifdef _PC_LINK_MAX - {"PC_LINK_MAX", _PC_LINK_MAX}, -#endif -#ifdef _PC_MAX_CANON - {"PC_MAX_CANON", _PC_MAX_CANON}, -#endif -#ifdef _PC_MAX_INPUT - {"PC_MAX_INPUT", _PC_MAX_INPUT}, -#endif -#ifdef _PC_NAME_MAX - {"PC_NAME_MAX", _PC_NAME_MAX}, -#endif -#ifdef _PC_NO_TRUNC - {"PC_NO_TRUNC", _PC_NO_TRUNC}, -#endif -#ifdef _PC_PATH_MAX - {"PC_PATH_MAX", _PC_PATH_MAX}, -#endif -#ifdef _PC_PIPE_BUF - {"PC_PIPE_BUF", _PC_PIPE_BUF}, -#endif -#ifdef _PC_PRIO_IO - {"PC_PRIO_IO", _PC_PRIO_IO}, -#endif -#ifdef _PC_SOCK_MAXBUF - {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF}, -#endif -#ifdef _PC_SYNC_IO - {"PC_SYNC_IO", _PC_SYNC_IO}, -#endif -#ifdef _PC_VDISABLE - {"PC_VDISABLE", _PC_VDISABLE}, -#endif -}; - -static int -conv_path_confname(PyObject *arg, int *valuep) -{ - return conv_confname(arg, valuep, posix_constants_pathconf, - sizeof(posix_constants_pathconf) - / sizeof(struct constdef)); -} -#endif - -#ifdef HAVE_FPATHCONF -PyDoc_STRVAR(posix_fpathconf__doc__, -"fpathconf(fd, name) -> integer\n\n\ -Return the configuration limit name for the file descriptor fd.\n\ -If there is no limit, return -1."); - -static PyObject * -posix_fpathconf(PyObject *self, PyObject *args) -{ - PyObject *result = NULL; - int name, fd; - - if (PyArg_ParseTuple(args, "iO&:fpathconf", &fd, - conv_path_confname, &name)) { - long limit; - - errno = 0; - limit = fpathconf(fd, name); - if (limit == -1 && errno != 0) - posix_error(); - else - result = PyInt_FromLong(limit); - } - return result; -} -#endif - - -#ifdef HAVE_PATHCONF -PyDoc_STRVAR(posix_pathconf__doc__, -"pathconf(path, name) -> integer\n\n\ -Return the configuration limit name for the file or directory path.\n\ -If there is no limit, return -1."); - -static PyObject * -posix_pathconf(PyObject *self, PyObject *args) -{ - PyObject *result = NULL; - int name; - char *path; - - if (PyArg_ParseTuple(args, "sO&:pathconf", &path, - conv_path_confname, &name)) { - long limit; - - errno = 0; - limit = pathconf(path, name); - if (limit == -1 && errno != 0) { - if (errno == EINVAL) - /* could be a path or name problem */ - posix_error(); - else - posix_error_with_filename(path); - } - else - result = PyInt_FromLong(limit); - } - return result; -} -#endif - -#ifdef HAVE_CONFSTR -static struct constdef posix_constants_confstr[] = { -#ifdef _CS_ARCHITECTURE - {"CS_ARCHITECTURE", _CS_ARCHITECTURE}, -#endif -#ifdef _CS_HOSTNAME - {"CS_HOSTNAME", _CS_HOSTNAME}, -#endif -#ifdef _CS_HW_PROVIDER - {"CS_HW_PROVIDER", _CS_HW_PROVIDER}, -#endif -#ifdef _CS_HW_SERIAL - {"CS_HW_SERIAL", _CS_HW_SERIAL}, -#endif -#ifdef _CS_INITTAB_NAME - {"CS_INITTAB_NAME", _CS_INITTAB_NAME}, -#endif -#ifdef _CS_LFS64_CFLAGS - {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS}, -#endif -#ifdef _CS_LFS64_LDFLAGS - {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS}, -#endif -#ifdef _CS_LFS64_LIBS - {"CS_LFS64_LIBS", _CS_LFS64_LIBS}, -#endif -#ifdef _CS_LFS64_LINTFLAGS - {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS}, -#endif -#ifdef _CS_LFS_CFLAGS - {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS}, -#endif -#ifdef _CS_LFS_LDFLAGS - {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS}, -#endif -#ifdef _CS_LFS_LIBS - {"CS_LFS_LIBS", _CS_LFS_LIBS}, -#endif -#ifdef _CS_LFS_LINTFLAGS - {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS}, -#endif -#ifdef _CS_MACHINE - {"CS_MACHINE", _CS_MACHINE}, -#endif -#ifdef _CS_PATH - {"CS_PATH", _CS_PATH}, -#endif -#ifdef _CS_RELEASE - {"CS_RELEASE", _CS_RELEASE}, -#endif -#ifdef _CS_SRPC_DOMAIN - {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN}, -#endif -#ifdef _CS_SYSNAME - {"CS_SYSNAME", _CS_SYSNAME}, -#endif -#ifdef _CS_VERSION - {"CS_VERSION", _CS_VERSION}, -#endif -#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS - {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS}, -#endif -#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS - {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS}, -#endif -#ifdef _CS_XBS5_ILP32_OFF32_LIBS - {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS}, -#endif -#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS - {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS}, -#endif -#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS - {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS}, -#endif -#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS - {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS}, -#endif -#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS - {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS}, -#endif -#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS - {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS}, -#endif -#ifdef _CS_XBS5_LP64_OFF64_CFLAGS - {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS}, -#endif -#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS - {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS}, -#endif -#ifdef _CS_XBS5_LP64_OFF64_LIBS - {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS}, -#endif -#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS - {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS}, -#endif -#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS - {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS}, -#endif -#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS - {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS}, -#endif -#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS - {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS}, -#endif -#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS - {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS}, -#endif -#ifdef _MIPS_CS_AVAIL_PROCESSORS - {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS}, -#endif -#ifdef _MIPS_CS_BASE - {"MIPS_CS_BASE", _MIPS_CS_BASE}, -#endif -#ifdef _MIPS_CS_HOSTID - {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID}, -#endif -#ifdef _MIPS_CS_HW_NAME - {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME}, -#endif -#ifdef _MIPS_CS_NUM_PROCESSORS - {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS}, -#endif -#ifdef _MIPS_CS_OSREL_MAJ - {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ}, -#endif -#ifdef _MIPS_CS_OSREL_MIN - {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN}, -#endif -#ifdef _MIPS_CS_OSREL_PATCH - {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH}, -#endif -#ifdef _MIPS_CS_OS_NAME - {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME}, -#endif -#ifdef _MIPS_CS_OS_PROVIDER - {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER}, -#endif -#ifdef _MIPS_CS_PROCESSORS - {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS}, -#endif -#ifdef _MIPS_CS_SERIAL - {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL}, -#endif -#ifdef _MIPS_CS_VENDOR - {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR}, -#endif -}; - -static int -conv_confstr_confname(PyObject *arg, int *valuep) -{ - return conv_confname(arg, valuep, posix_constants_confstr, - sizeof(posix_constants_confstr) - / sizeof(struct constdef)); -} - -PyDoc_STRVAR(posix_confstr__doc__, -"confstr(name) -> string\n\n\ -Return a string-valued system configuration variable."); - -static PyObject * -posix_confstr(PyObject *self, PyObject *args) -{ - PyObject *result = NULL; - int name; - char buffer[256]; - - if (PyArg_ParseTuple(args, "O&:confstr", conv_confstr_confname, &name)) { - int len; - - errno = 0; - len = confstr(name, buffer, sizeof(buffer)); - if (len == 0) { - if (errno) { - posix_error(); - } - else { - result = Py_None; - Py_INCREF(Py_None); - } - } - else { - if ((unsigned int)len >= sizeof(buffer)) { - result = PyString_FromStringAndSize(NULL, len-1); - if (result != NULL) - confstr(name, PyString_AS_STRING(result), len); - } - else - result = PyString_FromStringAndSize(buffer, len-1); - } - } - return result; -} -#endif - - -#ifdef HAVE_SYSCONF -static struct constdef posix_constants_sysconf[] = { -#ifdef _SC_2_CHAR_TERM - {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM}, -#endif -#ifdef _SC_2_C_BIND - {"SC_2_C_BIND", _SC_2_C_BIND}, -#endif -#ifdef _SC_2_C_DEV - {"SC_2_C_DEV", _SC_2_C_DEV}, -#endif -#ifdef _SC_2_C_VERSION - {"SC_2_C_VERSION", _SC_2_C_VERSION}, -#endif -#ifdef _SC_2_FORT_DEV - {"SC_2_FORT_DEV", _SC_2_FORT_DEV}, -#endif -#ifdef _SC_2_FORT_RUN - {"SC_2_FORT_RUN", _SC_2_FORT_RUN}, -#endif -#ifdef _SC_2_LOCALEDEF - {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF}, -#endif -#ifdef _SC_2_SW_DEV - {"SC_2_SW_DEV", _SC_2_SW_DEV}, -#endif -#ifdef _SC_2_UPE - {"SC_2_UPE", _SC_2_UPE}, -#endif -#ifdef _SC_2_VERSION - {"SC_2_VERSION", _SC_2_VERSION}, -#endif -#ifdef _SC_ABI_ASYNCHRONOUS_IO - {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO}, -#endif -#ifdef _SC_ACL - {"SC_ACL", _SC_ACL}, -#endif -#ifdef _SC_AIO_LISTIO_MAX - {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX}, -#endif -#ifdef _SC_AIO_MAX - {"SC_AIO_MAX", _SC_AIO_MAX}, -#endif -#ifdef _SC_AIO_PRIO_DELTA_MAX - {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX}, -#endif -#ifdef _SC_ARG_MAX - {"SC_ARG_MAX", _SC_ARG_MAX}, -#endif -#ifdef _SC_ASYNCHRONOUS_IO - {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO}, -#endif -#ifdef _SC_ATEXIT_MAX - {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX}, -#endif -#ifdef _SC_AUDIT - {"SC_AUDIT", _SC_AUDIT}, -#endif -#ifdef _SC_AVPHYS_PAGES - {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES}, -#endif -#ifdef _SC_BC_BASE_MAX - {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX}, -#endif -#ifdef _SC_BC_DIM_MAX - {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX}, -#endif -#ifdef _SC_BC_SCALE_MAX - {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX}, -#endif -#ifdef _SC_BC_STRING_MAX - {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX}, -#endif -#ifdef _SC_CAP - {"SC_CAP", _SC_CAP}, -#endif -#ifdef _SC_CHARCLASS_NAME_MAX - {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX}, -#endif -#ifdef _SC_CHAR_BIT - {"SC_CHAR_BIT", _SC_CHAR_BIT}, -#endif -#ifdef _SC_CHAR_MAX - {"SC_CHAR_MAX", _SC_CHAR_MAX}, -#endif -#ifdef _SC_CHAR_MIN - {"SC_CHAR_MIN", _SC_CHAR_MIN}, -#endif -#ifdef _SC_CHILD_MAX - {"SC_CHILD_MAX", _SC_CHILD_MAX}, -#endif -#ifdef _SC_CLK_TCK - {"SC_CLK_TCK", _SC_CLK_TCK}, -#endif -#ifdef _SC_COHER_BLKSZ - {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ}, -#endif -#ifdef _SC_COLL_WEIGHTS_MAX - {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX}, -#endif -#ifdef _SC_DCACHE_ASSOC - {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC}, -#endif -#ifdef _SC_DCACHE_BLKSZ - {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ}, -#endif -#ifdef _SC_DCACHE_LINESZ - {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ}, -#endif -#ifdef _SC_DCACHE_SZ - {"SC_DCACHE_SZ", _SC_DCACHE_SZ}, -#endif -#ifdef _SC_DCACHE_TBLKSZ - {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ}, -#endif -#ifdef _SC_DELAYTIMER_MAX - {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX}, -#endif -#ifdef _SC_EQUIV_CLASS_MAX - {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX}, -#endif -#ifdef _SC_EXPR_NEST_MAX - {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX}, -#endif -#ifdef _SC_FSYNC - {"SC_FSYNC", _SC_FSYNC}, -#endif -#ifdef _SC_GETGR_R_SIZE_MAX - {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX}, -#endif -#ifdef _SC_GETPW_R_SIZE_MAX - {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX}, -#endif -#ifdef _SC_ICACHE_ASSOC - {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC}, -#endif -#ifdef _SC_ICACHE_BLKSZ - {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ}, -#endif -#ifdef _SC_ICACHE_LINESZ - {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ}, -#endif -#ifdef _SC_ICACHE_SZ - {"SC_ICACHE_SZ", _SC_ICACHE_SZ}, -#endif -#ifdef _SC_INF - {"SC_INF", _SC_INF}, -#endif -#ifdef _SC_INT_MAX - {"SC_INT_MAX", _SC_INT_MAX}, -#endif -#ifdef _SC_INT_MIN - {"SC_INT_MIN", _SC_INT_MIN}, -#endif -#ifdef _SC_IOV_MAX - {"SC_IOV_MAX", _SC_IOV_MAX}, -#endif -#ifdef _SC_IP_SECOPTS - {"SC_IP_SECOPTS", _SC_IP_SECOPTS}, -#endif -#ifdef _SC_JOB_CONTROL - {"SC_JOB_CONTROL", _SC_JOB_CONTROL}, -#endif -#ifdef _SC_KERN_POINTERS - {"SC_KERN_POINTERS", _SC_KERN_POINTERS}, -#endif -#ifdef _SC_KERN_SIM - {"SC_KERN_SIM", _SC_KERN_SIM}, -#endif -#ifdef _SC_LINE_MAX - {"SC_LINE_MAX", _SC_LINE_MAX}, -#endif -#ifdef _SC_LOGIN_NAME_MAX - {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX}, -#endif -#ifdef _SC_LOGNAME_MAX - {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX}, -#endif -#ifdef _SC_LONG_BIT - {"SC_LONG_BIT", _SC_LONG_BIT}, -#endif -#ifdef _SC_MAC - {"SC_MAC", _SC_MAC}, -#endif -#ifdef _SC_MAPPED_FILES - {"SC_MAPPED_FILES", _SC_MAPPED_FILES}, -#endif -#ifdef _SC_MAXPID - {"SC_MAXPID", _SC_MAXPID}, -#endif -#ifdef _SC_MB_LEN_MAX - {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX}, -#endif -#ifdef _SC_MEMLOCK - {"SC_MEMLOCK", _SC_MEMLOCK}, -#endif -#ifdef _SC_MEMLOCK_RANGE - {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE}, -#endif -#ifdef _SC_MEMORY_PROTECTION - {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION}, -#endif -#ifdef _SC_MESSAGE_PASSING - {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING}, -#endif -#ifdef _SC_MMAP_FIXED_ALIGNMENT - {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT}, -#endif -#ifdef _SC_MQ_OPEN_MAX - {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX}, -#endif -#ifdef _SC_MQ_PRIO_MAX - {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX}, -#endif -#ifdef _SC_NACLS_MAX - {"SC_NACLS_MAX", _SC_NACLS_MAX}, -#endif -#ifdef _SC_NGROUPS_MAX - {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX}, -#endif -#ifdef _SC_NL_ARGMAX - {"SC_NL_ARGMAX", _SC_NL_ARGMAX}, -#endif -#ifdef _SC_NL_LANGMAX - {"SC_NL_LANGMAX", _SC_NL_LANGMAX}, -#endif -#ifdef _SC_NL_MSGMAX - {"SC_NL_MSGMAX", _SC_NL_MSGMAX}, -#endif -#ifdef _SC_NL_NMAX - {"SC_NL_NMAX", _SC_NL_NMAX}, -#endif -#ifdef _SC_NL_SETMAX - {"SC_NL_SETMAX", _SC_NL_SETMAX}, -#endif -#ifdef _SC_NL_TEXTMAX - {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX}, -#endif -#ifdef _SC_NPROCESSORS_CONF - {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF}, -#endif -#ifdef _SC_NPROCESSORS_ONLN - {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN}, -#endif -#ifdef _SC_NPROC_CONF - {"SC_NPROC_CONF", _SC_NPROC_CONF}, -#endif -#ifdef _SC_NPROC_ONLN - {"SC_NPROC_ONLN", _SC_NPROC_ONLN}, -#endif -#ifdef _SC_NZERO - {"SC_NZERO", _SC_NZERO}, -#endif -#ifdef _SC_OPEN_MAX - {"SC_OPEN_MAX", _SC_OPEN_MAX}, -#endif -#ifdef _SC_PAGESIZE - {"SC_PAGESIZE", _SC_PAGESIZE}, -#endif -#ifdef _SC_PAGE_SIZE - {"SC_PAGE_SIZE", _SC_PAGE_SIZE}, -#endif -#ifdef _SC_PASS_MAX - {"SC_PASS_MAX", _SC_PASS_MAX}, -#endif -#ifdef _SC_PHYS_PAGES - {"SC_PHYS_PAGES", _SC_PHYS_PAGES}, -#endif -#ifdef _SC_PII - {"SC_PII", _SC_PII}, -#endif -#ifdef _SC_PII_INTERNET - {"SC_PII_INTERNET", _SC_PII_INTERNET}, -#endif -#ifdef _SC_PII_INTERNET_DGRAM - {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM}, -#endif -#ifdef _SC_PII_INTERNET_STREAM - {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM}, -#endif -#ifdef _SC_PII_OSI - {"SC_PII_OSI", _SC_PII_OSI}, -#endif -#ifdef _SC_PII_OSI_CLTS - {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS}, -#endif -#ifdef _SC_PII_OSI_COTS - {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS}, -#endif -#ifdef _SC_PII_OSI_M - {"SC_PII_OSI_M", _SC_PII_OSI_M}, -#endif -#ifdef _SC_PII_SOCKET - {"SC_PII_SOCKET", _SC_PII_SOCKET}, -#endif -#ifdef _SC_PII_XTI - {"SC_PII_XTI", _SC_PII_XTI}, -#endif -#ifdef _SC_POLL - {"SC_POLL", _SC_POLL}, -#endif -#ifdef _SC_PRIORITIZED_IO - {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO}, -#endif -#ifdef _SC_PRIORITY_SCHEDULING - {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING}, -#endif -#ifdef _SC_REALTIME_SIGNALS - {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS}, -#endif -#ifdef _SC_RE_DUP_MAX - {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX}, -#endif -#ifdef _SC_RTSIG_MAX - {"SC_RTSIG_MAX", _SC_RTSIG_MAX}, -#endif -#ifdef _SC_SAVED_IDS - {"SC_SAVED_IDS", _SC_SAVED_IDS}, -#endif -#ifdef _SC_SCHAR_MAX - {"SC_SCHAR_MAX", _SC_SCHAR_MAX}, -#endif -#ifdef _SC_SCHAR_MIN - {"SC_SCHAR_MIN", _SC_SCHAR_MIN}, -#endif -#ifdef _SC_SELECT - {"SC_SELECT", _SC_SELECT}, -#endif -#ifdef _SC_SEMAPHORES - {"SC_SEMAPHORES", _SC_SEMAPHORES}, -#endif -#ifdef _SC_SEM_NSEMS_MAX - {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX}, -#endif -#ifdef _SC_SEM_VALUE_MAX - {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX}, -#endif -#ifdef _SC_SHARED_MEMORY_OBJECTS - {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS}, -#endif -#ifdef _SC_SHRT_MAX - {"SC_SHRT_MAX", _SC_SHRT_MAX}, -#endif -#ifdef _SC_SHRT_MIN - {"SC_SHRT_MIN", _SC_SHRT_MIN}, -#endif -#ifdef _SC_SIGQUEUE_MAX - {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX}, -#endif -#ifdef _SC_SIGRT_MAX - {"SC_SIGRT_MAX", _SC_SIGRT_MAX}, -#endif -#ifdef _SC_SIGRT_MIN - {"SC_SIGRT_MIN", _SC_SIGRT_MIN}, -#endif -#ifdef _SC_SOFTPOWER - {"SC_SOFTPOWER", _SC_SOFTPOWER}, -#endif -#ifdef _SC_SPLIT_CACHE - {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE}, -#endif -#ifdef _SC_SSIZE_MAX - {"SC_SSIZE_MAX", _SC_SSIZE_MAX}, -#endif -#ifdef _SC_STACK_PROT - {"SC_STACK_PROT", _SC_STACK_PROT}, -#endif -#ifdef _SC_STREAM_MAX - {"SC_STREAM_MAX", _SC_STREAM_MAX}, -#endif -#ifdef _SC_SYNCHRONIZED_IO - {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO}, -#endif -#ifdef _SC_THREADS - {"SC_THREADS", _SC_THREADS}, -#endif -#ifdef _SC_THREAD_ATTR_STACKADDR - {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR}, -#endif -#ifdef _SC_THREAD_ATTR_STACKSIZE - {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE}, -#endif -#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS - {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS}, -#endif -#ifdef _SC_THREAD_KEYS_MAX - {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX}, -#endif -#ifdef _SC_THREAD_PRIORITY_SCHEDULING - {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING}, -#endif -#ifdef _SC_THREAD_PRIO_INHERIT - {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT}, -#endif -#ifdef _SC_THREAD_PRIO_PROTECT - {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT}, -#endif -#ifdef _SC_THREAD_PROCESS_SHARED - {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED}, -#endif -#ifdef _SC_THREAD_SAFE_FUNCTIONS - {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS}, -#endif -#ifdef _SC_THREAD_STACK_MIN - {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN}, -#endif -#ifdef _SC_THREAD_THREADS_MAX - {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX}, -#endif -#ifdef _SC_TIMERS - {"SC_TIMERS", _SC_TIMERS}, -#endif -#ifdef _SC_TIMER_MAX - {"SC_TIMER_MAX", _SC_TIMER_MAX}, -#endif -#ifdef _SC_TTY_NAME_MAX - {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX}, -#endif -#ifdef _SC_TZNAME_MAX - {"SC_TZNAME_MAX", _SC_TZNAME_MAX}, -#endif -#ifdef _SC_T_IOV_MAX - {"SC_T_IOV_MAX", _SC_T_IOV_MAX}, -#endif -#ifdef _SC_UCHAR_MAX - {"SC_UCHAR_MAX", _SC_UCHAR_MAX}, -#endif -#ifdef _SC_UINT_MAX - {"SC_UINT_MAX", _SC_UINT_MAX}, -#endif -#ifdef _SC_UIO_MAXIOV - {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV}, -#endif -#ifdef _SC_ULONG_MAX - {"SC_ULONG_MAX", _SC_ULONG_MAX}, -#endif -#ifdef _SC_USHRT_MAX - {"SC_USHRT_MAX", _SC_USHRT_MAX}, -#endif -#ifdef _SC_VERSION - {"SC_VERSION", _SC_VERSION}, -#endif -#ifdef _SC_WORD_BIT - {"SC_WORD_BIT", _SC_WORD_BIT}, -#endif -#ifdef _SC_XBS5_ILP32_OFF32 - {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32}, -#endif -#ifdef _SC_XBS5_ILP32_OFFBIG - {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG}, -#endif -#ifdef _SC_XBS5_LP64_OFF64 - {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64}, -#endif -#ifdef _SC_XBS5_LPBIG_OFFBIG - {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG}, -#endif -#ifdef _SC_XOPEN_CRYPT - {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT}, -#endif -#ifdef _SC_XOPEN_ENH_I18N - {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N}, -#endif -#ifdef _SC_XOPEN_LEGACY - {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY}, -#endif -#ifdef _SC_XOPEN_REALTIME - {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME}, -#endif -#ifdef _SC_XOPEN_REALTIME_THREADS - {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS}, -#endif -#ifdef _SC_XOPEN_SHM - {"SC_XOPEN_SHM", _SC_XOPEN_SHM}, -#endif -#ifdef _SC_XOPEN_UNIX - {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX}, -#endif -#ifdef _SC_XOPEN_VERSION - {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION}, -#endif -#ifdef _SC_XOPEN_XCU_VERSION - {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION}, -#endif -#ifdef _SC_XOPEN_XPG2 - {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2}, -#endif -#ifdef _SC_XOPEN_XPG3 - {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3}, -#endif -#ifdef _SC_XOPEN_XPG4 - {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4}, -#endif -}; - -static int -conv_sysconf_confname(PyObject *arg, int *valuep) -{ - return conv_confname(arg, valuep, posix_constants_sysconf, - sizeof(posix_constants_sysconf) - / sizeof(struct constdef)); -} - -PyDoc_STRVAR(posix_sysconf__doc__, -"sysconf(name) -> integer\n\n\ -Return an integer-valued system configuration variable."); - -static PyObject * -posix_sysconf(PyObject *self, PyObject *args) -{ - PyObject *result = NULL; - int name; - - if (PyArg_ParseTuple(args, "O&:sysconf", conv_sysconf_confname, &name)) { - int value; - - errno = 0; - value = sysconf(name); - if (value == -1 && errno != 0) - posix_error(); - else - result = PyInt_FromLong(value); - } - return result; -} -#endif - - -#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF) || defined(HAVE_CONFSTR) || defined(HAVE_SYSCONF) -/* This code is used to ensure that the tables of configuration value names - * are in sorted order as required by conv_confname(), and also to build the - * the exported dictionaries that are used to publish information about the - * names available on the host platform. - * - * Sorting the table at runtime ensures that the table is properly ordered - * when used, even for platforms we're not able to test on. It also makes - * it easier to add additional entries to the tables. - */ - -static int -cmp_constdefs(const void *v1, const void *v2) -{ - const struct constdef *c1 = - (const struct constdef *) v1; - const struct constdef *c2 = - (const struct constdef *) v2; - - return strcmp(c1->name, c2->name); -} - -static int -setup_confname_table(struct constdef *table, size_t tablesize, - char *tablename, PyObject *module) -{ - PyObject *d = NULL; - size_t i; - - qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs); - d = PyDict_New(); - if (d == NULL) - return -1; - - for (i=0; i < tablesize; ++i) { - PyObject *o = PyInt_FromLong(table[i].value); - if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) { - Py_XDECREF(o); - Py_DECREF(d); - return -1; - } - Py_DECREF(o); - } - return PyModule_AddObject(module, tablename, d); -} -#endif /* HAVE_FPATHCONF || HAVE_PATHCONF || HAVE_CONFSTR || HAVE_SYSCONF */ - -/* Return -1 on failure, 0 on success. */ -static int -setup_confname_tables(PyObject *module) -{ -#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF) - if (setup_confname_table(posix_constants_pathconf, - sizeof(posix_constants_pathconf) - / sizeof(struct constdef), - "pathconf_names", module)) - return -1; -#endif -#ifdef HAVE_CONFSTR - if (setup_confname_table(posix_constants_confstr, - sizeof(posix_constants_confstr) - / sizeof(struct constdef), - "confstr_names", module)) - return -1; -#endif -#ifdef HAVE_SYSCONF - if (setup_confname_table(posix_constants_sysconf, - sizeof(posix_constants_sysconf) - / sizeof(struct constdef), - "sysconf_names", module)) - return -1; -#endif - return 0; -} - - -PyDoc_STRVAR(posix_abort__doc__, -"abort() -> does not return!\n\n\ -Abort the interpreter immediately. This 'dumps core' or otherwise fails\n\ -in the hardest way possible on the hosting operating system."); - -static PyObject * -posix_abort(PyObject *self, PyObject *noargs) -{ - abort(); - /*NOTREACHED*/ - Py_FatalError("abort() called from Python code didn't abort!"); - return NULL; -} - -#ifdef HAVE_SETRESUID -PyDoc_STRVAR(posix_setresuid__doc__, -"setresuid(ruid, euid, suid)\n\n\ -Set the current process's real, effective, and saved user ids."); - -static PyObject* -posix_setresuid (PyObject *self, PyObject *args) -{ - /* We assume uid_t is no larger than a long. */ - long ruid, euid, suid; - if (!PyArg_ParseTuple(args, "lll", &ruid, &euid, &suid)) - return NULL; - if (setresuid(ruid, euid, suid) < 0) - return posix_error(); - Py_RETURN_NONE; -} -#endif - -#ifdef HAVE_SETRESGID -PyDoc_STRVAR(posix_setresgid__doc__, -"setresgid(rgid, egid, sgid)\n\n\ -Set the current process's real, effective, and saved group ids."); - -static PyObject* -posix_setresgid (PyObject *self, PyObject *args) -{ - /* We assume uid_t is no larger than a long. */ - long rgid, egid, sgid; - if (!PyArg_ParseTuple(args, "lll", &rgid, &egid, &sgid)) - return NULL; - if (setresgid(rgid, egid, sgid) < 0) - return posix_error(); - Py_RETURN_NONE; -} -#endif - -#ifdef HAVE_GETRESUID -PyDoc_STRVAR(posix_getresuid__doc__, -"getresuid() -> (ruid, euid, suid)\n\n\ -Get tuple of the current process's real, effective, and saved user ids."); - -static PyObject* -posix_getresuid (PyObject *self, PyObject *noargs) -{ - uid_t ruid, euid, suid; - long l_ruid, l_euid, l_suid; - if (getresuid(&ruid, &euid, &suid) < 0) - return posix_error(); - /* Force the values into long's as we don't know the size of uid_t. */ - l_ruid = ruid; - l_euid = euid; - l_suid = suid; - return Py_BuildValue("(lll)", l_ruid, l_euid, l_suid); -} -#endif - -#ifdef HAVE_GETRESGID -PyDoc_STRVAR(posix_getresgid__doc__, -"getresgid() -> (rgid, egid, sgid)\n\n\ -Get tuple of the current process's real, effective, and saved group ids."); - -static PyObject* -posix_getresgid (PyObject *self, PyObject *noargs) -{ - uid_t rgid, egid, sgid; - long l_rgid, l_egid, l_sgid; - if (getresgid(&rgid, &egid, &sgid) < 0) - return posix_error(); - /* Force the values into long's as we don't know the size of uid_t. */ - l_rgid = rgid; - l_egid = egid; - l_sgid = sgid; - return Py_BuildValue("(lll)", l_rgid, l_egid, l_sgid); -} -#endif - -static PyMethodDef posix_methods[] = { - {"access", posix_access, METH_VARARGS, posix_access__doc__}, -#ifdef HAVE_TTYNAME - {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, -#endif - {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, -#ifdef HAVE_CHFLAGS - {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, -#endif /* HAVE_CHFLAGS */ - {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, -#ifdef HAVE_FCHMOD - {"fchmod", posix_fchmod, METH_VARARGS, posix_fchmod__doc__}, -#endif /* HAVE_FCHMOD */ -#ifdef HAVE_CHOWN - {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, -#endif /* HAVE_CHOWN */ -#ifdef HAVE_LCHMOD - {"lchmod", posix_lchmod, METH_VARARGS, posix_lchmod__doc__}, -#endif /* HAVE_LCHMOD */ -#ifdef HAVE_FCHOWN - {"fchown", posix_fchown, METH_VARARGS, posix_fchown__doc__}, -#endif /* HAVE_FCHOWN */ -#ifdef HAVE_LCHFLAGS - {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, -#endif /* HAVE_LCHFLAGS */ -#ifdef HAVE_LCHOWN - {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, -#endif /* HAVE_LCHOWN */ -#ifdef HAVE_CHROOT - {"chroot", posix_chroot, METH_VARARGS, posix_chroot__doc__}, -#endif -#ifdef HAVE_CTERMID - {"ctermid", posix_ctermid, METH_NOARGS, posix_ctermid__doc__}, -#endif -#ifdef HAVE_GETCWD - {"getcwd", posix_getcwd, METH_NOARGS, posix_getcwd__doc__}, -#ifdef Py_USING_UNICODE - {"getcwdu", posix_getcwdu, METH_NOARGS, posix_getcwdu__doc__}, -#endif -#endif -#ifdef HAVE_LINK - {"link", posix_link, METH_VARARGS, posix_link__doc__}, -#endif /* HAVE_LINK */ - {"listdir", posix_listdir, METH_VARARGS, posix_listdir__doc__}, - {"lstat", posix_lstat, METH_VARARGS, posix_lstat__doc__}, - {"mkdir", posix_mkdir, METH_VARARGS, posix_mkdir__doc__}, -#ifdef HAVE_NICE - {"nice", posix_nice, METH_VARARGS, posix_nice__doc__}, -#endif /* HAVE_NICE */ -#ifdef HAVE_READLINK - {"readlink", posix_readlink, METH_VARARGS, posix_readlink__doc__}, -#endif /* HAVE_READLINK */ - {"rename", posix_rename, METH_VARARGS, posix_rename__doc__}, - {"rmdir", posix_rmdir, METH_VARARGS, posix_rmdir__doc__}, - {"stat", posix_stat, METH_VARARGS, posix_stat__doc__}, - //{"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__}, -#ifdef HAVE_SYMLINK - {"symlink", posix_symlink, METH_VARARGS, posix_symlink__doc__}, -#endif /* HAVE_SYMLINK */ -#ifdef HAVE_SYSTEM - {"system", posix_system, METH_VARARGS, posix_system__doc__}, -#endif - {"umask", posix_umask, METH_VARARGS, posix_umask__doc__}, -#ifdef HAVE_UNAME - {"uname", posix_uname, METH_NOARGS, posix_uname__doc__}, -#endif /* HAVE_UNAME */ - {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__}, - {"remove", posix_unlink, METH_VARARGS, posix_remove__doc__}, - {"utime", posix_utime, METH_VARARGS, posix_utime__doc__}, -#ifdef HAVE_TIMES - {"times", posix_times, METH_NOARGS, posix_times__doc__}, -#endif /* HAVE_TIMES */ - {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__}, -#ifdef HAVE_EXECV - {"execv", posix_execv, METH_VARARGS, posix_execv__doc__}, - {"execve", posix_execve, METH_VARARGS, posix_execve__doc__}, -#endif /* HAVE_EXECV */ -#ifdef HAVE_SPAWNV - {"spawnv", posix_spawnv, METH_VARARGS, posix_spawnv__doc__}, - {"spawnve", posix_spawnve, METH_VARARGS, posix_spawnve__doc__}, -#if defined(PYOS_OS2) - {"spawnvp", posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__}, - {"spawnvpe", posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__}, -#endif /* PYOS_OS2 */ -#endif /* HAVE_SPAWNV */ -#ifdef HAVE_FORK1 - {"fork1", posix_fork1, METH_NOARGS, posix_fork1__doc__}, -#endif /* HAVE_FORK1 */ -#ifdef HAVE_FORK - {"fork", posix_fork, METH_NOARGS, posix_fork__doc__}, -#endif /* HAVE_FORK */ -#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) - {"openpty", posix_openpty, METH_NOARGS, posix_openpty__doc__}, -#endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */ -#ifdef HAVE_FORKPTY - {"forkpty", posix_forkpty, METH_NOARGS, posix_forkpty__doc__}, -#endif /* HAVE_FORKPTY */ -#ifdef HAVE_GETEGID - {"getegid", posix_getegid, METH_NOARGS, posix_getegid__doc__}, -#endif /* HAVE_GETEGID */ -#ifdef HAVE_GETEUID - {"geteuid", posix_geteuid, METH_NOARGS, posix_geteuid__doc__}, -#endif /* HAVE_GETEUID */ -#ifdef HAVE_GETGID - {"getgid", posix_getgid, METH_NOARGS, posix_getgid__doc__}, -#endif /* HAVE_GETGID */ -#ifdef HAVE_GETGROUPS - {"getgroups", posix_getgroups, METH_NOARGS, posix_getgroups__doc__}, -#endif - {"getpid", posix_getpid, METH_NOARGS, posix_getpid__doc__}, -#ifdef HAVE_GETPGRP - {"getpgrp", posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__}, -#endif /* HAVE_GETPGRP */ -#ifdef HAVE_GETPPID - {"getppid", posix_getppid, METH_NOARGS, posix_getppid__doc__}, -#endif /* HAVE_GETPPID */ -#ifdef HAVE_GETUID - {"getuid", posix_getuid, METH_NOARGS, posix_getuid__doc__}, -#endif /* HAVE_GETUID */ -#ifdef HAVE_GETLOGIN - {"getlogin", posix_getlogin, METH_NOARGS, posix_getlogin__doc__}, -#endif -#ifdef HAVE_KILL - {"kill", posix_kill, METH_VARARGS, posix_kill__doc__}, -#endif /* HAVE_KILL */ -#ifdef HAVE_KILLPG - {"killpg", posix_killpg, METH_VARARGS, posix_killpg__doc__}, -#endif /* HAVE_KILLPG */ -#ifdef HAVE_PLOCK - {"plock", posix_plock, METH_VARARGS, posix_plock__doc__}, -#endif /* HAVE_PLOCK */ -#ifdef HAVE_POPEN - {"popen", posix_popen, METH_VARARGS, posix_popen__doc__}, -#ifdef MS_WINDOWS - {"popen2", win32_popen2, METH_VARARGS}, - {"popen3", win32_popen3, METH_VARARGS}, - {"popen4", win32_popen4, METH_VARARGS}, - {"startfile", win32_startfile, METH_VARARGS, win32_startfile__doc__}, - {"kill", win32_kill, METH_VARARGS, win32_kill__doc__}, -#else -#if defined(PYOS_OS2) && defined(PYCC_GCC) - {"popen2", os2emx_popen2, METH_VARARGS}, - {"popen3", os2emx_popen3, METH_VARARGS}, - {"popen4", os2emx_popen4, METH_VARARGS}, -#endif -#endif -#endif /* HAVE_POPEN */ -#ifdef HAVE_SETUID - {"setuid", posix_setuid, METH_VARARGS, posix_setuid__doc__}, -#endif /* HAVE_SETUID */ -#ifdef HAVE_SETEUID - {"seteuid", posix_seteuid, METH_VARARGS, posix_seteuid__doc__}, -#endif /* HAVE_SETEUID */ -#ifdef HAVE_SETEGID - {"setegid", posix_setegid, METH_VARARGS, posix_setegid__doc__}, -#endif /* HAVE_SETEGID */ -#ifdef HAVE_SETREUID - {"setreuid", posix_setreuid, METH_VARARGS, posix_setreuid__doc__}, -#endif /* HAVE_SETREUID */ -#ifdef HAVE_SETREGID - {"setregid", posix_setregid, METH_VARARGS, posix_setregid__doc__}, -#endif /* HAVE_SETREGID */ -#ifdef HAVE_SETGID - {"setgid", posix_setgid, METH_VARARGS, posix_setgid__doc__}, -#endif /* HAVE_SETGID */ -#ifdef HAVE_SETGROUPS - {"setgroups", posix_setgroups, METH_O, posix_setgroups__doc__}, -#endif /* HAVE_SETGROUPS */ -#ifdef HAVE_INITGROUPS - {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__}, -#endif /* HAVE_INITGROUPS */ -#ifdef HAVE_GETPGID - {"getpgid", posix_getpgid, METH_VARARGS, posix_getpgid__doc__}, -#endif /* HAVE_GETPGID */ -#ifdef HAVE_SETPGRP - {"setpgrp", posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__}, -#endif /* HAVE_SETPGRP */ -#ifdef HAVE_WAIT - {"wait", posix_wait, METH_NOARGS, posix_wait__doc__}, -#endif /* HAVE_WAIT */ -#ifdef HAVE_WAIT3 - {"wait3", posix_wait3, METH_VARARGS, posix_wait3__doc__}, -#endif /* HAVE_WAIT3 */ -#ifdef HAVE_WAIT4 - {"wait4", posix_wait4, METH_VARARGS, posix_wait4__doc__}, -#endif /* HAVE_WAIT4 */ -#if defined(HAVE_WAITPID) || defined(HAVE_CWAIT) - {"waitpid", posix_waitpid, METH_VARARGS, posix_waitpid__doc__}, -#endif /* HAVE_WAITPID */ -#ifdef HAVE_GETSID - {"getsid", posix_getsid, METH_VARARGS, posix_getsid__doc__}, -#endif /* HAVE_GETSID */ -#ifdef HAVE_SETSID - {"setsid", posix_setsid, METH_NOARGS, posix_setsid__doc__}, -#endif /* HAVE_SETSID */ -#ifdef HAVE_SETPGID - {"setpgid", posix_setpgid, METH_VARARGS, posix_setpgid__doc__}, -#endif /* HAVE_SETPGID */ -#ifdef HAVE_TCGETPGRP - {"tcgetpgrp", posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__}, -#endif /* HAVE_TCGETPGRP */ -#ifdef HAVE_TCSETPGRP - {"tcsetpgrp", posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__}, -#endif /* HAVE_TCSETPGRP */ - {"open", posix_open, METH_VARARGS, posix_open__doc__}, - {"close", posix_close, METH_VARARGS, posix_close__doc__}, - {"closerange", posix_closerange, METH_VARARGS, posix_closerange__doc__}, - {"dup", posix_dup, METH_VARARGS, posix_dup__doc__}, - {"dup2", posix_dup2, METH_VARARGS, posix_dup2__doc__}, - {"lseek", posix_lseek, METH_VARARGS, posix_lseek__doc__}, - {"read", posix_read, METH_VARARGS, posix_read__doc__}, - {"write", posix_write, METH_VARARGS, posix_write__doc__}, - {"fstat", posix_fstat, METH_VARARGS, posix_fstat__doc__}, - {"fdopen", posix_fdopen, METH_VARARGS, posix_fdopen__doc__}, - {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__}, -#ifdef HAVE_PIPE - {"pipe", posix_pipe, METH_NOARGS, posix_pipe__doc__}, -#endif -#ifdef HAVE_MKFIFO - {"mkfifo", posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__}, -#endif -#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) - {"mknod", posix_mknod, METH_VARARGS, posix_mknod__doc__}, -#endif -#ifdef HAVE_DEVICE_MACROS - {"major", posix_major, METH_VARARGS, posix_major__doc__}, - {"minor", posix_minor, METH_VARARGS, posix_minor__doc__}, - {"makedev", posix_makedev, METH_VARARGS, posix_makedev__doc__}, -#endif -#ifdef HAVE_FTRUNCATE - {"ftruncate", posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__}, -#endif -#ifdef HAVE_PUTENV - {"putenv", posix_putenv, METH_VARARGS, posix_putenv__doc__}, -#endif -#ifdef HAVE_UNSETENV - {"unsetenv", posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__}, -#endif - {"strerror", posix_strerror, METH_VARARGS, posix_strerror__doc__}, -#ifdef HAVE_FCHDIR - {"fchdir", posix_fchdir, METH_O, posix_fchdir__doc__}, -#endif -#ifdef HAVE_FSYNC - {"fsync", posix_fsync, METH_O, posix_fsync__doc__}, -#endif -#ifdef HAVE_FDATASYNC - {"fdatasync", posix_fdatasync, METH_O, posix_fdatasync__doc__}, -#endif -#ifdef HAVE_SYS_WAIT_H -#ifdef WCOREDUMP - {"WCOREDUMP", posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__}, -#endif /* WCOREDUMP */ -#ifdef WIFCONTINUED - {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__}, -#endif /* WIFCONTINUED */ -#ifdef WIFSTOPPED - {"WIFSTOPPED", posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__}, -#endif /* WIFSTOPPED */ -#ifdef WIFSIGNALED - {"WIFSIGNALED", posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__}, -#endif /* WIFSIGNALED */ -#ifdef WIFEXITED - {"WIFEXITED", posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__}, -#endif /* WIFEXITED */ -#ifdef WEXITSTATUS - {"WEXITSTATUS", posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__}, -#endif /* WEXITSTATUS */ -#ifdef WTERMSIG - {"WTERMSIG", posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__}, -#endif /* WTERMSIG */ -#ifdef WSTOPSIG - {"WSTOPSIG", posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__}, -#endif /* WSTOPSIG */ -#endif /* HAVE_SYS_WAIT_H */ -#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) - {"fstatvfs", posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__}, -#endif -#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) - {"statvfs", posix_statvfs, METH_VARARGS, posix_statvfs__doc__}, -#endif -#ifdef HAVE_TMPFILE - {"tmpfile", posix_tmpfile, METH_NOARGS, posix_tmpfile__doc__}, -#endif -#ifdef HAVE_TEMPNAM - {"tempnam", posix_tempnam, METH_VARARGS, posix_tempnam__doc__}, -#endif -#ifdef HAVE_TMPNAM - {"tmpnam", posix_tmpnam, METH_NOARGS, posix_tmpnam__doc__}, -#endif -#ifdef HAVE_CONFSTR - {"confstr", posix_confstr, METH_VARARGS, posix_confstr__doc__}, -#endif -#ifdef HAVE_SYSCONF - {"sysconf", posix_sysconf, METH_VARARGS, posix_sysconf__doc__}, -#endif -#ifdef HAVE_FPATHCONF - {"fpathconf", posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__}, -#endif -#ifdef HAVE_PATHCONF - {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__}, -#endif - {"abort", posix_abort, METH_NOARGS, posix_abort__doc__}, -#ifdef HAVE_SETRESUID - {"setresuid", posix_setresuid, METH_VARARGS, posix_setresuid__doc__}, -#endif -#ifdef HAVE_SETRESGID - {"setresgid", posix_setresgid, METH_VARARGS, posix_setresgid__doc__}, -#endif -#ifdef HAVE_GETRESUID - {"getresuid", posix_getresuid, METH_NOARGS, posix_getresuid__doc__}, -#endif -#ifdef HAVE_GETRESGID - {"getresgid", posix_getresgid, METH_NOARGS, posix_getresgid__doc__}, -#endif - - {NULL, NULL} /* Sentinel */ -}; - - -static int -ins(PyObject *module, char *symbol, long value) -{ - return PyModule_AddIntConstant(module, symbol, value); -} - -static int -all_ins(PyObject *d) -{ -#ifdef F_OK - if (ins(d, "F_OK", (long)F_OK)) return -1; -#endif -#ifdef R_OK - if (ins(d, "R_OK", (long)R_OK)) return -1; -#endif -#ifdef W_OK - if (ins(d, "W_OK", (long)W_OK)) return -1; -#endif -#ifdef X_OK - if (ins(d, "X_OK", (long)X_OK)) return -1; -#endif -#ifdef NGROUPS_MAX - if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1; -#endif -#ifdef TMP_MAX - if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1; -#endif -#ifdef WCONTINUED - if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1; -#endif -#ifdef WNOHANG - if (ins(d, "WNOHANG", (long)WNOHANG)) return -1; -#endif -#ifdef WUNTRACED - if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1; -#endif -#ifdef O_RDONLY - if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1; -#endif -#ifdef O_WRONLY - if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1; -#endif -#ifdef O_RDWR - if (ins(d, "O_RDWR", (long)O_RDWR)) return -1; -#endif -#ifdef O_NDELAY - if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1; -#endif -#ifdef O_NONBLOCK - if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1; -#endif -#ifdef O_APPEND - if (ins(d, "O_APPEND", (long)O_APPEND)) return -1; -#endif -#ifdef O_DSYNC - if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1; -#endif -#ifdef O_RSYNC - if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1; -#endif -#ifdef O_SYNC - if (ins(d, "O_SYNC", (long)O_SYNC)) return -1; -#endif -#ifdef O_NOCTTY - if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1; -#endif -#ifdef O_CREAT - if (ins(d, "O_CREAT", (long)O_CREAT)) return -1; -#endif -#ifdef O_EXCL - if (ins(d, "O_EXCL", (long)O_EXCL)) return -1; -#endif -#ifdef O_TRUNC - if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1; -#endif -#ifdef O_BINARY - if (ins(d, "O_BINARY", (long)O_BINARY)) return -1; -#endif -#ifdef O_TEXT - if (ins(d, "O_TEXT", (long)O_TEXT)) return -1; -#endif -#ifdef O_LARGEFILE - if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1; -#endif -#ifdef O_SHLOCK - if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1; -#endif -#ifdef O_EXLOCK - if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1; -#endif - -/* MS Windows */ -#ifdef O_NOINHERIT - /* Don't inherit in child processes. */ - if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1; -#endif -#ifdef _O_SHORT_LIVED - /* Optimize for short life (keep in memory). */ - /* MS forgot to define this one with a non-underscore form too. */ - if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1; -#endif -#ifdef O_TEMPORARY - /* Automatically delete when last handle is closed. */ - if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1; -#endif -#ifdef O_RANDOM - /* Optimize for random access. */ - if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1; -#endif -#ifdef O_SEQUENTIAL - /* Optimize for sequential access. */ - if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1; -#endif - -/* GNU extensions. */ -#ifdef O_ASYNC - /* Send a SIGIO signal whenever input or output - becomes available on file descriptor */ - if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1; -#endif -#ifdef O_DIRECT - /* Direct disk access. */ - if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1; -#endif -#ifdef O_DIRECTORY - /* Must be a directory. */ - if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1; -#endif -#ifdef O_NOFOLLOW - /* Do not follow links. */ - if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1; -#endif -#ifdef O_NOATIME - /* Do not update the access time. */ - if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1; -#endif - - /* These come from sysexits.h */ -#ifdef EX_OK - if (ins(d, "EX_OK", (long)EX_OK)) return -1; -#endif /* EX_OK */ -#ifdef EX_USAGE - if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1; -#endif /* EX_USAGE */ -#ifdef EX_DATAERR - if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1; -#endif /* EX_DATAERR */ -#ifdef EX_NOINPUT - if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1; -#endif /* EX_NOINPUT */ -#ifdef EX_NOUSER - if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1; -#endif /* EX_NOUSER */ -#ifdef EX_NOHOST - if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1; -#endif /* EX_NOHOST */ -#ifdef EX_UNAVAILABLE - if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1; -#endif /* EX_UNAVAILABLE */ -#ifdef EX_SOFTWARE - if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1; -#endif /* EX_SOFTWARE */ -#ifdef EX_OSERR - if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1; -#endif /* EX_OSERR */ -#ifdef EX_OSFILE - if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1; -#endif /* EX_OSFILE */ -#ifdef EX_CANTCREAT - if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1; -#endif /* EX_CANTCREAT */ -#ifdef EX_IOERR - if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1; -#endif /* EX_IOERR */ -#ifdef EX_TEMPFAIL - if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1; -#endif /* EX_TEMPFAIL */ -#ifdef EX_PROTOCOL - if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1; -#endif /* EX_PROTOCOL */ -#ifdef EX_NOPERM - if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1; -#endif /* EX_NOPERM */ -#ifdef EX_CONFIG - if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1; -#endif /* EX_CONFIG */ -#ifdef EX_NOTFOUND - if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1; -#endif /* EX_NOTFOUND */ - -#ifdef HAVE_SPAWNV -#if defined(PYOS_OS2) && defined(PYCC_GCC) - if (ins(d, "P_WAIT", (long)P_WAIT)) return -1; - if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1; - if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1; - if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1; - if (ins(d, "P_SESSION", (long)P_SESSION)) return -1; - if (ins(d, "P_DETACH", (long)P_DETACH)) return -1; - if (ins(d, "P_PM", (long)P_PM)) return -1; - if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1; - if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1; - if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1; - if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1; - if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1; - if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1; - if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1; - if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1; - if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1; - if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1; - if (ins(d, "P_TILDE", (long)P_TILDE)) return -1; - if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1; - if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1; -#else - if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1; - if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1; - if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1; - if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1; - if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1; -#endif -#endif - return 0; -} - -#define INITFUNC initedk2 -#define MODNAME "edk2" - -PyMODINIT_FUNC -INITFUNC(void) -{ - PyObject *m; - -#ifndef UEFI_C_SOURCE - PyObject *v; -#endif - - m = Py_InitModule3(MODNAME, - posix_methods, - edk2__doc__); - if (m == NULL) - return; - -#ifndef UEFI_C_SOURCE - /* Initialize environ dictionary */ - v = convertenviron(); - Py_XINCREF(v); - if (v == NULL || PyModule_AddObject(m, "environ", v) != 0) - return; - Py_DECREF(v); -#endif /* UEFI_C_SOURCE */ - - if (all_ins(m)) - return; - - if (setup_confname_tables(m)) - return; - - Py_INCREF(PyExc_OSError); - PyModule_AddObject(m, "error", PyExc_OSError); - -#ifdef HAVE_PUTENV - if (posix_putenv_garbage == NULL) - posix_putenv_garbage = PyDict_New(); -#endif - - if (!initialized) { - stat_result_desc.name = MODNAME ".stat_result"; - stat_result_desc.fields[2].name = PyStructSequence_UnnamedField; - stat_result_desc.fields[3].name = PyStructSequence_UnnamedField; - stat_result_desc.fields[4].name = PyStructSequence_UnnamedField; - PyStructSequence_InitType(&StatResultType, &stat_result_desc); - structseq_new = StatResultType.tp_new; - StatResultType.tp_new = statresult_new; - - //statvfs_result_desc.name = MODNAME ".statvfs_result"; - //PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc); -#ifdef NEED_TICKS_PER_SECOND -# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK) - ticks_per_second = sysconf(_SC_CLK_TCK); -# elif defined(HZ) - ticks_per_second = HZ; -# else - ticks_per_second = 60; /* magic fallback value; may be bogus */ -# endif -#endif - } - Py_INCREF((PyObject*) &StatResultType); - PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType); - //Py_INCREF((PyObject*) &StatVFSResultType); - //PyModule_AddObject(m, "statvfs_result", - // (PyObject*) &StatVFSResultType); - initialized = 1; - -} - -#ifdef __cplusplus -} -#endif - - diff --git a/AppPkg/Applications/Python/Efi/getpath.c b/AppPkg/Applications/Python/Efi/getpath.c deleted file mode 100644 index 208bb7e..0000000 --- a/AppPkg/Applications/Python/Efi/getpath.c +++ /dev/null @@ -1,719 +0,0 @@ -/** @file - Return the initial module search path. - - Search in specified locations for the associated Python libraries. - - Py_GetPath returns module_search_path. - Py_GetPrefix returns PREFIX - Py_GetExec_Prefix returns PREFIX - Py_GetProgramFullPath returns the full path to the python executable. - - These are built dynamically so that the proper volume name can be prefixed - to the paths. - - For the EDK II, UEFI, implementation of Python, PREFIX and EXEC_PREFIX - are set as follows: - PREFIX = /Efi/StdLib - EXEC_PREFIX = PREFIX - - The following final paths are assumed: - /Efi/Tools/Python.efi The Python executable. - /Efi/StdLib/lib/python.VERSION The platform independent Python modules. - /Efi/StdLib/lib/python.VERSION/dynalib Dynamically loadable Python extension modules. - - Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent -**/ -#include -#include -#include - -#ifdef __cplusplus - extern "C" { -#endif - -/* VERSION must be at least two characters long. */ -#ifndef VERSION - #define VERSION "27" -#endif - -#ifndef VPATH - #define VPATH "." -#endif - -/* Search path entry delimiter */ -#ifdef DELIM - #define sDELIM ";" -#endif - -#ifndef PREFIX - #define PREFIX "/Efi/StdLib" -#endif - -#ifndef EXEC_PREFIX - #define EXEC_PREFIX PREFIX -#endif - -#ifndef LIBPYTHON - #define LIBPYTHON "lib/python." VERSION -#endif - -#ifndef PYTHONPATH - #ifdef HAVE_ENVIRONMENT_OPS - #define PYTHONPATH PREFIX LIBPYTHON sDELIM \ - EXEC_PREFIX LIBPYTHON "/lib-dynload" - #else - #define PYTHONPATH LIBPYTHON - #endif -#endif - -#ifndef LANDMARK -#define LANDMARK "os.py" -#endif - -static char prefix[MAXPATHLEN+1]; -static char exec_prefix[MAXPATHLEN+1]; -static char progpath[MAXPATHLEN+1]; -static char *module_search_path = NULL; -static char lib_python[] = LIBPYTHON; -static char volume_name[32] = { 0 }; - -/** Determine if "ch" is a separator character. - - @param[in] ch The character to test. - - @retval TRUE ch is a separator character. - @retval FALSE ch is NOT a separator character. -**/ -static int -is_sep(char ch) -{ -#ifdef ALTSEP - return ch == SEP || ch == ALTSEP; -#else - return ch == SEP; -#endif -} - -/** Reduce a path by its last element. - - The last element (everything to the right of the last separator character) - in the path, dir, is removed from the path. Parameter dir is modified in place. - - @param[in,out] dir Pointer to the path to modify. -**/ -static void -reduce(char *dir) -{ - size_t i = strlen(dir); - while (i > 0 && !is_sep(dir[i])) - --i; - dir[i] = '\0'; -} - -#ifndef UEFI_C_SOURCE -/** Does filename point to a file and not directory? - - @param[in] filename The fully qualified path to the object to test. - - @retval 0 Filename was not found, or is a directory. - @retval 1 Filename refers to a regular file. -**/ -static int -isfile(char *filename) -{ - struct stat buf; - if (stat(filename, &buf) != 0) { - return 0; - } - //if (!S_ISREG(buf.st_mode)) - if (S_ISDIR(buf.st_mode)) { - return 0; - } - return 1; -} - -/** Determine if filename refers to a Python module. - - A Python module is indicated if the file exists, or if the file with - 'o' or 'c' appended exists. - - @param[in] filename The fully qualified path to the object to test. - - @retval 0 -**/ -static int -ismodule(char *filename) -{ - if (isfile(filename)) { - //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: file = \"%s\"\n", __func__, __LINE__, filename); - return 1; - } - - /* Check for the compiled version of prefix. */ - if (strlen(filename) < MAXPATHLEN) { - strcat(filename, Py_OptimizeFlag ? "o" : "c"); - if (isfile(filename)) { - return 1; - } - } - return 0; -} - -/** Does filename point to a directory? - - @param[in] filename The fully qualified path to the object to test. - - @retval 0 Filename was not found, or is not a regular file. - @retval 1 Filename refers to a directory. -**/ -static int -isdir(char *filename) -{ - struct stat buf; - - if (stat(filename, &buf) != 0) - return 0; - - if (!S_ISDIR(buf.st_mode)) - return 0; - - return 1; -} -#endif /* UEFI_C_SOURCE */ - -/** Determine if a path is absolute, or not. - An absolute path consists of a volume name, "VOL:", followed by a rooted path, - "/path/elements". If both of these components are present, the path is absolute. - - Let P be a pointer to the path to test. - Let A be a pointer to the first ':' in P. - Let B be a pointer to the first '/' or '\\' in P. - - If A and B are not NULL - If (A-P+1) == (B-P) then the path is absolute. - Otherwise, the path is NOT absolute. - - @param[in] path The path to test. - - @retval -1 Path is absolute but lacking volume name. - @retval 0 Path is NOT absolute. - @retval 1 Path is absolute. -*/ -static int -is_absolute(char *path) -{ - char *A; - char *B; - - A = strchr(path, ':'); - B = strpbrk(path, "/\\"); - - if(B != NULL) { - if(A == NULL) { - if(B == path) { - return -1; - } - } - else { - if(((A - path) + 1) == (B - path)) { - return 1; - } - } - } - return 0; -} - - -/** Add a path component, by appending stuff to buffer. - buffer must have at least MAXPATHLEN + 1 bytes allocated, and contain a - NUL-terminated string with no more than MAXPATHLEN characters (not counting - the trailing NUL). It's a fatal error if it contains a string longer than - that (callers must be careful!). If these requirements are met, it's - guaranteed that buffer will still be a NUL-terminated string with no more - than MAXPATHLEN characters at exit. If stuff is too long, only as much of - stuff as fits will be appended. - - @param[in,out] buffer The path to be extended. - @param[in] stuff The stuff to join onto the path. -*/ -static void -joinpath(char *buffer, char *stuff) -{ - size_t n, k; - - k = 0; - if (is_absolute(stuff) == 1) { - n = 0; - } - else { - n = strlen(buffer); - if(n == 0) { - strncpy(buffer, volume_name, MAXPATHLEN); - n = strlen(buffer); - } - /* We must not use an else clause here because we want to test n again. - volume_name may have been empty. - */ - if (n > 0 && n < MAXPATHLEN) { - if(!is_sep(buffer[n-1])) { - buffer[n++] = SEP; - } - if(is_sep(stuff[0])) ++stuff; - } - } - if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpath.c's joinpath()"); - k = strlen(stuff); - if (n + k > MAXPATHLEN) - k = MAXPATHLEN - n; - strncpy(buffer+n, stuff, k); - buffer[n+k] = '\0'; -} - -/** Is filename an executable file? - - An executable file: - 1) exists - 2) is a file, not a directory - 3) has a name ending with ".efi" - 4) Only has a single '.' in the name. - - If basename(filename) does not contain a '.', append ".efi" to filename - If filename ends in ".efi", it is executable, else it isn't. - - This routine is used to when searching for the file named by argv[0]. - As such, there is no need to search for extensions other than ".efi". - - @param[in] filename The name of the file to test. It may, or may not, have an extension. - - @retval 0 filename already has a path other than ".efi", or it doesn't exist, or is a directory. - @retval 1 filename refers to an executable file. -**/ -static int -isxfile(char *filename) -{ - struct stat buf; - char *bn; - char *newbn; - int bnlen; - - bn = basename(filename); // Separate off the file name component - reduce(filename); // and isolate the path component - bnlen = strlen(bn); - newbn = strrchr(bn, '.'); // Does basename contain a period? - if(newbn == NULL) { // Does NOT contain a period. - newbn = &bn[bnlen]; - strncpyX(newbn, ".efi", MAXPATHLEN - bnlen); // append ".efi" to basename - bnlen += 4; - } - else if(strcmp(newbn, ".efi") != 0) { - return 0; // File can not be executable. - } - joinpath(filename, bn); // Stitch path and file name back together - - if (stat(filename, &buf) != 0) { // Now, verify that file exists - return 0; - } - if(S_ISDIR(buf.st_mode)) { // And it is not a directory. - return 0; - } - - return 1; -} - -/** Copy p into path, ensuring that the result is an absolute path. - - copy_absolute requires that path be allocated at least - MAXPATHLEN + 1 bytes and that p be no more than MAXPATHLEN bytes. - - @param[out] path Destination to receive the absolute path. - @param[in] p Path to be tested and possibly converted. -**/ -static void -copy_absolute(char *path, char *p) -{ - if (is_absolute(p) == 1) - strcpy(path, p); - else { - if (!getcwd(path, MAXPATHLEN)) { - /* unable to get the current directory */ - if(volume_name[0] != 0) { - strcpy(path, volume_name); - joinpath(path, p); - } - else - strcpy(path, p); - return; - } - if (p[0] == '.' && is_sep(p[1])) - p += 2; - joinpath(path, p); - } -} - -/** Modify path so that the result is an absolute path. - absolutize() requires that path be allocated at least MAXPATHLEN+1 bytes. - - @param[in,out] path The path to be made absolute. -*/ -static void -absolutize(char *path) -{ - char buffer[MAXPATHLEN + 1]; - - if (is_absolute(path) == 1) - return; - copy_absolute(buffer, path); - strcpy(path, buffer); -} - -/** Extract the volume name from a path. - - @param[out] Dest Pointer to location in which to store the extracted volume name. - @param[in] path Pointer to the path to extract the volume name from. -**/ -static void -set_volume(char *Dest, char *path) -{ - size_t VolLen; - - if(is_absolute(path)) { - VolLen = strcspn(path, "/\\:"); - if((VolLen != 0) && (path[VolLen] == ':')) { - (void) strncpyX(Dest, path, VolLen + 1); - } - } -} - - -/** Determine paths. - - Two directories must be found, the platform independent directory - (prefix), containing the common .py and .pyc files, and the platform - dependent directory (exec_prefix), containing the shared library - modules. Note that prefix and exec_prefix are the same directory - for UEFI installations. - - Separate searches are carried out for prefix and exec_prefix. - Each search tries a number of different locations until a ``landmark'' - file or directory is found. If no prefix or exec_prefix is found, a - warning message is issued and the preprocessor defined PREFIX and - EXEC_PREFIX are used (even though they may not work); python carries on - as best as is possible, but some imports may fail. - - Before any searches are done, the location of the executable is - determined. If argv[0] has one or more slashes in it, it is used - unchanged. Otherwise, it must have been invoked from the shell's path, - so we search %PATH% for the named executable and use that. If the - executable was not found on %PATH% (or there was no %PATH% environment - variable), the original argv[0] string is used. - - Finally, argv0_path is set to the directory containing the executable - (i.e. the last component is stripped). - - With argv0_path in hand, we perform a number of steps. The same steps - are performed for prefix and for exec_prefix, but with a different - landmark. - - The prefix landmark will always be lib/python.VERSION/os.py and the - exec_prefix will always be lib/python.VERSION/dynaload, where VERSION - is Python's version number as defined at the beginning of this file. - - First. See if the %PYTHONHOME% environment variable points to the - installed location of the Python libraries. If %PYTHONHOME% is set, then - it points to prefix and exec_prefix. %PYTHONHOME% can be a single - directory, which is used for both, or the prefix and exec_prefix - directories separated by the DELIM character. - - Next. Search the directories pointed to by the preprocessor variables - PREFIX and EXEC_PREFIX. These paths are prefixed with the volume name - extracted from argv0_path. The volume names correspond to the UEFI - shell "map" names. - - That's it! - - Well, almost. Once we have determined prefix and exec_prefix, the - preprocessor variable PYTHONPATH is used to construct a path. Each - relative path on PYTHONPATH is prefixed with prefix. Then the directory - containing the shared library modules is appended. The environment - variable $PYTHONPATH is inserted in front of it all. Finally, the - prefix and exec_prefix globals are tweaked so they reflect the values - expected by other code, by stripping the "lib/python$VERSION/..." stuff - off. This seems to make more sense given that currently the only - known use of sys.prefix and sys.exec_prefix is for the ILU installation - process to find the installed Python tree. - - The final, fully resolved, paths should look something like: - fs0:/Efi/Tools/python.efi - fs0:/Efi/StdLib/lib/python27 - fs0:/Efi/StdLib/lib/python27/dynaload - -**/ -static void -calculate_path(void) -{ - extern char *Py_GetProgramName(void); - - static char delimiter[2] = {DELIM, '\0'}; - static char separator[2] = {SEP, '\0'}; - char *pythonpath = PYTHONPATH; - char *rtpypath = Py_GETENV("PYTHONPATH"); - //char *home = Py_GetPythonHome(); - char *path = getenv("PATH"); - char *prog = Py_GetProgramName(); - char argv0_path[MAXPATHLEN+1]; - char zip_path[MAXPATHLEN+1]; - char *buf; - size_t bufsz; - size_t prefixsz; - char *defpath; - - -/* ########################################################################### - Determine path to the Python.efi binary. - Produces progpath, argv0_path, and volume_name. -########################################################################### */ - - /* If there is no slash in the argv0 path, then we have to - * assume python is on the user's $PATH, since there's no - * other way to find a directory to start the search from. If - * $PATH isn't exported, you lose. - */ - if (strchr(prog, SEP)) - strncpy(progpath, prog, MAXPATHLEN); - else if (path) { - while (1) { - char *delim = strchr(path, DELIM); - - if (delim) { - size_t len = delim - path; - if (len > MAXPATHLEN) - len = MAXPATHLEN; - strncpy(progpath, path, len); - *(progpath + len) = '\0'; - } - else - strncpy(progpath, path, MAXPATHLEN); - - joinpath(progpath, prog); - if (isxfile(progpath)) - break; - - if (!delim) { - progpath[0] = '\0'; - break; - } - path = delim + 1; - } - } - else - progpath[0] = '\0'; - if ( (!is_absolute(progpath)) && (progpath[0] != '\0') ) - absolutize(progpath); - strncpy(argv0_path, progpath, MAXPATHLEN); - argv0_path[MAXPATHLEN] = '\0'; - set_volume(volume_name, argv0_path); - - reduce(argv0_path); - /* At this point, argv0_path is guaranteed to be less than - MAXPATHLEN bytes long. - */ - -/* ########################################################################### - Build the FULL prefix string, including volume name. - This is the full path to the platform independent libraries. -########################################################################### */ - - strncpy(prefix, volume_name, MAXPATHLEN); - joinpath(prefix, PREFIX); - joinpath(prefix, lib_python); - -/* ########################################################################### - Build the FULL path to the zipped-up Python library. -########################################################################### */ - - strncpy(zip_path, prefix, MAXPATHLEN); - zip_path[MAXPATHLEN] = '\0'; - reduce(zip_path); - joinpath(zip_path, "python00.zip"); - bufsz = strlen(zip_path); /* Replace "00" with version */ - zip_path[bufsz - 6] = VERSION[0]; - zip_path[bufsz - 5] = VERSION[1]; - -/* ########################################################################### - Build the FULL path to dynamically loadable libraries. -########################################################################### */ - - strncpy(exec_prefix, volume_name, MAXPATHLEN); - joinpath(exec_prefix, EXEC_PREFIX); - joinpath(exec_prefix, lib_python); - joinpath(exec_prefix, "lib-dynload"); - -/* ########################################################################### - Build the module search path. -########################################################################### */ - - /* Reduce prefix and exec_prefix to their essence, - * e.g. /usr/local/lib/python1.5 is reduced to /usr/local. - * If we're loading relative to the build directory, - * return the compiled-in defaults instead. - */ - reduce(prefix); - reduce(prefix); - /* The prefix is the root directory, but reduce() chopped - * off the "/". */ - if (!prefix[0]) { - strcpy(prefix, volume_name); - } - bufsz = strlen(prefix); - if(prefix[bufsz-1] == ':') { - prefix[bufsz] = SEP; - prefix[bufsz+1] = 0; - } - - /* Calculate size of return buffer. - */ - defpath = pythonpath; - bufsz = 0; - - if (rtpypath) - bufsz += strlen(rtpypath) + 1; - - prefixsz = strlen(prefix) + 1; - - while (1) { - char *delim = strchr(defpath, DELIM); - - if (is_absolute(defpath) == 0) - /* Paths are relative to prefix */ - bufsz += prefixsz; - - if (delim) - bufsz += delim - defpath + 1; - else { - bufsz += strlen(defpath) + 1; - break; - } - defpath = delim + 1; - } - - bufsz += strlen(zip_path) + 1; - bufsz += strlen(exec_prefix) + 1; - - /* This is the only malloc call in this file */ - buf = (char *)PyMem_Malloc(bufsz); - - if (buf == NULL) { - /* We can't exit, so print a warning and limp along */ - fprintf(stderr, "Not enough memory for dynamic PYTHONPATH.\n"); - fprintf(stderr, "Using default static PYTHONPATH.\n"); - module_search_path = PYTHONPATH; - } - else { - /* Run-time value of $PYTHONPATH goes first */ - if (rtpypath) { - strcpy(buf, rtpypath); - strcat(buf, delimiter); - } - else - buf[0] = '\0'; - - /* Next is the default zip path */ - strcat(buf, zip_path); - strcat(buf, delimiter); - - /* Next goes merge of compile-time $PYTHONPATH with - * dynamically located prefix. - */ - defpath = pythonpath; - while (1) { - char *delim = strchr(defpath, DELIM); - - if (is_absolute(defpath) != 1) { - strcat(buf, prefix); - strcat(buf, separator); - } - - if (delim) { - size_t len = delim - defpath + 1; - size_t end = strlen(buf) + len; - strncat(buf, defpath, len); - *(buf + end) = '\0'; - } - else { - strcat(buf, defpath); - break; - } - defpath = delim + 1; - } - strcat(buf, delimiter); - - /* Finally, on goes the directory for dynamic-load modules */ - strcat(buf, exec_prefix); - - /* And publish the results */ - module_search_path = buf; - } - /* At this point, exec_prefix is set to VOL:/Efi/StdLib/lib/python.27/dynalib. - We want to get back to the root value, so we have to remove the final three - segments to get VOL:/Efi/StdLib. Because we don't know what VOL is, and - EXEC_PREFIX is also indeterminate, we just remove the three final segments. - */ - reduce(exec_prefix); - reduce(exec_prefix); - reduce(exec_prefix); - if (!exec_prefix[0]) { - strcpy(exec_prefix, volume_name); - } - bufsz = strlen(exec_prefix); - if(exec_prefix[bufsz-1] == ':') { - exec_prefix[bufsz] = SEP; - exec_prefix[bufsz+1] = 0; - } - if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: module_search_path = \"%s\"\n", __func__, __LINE__, module_search_path); - if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: prefix = \"%s\"\n", __func__, __LINE__, prefix); - if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: exec_prefix = \"%s\"\n", __func__, __LINE__, exec_prefix); - if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: progpath = \"%s\"\n", __func__, __LINE__, progpath); -} - - -/* External interface */ - -char * -Py_GetPath(void) -{ - if (!module_search_path) - calculate_path(); - return module_search_path; -} - -char * -Py_GetPrefix(void) -{ - if (!module_search_path) - calculate_path(); - return prefix; -} - -char * -Py_GetExecPrefix(void) -{ - if (!module_search_path) - calculate_path(); - return exec_prefix; -} - -char * -Py_GetProgramFullPath(void) -{ - if (!module_search_path) - calculate_path(); - return progpath; -} - - -#ifdef __cplusplus -} -#endif - diff --git a/AppPkg/Applications/Python/Ia32/pyconfig.h b/AppPkg/Applications/Python/Ia32/pyconfig.h deleted file mode 100644 index 2d73346..0000000 --- a/AppPkg/Applications/Python/Ia32/pyconfig.h +++ /dev/null @@ -1,1256 +0,0 @@ -/** @file - Manually generated Python Configuration file for EDK II. - - Copyright (c) 2011 - 2016, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent -**/ -#ifndef Py_PYCONFIG_H -#define Py_PYCONFIG_H - -#include - -#define PLATFORM "uefi" - -/* Define if building universal (internal helper macro) */ -#undef AC_APPLE_UNIVERSAL_BUILD - -/* Define for AIX if your compiler is a genuine IBM xlC/xlC_r and you want - support for AIX C++ shared extension modules. */ -#undef AIX_GENUINE_CPLUSPLUS - -/* Define this if you have AtheOS threads. */ -#undef ATHEOS_THREADS - -/* Define this if you have BeOS threads. */ -#undef BEOS_THREADS - -/* Define if you have the Mach cthreads package */ -#undef C_THREADS - -/* Define if C doubles are 64-bit IEEE 754 binary format, stored in ARM - mixed-endian order (byte order 45670123) */ -#undef DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754 - -/* Define if C doubles are 64-bit IEEE 754 binary format, stored with the most - significant byte first */ -#undef DOUBLE_IS_BIG_ENDIAN_IEEE754 - -/* Define if C doubles are 64-bit IEEE 754 binary format, stored with the - least significant byte first */ -#define DOUBLE_IS_LITTLE_ENDIAN_IEEE754 - -/* Define if --enable-ipv6 is specified */ -#undef ENABLE_IPV6 - -/* Define if flock needs to be linked with bsd library. */ -#undef FLOCK_NEEDS_LIBBSD - -/* Define if getpgrp() must be called as getpgrp(0). */ -#undef GETPGRP_HAVE_ARG - -/* Define if gettimeofday() does not have second (timezone) argument This is - the case on Motorola V4 (R40V4.2) */ -#undef GETTIMEOFDAY_NO_TZ - -/* Define to 1 if you have the 'acosh' function. */ -#undef HAVE_ACOSH - -/* struct addrinfo (netdb.h) */ -#undef HAVE_ADDRINFO - -/* Define to 1 if you have the 'alarm' function. */ -#undef HAVE_ALARM - -/* Define this if your time.h defines altzone. */ -#undef HAVE_ALTZONE - -/* Define to 1 if you have the 'asinh' function. */ -#undef HAVE_ASINH - -/* Define to 1 if you have the header file. */ -#undef HAVE_ASM_TYPES_H - -/* Define to 1 if you have the 'atanh' function. */ -#undef HAVE_ATANH - -/* Define if GCC supports __attribute__((format(PyArg_ParseTuple, 2, 3))) */ -#undef HAVE_ATTRIBUTE_FORMAT_PARSETUPLE - -/* Define to 1 if you have the 'bind_textdomain_codeset' function. */ -#undef HAVE_BIND_TEXTDOMAIN_CODESET - -/* Define to 1 if you have the header file. */ -#undef HAVE_BLUETOOTH_BLUETOOTH_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_BLUETOOTH_H - -/* Define if nice() returns success/failure instead of the new priority. */ -#undef HAVE_BROKEN_NICE - -/* Define if the system reports an invalid PIPE_BUF value. */ -#undef HAVE_BROKEN_PIPE_BUF - -/* Define if poll() sets errno on invalid file descriptors. */ -#undef HAVE_BROKEN_POLL - -/* Define if the Posix semaphores do not work on your system */ -#define HAVE_BROKEN_POSIX_SEMAPHORES 1 - -/* Define if pthread_sigmask() does not work on your system. */ -#define HAVE_BROKEN_PTHREAD_SIGMASK 1 - -/* define to 1 if your sem_getvalue is broken. */ -#define HAVE_BROKEN_SEM_GETVALUE 1 - -/* Define this if you have the type _Bool. */ -#define HAVE_C99_BOOL 1 - -/* Define to 1 if you have the 'chflags' function. */ -#undef HAVE_CHFLAGS - -/* Define to 1 if you have the 'chown' function. */ -#undef HAVE_CHOWN - -/* Define if you have the 'chroot' function. */ -#undef HAVE_CHROOT - -/* Define to 1 if you have the 'clock' function. */ -#define HAVE_CLOCK 1 - -/* Define to 1 if you have the 'confstr' function. */ -#undef HAVE_CONFSTR - -/* Define to 1 if you have the header file. */ -#undef HAVE_CONIO_H - -/* Define to 1 if you have the 'copysign' function. */ -#define HAVE_COPYSIGN 1 - -/* Define to 1 if you have the 'ctermid' function. */ -#undef HAVE_CTERMID - -/* Define if you have the 'ctermid_r' function. */ -#undef HAVE_CTERMID_R - -/* Define to 1 if you have the header file. */ -#undef HAVE_CURSES_H - -/* Define if you have the 'is_term_resized' function. */ -#undef HAVE_CURSES_IS_TERM_RESIZED - -/* Define if you have the 'resizeterm' function. */ -#undef HAVE_CURSES_RESIZETERM - -/* Define if you have the 'resize_term' function. */ -#undef HAVE_CURSES_RESIZE_TERM - -/* Define to 1 if you have the declaration of 'isfinite', and to 0 if you - don't. */ -#define HAVE_DECL_ISFINITE 0 - -/* Define to 1 if you have the declaration of 'isinf', and to 0 if you don't. - */ -#define HAVE_DECL_ISINF 1 - -/* Define to 1 if you have the declaration of 'isnan', and to 0 if you don't. - */ -#define HAVE_DECL_ISNAN 1 - -/* Define to 1 if you have the declaration of 'tzname', and to 0 if you don't. - */ -#define HAVE_DECL_TZNAME 0 - -/* Define to 1 if you have the device macros. */ -#undef HAVE_DEVICE_MACROS - -/* Define if we have /dev/ptc. */ -#undef HAVE_DEV_PTC - -/* Define if we have /dev/ptmx. */ -#undef HAVE_DEV_PTMX - -/* Define to 1 if you have the header file. */ -#undef HAVE_DIRECT_H - -/* Define to 1 if you have the header file, and it defines 'DIR'. - */ -#define HAVE_DIRENT_H 1 - -/* Define to 1 if you have the header file. */ -#undef HAVE_DLFCN_H - -/* Define to 1 if you have the 'dlopen' function. */ -#undef HAVE_DLOPEN - -/* Define to 1 if you have the 'dup2' function. */ -#define HAVE_DUP2 1 - -/* Defined when any dynamic module loading is enabled. */ -#undef HAVE_DYNAMIC_LOADING - -/* Define if you have the 'epoll' functions. */ -#undef HAVE_EPOLL - -/* Define to 1 if you have the 'erf' function. */ -#undef HAVE_ERF - -/* Define to 1 if you have the 'erfc' function. */ -#undef HAVE_ERFC - -/* Define to 1 if you have the header file. */ -#define HAVE_ERRNO_H 1 - -/* Define to 1 if you have the 'execv' function. */ -#undef HAVE_EXECV - -/* Define to 1 if you have the 'expm1' function. */ -#undef HAVE_EXPM1 - -/* Define if you have the 'fchdir' function. */ -#undef HAVE_FCHDIR - -/* Define to 1 if you have the 'fchmod' function. */ -#undef HAVE_FCHMOD - -/* Define to 1 if you have the 'fchown' function. */ -#undef HAVE_FCHOWN - -/* Define to 1 if you have the header file. */ -#define HAVE_FCNTL_H 1 - -/* Define if you have the 'fdatasync' function. */ -#undef HAVE_FDATASYNC - -/* Define to 1 if you have the 'finite' function. */ -#define HAVE_FINITE 1 - -/* Define to 1 if you have the 'flock' function. */ -#undef HAVE_FLOCK - -/* Define to 1 if you have the 'fork' function. */ -#undef HAVE_FORK - -/* Define to 1 if you have the 'forkpty' function. */ -#undef HAVE_FORKPTY - -/* Define to 1 if you have the 'fpathconf' function. */ -#undef HAVE_FPATHCONF - -/* Define to 1 if you have the 'fseek64' function. */ -#undef HAVE_FSEEK64 - -/* Define to 1 if you have the 'fseeko' function. */ -#define HAVE_FSEEKO 1 - -/* Define to 1 if you have the 'fstatvfs' function. */ -#undef HAVE_FSTATVFS - -/* Define if you have the 'fsync' function. */ -#undef HAVE_FSYNC - -/* Define to 1 if you have the 'ftell64' function. */ -#undef HAVE_FTELL64 - -/* Define to 1 if you have the 'ftello' function. */ -#define HAVE_FTELLO 1 - -/* Define to 1 if you have the 'ftime' function. */ -#undef HAVE_FTIME - -/* Define to 1 if you have the 'ftruncate' function. */ -#undef HAVE_FTRUNCATE - -/* Define to 1 if you have the 'gai_strerror' function. */ -#undef HAVE_GAI_STRERROR - -/* Define to 1 if you have the 'gamma' function. */ -#undef HAVE_GAMMA - -/* Define if we can use gcc inline assembler to get and set x87 control word -*/ -#if defined(__GNUC__) - #define HAVE_GCC_ASM_FOR_X87 1 -#else - #undef HAVE_GCC_ASM_FOR_X87 -#endif - -/* Define if you have the getaddrinfo function. */ -#undef HAVE_GETADDRINFO - -/* Define to 1 if you have the 'getcwd' function. */ -#define HAVE_GETCWD 1 - -/* Define this if you have flockfile(), getc_unlocked(), and funlockfile() */ -#undef HAVE_GETC_UNLOCKED - -/* Define to 1 if you have the 'getgroups' function. */ -#undef HAVE_GETGROUPS - -/* Define to 1 if you have the 'gethostbyname' function. */ -#undef HAVE_GETHOSTBYNAME - -/* Define this if you have some version of gethostbyname_r() */ -#undef HAVE_GETHOSTBYNAME_R - -/* Define this if you have the 3-arg version of gethostbyname_r(). */ -#undef HAVE_GETHOSTBYNAME_R_3_ARG - -/* Define this if you have the 5-arg version of gethostbyname_r(). */ -#undef HAVE_GETHOSTBYNAME_R_5_ARG - -/* Define this if you have the 6-arg version of gethostbyname_r(). */ -#undef HAVE_GETHOSTBYNAME_R_6_ARG - -/* Define to 1 if you have the 'getitimer' function. */ -#undef HAVE_GETITIMER - -/* Define to 1 if you have the 'getloadavg' function. */ -#undef HAVE_GETLOADAVG - -/* Define to 1 if you have the 'getlogin' function. */ -#undef HAVE_GETLOGIN - -/* Define to 1 if you have the 'getnameinfo' function. */ -#undef HAVE_GETNAMEINFO - -/* Define if you have the 'getpagesize' function. */ -#undef HAVE_GETPAGESIZE - -/* Define to 1 if you have the 'getpeername' function. */ -#define HAVE_GETPEERNAME 1 - -/* Define to 1 if you have the 'getpgid' function. */ -#undef HAVE_GETPGID - -/* Define to 1 if you have the 'getpgrp' function. */ -#undef HAVE_GETPGRP - -/* Define to 1 if you have the 'getpid' function. */ -#undef HAVE_GETPID - -/* Define to 1 if you have the 'getpriority' function. */ -#undef HAVE_GETPRIORITY - -/* Define to 1 if you have the 'getpwent' function. */ -#undef HAVE_GETPWENT - -/* Define to 1 if you have the 'getresgid' function. */ -#undef HAVE_GETRESGID - -/* Define to 1 if you have the 'getresuid' function. */ -#undef HAVE_GETRESUID - -/* Define to 1 if you have the 'getsid' function. */ -#undef HAVE_GETSID - -/* Define to 1 if you have the 'getspent' function. */ -#undef HAVE_GETSPENT - -/* Define to 1 if you have the 'getspnam' function. */ -#undef HAVE_GETSPNAM - -/* Define to 1 if you have the 'gettimeofday' function. */ -#undef HAVE_GETTIMEOFDAY - -/* Define to 1 if you have the 'getwd' function. */ -#undef HAVE_GETWD - -/* Define to 1 if you have the header file. */ -#undef HAVE_GRP_H - -/* Define if you have the 'hstrerror' function. */ -#undef HAVE_HSTRERROR - -/* Define to 1 if you have the 'hypot' function. */ -#undef HAVE_HYPOT - -/* Define to 1 if you have the header file. */ -#undef HAVE_IEEEFP_H - -/* Define if you have the 'inet_aton' function. */ -#define HAVE_INET_ATON 1 - -/* Define if you have the 'inet_pton' function. */ -#define HAVE_INET_PTON 1 - -/* Define to 1 if you have the 'initgroups' function. */ -#undef HAVE_INITGROUPS - -/* Define to 1 if you have the header file. */ -#define HAVE_INTTYPES_H 1 - -/* Define to 1 if you have the header file. */ -#undef HAVE_IO_H - -/* Define to 1 if you have the 'kill' function. */ -#undef HAVE_KILL - -/* Define to 1 if you have the 'killpg' function. */ -#undef HAVE_KILLPG - -/* Define if you have the 'kqueue' functions. */ -#undef HAVE_KQUEUE - -/* Define to 1 if you have the header file. */ -#undef HAVE_LANGINFO_H /* non-functional in EFI. */ - -/* Defined to enable large file support when an off_t is bigger than a long - and long long is available and at least as big as an off_t. You may need to - add some flags for configuration and compilation to enable this mode. (For - Solaris and Linux, the necessary defines are already defined.) */ -#undef HAVE_LARGEFILE_SUPPORT - -/* Define to 1 if you have the 'lchflags' function. */ -#undef HAVE_LCHFLAGS - -/* Define to 1 if you have the 'lchmod' function. */ -#undef HAVE_LCHMOD - -/* Define to 1 if you have the 'lchown' function. */ -#undef HAVE_LCHOWN - -/* Define to 1 if you have the 'lgamma' function. */ -#undef HAVE_LGAMMA - -/* Define to 1 if you have the 'dl' library (-ldl). */ -#undef HAVE_LIBDL - -/* Define to 1 if you have the 'dld' library (-ldld). */ -#undef HAVE_LIBDLD - -/* Define to 1 if you have the 'ieee' library (-lieee). */ -#undef HAVE_LIBIEEE - -/* Define to 1 if you have the header file. */ -#undef HAVE_LIBINTL_H - -/* Define if you have the readline library (-lreadline). */ -#undef HAVE_LIBREADLINE - -/* Define to 1 if you have the 'resolv' library (-lresolv). */ -#undef HAVE_LIBRESOLV - -/* Define to 1 if you have the header file. */ -#undef HAVE_LIBUTIL_H - -/* Define if you have the 'link' function. */ -#undef HAVE_LINK - -/* Define to 1 if you have the header file. */ -#undef HAVE_LINUX_NETLINK_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_LINUX_TIPC_H - -/* Define to 1 if you have the 'log1p' function. */ -#undef HAVE_LOG1P - -/* Define this if you have the type long double. */ -#undef HAVE_LONG_DOUBLE - -/* Define this if you have the type long long. */ -#define HAVE_LONG_LONG 1 - -/* Define to 1 if you have the 'lstat' function. */ -#define HAVE_LSTAT 1 - -/* Define this if you have the makedev macro. */ -#undef HAVE_MAKEDEV - -/* Define to 1 if you have the 'memmove' function. */ -#define HAVE_MEMMOVE 1 - -/* Define to 1 if you have the header file. */ -#undef HAVE_MEMORY_H - -/* Define to 1 if you have the 'mkfifo' function. */ -#undef HAVE_MKFIFO - -/* Define to 1 if you have the 'mknod' function. */ -#undef HAVE_MKNOD - -/* Define to 1 if you have the 'mktime' function. */ -#define HAVE_MKTIME 1 - -/* Define to 1 if you have the 'mremap' function. */ -#undef HAVE_MREMAP - -/* Define to 1 if you have the header file. */ -#undef HAVE_NCURSES_H - -/* Define to 1 if you have the header file, and it defines 'DIR'. */ -#undef HAVE_NDIR_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_NETPACKET_PACKET_H - -/* Define to 1 if you have the 'nice' function. */ -#undef HAVE_NICE - -/* Define to 1 if you have the 'openpty' function. */ -#undef HAVE_OPENPTY - -/* Define if compiling using MacOS X 10.5 SDK or later. */ -#undef HAVE_OSX105_SDK - -/* Define to 1 if you have the 'pathconf' function. */ -#undef HAVE_PATHCONF - -/* Define to 1 if you have the 'pause' function. */ -#undef HAVE_PAUSE - -/* Define to 1 if you have the 'plock' function. */ -#undef HAVE_PLOCK - -/* Define to 1 if you have the 'poll' function. */ -#define HAVE_POLL 1 - -/* Define to 1 if you have the header file. */ -#undef HAVE_POLL_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_PROCESS_H - -/* Define if your compiler supports function prototype */ -#define HAVE_PROTOTYPES 1 - -/* Define if you have GNU PTH threads. */ -#undef HAVE_PTH - -/* Defined for Solaris 2.6 bug in pthread header. */ -#undef HAVE_PTHREAD_DESTRUCTOR - -/* Define to 1 if you have the header file. */ -#undef HAVE_PTHREAD_H - -/* Define to 1 if you have the 'pthread_init' function. */ -#undef HAVE_PTHREAD_INIT - -/* Define to 1 if you have the 'pthread_sigmask' function. */ -#undef HAVE_PTHREAD_SIGMASK - -/* Define to 1 if you have the header file. */ -#undef HAVE_PTY_H - -/* Define to 1 if you have the 'putenv' function. */ -#undef HAVE_PUTENV - -/* Define to 1 if you have the 'readlink' function. */ -#undef HAVE_READLINK - -/* Define to 1 if you have the 'realpath' function. */ -#define HAVE_REALPATH 1 - -/* Define if you have readline 2.1 */ -#undef HAVE_RL_CALLBACK - -/* Define if you can turn off readline's signal handling. */ -#undef HAVE_RL_CATCH_SIGNAL - -/* Define if you have readline 2.2 */ -#undef HAVE_RL_COMPLETION_APPEND_CHARACTER - -/* Define if you have readline 4.0 */ -#undef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK - -/* Define if you have readline 4.2 */ -#undef HAVE_RL_COMPLETION_MATCHES - -/* Define if you have rl_completion_suppress_append */ -#undef HAVE_RL_COMPLETION_SUPPRESS_APPEND - -/* Define if you have readline 4.0 */ -#undef HAVE_RL_PRE_INPUT_HOOK - -/* Define to 1 if you have the 'round' function. */ -#undef HAVE_ROUND - -/* Define to 1 if you have the 'select' function. */ -#define HAVE_SELECT 1 - -/* Define to 1 if you have the 'sem_getvalue' function. */ -#undef HAVE_SEM_GETVALUE - -/* Define to 1 if you have the 'sem_open' function. */ -#undef HAVE_SEM_OPEN - -/* Define to 1 if you have the 'sem_timedwait' function. */ -#undef HAVE_SEM_TIMEDWAIT - -/* Define to 1 if you have the 'sem_unlink' function. */ -#undef HAVE_SEM_UNLINK - -/* Define to 1 if you have the 'setegid' function. */ -#undef HAVE_SETEGID - -/* Define to 1 if you have the 'seteuid' function. */ -#undef HAVE_SETEUID - -/* Define to 1 if you have the 'setgid' function. */ -#undef HAVE_SETGID - -/* Define if you have the 'setgroups' function. */ -#undef HAVE_SETGROUPS - -/* Define to 1 if you have the 'setitimer' function. */ -#undef HAVE_SETITIMER - -/* Define to 1 if you have the 'setlocale' function. */ -#define HAVE_SETLOCALE 1 - -/* Define to 1 if you have the 'setpgid' function. */ -#undef HAVE_SETPGID - -/* Define to 1 if you have the 'setpgrp' function. */ -#undef HAVE_SETPGRP - -/* Define to 1 if you have the 'setregid' function. */ -#undef HAVE_SETREGID - -/* Define to 1 if you have the 'setresgid' function. */ -#undef HAVE_SETRESGID - -/* Define to 1 if you have the 'setresuid' function. */ -#undef HAVE_SETRESUID - -/* Define to 1 if you have the 'setreuid' function. */ -#undef HAVE_SETREUID - -/* Define to 1 if you have the 'setsid' function. */ -#undef HAVE_SETSID - -/* Define to 1 if you have the 'setuid' function. */ -#undef HAVE_SETUID - -/* Define to 1 if you have the 'setvbuf' function. */ -#define HAVE_SETVBUF 1 - -/* Define to 1 if you have the header file. */ -#undef HAVE_SHADOW_H - -/* Define to 1 if you have the 'sigaction' function. */ -#undef HAVE_SIGACTION - -/* Define to 1 if you have the 'siginterrupt' function. */ -#undef HAVE_SIGINTERRUPT - -/* Define to 1 if you have the header file. */ -#define HAVE_SIGNAL_H 1 - -/* Define to 1 if you have the 'sigrelse' function. */ -#undef HAVE_SIGRELSE - -/* Define to 1 if you have the 'snprintf' function. */ -#define HAVE_SNPRINTF 1 - -/* Define if sockaddr has sa_len member */ -#undef HAVE_SOCKADDR_SA_LEN - -/* struct sockaddr_storage (sys/socket.h) */ -#undef HAVE_SOCKADDR_STORAGE - -/* Define if you have the 'socketpair' function. */ -#undef HAVE_SOCKETPAIR - -/* Define to 1 if you have the header file. */ -#undef HAVE_SPAWN_H - -/* Define if your compiler provides ssize_t */ -#define HAVE_SSIZE_T 1 - -/* Define to 1 if you have the 'statvfs' function. */ -#undef HAVE_STATVFS - -/* Define if you have struct stat.st_mtim.tv_nsec */ -#undef HAVE_STAT_TV_NSEC - -/* Define if you have struct stat.st_mtimensec */ -#undef HAVE_STAT_TV_NSEC2 - -/* Define if your compiler supports variable length function prototypes (e.g. - void fprintf(FILE *, char *, ...);) *and* */ -#define HAVE_STDARG_PROTOTYPES 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDINT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDLIB_H 1 - -/* Define to 1 if you have the 'strdup' function. */ -#define HAVE_STRDUP 1 - -/* Define to 1 if you have the 'strftime' function. */ -#define HAVE_STRFTIME 1 - -/* Define to 1 if you have the header file. */ -#undef HAVE_STRINGS_H - -/* Define to 1 if you have the header file. */ -#define HAVE_STRING_H 1 - -/* Define to 1 if you have the header file. */ -#undef HAVE_STROPTS_H - -/* Define to 1 if 'st_birthtime' is a member of 'struct stat'. */ -#define HAVE_STRUCT_STAT_ST_BIRTHTIME 1 - -/* Define to 1 if 'st_blksize' is a member of 'struct stat'. */ -#define HAVE_STRUCT_STAT_ST_BLKSIZE 1 - -/* Define to 1 if 'st_blocks' is a member of 'struct stat'. */ -#undef HAVE_STRUCT_STAT_ST_BLOCKS - -/* Define to 1 if 'st_flags' is a member of 'struct stat'. */ -#undef HAVE_STRUCT_STAT_ST_FLAGS - -/* Define to 1 if 'st_gen' is a member of 'struct stat'. */ -#undef HAVE_STRUCT_STAT_ST_GEN - -/* Define to 1 if 'st_rdev' is a member of 'struct stat'. */ -#undef HAVE_STRUCT_STAT_ST_RDEV - -/* Define to 1 if 'tm_zone' is a member of 'struct tm'. */ -#undef HAVE_STRUCT_TM_TM_ZONE - -/* Define to 1 if your 'struct stat' has 'st_blocks'. Deprecated, use - 'HAVE_STRUCT_STAT_ST_BLOCKS' instead. */ -#undef HAVE_ST_BLOCKS - -/* Define if you have the 'symlink' function. */ -#undef HAVE_SYMLINK - -/* Define to 1 if you have the 'sysconf' function. */ -#undef HAVE_SYSCONF - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYSEXITS_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_AUDIOIO_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_BSDTTY_H - -/* Define to 1 if you have the header file, and it defines 'DIR'. - */ -#undef HAVE_SYS_DIR_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_EPOLL_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_EVENT_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_FILE_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_LOADAVG_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_LOCK_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_MKDEV_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_MODEM_H - -/* Define to 1 if you have the header file, and it defines 'DIR'. - */ -#undef HAVE_SYS_NDIR_H - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_PARAM_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_POLL_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_RESOURCE_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_SELECT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_SOCKET_H 1 - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_STATVFS_H - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_STAT_H 1 - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_TERMIO_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_TIMES_H - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_TIME_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_TYPES_H 1 - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_UN_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_UTSNAME_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_WAIT_H - -/* Define to 1 if you have the system() command. */ -#define HAVE_SYSTEM 1 - -/* Define to 1 if you have the 'tcgetpgrp' function. */ -#undef HAVE_TCGETPGRP - -/* Define to 1 if you have the 'tcsetpgrp' function. */ -#undef HAVE_TCSETPGRP - -/* Define to 1 if you have the 'tempnam' function. */ -#define HAVE_TEMPNAM 1 - -/* Define to 1 if you have the header file. */ -#undef HAVE_TERMIOS_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_TERM_H - -/* Define to 1 if you have the 'tgamma' function. */ -#undef HAVE_TGAMMA - -/* Define to 1 if you have the header file. */ -#undef HAVE_THREAD_H - -/* Define to 1 if you have the 'timegm' function. */ -#undef HAVE_TIMEGM - -/* Define to 1 if you have the 'times' function. */ -#undef HAVE_TIMES - -/* Define to 1 if you have the 'tmpfile' function. */ -#define HAVE_TMPFILE 1 - -/* Define to 1 if you have the 'tmpnam' function. */ -#define HAVE_TMPNAM 1 - -/* Define to 1 if you have the 'tmpnam_r' function. */ -#undef HAVE_TMPNAM_R - -/* Define to 1 if your 'struct tm' has 'tm_zone'. Deprecated, use - 'HAVE_STRUCT_TM_TM_ZONE' instead. */ -#undef HAVE_TM_ZONE - -/* Define to 1 if you have the 'truncate' function. */ -#undef HAVE_TRUNCATE - -/* Define to 1 if you don't have 'tm_zone' but do have the external array - 'tzname'. */ -#undef HAVE_TZNAME - -/* Define this if you have tcl and TCL_UTF_MAX==6 */ -#undef HAVE_UCS4_TCL - -/* Define to 1 if the system has the type 'uintptr_t'. */ -#define HAVE_UINTPTR_T 1 - -/* Define to 1 if you have the 'uname' function. */ -#undef HAVE_UNAME - -/* Define to 1 if you have the header file. */ -#define HAVE_UNISTD_H 1 - -/* Define to 1 if you have the 'unsetenv' function. */ -#undef HAVE_UNSETENV - -/* Define if you have a useable wchar_t type defined in wchar.h; useable means - wchar_t must be an unsigned type with at least 16 bits. (see - Include/unicodeobject.h). */ -#define HAVE_USABLE_WCHAR_T 1 - -/* Define to 1 if you have the header file. */ -#undef HAVE_UTIL_H - -/* Define to 1 if you have the 'utimes' function. */ -#undef HAVE_UTIMES - -/* Define to 1 if you have the header file. */ -#define HAVE_UTIME_H 1 - -/* Define to 1 if you have the 'wait3' function. */ -#undef HAVE_WAIT3 - -/* Define to 1 if you have the 'wait4' function. */ -#undef HAVE_WAIT4 - -/* Define to 1 if you have the 'waitpid' function. */ -#undef HAVE_WAITPID - -/* Define if the compiler provides a wchar.h header file. */ -#define HAVE_WCHAR_H 1 - -/* Define to 1 if you have the 'wcscoll' function. */ -#define HAVE_WCSCOLL 1 - -/* Define if tzset() actually switches the local timezone in a meaningful way. - */ -#undef HAVE_WORKING_TZSET - -/* Define if the zlib library has inflateCopy */ -#undef HAVE_ZLIB_COPY - -/* Define to 1 if you have the '_getpty' function. */ -#undef HAVE__GETPTY - -/* Define if you are using Mach cthreads directly under /include */ -#undef HURD_C_THREADS - -/* Define if you are using Mach cthreads under mach / */ -#undef MACH_C_THREADS - -/* Define to 1 if 'major', 'minor', and 'makedev' are declared in . - */ -#undef MAJOR_IN_MKDEV - -/* Define to 1 if 'major', 'minor', and 'makedev' are declared in - . */ -#undef MAJOR_IN_SYSMACROS - -/* Define if mvwdelch in curses.h is an expression. */ -#undef MVWDELCH_IS_EXPRESSION - -/* Define to the address where bug reports for this package should be sent. */ -#define PACKAGE_BUGREPORT "edk2-devel@lists.01.org" - -/* Define to the full name of this package. */ -#define PACKAGE_NAME "EDK II Python Package" - -/* Define to the full name and version of this package. */ -#define PACKAGE_STRING "EDK II Python Package V0.8" - -/* Define to the one symbol short name of this package. */ -#define PACKAGE_TARNAME "EADK_Python" - -/* Define to the home page for this package. */ -#define PACKAGE_URL "https://github.com/tianocore/edk2/tree/master/AppPkg/Applications/Python" - -/* Define to the version of this package. */ -#define PACKAGE_VERSION "V0.8" - -/* Define if POSIX semaphores aren't enabled on your system */ -#define POSIX_SEMAPHORES_NOT_ENABLED 1 - -/* Defined if PTHREAD_SCOPE_SYSTEM supported. */ -#undef PTHREAD_SYSTEM_SCHED_SUPPORTED - -/* Define as the preferred size in bits of long digits */ -#undef PYLONG_BITS_IN_DIGIT - -/* Define to printf format modifier for long long type */ -#define PY_FORMAT_LONG_LONG "ll" - -/* Define to printf format modifier for Py_ssize_t */ -#define PY_FORMAT_SIZE_T "z" - -/* Define as the integral type used for Unicode representation. */ -#define PY_UNICODE_TYPE wchar_t - -/* Define if you want to build an interpreter with many run-time checks. */ -#undef Py_DEBUG - -/* Defined if Python is built as a shared library. */ -#undef Py_ENABLE_SHARED - -/* Define as the size of the unicode type. */ -#define Py_UNICODE_SIZE 2 - -/* Define if you want to have a Unicode type. */ -#define Py_USING_UNICODE - -/* assume C89 semantics that RETSIGTYPE is always void */ -#undef RETSIGTYPE - -/* Define if setpgrp() must be called as setpgrp(0, 0). */ -#undef SETPGRP_HAVE_ARG - -/* Define this to be extension of shared libraries (including the dot!). */ -#undef SHLIB_EXT - -/* Define if i>>j for signed int i does not extend the sign bit when i < 0 */ -#undef SIGNED_RIGHT_SHIFT_ZERO_FILLS - -/* The size of 'double', as computed by sizeof. */ -#define SIZEOF_DOUBLE 8 - -/* The size of 'float', as computed by sizeof. */ -#define SIZEOF_FLOAT 4 - -/* The size of 'fpos_t', as computed by sizeof. */ -#define SIZEOF_FPOS_T 8 - -/* The size of 'int', as computed by sizeof. */ -#define SIZEOF_INT 4 - -/* The size of 'long', as computed by sizeof. */ -#define SIZEOF_LONG 4 - -/* The size of 'long double', as computed by sizeof. */ -#undef SIZEOF_LONG_DOUBLE - -/* The size of 'long long', as computed by sizeof. */ -#define SIZEOF_LONG_LONG 8 - -/* The size of 'off_t', as computed by sizeof. */ -#define SIZEOF_OFF_T 4 - -/* The size of 'pid_t', as computed by sizeof. */ -#define SIZEOF_PID_T 4 - -/* The size of 'pthread_t', as computed by sizeof. */ -#undef SIZEOF_PTHREAD_T - -/* The size of 'short', as computed by sizeof. */ -#define SIZEOF_SHORT 2 - -/* The size of 'size_t', as computed by sizeof. */ -#define SIZEOF_SIZE_T 4 - -/* The size of 'time_t', as computed by sizeof. */ -#define SIZEOF_TIME_T 4 - -/* The size of 'uintptr_t', as computed by sizeof. */ -#define SIZEOF_UINTPTR_T 4 - -/* The size of 'void *', as computed by sizeof. */ -#define SIZEOF_VOID_P 4 - -/* The size of 'wchar_t', as computed by sizeof. */ -#define SIZEOF_WCHAR_T 2 - -/* The size of '_Bool', as computed by sizeof. */ -#define SIZEOF__BOOL 1 - -/* Define to 1 if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define if you can safely include both and - (which you can't on SCO ODT 3.0). */ -#undef SYS_SELECT_WITH_SYS_TIME - -/* Define if tanh(-0.) is -0., or if platform doesn't have signed zeros */ -#undef TANH_PRESERVES_ZERO_SIGN - -/* Define to 1 if you can safely include both and . */ -#undef TIME_WITH_SYS_TIME - -/* Define to 1 if your declares 'struct tm'. */ -#undef TM_IN_SYS_TIME - -/* Enable extensions on AIX 3, Interix. */ -#ifndef _ALL_SOURCE -# undef _ALL_SOURCE -#endif -/* Enable GNU extensions on systems that have them. */ -#ifndef _GNU_SOURCE -# undef _GNU_SOURCE -#endif -/* Enable threading extensions on Solaris. */ -#ifndef _POSIX_PTHREAD_SEMANTICS -# undef _POSIX_PTHREAD_SEMANTICS -#endif -/* Enable extensions on HP NonStop. */ -#ifndef _TANDEM_SOURCE -# undef _TANDEM_SOURCE -#endif -/* Enable general extensions on Solaris. */ -#ifndef __EXTENSIONS__ -# undef __EXTENSIONS__ -#endif - - -/* Define if you want to use MacPython modules on MacOSX in unix-Python. */ -#undef USE_TOOLBOX_OBJECT_GLUE - -/* Define if a va_list is an array of some kind */ -#undef VA_LIST_IS_ARRAY - -/* Define if you want SIGFPE handled (see Include/pyfpe.h). */ -#undef WANT_SIGFPE_HANDLER - -/* Define if you want wctype.h functions to be used instead of the one - supplied by Python itself. (see Include/unicodectype.h). */ -#define WANT_WCTYPE_FUNCTIONS 1 - -/* Define if WINDOW in curses.h offers a field _flags. */ -#undef WINDOW_HAS_FLAGS - -/* Define if you want documentation strings in extension modules */ -#undef WITH_DOC_STRINGS - -/* Define if you want to use the new-style (Openstep, Rhapsody, MacOS) dynamic - linker (dyld) instead of the old-style (NextStep) dynamic linker (rld). - Dyld is necessary to support frameworks. */ -#undef WITH_DYLD - -/* Define to 1 if libintl is needed for locale functions. */ -#undef WITH_LIBINTL - -/* Define if you want to produce an OpenStep/Rhapsody framework (shared - library plus accessory files). */ -#undef WITH_NEXT_FRAMEWORK - -/* Define if you want to compile in Python-specific mallocs */ -#undef WITH_PYMALLOC - -/* Define if you want to compile in rudimentary thread support */ -#undef WITH_THREAD - -/* Define to profile with the Pentium timestamp counter */ -#undef WITH_TSC - -/* Define if you want pymalloc to be disabled when running under valgrind */ -#undef WITH_VALGRIND - -/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most - significant byte first (like Motorola and SPARC, unlike Intel). */ -#if defined AC_APPLE_UNIVERSAL_BUILD -# if defined __BIG_ENDIAN__ -# define WORDS_BIGENDIAN 1 -# endif -#else -# ifndef WORDS_BIGENDIAN -# undef WORDS_BIGENDIAN -# endif -#endif - -/* Define if arithmetic is subject to x87-style double rounding issue */ -#undef X87_DOUBLE_ROUNDING - -/* Define on OpenBSD to activate all library features */ -#undef _BSD_SOURCE - -/* Define on Irix to enable u_int */ -#undef _BSD_TYPES - -/* Define on Darwin to activate all library features */ -#undef _DARWIN_C_SOURCE - -/* This must be set to 64 on some systems to enable large file support. */ -#undef _FILE_OFFSET_BITS - -/* Define on Linux to activate all library features */ -#undef _GNU_SOURCE - -/* This must be defined on some systems to enable large file support. */ -#undef _LARGEFILE_SOURCE - -/* Define to 1 if on MINIX. */ -#undef _MINIX - -/* Define on NetBSD to activate all library features */ -#ifndef _NETBSD_SOURCE - #define _NETBSD_SOURCE 1 -#endif - -/* Define _OSF_SOURCE to get the makedev macro. */ -#undef _OSF_SOURCE - -/* Define to 2 if the system does not provide POSIX.1 features except with - this defined. */ -#undef _POSIX_1_SOURCE - -/* Define to activate features from IEEE Stds 1003.1-2001 */ -#undef _POSIX_C_SOURCE - -/* Define to 1 if you need to in order for 'stat' and other things to work. */ -#undef _POSIX_SOURCE - -/* Define if you have POSIX threads, and your system does not define that. */ -#undef _POSIX_THREADS - -/* Define to force use of thread-safe errno, h_errno, and other functions */ -#undef _REENTRANT - -/* Define for Solaris 2.5.1 so the uint32_t typedef from , - , or is not used. If the typedef were allowed, the - #define below would cause a syntax error. */ -#undef _UINT32_T - -/* Define for Solaris 2.5.1 so the uint64_t typedef from , - , or is not used. If the typedef were allowed, the - #define below would cause a syntax error. */ -#undef _UINT64_T - -/* Define to the level of X/Open that your system supports */ -#undef _XOPEN_SOURCE - -/* Define to activate Unix95-and-earlier features */ -#undef _XOPEN_SOURCE_EXTENDED - -/* Define on FreeBSD to activate all library features */ -#undef __BSD_VISIBLE - -/* Define to 1 if type 'char' is unsigned and you are not using gcc. */ -#ifndef __CHAR_UNSIGNED__ -# undef __CHAR_UNSIGNED__ -#endif - -/* Defined on Solaris to see additional function prototypes. */ -#undef __EXTENSIONS__ - -/* Define to 'long' if doesn't define. */ -//#undef clock_t - -/* Define to empty if 'const' does not conform to ANSI C. */ -//#undef const - -/* Define to 'int' if doesn't define. */ -//#undef gid_t - -/* Define to the type of a signed integer type of width exactly 32 bits if - such a type exists and the standard includes do not define it. */ -//#undef int32_t - -/* Define to the type of a signed integer type of width exactly 64 bits if - such a type exists and the standard includes do not define it. */ -//#undef int64_t - -/* Define to 'int' if does not define. */ -//#undef mode_t - -/* Define to 'long int' if does not define. */ -//#undef off_t - -/* Define to 'int' if does not define. */ -//#undef pid_t - -/* Define to empty if the keyword does not work. */ -//#undef signed - -/* Define to 'unsigned int' if does not define. */ -//#undef size_t - -/* Define to 'int' if does not define. */ -//#undef socklen_t - -/* Define to 'int' if doesn't define. */ -//#undef uid_t - -/* Define to the type of an unsigned integer type of width exactly 32 bits if - such a type exists and the standard includes do not define it. */ -//#undef uint32_t - -/* Define to the type of an unsigned integer type of width exactly 64 bits if - such a type exists and the standard includes do not define it. */ -//#undef uint64_t - -/* Define to empty if the keyword does not work. */ -//#undef volatile - -#endif /*Py_PYCONFIG_H*/ diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Include/fileobject.h b/AppPkg/Applications/Python/PyMod-2.7.2/Include/fileobject.h deleted file mode 100644 index f1fdde2..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Include/fileobject.h +++ /dev/null @@ -1,102 +0,0 @@ -/** @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/PyMod-2.7.2/Include/osdefs.h b/AppPkg/Applications/Python/PyMod-2.7.2/Include/osdefs.h deleted file mode 100644 index bf6ec11..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Include/osdefs.h +++ /dev/null @@ -1,71 +0,0 @@ -/** @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/PyMod-2.7.2/Include/pyport.h b/AppPkg/Applications/Python/PyMod-2.7.2/Include/pyport.h deleted file mode 100644 index d1494d3..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Include/pyport.h +++ /dev/null @@ -1,918 +0,0 @@ -/** @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/PyMod-2.7.2/Lib/ntpath.py b/AppPkg/Applications/Python/PyMod-2.7.2/Lib/ntpath.py deleted file mode 100644 index 970a603..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Lib/ntpath.py +++ /dev/null @@ -1,528 +0,0 @@ -# Module 'ntpath' -- common operations on WinNT/Win95 pathnames -"""Common pathname manipulations, WindowsNT/95 version. - -Instead of importing this module directly, import os and refer to this -module as os.path. -""" - -import os -import sys -import stat -import genericpath -import warnings - -from genericpath import * - -__all__ = ["normcase","isabs","join","splitdrive","split","splitext", - "basename","dirname","commonprefix","getsize","getmtime", - "getatime","getctime", "islink","exists","lexists","isdir","isfile", - "ismount","walk","expanduser","expandvars","normpath","abspath", - "splitunc","curdir","pardir","sep","pathsep","defpath","altsep", - "extsep","devnull","realpath","supports_unicode_filenames","relpath"] - -# strings representing various path-related bits and pieces -curdir = '.' -pardir = '..' -extsep = '.' -sep = '\\' -pathsep = ';' -altsep = '/' -defpath = '.;C:\\bin' -if 'ce' in sys.builtin_module_names: - defpath = '\\Windows' -elif 'os2' in sys.builtin_module_names: - # OS/2 w/ VACPP - altsep = '/' -devnull = 'nul' - -# Normalize the case of a pathname and map slashes to backslashes. -# Other normalizations (such as optimizing '../' away) are not done -# (this is done by normpath). - -def normcase(s): - """Normalize case of pathname. - - Makes all characters lowercase and all slashes into backslashes.""" - return s.replace("/", "\\").lower() - - -# Return whether a path is absolute. -# Trivial in Posix, harder on the Mac or MS-DOS. -# For DOS it is absolute if it starts with a slash or backslash (current -# volume), or if a pathname after the volume letter and colon / UNC resource -# starts with a slash or backslash. - -def isabs(s): - """Test whether a path is absolute""" - s = splitdrive(s)[1] - return s != '' and s[:1] in '/\\' - - -# Join two (or more) paths. - -def join(a, *p): - """Join two or more pathname components, inserting "\\" as needed. - If any component is an absolute path, all previous path components - will be discarded.""" - path = a - for b in p: - b_wins = 0 # set to 1 iff b makes path irrelevant - if path == "": - b_wins = 1 - - elif isabs(b): - # This probably wipes out path so far. However, it's more - # complicated if path begins with a drive letter: - # 1. join('c:', '/a') == 'c:/a' - # 2. join('c:/', '/a') == 'c:/a' - # But - # 3. join('c:/a', '/b') == '/b' - # 4. join('c:', 'd:/') = 'd:/' - # 5. join('c:/', 'd:/') = 'd:/' - if path[1:2] != ":" or b[1:2] == ":": - # Path doesn't start with a drive letter, or cases 4 and 5. - b_wins = 1 - - # Else path has a drive letter, and b doesn't but is absolute. - elif len(path) > 3 or (len(path) == 3 and - path[-1] not in "/\\"): - # case 3 - b_wins = 1 - - if b_wins: - path = b - else: - # Join, and ensure there's a separator. - assert len(path) > 0 - if path[-1] in "/\\": - if b and b[0] in "/\\": - path += b[1:] - else: - path += b - elif path[-1] == ":": - path += b - elif b: - if b[0] in "/\\": - path += b - else: - path += "\\" + b - else: - # path is not empty and does not end with a backslash, - # but b is empty; since, e.g., split('a/') produces - # ('a', ''), it's best if join() adds a backslash in - # this case. - path += '\\' - - return path - - -# Split a path in a drive specification (a drive letter followed by a -# colon) and the path specification. -# It is always true that drivespec + pathspec == p -def splitdrive(p): - """Split a pathname into drive and path specifiers. Returns a 2-tuple -"(drive,path)"; either part may be empty""" - pparts = p.split(':', 2) - numparts = len(pparts) - if numparts == 2: - return pparts[0] + ':', pparts[1] - else: - if numparts == 1: - return '', pparts[0] - return '', p - - -# Parse UNC paths -def splitunc(p): - """Split a pathname into UNC mount point and relative path specifiers. - - Return a 2-tuple (unc, rest); either part may be empty. - If unc is not empty, it has the form '//host/mount' (or similar - using backslashes). unc+rest is always the input path. - Paths containing drive letters never have an UNC part. - """ - if len(p.split(':', 2)) > 1: - return '', p # Drive letter present - firstTwo = p[0:2] - if firstTwo == '//' or firstTwo == '\\\\': - # is a UNC path: - # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter - # \\machine\mountpoint\directories... - # directory ^^^^^^^^^^^^^^^ - normp = normcase(p) - index = normp.find('\\', 2) - if index == -1: - ##raise RuntimeError, 'illegal UNC path: "' + p + '"' - return ("", p) - index = normp.find('\\', index + 1) - if index == -1: - index = len(p) - return p[:index], p[index:] - return '', p - - -# Split a path in head (everything up to the last '/') and tail (the -# rest). After the trailing '/' is stripped, the invariant -# join(head, tail) == p holds. -# The resulting head won't end in '/' unless it is the root. - -def split(p): - """Split a pathname. - - Return tuple (head, tail) where tail is everything after the final slash. - Either part may be empty.""" - - d, p = splitdrive(p) - # set i to index beyond p's last slash - i = len(p) - while i and p[i-1] not in '/\\': - i = i - 1 - head, tail = p[:i], p[i:] # now tail has no slashes - # remove trailing slashes from head, unless it's all slashes - head2 = head - while head2 and head2[-1] in '/\\': - head2 = head2[:-1] - head = head2 or head - return d + head, tail - - -# Split a path in root and extension. -# The extension is everything starting at the last dot in the last -# pathname component; the root is everything before that. -# It is always true that root + ext == p. - -def splitext(p): - return genericpath._splitext(p, sep, altsep, extsep) -splitext.__doc__ = genericpath._splitext.__doc__ - - -# Return the tail (basename) part of a path. - -def basename(p): - """Returns the final component of a pathname""" - return split(p)[1] - - -# Return the head (dirname) part of a path. - -def dirname(p): - """Returns the directory component of a pathname""" - return split(p)[0] - -# Is a path a symbolic link? -# This will always return false on systems where posix.lstat doesn't exist. - -def islink(path): - """Test for symbolic link. - On WindowsNT/95 and OS/2 always returns false - """ - return False - -# alias exists to lexists -lexists = exists - -# Is a path a mount point? Either a root (with or without drive letter) -# or an UNC path with at most a / or \ after the mount point. - -def ismount(path): - """Test whether a path is a mount point (defined as root of drive)""" - unc, rest = splitunc(path) - if unc: - return rest in ("", "/", "\\") - p = splitdrive(path)[1] - return len(p) == 1 and p[0] in '/\\' - - -# Directory tree walk. -# For each directory under top (including top itself, but excluding -# '.' and '..'), func(arg, dirname, filenames) is called, where -# dirname is the name of the directory and filenames is the list -# of files (and subdirectories etc.) in the directory. -# The func may modify the filenames list, to implement a filter, -# or to impose a different order of visiting. - -def walk(top, func, arg): - """Directory tree walk with callback function. - - For each directory in the directory tree rooted at top (including top - itself, but excluding '.' and '..'), call func(arg, dirname, fnames). - dirname is the name of the directory, and fnames a list of the names of - the files and subdirectories in dirname (excluding '.' and '..'). func - may modify the fnames list in-place (e.g. via del or slice assignment), - and walk will only recurse into the subdirectories whose names remain in - fnames; this can be used to implement a filter, or to impose a specific - order of visiting. No semantics are defined for, or required of, arg, - beyond that arg is always passed to func. It can be used, e.g., to pass - a filename pattern, or a mutable object designed to accumulate - statistics. Passing None for arg is common.""" - warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.", - stacklevel=2) - try: - names = os.listdir(top) - except os.error: - return - func(arg, top, names) - for name in names: - name = join(top, name) - if isdir(name): - walk(name, func, arg) - - -# Expand paths beginning with '~' or '~user'. -# '~' means $HOME; '~user' means that user's home directory. -# If the path doesn't begin with '~', or if the user or $HOME is unknown, -# the path is returned unchanged (leaving error reporting to whatever -# function is called with the expanded path as argument). -# See also module 'glob' for expansion of *, ? and [...] in pathnames. -# (A function should also be defined to do full *sh-style environment -# variable expansion.) - -def expanduser(path): - """Expand ~ and ~user constructs. - - If user or $HOME is unknown, do nothing.""" - if path[:1] != '~': - return path - i, n = 1, len(path) - while i < n and path[i] not in '/\\': - i = i + 1 - - if 'HOME' in os.environ: - userhome = os.environ['HOME'] - elif 'USERPROFILE' in os.environ: - userhome = os.environ['USERPROFILE'] - elif not 'HOMEPATH' in os.environ: - return path - else: - try: - drive = os.environ['HOMEDRIVE'] - except KeyError: - drive = '' - userhome = join(drive, os.environ['HOMEPATH']) - - if i != 1: #~user - userhome = join(dirname(userhome), path[1:i]) - - return userhome + path[i:] - - -# Expand paths containing shell variable substitutions. -# The following rules apply: -# - no expansion within single quotes -# - '$$' is translated into '$' -# - '%%' is translated into '%' if '%%' are not seen in %var1%%var2% -# - ${varname} is accepted. -# - $varname is accepted. -# - %varname% is accepted. -# - varnames can be made out of letters, digits and the characters '_-' -# (though is not verified in the ${varname} and %varname% cases) -# XXX With COMMAND.COM you can use any characters in a variable name, -# XXX except '^|<>='. - -def expandvars(path): - """Expand shell variables of the forms $var, ${var} and %var%. - - Unknown variables are left unchanged.""" - if '$' not in path and '%' not in path: - return path - import string - varchars = string.ascii_letters + string.digits + '_-' - res = '' - index = 0 - pathlen = len(path) - while index < pathlen: - c = path[index] - if c == '\'': # no expansion within single quotes - path = path[index + 1:] - pathlen = len(path) - try: - index = path.index('\'') - res = res + '\'' + path[:index + 1] - except ValueError: - res = res + path - index = pathlen - 1 - elif c == '%': # variable or '%' - if path[index + 1:index + 2] == '%': - res = res + c - index = index + 1 - else: - path = path[index+1:] - pathlen = len(path) - try: - index = path.index('%') - except ValueError: - res = res + '%' + path - index = pathlen - 1 - else: - var = path[:index] - if var in os.environ: - res = res + os.environ[var] - else: - res = res + '%' + var + '%' - elif c == '$': # variable or '$$' - if path[index + 1:index + 2] == '$': - res = res + c - index = index + 1 - elif path[index + 1:index + 2] == '{': - path = path[index+2:] - pathlen = len(path) - try: - index = path.index('}') - var = path[:index] - if var in os.environ: - res = res + os.environ[var] - else: - res = res + '${' + var + '}' - except ValueError: - res = res + '${' + path - index = pathlen - 1 - else: - var = '' - index = index + 1 - c = path[index:index + 1] - while c != '' and c in varchars: - var = var + c - index = index + 1 - c = path[index:index + 1] - if var in os.environ: - res = res + os.environ[var] - else: - res = res + '$' + var - if c != '': - index = index - 1 - else: - res = res + c - index = index + 1 - return res - - -# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B. -# Previously, this function also truncated pathnames to 8+3 format, -# but as this module is called "ntpath", that's obviously wrong! - -def normpath(path): - """Normalize path, eliminating double slashes, etc.""" - # Preserve unicode (if path is unicode) - backslash, dot = (u'\\', u'.') if isinstance(path, unicode) else ('\\', '.') - if path.startswith(('\\\\.\\', '\\\\?\\')): - # in the case of paths with these prefixes: - # \\.\ -> device names - # \\?\ -> literal paths - # do not do any normalization, but return the path unchanged - return path - path = path.replace("/", "\\") - prefix, path = splitdrive(path) - # We need to be careful here. If the prefix is empty, and the path starts - # with a backslash, it could either be an absolute path on the current - # drive (\dir1\dir2\file) or a UNC filename (\\server\mount\dir1\file). It - # is therefore imperative NOT to collapse multiple backslashes blindly in - # that case. - # The code below preserves multiple backslashes when there is no drive - # letter. This means that the invalid filename \\\a\b is preserved - # unchanged, where a\\\b is normalised to a\b. It's not clear that there - # is any better behaviour for such edge cases. - if prefix == '': - # No drive letter - preserve initial backslashes - while path[:1] == "\\": - prefix = prefix + backslash - path = path[1:] - else: - # We have a drive letter - collapse initial backslashes - if path.startswith("\\"): - prefix = prefix + backslash - path = path.lstrip("\\") - comps = path.split("\\") - i = 0 - while i < len(comps): - if comps[i] in ('.', ''): - del comps[i] - elif comps[i] == '..': - if i > 0 and comps[i-1] != '..': - del comps[i-1:i+1] - i -= 1 - elif i == 0 and prefix.endswith("\\"): - del comps[i] - else: - i += 1 - else: - i += 1 - # If the path is now empty, substitute '.' - if not prefix and not comps: - comps.append(dot) - return prefix + backslash.join(comps) - - -# Return an absolute path. -try: - from nt import _getfullpathname - -except ImportError: # not running on Windows - mock up something sensible - def abspath(path): - """Return the absolute version of a path.""" - if not isabs(path): - if isinstance(path, unicode): - cwd = os.getcwdu() - else: - cwd = os.getcwd() - path = join(cwd, path) - return normpath(path) - -else: # use native Windows method on Windows - def abspath(path): - """Return the absolute version of a path.""" - - if path: # Empty path must return current working directory. - try: - path = _getfullpathname(path) - except WindowsError: - pass # Bad path - return unchanged. - elif isinstance(path, unicode): - path = os.getcwdu() - else: - path = os.getcwd() - return normpath(path) - -# realpath is a no-op on systems without islink support -realpath = abspath -# Win9x family and earlier have no Unicode filename support. -supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and - sys.getwindowsversion()[3] >= 2) - -def _abspath_split(path): - abs = abspath(normpath(path)) - prefix, rest = splitunc(abs) - is_unc = bool(prefix) - if not is_unc: - prefix, rest = splitdrive(abs) - return is_unc, prefix, [x for x in rest.split(sep) if x] - -def relpath(path, start=curdir): - """Return a relative version of a path""" - - if not path: - raise ValueError("no path specified") - - start_is_unc, start_prefix, start_list = _abspath_split(start) - path_is_unc, path_prefix, path_list = _abspath_split(path) - - if path_is_unc ^ start_is_unc: - raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)" - % (path, start)) - if path_prefix.lower() != start_prefix.lower(): - if path_is_unc: - raise ValueError("path is on UNC root %s, start on UNC root %s" - % (path_prefix, start_prefix)) - else: - raise ValueError("path is on drive %s, start on drive %s" - % (path_prefix, start_prefix)) - # Work out how much of the filepath is shared by start and path. - i = 0 - for e1, e2 in zip(start_list, path_list): - if e1.lower() != e2.lower(): - break - i += 1 - - rel_list = [pardir] * (len(start_list)-i) + path_list[i:] - if not rel_list: - return curdir - return join(*rel_list) diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Lib/os.py b/AppPkg/Applications/Python/PyMod-2.7.2/Lib/os.py deleted file mode 100644 index 413e4ae..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Lib/os.py +++ /dev/null @@ -1,773 +0,0 @@ -"""OS routines for Mac, NT, Posix, or UEFI depending on what system we're on. - -This exports: - - all functions from edk2, posix, nt, os2, or ce, e.g. unlink, stat, etc. - - os.path is one of the modules uefipath, posixpath, or ntpath - - os.name is 'edk2', 'posix', 'nt', 'os2', 'ce' or 'riscos' - - os.curdir is a string representing the current directory ('.' or ':') - - os.pardir is a string representing the parent directory ('..' or '::') - - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\') - - os.extsep is the extension separator ('.' or '/') - - os.altsep is the alternate pathname separator (None or '/') - - os.pathsep is the component separator used in $PATH etc - - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n') - - os.defpath is the default search path for executables - - os.devnull is the file path of the null device ('/dev/null', etc.) - -Programs that import and use 'os' stand a better chance of being -portable between different platforms. Of course, they must then -only use functions that are defined by all platforms (e.g., unlink -and opendir), and leave all pathname manipulation to os.path -(e.g., split and join). -""" - -#' - -import sys, errno - -_names = sys.builtin_module_names - -# Note: more names are added to __all__ later. -__all__ = ["altsep", "curdir", "pardir", "sep", "extsep", "pathsep", "linesep", - "defpath", "name", "path", "devnull", - "SEEK_SET", "SEEK_CUR", "SEEK_END"] - -def _get_exports_list(module): - try: - return list(module.__all__) - except AttributeError: - return [n for n in dir(module) if n[0] != '_'] - -if 'posix' in _names: - name = 'posix' - linesep = '\n' - from posix import * - try: - from posix import _exit - except ImportError: - pass - import posixpath as path - - import posix - __all__.extend(_get_exports_list(posix)) - del posix - -elif 'nt' in _names: - name = 'nt' - linesep = '\r\n' - from nt import * - try: - from nt import _exit - except ImportError: - pass - import ntpath as path - - import nt - __all__.extend(_get_exports_list(nt)) - del nt - -elif 'os2' in _names: - name = 'os2' - linesep = '\r\n' - from os2 import * - try: - from os2 import _exit - except ImportError: - pass - if sys.version.find('EMX GCC') == -1: - import ntpath as path - else: - import os2emxpath as path - from _emx_link import link - - import os2 - __all__.extend(_get_exports_list(os2)) - del os2 - -elif 'ce' in _names: - name = 'ce' - linesep = '\r\n' - from ce import * - try: - from ce import _exit - except ImportError: - pass - # We can use the standard Windows path. - import ntpath as path - - import ce - __all__.extend(_get_exports_list(ce)) - del ce - -elif 'riscos' in _names: - name = 'riscos' - linesep = '\n' - from riscos import * - try: - from riscos import _exit - except ImportError: - pass - import riscospath as path - - import riscos - __all__.extend(_get_exports_list(riscos)) - del riscos - -elif 'edk2' in _names: - name = 'edk2' - linesep = '\n' - from edk2 import * - try: - from edk2 import _exit - except ImportError: - pass - import ntpath as path - - import edk2 - __all__.extend(_get_exports_list(edk2)) - del edk2 - -else: - raise ImportError, 'no os specific module found' - -sys.modules['os.path'] = path -from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep, - devnull) - -del _names - -# Python uses fixed values for the SEEK_ constants; they are mapped -# to native constants if necessary in posixmodule.c -SEEK_SET = 0 -SEEK_CUR = 1 -SEEK_END = 2 - -#' - -# Super directory utilities. -# (Inspired by Eric Raymond; the doc strings are mostly his) - -def makedirs(name, mode=0777): - """makedirs(path [, mode=0777]) - - Super-mkdir; create a leaf directory and all intermediate ones. - Works like mkdir, except that any intermediate path segment (not - just the rightmost) will be created if it does not exist. This is - recursive. - - """ - head, tail = path.split(name) - if not tail: - head, tail = path.split(head) - if head and tail and not path.exists(head): - try: - makedirs(head, mode) - except OSError, e: - # be happy if someone already created the path - if e.errno != errno.EEXIST: - raise - if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists - return - mkdir(name, mode) - -def removedirs(name): - """removedirs(path) - - Super-rmdir; remove a leaf directory and all empty intermediate - ones. Works like rmdir except that, if the leaf directory is - successfully removed, directories corresponding to rightmost path - segments will be pruned away until either the whole path is - consumed or an error occurs. Errors during this latter phase are - ignored -- they generally mean that a directory was not empty. - - """ - rmdir(name) - head, tail = path.split(name) - if not tail: - head, tail = path.split(head) - while head and tail: - try: - rmdir(head) - except error: - break - head, tail = path.split(head) - -def renames(old, new): - """renames(old, new) - - Super-rename; create directories as necessary and delete any left - empty. Works like rename, except creation of any intermediate - directories needed to make the new pathname good is attempted - first. After the rename, directories corresponding to rightmost - path segments of the old name will be pruned way until either the - whole path is consumed or a nonempty directory is found. - - Note: this function can fail with the new directory structure made - if you lack permissions needed to unlink the leaf directory or - file. - - """ - head, tail = path.split(new) - if head and tail and not path.exists(head): - makedirs(head) - rename(old, new) - head, tail = path.split(old) - if head and tail: - try: - removedirs(head) - except error: - pass - -__all__.extend(["makedirs", "removedirs", "renames"]) - -def walk(top, topdown=True, onerror=None, followlinks=False): - """Directory tree generator. - - For each directory in the directory tree rooted at top (including top - itself, but excluding '.' and '..'), yields a 3-tuple - - dirpath, dirnames, filenames - - dirpath is a string, the path to the directory. dirnames is a list of - the names of the subdirectories in dirpath (excluding '.' and '..'). - filenames is a list of the names of the non-directory files in dirpath. - Note that the names in the lists are just names, with no path components. - To get a full path (which begins with top) to a file or directory in - dirpath, do os.path.join(dirpath, name). - - If optional arg 'topdown' is true or not specified, the triple for a - directory is generated before the triples for any of its subdirectories - (directories are generated top down). If topdown is false, the triple - for a directory is generated after the triples for all of its - subdirectories (directories are generated bottom up). - - When topdown is true, the caller can modify the dirnames list in-place - (e.g., via del or slice assignment), and walk will only recurse into the - subdirectories whose names remain in dirnames; this can be used to prune - the search, or to impose a specific order of visiting. Modifying - dirnames when topdown is false is ineffective, since the directories in - dirnames have already been generated by the time dirnames itself is - generated. - - By default errors from the os.listdir() call are ignored. If - optional arg 'onerror' is specified, it should be a function; it - will be called with one argument, an os.error instance. It can - report the error to continue with the walk, or raise the exception - to abort the walk. Note that the filename is available as the - filename attribute of the exception object. - - By default, os.walk does not follow symbolic links to subdirectories on - systems that support them. In order to get this functionality, set the - optional argument 'followlinks' to true. - - Caution: if you pass a relative pathname for top, don't change the - current working directory between resumptions of walk. walk never - changes the current directory, and assumes that the client doesn't - either. - - Example: - - import os - from os.path import join, getsize - for root, dirs, files in os.walk('python/Lib/email'): - print root, "consumes", - print sum([getsize(join(root, name)) for name in files]), - print "bytes in", len(files), "non-directory files" - if 'CVS' in dirs: - dirs.remove('CVS') # don't visit CVS directories - """ - - islink, join, isdir = path.islink, path.join, path.isdir - - # We may not have read permission for top, in which case we can't - # get a list of the files the directory contains. os.path.walk - # always suppressed the exception then, rather than blow up for a - # minor reason when (say) a thousand readable directories are still - # left to visit. That logic is copied here. - try: - # Note that listdir and error are globals in this module due - # to earlier import-*. - names = listdir(top) - except error, err: - if onerror is not None: - onerror(err) - return - - dirs, nondirs = [], [] - for name in names: - if isdir(join(top, name)): - dirs.append(name) - else: - nondirs.append(name) - - if topdown: - yield top, dirs, nondirs - for name in dirs: - new_path = join(top, name) - if followlinks or not islink(new_path): - for x in walk(new_path, topdown, onerror, followlinks): - yield x - if not topdown: - yield top, dirs, nondirs - -__all__.append("walk") - -# Make sure os.environ exists, at least -try: - environ -except NameError: - environ = {} - -def execl(file, *args): - """execl(file, *args) - - Execute the executable file with argument list args, replacing the - current process. """ - execv(file, args) - -def execle(file, *args): - """execle(file, *args, env) - - Execute the executable file with argument list args and - environment env, replacing the current process. """ - env = args[-1] - execve(file, args[:-1], env) - -def execlp(file, *args): - """execlp(file, *args) - - Execute the executable file (which is searched for along $PATH) - with argument list args, replacing the current process. """ - execvp(file, args) - -def execlpe(file, *args): - """execlpe(file, *args, env) - - Execute the executable file (which is searched for along $PATH) - with argument list args and environment env, replacing the current - process. """ - env = args[-1] - execvpe(file, args[:-1], env) - -def execvp(file, args): - """execvp(file, args) - - Execute the executable file (which is searched for along $PATH) - with argument list args, replacing the current process. - args may be a list or tuple of strings. """ - _execvpe(file, args) - -def execvpe(file, args, env): - """execvpe(file, args, env) - - Execute the executable file (which is searched for along $PATH) - with argument list args and environment env , replacing the - current process. - args may be a list or tuple of strings. """ - _execvpe(file, args, env) - -__all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"]) - -def _execvpe(file, args, env=None): - if env is not None: - func = execve - argrest = (args, env) - else: - func = execv - argrest = (args,) - env = environ - - head, tail = path.split(file) - if head: - func(file, *argrest) - return - if 'PATH' in env: - envpath = env['PATH'] - else: - envpath = defpath - PATH = envpath.split(pathsep) - saved_exc = None - saved_tb = None - for dir in PATH: - fullname = path.join(dir, file) - try: - func(fullname, *argrest) - except error, e: - tb = sys.exc_info()[2] - if (e.errno != errno.ENOENT and e.errno != errno.ENOTDIR - and saved_exc is None): - saved_exc = e - saved_tb = tb - if saved_exc: - raise error, saved_exc, saved_tb - raise error, e, tb - -# Change environ to automatically call putenv() if it exists -try: - # This will fail if there's no putenv - putenv -except NameError: - pass -else: - import UserDict - - # Fake unsetenv() for Windows - # not sure about os2 here but - # I'm guessing they are the same. - - if name in ('os2', 'nt'): - def unsetenv(key): - putenv(key, "") - - if name == "riscos": - # On RISC OS, all env access goes through getenv and putenv - from riscosenviron import _Environ - elif name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE - # But we store them as upper case - class _Environ(UserDict.IterableUserDict): - def __init__(self, environ): - UserDict.UserDict.__init__(self) - data = self.data - for k, v in environ.items(): - data[k.upper()] = v - def __setitem__(self, key, item): - putenv(key, item) - self.data[key.upper()] = item - def __getitem__(self, key): - return self.data[key.upper()] - try: - unsetenv - except NameError: - def __delitem__(self, key): - del self.data[key.upper()] - else: - def __delitem__(self, key): - unsetenv(key) - del self.data[key.upper()] - def clear(self): - for key in self.data.keys(): - unsetenv(key) - del self.data[key] - def pop(self, key, *args): - unsetenv(key) - return self.data.pop(key.upper(), *args) - def has_key(self, key): - return key.upper() in self.data - def __contains__(self, key): - return key.upper() in self.data - def get(self, key, failobj=None): - return self.data.get(key.upper(), failobj) - def update(self, dict=None, **kwargs): - if dict: - try: - keys = dict.keys() - except AttributeError: - # List of (key, value) - for k, v in dict: - self[k] = v - else: - # got keys - # cannot use items(), since mappings - # may not have them. - for k in keys: - self[k] = dict[k] - if kwargs: - self.update(kwargs) - def copy(self): - return dict(self) - - else: # Where Env Var Names Can Be Mixed Case - class _Environ(UserDict.IterableUserDict): - def __init__(self, environ): - UserDict.UserDict.__init__(self) - self.data = environ - def __setitem__(self, key, item): - putenv(key, item) - self.data[key] = item - def update(self, dict=None, **kwargs): - if dict: - try: - keys = dict.keys() - except AttributeError: - # List of (key, value) - for k, v in dict: - self[k] = v - else: - # got keys - # cannot use items(), since mappings - # may not have them. - for k in keys: - self[k] = dict[k] - if kwargs: - self.update(kwargs) - try: - unsetenv - except NameError: - pass - else: - def __delitem__(self, key): - unsetenv(key) - del self.data[key] - def clear(self): - for key in self.data.keys(): - unsetenv(key) - del self.data[key] - def pop(self, key, *args): - unsetenv(key) - return self.data.pop(key, *args) - def copy(self): - return dict(self) - - - environ = _Environ(environ) - -def getenv(key, default=None): - """Get an environment variable, return None if it doesn't exist. - The optional second argument can specify an alternate default.""" - return environ.get(key, default) -__all__.append("getenv") - -def _exists(name): - return name in globals() - -# Supply spawn*() (probably only for Unix) -if _exists("fork") and not _exists("spawnv") and _exists("execv"): - - P_WAIT = 0 - P_NOWAIT = P_NOWAITO = 1 - - # XXX Should we support P_DETACH? I suppose it could fork()**2 - # and close the std I/O streams. Also, P_OVERLAY is the same - # as execv*()? - - def _spawnvef(mode, file, args, env, func): - # Internal helper; func is the exec*() function to use - pid = fork() - if not pid: - # Child - try: - if env is None: - func(file, args) - else: - func(file, args, env) - except: - _exit(127) - else: - # Parent - if mode == P_NOWAIT: - return pid # Caller is responsible for waiting! - while 1: - wpid, sts = waitpid(pid, 0) - if WIFSTOPPED(sts): - continue - elif WIFSIGNALED(sts): - return -WTERMSIG(sts) - elif WIFEXITED(sts): - return WEXITSTATUS(sts) - else: - raise error, "Not stopped, signaled or exited???" - - def spawnv(mode, file, args): - """spawnv(mode, file, args) -> integer - -Execute file with arguments from args in a subprocess. -If mode == P_NOWAIT return the pid of the process. -If mode == P_WAIT return the process's exit code if it exits normally; -otherwise return -SIG, where SIG is the signal that killed it. """ - return _spawnvef(mode, file, args, None, execv) - - def spawnve(mode, file, args, env): - """spawnve(mode, file, args, env) -> integer - -Execute file with arguments from args in a subprocess with the -specified environment. -If mode == P_NOWAIT return the pid of the process. -If mode == P_WAIT return the process's exit code if it exits normally; -otherwise return -SIG, where SIG is the signal that killed it. """ - return _spawnvef(mode, file, args, env, execve) - - # Note: spawnvp[e] is't currently supported on Windows - - def spawnvp(mode, file, args): - """spawnvp(mode, file, args) -> integer - -Execute file (which is looked for along $PATH) with arguments from -args in a subprocess. -If mode == P_NOWAIT return the pid of the process. -If mode == P_WAIT return the process's exit code if it exits normally; -otherwise return -SIG, where SIG is the signal that killed it. """ - return _spawnvef(mode, file, args, None, execvp) - - def spawnvpe(mode, file, args, env): - """spawnvpe(mode, file, args, env) -> integer - -Execute file (which is looked for along $PATH) with arguments from -args in a subprocess with the supplied environment. -If mode == P_NOWAIT return the pid of the process. -If mode == P_WAIT return the process's exit code if it exits normally; -otherwise return -SIG, where SIG is the signal that killed it. """ - return _spawnvef(mode, file, args, env, execvpe) - -if _exists("spawnv"): - # These aren't supplied by the basic Windows code - # but can be easily implemented in Python - - def spawnl(mode, file, *args): - """spawnl(mode, file, *args) -> integer - -Execute file with arguments from args in a subprocess. -If mode == P_NOWAIT return the pid of the process. -If mode == P_WAIT return the process's exit code if it exits normally; -otherwise return -SIG, where SIG is the signal that killed it. """ - return spawnv(mode, file, args) - - def spawnle(mode, file, *args): - """spawnle(mode, file, *args, env) -> integer - -Execute file with arguments from args in a subprocess with the -supplied environment. -If mode == P_NOWAIT return the pid of the process. -If mode == P_WAIT return the process's exit code if it exits normally; -otherwise return -SIG, where SIG is the signal that killed it. """ - env = args[-1] - return spawnve(mode, file, args[:-1], env) - - - __all__.extend(["spawnv", "spawnve", "spawnl", "spawnle",]) - - -if _exists("spawnvp"): - # At the moment, Windows doesn't implement spawnvp[e], - # so it won't have spawnlp[e] either. - def spawnlp(mode, file, *args): - """spawnlp(mode, file, *args) -> integer - -Execute file (which is looked for along $PATH) with arguments from -args in a subprocess with the supplied environment. -If mode == P_NOWAIT return the pid of the process. -If mode == P_WAIT return the process's exit code if it exits normally; -otherwise return -SIG, where SIG is the signal that killed it. """ - return spawnvp(mode, file, args) - - def spawnlpe(mode, file, *args): - """spawnlpe(mode, file, *args, env) -> integer - -Execute file (which is looked for along $PATH) with arguments from -args in a subprocess with the supplied environment. -If mode == P_NOWAIT return the pid of the process. -If mode == P_WAIT return the process's exit code if it exits normally; -otherwise return -SIG, where SIG is the signal that killed it. """ - env = args[-1] - return spawnvpe(mode, file, args[:-1], env) - - - __all__.extend(["spawnvp", "spawnvpe", "spawnlp", "spawnlpe",]) - - -# Supply popen2 etc. (for Unix) -if _exists("fork"): - if not _exists("popen2"): - def popen2(cmd, mode="t", bufsize=-1): - """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' - may be a sequence, in which case arguments will be passed directly to - the program without shell intervention (as with os.spawnv()). If 'cmd' - is a string it will be passed to the shell (as with os.system()). If - 'bufsize' is specified, it sets the buffer size for the I/O pipes. The - file objects (child_stdin, child_stdout) are returned.""" - import warnings - msg = "os.popen2 is deprecated. Use the subprocess module." - warnings.warn(msg, DeprecationWarning, stacklevel=2) - - import subprocess - PIPE = subprocess.PIPE - p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring), - bufsize=bufsize, stdin=PIPE, stdout=PIPE, - close_fds=True) - return p.stdin, p.stdout - __all__.append("popen2") - - if not _exists("popen3"): - def popen3(cmd, mode="t", bufsize=-1): - """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' - may be a sequence, in which case arguments will be passed directly to - the program without shell intervention (as with os.spawnv()). If 'cmd' - is a string it will be passed to the shell (as with os.system()). If - 'bufsize' is specified, it sets the buffer size for the I/O pipes. The - file objects (child_stdin, child_stdout, child_stderr) are returned.""" - import warnings - msg = "os.popen3 is deprecated. Use the subprocess module." - warnings.warn(msg, DeprecationWarning, stacklevel=2) - - import subprocess - PIPE = subprocess.PIPE - p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring), - bufsize=bufsize, stdin=PIPE, stdout=PIPE, - stderr=PIPE, close_fds=True) - return p.stdin, p.stdout, p.stderr - __all__.append("popen3") - - if not _exists("popen4"): - def popen4(cmd, mode="t", bufsize=-1): - """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' - may be a sequence, in which case arguments will be passed directly to - the program without shell intervention (as with os.spawnv()). If 'cmd' - is a string it will be passed to the shell (as with os.system()). If - 'bufsize' is specified, it sets the buffer size for the I/O pipes. The - file objects (child_stdin, child_stdout_stderr) are returned.""" - import warnings - msg = "os.popen4 is deprecated. Use the subprocess module." - warnings.warn(msg, DeprecationWarning, stacklevel=2) - - import subprocess - PIPE = subprocess.PIPE - p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring), - bufsize=bufsize, stdin=PIPE, stdout=PIPE, - stderr=subprocess.STDOUT, close_fds=True) - return p.stdin, p.stdout - __all__.append("popen4") - -import copy_reg as _copy_reg - -def _make_stat_result(tup, dict): - return stat_result(tup, dict) - -def _pickle_stat_result(sr): - (type, args) = sr.__reduce__() - return (_make_stat_result, args) - -try: - _copy_reg.pickle(stat_result, _pickle_stat_result, _make_stat_result) -except NameError: # stat_result may not exist - pass - -def _make_statvfs_result(tup, dict): - return statvfs_result(tup, dict) - -def _pickle_statvfs_result(sr): - (type, args) = sr.__reduce__() - return (_make_statvfs_result, args) - -try: - _copy_reg.pickle(statvfs_result, _pickle_statvfs_result, - _make_statvfs_result) -except NameError: # statvfs_result may not exist - pass - -if not _exists("urandom"): - def urandom(n): - """urandom(n) -> str - - Return a string of n random bytes suitable for cryptographic use. - - """ - try: - _urandomfd = open("/dev/urandom", O_RDONLY) - except (OSError, IOError): - raise NotImplementedError("/dev/urandom (or equivalent) not found") - try: - bs = b"" - while n > len(bs): - bs += read(_urandomfd, n - len(bs)) - finally: - close(_urandomfd) - return bs diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Lib/pydoc.py b/AppPkg/Applications/Python/PyMod-2.7.2/Lib/pydoc.py deleted file mode 100644 index a104b92..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Lib/pydoc.py +++ /dev/null @@ -1,2341 +0,0 @@ -#!/usr/bin/env python -# -*- coding: latin-1 -*- -"""Generate Python documentation in HTML or text for interactive use. - -In the Python interpreter, do "from pydoc import help" to provide online -help. Calling help(thing) on a Python object documents the object. - -Or, at the shell command line outside of Python: - -Run "pydoc " to show documentation on something. may be -the name of a function, module, package, or a dotted reference to a -class or function within a module or module in a package. If the -argument contains a path segment delimiter (e.g. slash on Unix, -backslash on Windows) it is treated as the path to a Python source file. - -Run "pydoc -k " to search for a keyword in the synopsis lines -of all available modules. - -Run "pydoc -p " to start an HTTP server on a given port on the -local machine to generate documentation web pages. - -For platforms without a command line, "pydoc -g" starts the HTTP server -and also pops up a little window for controlling it. - -Run "pydoc -w " to write out the HTML documentation for a module -to a file named ".html". - -Module docs for core modules are assumed to be in - - http://docs.python.org/library/ - -This can be overridden by setting the PYTHONDOCS environment variable -to a different URL or to a local directory containing the Library -Reference Manual pages. -""" - -__author__ = "Ka-Ping Yee " -__date__ = "26 February 2001" - -__version__ = "$Revision$" -__credits__ = """Guido van Rossum, for an excellent programming language. -Tommy Burnette, the original creator of manpy. -Paul Prescod, for all his work on onlinehelp. -Richard Chamberlain, for the first implementation of textdoc. -""" - -# Known bugs that can't be fixed here: -# - imp.load_module() cannot be prevented from clobbering existing -# loaded modules, so calling synopsis() on a binary module file -# changes the contents of any existing module with the same name. -# - If the __file__ attribute on a module is a relative path and -# the current directory is changed with os.chdir(), an incorrect -# path will be displayed. - -import sys, imp, os, re, types, inspect, __builtin__, pkgutil -from repr import Repr -from string import expandtabs, find, join, lower, split, strip, rfind, rstrip -from traceback import extract_tb -try: - from collections import deque -except ImportError: - # Python 2.3 compatibility - class deque(list): - def popleft(self): - return self.pop(0) - -# --------------------------------------------------------- common routines - -def pathdirs(): - """Convert sys.path into a list of absolute, existing, unique paths.""" - dirs = [] - normdirs = [] - for dir in sys.path: - dir = os.path.abspath(dir or '.') - normdir = os.path.normcase(dir) - if normdir not in normdirs and os.path.isdir(dir): - dirs.append(dir) - normdirs.append(normdir) - return dirs - -def getdoc(object): - """Get the doc string or comments for an object.""" - result = inspect.getdoc(object) or inspect.getcomments(object) - return result and re.sub('^ *\n', '', rstrip(result)) or '' - -def splitdoc(doc): - """Split a doc string into a synopsis line (if any) and the rest.""" - lines = split(strip(doc), '\n') - if len(lines) == 1: - return lines[0], '' - elif len(lines) >= 2 and not rstrip(lines[1]): - return lines[0], join(lines[2:], '\n') - return '', join(lines, '\n') - -def classname(object, modname): - """Get a class name and qualify it with a module name if necessary.""" - name = object.__name__ - if object.__module__ != modname: - name = object.__module__ + '.' + name - return name - -def isdata(object): - """Check if an object is of a type that probably means it's data.""" - return not (inspect.ismodule(object) or inspect.isclass(object) or - inspect.isroutine(object) or inspect.isframe(object) or - inspect.istraceback(object) or inspect.iscode(object)) - -def replace(text, *pairs): - """Do a series of global replacements on a string.""" - while pairs: - text = join(split(text, pairs[0]), pairs[1]) - pairs = pairs[2:] - return text - -def cram(text, maxlen): - """Omit part of a string if needed to make it fit in a maximum length.""" - if len(text) > maxlen: - pre = max(0, (maxlen-3)//2) - post = max(0, maxlen-3-pre) - return text[:pre] + '...' + text[len(text)-post:] - return text - -_re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE) -def stripid(text): - """Remove the hexadecimal id from a Python object representation.""" - # The behaviour of %p is implementation-dependent in terms of case. - return _re_stripid.sub(r'\1', text) - -def _is_some_method(obj): - return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj) - -def allmethods(cl): - methods = {} - for key, value in inspect.getmembers(cl, _is_some_method): - methods[key] = 1 - for base in cl.__bases__: - methods.update(allmethods(base)) # all your base are belong to us - for key in methods.keys(): - methods[key] = getattr(cl, key) - return methods - -def _split_list(s, predicate): - """Split sequence s via predicate, and return pair ([true], [false]). - - The return value is a 2-tuple of lists, - ([x for x in s if predicate(x)], - [x for x in s if not predicate(x)]) - """ - - yes = [] - no = [] - for x in s: - if predicate(x): - yes.append(x) - else: - no.append(x) - return yes, no - -def visiblename(name, all=None, obj=None): - """Decide whether to show documentation on a variable.""" - # Certain special names are redundant. - _hidden_names = ('__builtins__', '__doc__', '__file__', '__path__', - '__module__', '__name__', '__slots__', '__package__') - if name in _hidden_names: return 0 - # Private names are hidden, but special names are displayed. - if name.startswith('__') and name.endswith('__'): return 1 - # Namedtuples have public fields and methods with a single leading underscore - if name.startswith('_') and hasattr(obj, '_fields'): - return 1 - if all is not None: - # only document that which the programmer exported in __all__ - return name in all - else: - return not name.startswith('_') - -def classify_class_attrs(object): - """Wrap inspect.classify_class_attrs, with fixup for data descriptors.""" - def fixup(data): - name, kind, cls, value = data - if inspect.isdatadescriptor(value): - kind = 'data descriptor' - return name, kind, cls, value - return map(fixup, inspect.classify_class_attrs(object)) - -# ----------------------------------------------------- module manipulation - -def ispackage(path): - """Guess whether a path refers to a package directory.""" - if os.path.isdir(path): - for ext in ('.py', '.pyc', '.pyo'): - if os.path.isfile(os.path.join(path, '__init__' + ext)): - return True - return False - -def source_synopsis(file): - line = file.readline() - while line[:1] == '#' or not strip(line): - line = file.readline() - if not line: break - line = strip(line) - if line[:4] == 'r"""': line = line[1:] - if line[:3] == '"""': - line = line[3:] - if line[-1:] == '\\': line = line[:-1] - while not strip(line): - line = file.readline() - if not line: break - result = strip(split(line, '"""')[0]) - else: result = None - return result - -def synopsis(filename, cache={}): - """Get the one-line summary out of a module file.""" - mtime = os.stat(filename).st_mtime - lastupdate, result = cache.get(filename, (0, None)) - if lastupdate < mtime: - info = inspect.getmoduleinfo(filename) - try: - file = open(filename) - except IOError: - # module can't be opened, so skip it - return None - if info and 'b' in info[2]: # binary modules have to be imported - try: module = imp.load_module('__temp__', file, filename, info[1:]) - except: return None - result = (module.__doc__ or '').splitlines()[0] - del sys.modules['__temp__'] - else: # text modules can be directly examined - result = source_synopsis(file) - file.close() - cache[filename] = (mtime, result) - return result - -class ErrorDuringImport(Exception): - """Errors that occurred while trying to import something to document it.""" - def __init__(self, filename, exc_info): - exc, value, tb = exc_info - self.filename = filename - self.exc = exc - self.value = value - self.tb = tb - - def __str__(self): - exc = self.exc - if type(exc) is types.ClassType: - exc = exc.__name__ - return 'problem in %s - %s: %s' % (self.filename, exc, self.value) - -def importfile(path): - """Import a Python source file or compiled file given its path.""" - magic = imp.get_magic() - file = open(path, 'r') - if file.read(len(magic)) == magic: - kind = imp.PY_COMPILED - else: - kind = imp.PY_SOURCE - file.close() - filename = os.path.basename(path) - name, ext = os.path.splitext(filename) - file = open(path, 'r') - try: - module = imp.load_module(name, file, path, (ext, 'r', kind)) - except: - raise ErrorDuringImport(path, sys.exc_info()) - file.close() - return module - -def safeimport(path, forceload=0, cache={}): - """Import a module; handle errors; return None if the module isn't found. - - If the module *is* found but an exception occurs, it's wrapped in an - ErrorDuringImport exception and reraised. Unlike __import__, if a - package path is specified, the module at the end of the path is returned, - not the package at the beginning. If the optional 'forceload' argument - is 1, we reload the module from disk (unless it's a dynamic extension).""" - try: - # If forceload is 1 and the module has been previously loaded from - # disk, we always have to reload the module. Checking the file's - # mtime isn't good enough (e.g. the module could contain a class - # that inherits from another module that has changed). - if forceload and path in sys.modules: - if path not in sys.builtin_module_names: - # Avoid simply calling reload() because it leaves names in - # the currently loaded module lying around if they're not - # defined in the new source file. Instead, remove the - # module from sys.modules and re-import. Also remove any - # submodules because they won't appear in the newly loaded - # module's namespace if they're already in sys.modules. - subs = [m for m in sys.modules if m.startswith(path + '.')] - for key in [path] + subs: - # Prevent garbage collection. - cache[key] = sys.modules[key] - del sys.modules[key] - module = __import__(path) - except: - # Did the error occur before or after the module was found? - (exc, value, tb) = info = sys.exc_info() - if path in sys.modules: - # An error occurred while executing the imported module. - raise ErrorDuringImport(sys.modules[path].__file__, info) - elif exc is SyntaxError: - # A SyntaxError occurred before we could execute the module. - raise ErrorDuringImport(value.filename, info) - elif exc is ImportError and extract_tb(tb)[-1][2]=='safeimport': - # The import error occurred directly in this function, - # which means there is no such module in the path. - return None - else: - # Some other error occurred during the importing process. - raise ErrorDuringImport(path, sys.exc_info()) - for part in split(path, '.')[1:]: - try: module = getattr(module, part) - except AttributeError: return None - return module - -# ---------------------------------------------------- formatter base class - -class Doc: - def document(self, object, name=None, *args): - """Generate documentation for an object.""" - args = (object, name) + args - # 'try' clause is to attempt to handle the possibility that inspect - # identifies something in a way that pydoc itself has issues handling; - # think 'super' and how it is a descriptor (which raises the exception - # by lacking a __name__ attribute) and an instance. - if inspect.isgetsetdescriptor(object): return self.docdata(*args) - if inspect.ismemberdescriptor(object): return self.docdata(*args) - try: - if inspect.ismodule(object): return self.docmodule(*args) - if inspect.isclass(object): return self.docclass(*args) - if inspect.isroutine(object): return self.docroutine(*args) - except AttributeError: - pass - if isinstance(object, property): return self.docproperty(*args) - return self.docother(*args) - - def fail(self, object, name=None, *args): - """Raise an exception for unimplemented types.""" - message = "don't know how to document object%s of type %s" % ( - name and ' ' + repr(name), type(object).__name__) - raise TypeError, message - - docmodule = docclass = docroutine = docother = docproperty = docdata = fail - - def getdocloc(self, object): - """Return the location of module docs or None""" - - try: - file = inspect.getabsfile(object) - except TypeError: - file = '(built-in)' - - docloc = os.environ.get("PYTHONDOCS", - "http://docs.python.org/library") - basedir = os.path.join(sys.exec_prefix, "lib", - "python"+sys.version[0:3]) - if (isinstance(object, type(os)) and - (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', - 'marshal', 'posix', 'signal', 'sys', - 'thread', 'zipimport') or - (file.startswith(basedir) and - not file.startswith(os.path.join(basedir, 'site-packages')))) and - object.__name__ not in ('xml.etree', 'test.pydoc_mod')): - if docloc.startswith("http://"): - docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__) - else: - docloc = os.path.join(docloc, object.__name__ + ".html") - else: - docloc = None - return docloc - -# -------------------------------------------- HTML documentation generator - -class HTMLRepr(Repr): - """Class for safely making an HTML representation of a Python object.""" - def __init__(self): - Repr.__init__(self) - self.maxlist = self.maxtuple = 20 - self.maxdict = 10 - self.maxstring = self.maxother = 100 - - def escape(self, text): - return replace(text, '&', '&', '<', '<', '>', '>') - - def repr(self, object): - return Repr.repr(self, object) - - def repr1(self, x, level): - if hasattr(type(x), '__name__'): - methodname = 'repr_' + join(split(type(x).__name__), '_') - if hasattr(self, methodname): - return getattr(self, methodname)(x, level) - return self.escape(cram(stripid(repr(x)), self.maxother)) - - def repr_string(self, x, level): - test = cram(x, self.maxstring) - testrepr = repr(test) - if '\\' in test and '\\' not in replace(testrepr, r'\\', ''): - # Backslashes are only literal in the string and are never - # needed to make any special characters, so show a raw string. - return 'r' + testrepr[0] + self.escape(test) + testrepr[0] - return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)', - r'\1', - self.escape(testrepr)) - - repr_str = repr_string - - def repr_instance(self, x, level): - try: - return self.escape(cram(stripid(repr(x)), self.maxstring)) - except: - return self.escape('<%s instance>' % x.__class__.__name__) - - repr_unicode = repr_string - -class HTMLDoc(Doc): - """Formatter class for HTML documentation.""" - - # ------------------------------------------- HTML formatting utilities - - _repr_instance = HTMLRepr() - repr = _repr_instance.repr - escape = _repr_instance.escape - - def page(self, title, contents): - """Format an HTML page.""" - return ''' - -Python: %s - -%s -''' % (title, contents) - - def heading(self, title, fgcol, bgcol, extras=''): - """Format a page heading.""" - return ''' - - -
 
- 
%s
%s
- ''' % (bgcol, fgcol, title, fgcol, extras or ' ') - - def section(self, title, fgcol, bgcol, contents, width=6, - prelude='', marginalia=None, gap=' '): - """Format a section with a heading.""" - if marginalia is None: - marginalia = '' + ' ' * width + '' - result = '''

- - - - ''' % (bgcol, fgcol, title) - if prelude: - result = result + ''' - - -''' % (bgcol, marginalia, prelude, gap) - else: - result = result + ''' -''' % (bgcol, marginalia, gap) - - return result + '\n
 
-%s
%s%s
%s
%s%s%s
' % contents - - def bigsection(self, title, *args): - """Format a section with a big heading.""" - title = '%s' % title - return self.section(title, *args) - - def preformat(self, text): - """Format literal preformatted text.""" - text = self.escape(expandtabs(text)) - return replace(text, '\n\n', '\n \n', '\n\n', '\n \n', - ' ', ' ', '\n', '
\n') - - def multicolumn(self, list, format, cols=4): - """Format a list of items into a multi-column list.""" - result = '' - rows = (len(list)+cols-1)//cols - for col in range(cols): - result = result + '' % (100//cols) - for i in range(rows*col, rows*col+rows): - if i < len(list): - result = result + format(list[i]) + '
\n' - result = result + '' - return '%s
' % result - - def grey(self, text): return '%s' % text - - def namelink(self, name, *dicts): - """Make a link for an identifier, given name-to-URL mappings.""" - for dict in dicts: - if name in dict: - return '%s' % (dict[name], name) - return name - - def classlink(self, object, modname): - """Make a link for a class.""" - name, module = object.__name__, sys.modules.get(object.__module__) - if hasattr(module, name) and getattr(module, name) is object: - return '%s' % ( - module.__name__, name, classname(object, modname)) - return classname(object, modname) - - def modulelink(self, object): - """Make a link for a module.""" - return '%s' % (object.__name__, object.__name__) - - def modpkglink(self, data): - """Make a link for a module or package to display in an index.""" - name, path, ispackage, shadowed = data - if shadowed: - return self.grey(name) - if path: - url = '%s.%s.html' % (path, name) - else: - url = '%s.html' % name - if ispackage: - text = '%s (package)' % name - else: - text = name - return '%s' % (url, text) - - def markup(self, text, escape=None, funcs={}, classes={}, methods={}): - """Mark up some plain text, given a context of symbols to look for. - Each context dictionary maps object names to anchor names.""" - escape = escape or self.escape - results = [] - here = 0 - pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|' - r'RFC[- ]?(\d+)|' - r'PEP[- ]?(\d+)|' - r'(self\.)?(\w+))') - while True: - match = pattern.search(text, here) - if not match: break - start, end = match.span() - results.append(escape(text[here:start])) - - all, scheme, rfc, pep, selfdot, name = match.groups() - if scheme: - url = escape(all).replace('"', '"') - results.append('%s' % (url, url)) - elif rfc: - url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) - results.append('%s' % (url, escape(all))) - elif pep: - url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep) - results.append('%s' % (url, escape(all))) - elif text[end:end+1] == '(': - results.append(self.namelink(name, methods, funcs, classes)) - elif selfdot: - results.append('self.%s' % name) - else: - results.append(self.namelink(name, classes)) - here = end - results.append(escape(text[here:])) - return join(results, '') - - # ---------------------------------------------- type-specific routines - - def formattree(self, tree, modname, parent=None): - """Produce HTML for a class tree as given by inspect.getclasstree().""" - result = '' - for entry in tree: - if type(entry) is type(()): - c, bases = entry - result = result + '

' - result = result + self.classlink(c, modname) - if bases and bases != (parent,): - parents = [] - for base in bases: - parents.append(self.classlink(base, modname)) - result = result + '(' + join(parents, ', ') + ')' - result = result + '\n
' - elif type(entry) is type([]): - result = result + '
\n%s
\n' % self.formattree( - entry, modname, c) - return '
\n%s
\n' % result - - def docmodule(self, object, name=None, mod=None, *ignored): - """Produce HTML documentation for a module object.""" - name = object.__name__ # ignore the passed-in name - try: - all = object.__all__ - except AttributeError: - all = None - parts = split(name, '.') - links = [] - for i in range(len(parts)-1): - links.append( - '%s' % - (join(parts[:i+1], '.'), parts[i])) - linkedname = join(links + parts[-1:], '.') - head = '%s' % linkedname - try: - path = inspect.getabsfile(object) - url = path - if sys.platform == 'win32': - import nturl2path - url = nturl2path.pathname2url(path) - filelink = '%s' % (url, path) - except TypeError: - filelink = '(built-in)' - info = [] - if hasattr(object, '__version__'): - version = str(object.__version__) - if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': - version = strip(version[11:-1]) - info.append('version %s' % self.escape(version)) - if hasattr(object, '__date__'): - info.append(self.escape(str(object.__date__))) - if info: - head = head + ' (%s)' % join(info, ', ') - docloc = self.getdocloc(object) - if docloc is not None: - docloc = '
Module Docs' % locals() - else: - docloc = '' - result = self.heading( - head, '#ffffff', '#7799ee', - 'index
' + filelink + docloc) - - modules = inspect.getmembers(object, inspect.ismodule) - - classes, cdict = [], {} - for key, value in inspect.getmembers(object, inspect.isclass): - # if __all__ exists, believe it. Otherwise use old heuristic. - if (all is not None or - (inspect.getmodule(value) or object) is object): - if visiblename(key, all, object): - classes.append((key, value)) - cdict[key] = cdict[value] = '#' + key - for key, value in classes: - for base in value.__bases__: - key, modname = base.__name__, base.__module__ - module = sys.modules.get(modname) - if modname != name and module and hasattr(module, key): - if getattr(module, key) is base: - if not key in cdict: - cdict[key] = cdict[base] = modname + '.html#' + key - funcs, fdict = [], {} - for key, value in inspect.getmembers(object, inspect.isroutine): - # if __all__ exists, believe it. Otherwise use old heuristic. - if (all is not None or - inspect.isbuiltin(value) or inspect.getmodule(value) is object): - if visiblename(key, all, object): - funcs.append((key, value)) - fdict[key] = '#-' + key - if inspect.isfunction(value): fdict[value] = fdict[key] - data = [] - for key, value in inspect.getmembers(object, isdata): - if visiblename(key, all, object): - data.append((key, value)) - - doc = self.markup(getdoc(object), self.preformat, fdict, cdict) - doc = doc and '%s' % doc - result = result + '

%s

\n' % doc - - if hasattr(object, '__path__'): - modpkgs = [] - for importer, modname, ispkg in pkgutil.iter_modules(object.__path__): - modpkgs.append((modname, name, ispkg, 0)) - modpkgs.sort() - contents = self.multicolumn(modpkgs, self.modpkglink) - result = result + self.bigsection( - 'Package Contents', '#ffffff', '#aa55cc', contents) - elif modules: - contents = self.multicolumn( - modules, lambda key_value, s=self: s.modulelink(key_value[1])) - result = result + self.bigsection( - 'Modules', '#ffffff', '#aa55cc', contents) - - if classes: - classlist = map(lambda key_value: key_value[1], classes) - contents = [ - self.formattree(inspect.getclasstree(classlist, 1), name)] - for key, value in classes: - contents.append(self.document(value, key, name, fdict, cdict)) - result = result + self.bigsection( - 'Classes', '#ffffff', '#ee77aa', join(contents)) - if funcs: - contents = [] - for key, value in funcs: - contents.append(self.document(value, key, name, fdict, cdict)) - result = result + self.bigsection( - 'Functions', '#ffffff', '#eeaa77', join(contents)) - if data: - contents = [] - for key, value in data: - contents.append(self.document(value, key)) - result = result + self.bigsection( - 'Data', '#ffffff', '#55aa55', join(contents, '
\n')) - if hasattr(object, '__author__'): - contents = self.markup(str(object.__author__), self.preformat) - result = result + self.bigsection( - 'Author', '#ffffff', '#7799ee', contents) - if hasattr(object, '__credits__'): - contents = self.markup(str(object.__credits__), self.preformat) - result = result + self.bigsection( - 'Credits', '#ffffff', '#7799ee', contents) - - return result - - def docclass(self, object, name=None, mod=None, funcs={}, classes={}, - *ignored): - """Produce HTML documentation for a class object.""" - realname = object.__name__ - name = name or realname - bases = object.__bases__ - - contents = [] - push = contents.append - - # Cute little class to pump out a horizontal rule between sections. - class HorizontalRule: - def __init__(self): - self.needone = 0 - def maybe(self): - if self.needone: - push('
\n') - self.needone = 1 - hr = HorizontalRule() - - # List the mro, if non-trivial. - mro = deque(inspect.getmro(object)) - if len(mro) > 2: - hr.maybe() - push('
Method resolution order:
\n') - for base in mro: - push('
%s
\n' % self.classlink(base, - object.__module__)) - push('
\n') - - def spill(msg, attrs, predicate): - ok, attrs = _split_list(attrs, predicate) - if ok: - hr.maybe() - push(msg) - for name, kind, homecls, value in ok: - push(self.document(getattr(object, name), name, mod, - funcs, classes, mdict, object)) - push('\n') - return attrs - - def spilldescriptors(msg, attrs, predicate): - ok, attrs = _split_list(attrs, predicate) - if ok: - hr.maybe() - push(msg) - for name, kind, homecls, value in ok: - push(self._docdescriptor(name, value, mod)) - return attrs - - def spilldata(msg, attrs, predicate): - ok, attrs = _split_list(attrs, predicate) - if ok: - hr.maybe() - push(msg) - for name, kind, homecls, value in ok: - base = self.docother(getattr(object, name), name, mod) - if (hasattr(value, '__call__') or - inspect.isdatadescriptor(value)): - doc = getattr(value, "__doc__", None) - else: - doc = None - if doc is None: - push('
%s
\n' % base) - else: - doc = self.markup(getdoc(value), self.preformat, - funcs, classes, mdict) - doc = '
%s' % doc - push('
%s%s
\n' % (base, doc)) - push('\n') - return attrs - - attrs = filter(lambda data: visiblename(data[0], obj=object), - classify_class_attrs(object)) - mdict = {} - for key, kind, homecls, value in attrs: - mdict[key] = anchor = '#' + name + '-' + key - value = getattr(object, key) - try: - # The value may not be hashable (e.g., a data attr with - # a dict or list value). - mdict[value] = anchor - except TypeError: - pass - - while attrs: - if mro: - thisclass = mro.popleft() - else: - thisclass = attrs[0][2] - attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass) - - if thisclass is __builtin__.object: - attrs = inherited - continue - elif thisclass is object: - tag = 'defined here' - else: - tag = 'inherited from %s' % self.classlink(thisclass, - object.__module__) - tag += ':
\n' - - # Sort attrs by name. - try: - attrs.sort(key=lambda t: t[0]) - except TypeError: - attrs.sort(lambda t1, t2: cmp(t1[0], t2[0])) # 2.3 compat - - # Pump out the attrs, segregated by kind. - attrs = spill('Methods %s' % tag, attrs, - lambda t: t[1] == 'method') - attrs = spill('Class methods %s' % tag, attrs, - lambda t: t[1] == 'class method') - attrs = spill('Static methods %s' % tag, attrs, - lambda t: t[1] == 'static method') - attrs = spilldescriptors('Data descriptors %s' % tag, attrs, - lambda t: t[1] == 'data descriptor') - attrs = spilldata('Data and other attributes %s' % tag, attrs, - lambda t: t[1] == 'data') - assert attrs == [] - attrs = inherited - - contents = ''.join(contents) - - if name == realname: - title = 'class %s' % ( - name, realname) - else: - title = '%s = class %s' % ( - name, name, realname) - if bases: - parents = [] - for base in bases: - parents.append(self.classlink(base, object.__module__)) - title = title + '(%s)' % join(parents, ', ') - doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict) - doc = doc and '%s
 
' % doc - - return self.section(title, '#000000', '#ffc8d8', contents, 3, doc) - - def formatvalue(self, object): - """Format an argument default value as text.""" - return self.grey('=' + self.repr(object)) - - def docroutine(self, object, name=None, mod=None, - funcs={}, classes={}, methods={}, cl=None): - """Produce HTML documentation for a function or method object.""" - realname = object.__name__ - name = name or realname - anchor = (cl and cl.__name__ or '') + '-' + name - note = '' - skipdocs = 0 - if inspect.ismethod(object): - imclass = object.im_class - if cl: - if imclass is not cl: - note = ' from ' + self.classlink(imclass, mod) - else: - if object.im_self is not None: - note = ' method of %s instance' % self.classlink( - object.im_self.__class__, mod) - else: - note = ' unbound %s method' % self.classlink(imclass,mod) - object = object.im_func - - if name == realname: - title = '%s' % (anchor, realname) - else: - if (cl and realname in cl.__dict__ and - cl.__dict__[realname] is object): - reallink = '%s' % ( - cl.__name__ + '-' + realname, realname) - skipdocs = 1 - else: - reallink = realname - title = '%s = %s' % ( - anchor, name, reallink) - if inspect.isfunction(object): - args, varargs, varkw, defaults = inspect.getargspec(object) - argspec = inspect.formatargspec( - args, varargs, varkw, defaults, formatvalue=self.formatvalue) - if realname == '': - title = '%s lambda ' % name - argspec = argspec[1:-1] # remove parentheses - else: - argspec = '(...)' - - decl = title + argspec + (note and self.grey( - '%s' % note)) - - if skipdocs: - return '
%s
\n' % decl - else: - doc = self.markup( - getdoc(object), self.preformat, funcs, classes, methods) - doc = doc and '
%s
' % doc - return '
%s
%s
\n' % (decl, doc) - - def _docdescriptor(self, name, value, mod): - results = [] - push = results.append - - if name: - push('
%s
\n' % name) - if value.__doc__ is not None: - doc = self.markup(getdoc(value), self.preformat) - push('
%s
\n' % doc) - push('
\n') - - return ''.join(results) - - def docproperty(self, object, name=None, mod=None, cl=None): - """Produce html documentation for a property.""" - return self._docdescriptor(name, object, mod) - - def docother(self, object, name=None, mod=None, *ignored): - """Produce HTML documentation for a data object.""" - lhs = name and '%s = ' % name or '' - return lhs + self.repr(object) - - def docdata(self, object, name=None, mod=None, cl=None): - """Produce html documentation for a data descriptor.""" - return self._docdescriptor(name, object, mod) - - def index(self, dir, shadowed=None): - """Generate an HTML index for a directory of modules.""" - modpkgs = [] - if shadowed is None: shadowed = {} - for importer, name, ispkg in pkgutil.iter_modules([dir]): - modpkgs.append((name, '', ispkg, name in shadowed)) - shadowed[name] = 1 - - modpkgs.sort() - contents = self.multicolumn(modpkgs, self.modpkglink) - return self.bigsection(dir, '#ffffff', '#ee77aa', contents) - -# -------------------------------------------- text documentation generator - -class TextRepr(Repr): - """Class for safely making a text representation of a Python object.""" - def __init__(self): - Repr.__init__(self) - self.maxlist = self.maxtuple = 20 - self.maxdict = 10 - self.maxstring = self.maxother = 100 - - def repr1(self, x, level): - if hasattr(type(x), '__name__'): - methodname = 'repr_' + join(split(type(x).__name__), '_') - if hasattr(self, methodname): - return getattr(self, methodname)(x, level) - return cram(stripid(repr(x)), self.maxother) - - def repr_string(self, x, level): - test = cram(x, self.maxstring) - testrepr = repr(test) - if '\\' in test and '\\' not in replace(testrepr, r'\\', ''): - # Backslashes are only literal in the string and are never - # needed to make any special characters, so show a raw string. - return 'r' + testrepr[0] + test + testrepr[0] - return testrepr - - repr_str = repr_string - - def repr_instance(self, x, level): - try: - return cram(stripid(repr(x)), self.maxstring) - except: - return '<%s instance>' % x.__class__.__name__ - -class TextDoc(Doc): - """Formatter class for text documentation.""" - - # ------------------------------------------- text formatting utilities - - _repr_instance = TextRepr() - repr = _repr_instance.repr - - def bold(self, text): - """Format a string in bold by overstriking.""" - return join(map(lambda ch: ch + '\b' + ch, text), '') - - def indent(self, text, prefix=' '): - """Indent text by prepending a given prefix to each line.""" - if not text: return '' - lines = split(text, '\n') - lines = map(lambda line, prefix=prefix: prefix + line, lines) - if lines: lines[-1] = rstrip(lines[-1]) - return join(lines, '\n') - - def section(self, title, contents): - """Format a section with a given heading.""" - return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n' - - # ---------------------------------------------- type-specific routines - - def formattree(self, tree, modname, parent=None, prefix=''): - """Render in text a class tree as returned by inspect.getclasstree().""" - result = '' - for entry in tree: - if type(entry) is type(()): - c, bases = entry - result = result + prefix + classname(c, modname) - if bases and bases != (parent,): - parents = map(lambda c, m=modname: classname(c, m), bases) - result = result + '(%s)' % join(parents, ', ') - result = result + '\n' - elif type(entry) is type([]): - result = result + self.formattree( - entry, modname, c, prefix + ' ') - return result - - def docmodule(self, object, name=None, mod=None): - """Produce text documentation for a given module object.""" - name = object.__name__ # ignore the passed-in name - synop, desc = splitdoc(getdoc(object)) - result = self.section('NAME', name + (synop and ' - ' + synop)) - - try: - all = object.__all__ - except AttributeError: - all = None - - try: - file = inspect.getabsfile(object) - except TypeError: - file = '(built-in)' - result = result + self.section('FILE', file) - - docloc = self.getdocloc(object) - if docloc is not None: - result = result + self.section('MODULE DOCS', docloc) - - if desc: - result = result + self.section('DESCRIPTION', desc) - - classes = [] - for key, value in inspect.getmembers(object, inspect.isclass): - # if __all__ exists, believe it. Otherwise use old heuristic. - if (all is not None - or (inspect.getmodule(value) or object) is object): - if visiblename(key, all, object): - classes.append((key, value)) - funcs = [] - for key, value in inspect.getmembers(object, inspect.isroutine): - # if __all__ exists, believe it. Otherwise use old heuristic. - if (all is not None or - inspect.isbuiltin(value) or inspect.getmodule(value) is object): - if visiblename(key, all, object): - funcs.append((key, value)) - data = [] - for key, value in inspect.getmembers(object, isdata): - if visiblename(key, all, object): - data.append((key, value)) - - modpkgs = [] - modpkgs_names = set() - if hasattr(object, '__path__'): - for importer, modname, ispkg in pkgutil.iter_modules(object.__path__): - modpkgs_names.add(modname) - if ispkg: - modpkgs.append(modname + ' (package)') - else: - modpkgs.append(modname) - - modpkgs.sort() - result = result + self.section( - 'PACKAGE CONTENTS', join(modpkgs, '\n')) - - # Detect submodules as sometimes created by C extensions - submodules = [] - for key, value in inspect.getmembers(object, inspect.ismodule): - if value.__name__.startswith(name + '.') and key not in modpkgs_names: - submodules.append(key) - if submodules: - submodules.sort() - result = result + self.section( - 'SUBMODULES', join(submodules, '\n')) - - if classes: - classlist = map(lambda key_value: key_value[1], classes) - contents = [self.formattree( - inspect.getclasstree(classlist, 1), name)] - for key, value in classes: - contents.append(self.document(value, key, name)) - result = result + self.section('CLASSES', join(contents, '\n')) - - if funcs: - contents = [] - for key, value in funcs: - contents.append(self.document(value, key, name)) - result = result + self.section('FUNCTIONS', join(contents, '\n')) - - if data: - contents = [] - for key, value in data: - contents.append(self.docother(value, key, name, maxlen=70)) - result = result + self.section('DATA', join(contents, '\n')) - - if hasattr(object, '__version__'): - version = str(object.__version__) - if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': - version = strip(version[11:-1]) - result = result + self.section('VERSION', version) - if hasattr(object, '__date__'): - result = result + self.section('DATE', str(object.__date__)) - if hasattr(object, '__author__'): - result = result + self.section('AUTHOR', str(object.__author__)) - if hasattr(object, '__credits__'): - result = result + self.section('CREDITS', str(object.__credits__)) - return result - - def docclass(self, object, name=None, mod=None, *ignored): - """Produce text documentation for a given class object.""" - realname = object.__name__ - name = name or realname - bases = object.__bases__ - - def makename(c, m=object.__module__): - return classname(c, m) - - if name == realname: - title = 'class ' + self.bold(realname) - else: - title = self.bold(name) + ' = class ' + realname - if bases: - parents = map(makename, bases) - title = title + '(%s)' % join(parents, ', ') - - doc = getdoc(object) - contents = doc and [doc + '\n'] or [] - push = contents.append - - # List the mro, if non-trivial. - mro = deque(inspect.getmro(object)) - if len(mro) > 2: - push("Method resolution order:") - for base in mro: - push(' ' + makename(base)) - push('') - - # Cute little class to pump out a horizontal rule between sections. - class HorizontalRule: - def __init__(self): - self.needone = 0 - def maybe(self): - if self.needone: - push('-' * 70) - self.needone = 1 - hr = HorizontalRule() - - def spill(msg, attrs, predicate): - ok, attrs = _split_list(attrs, predicate) - if ok: - hr.maybe() - push(msg) - for name, kind, homecls, value in ok: - push(self.document(getattr(object, name), - name, mod, object)) - return attrs - - def spilldescriptors(msg, attrs, predicate): - ok, attrs = _split_list(attrs, predicate) - if ok: - hr.maybe() - push(msg) - for name, kind, homecls, value in ok: - push(self._docdescriptor(name, value, mod)) - return attrs - - def spilldata(msg, attrs, predicate): - ok, attrs = _split_list(attrs, predicate) - if ok: - hr.maybe() - push(msg) - for name, kind, homecls, value in ok: - if (hasattr(value, '__call__') or - inspect.isdatadescriptor(value)): - doc = getdoc(value) - else: - doc = None - push(self.docother(getattr(object, name), - name, mod, maxlen=70, doc=doc) + '\n') - return attrs - - attrs = filter(lambda data: visiblename(data[0], obj=object), - classify_class_attrs(object)) - while attrs: - if mro: - thisclass = mro.popleft() - else: - thisclass = attrs[0][2] - attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass) - - if thisclass is __builtin__.object: - attrs = inherited - continue - elif thisclass is object: - tag = "defined here" - else: - tag = "inherited from %s" % classname(thisclass, - object.__module__) - - # Sort attrs by name. - attrs.sort() - - # Pump out the attrs, segregated by kind. - attrs = spill("Methods %s:\n" % tag, attrs, - lambda t: t[1] == 'method') - attrs = spill("Class methods %s:\n" % tag, attrs, - lambda t: t[1] == 'class method') - attrs = spill("Static methods %s:\n" % tag, attrs, - lambda t: t[1] == 'static method') - attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs, - lambda t: t[1] == 'data descriptor') - attrs = spilldata("Data and other attributes %s:\n" % tag, attrs, - lambda t: t[1] == 'data') - assert attrs == [] - attrs = inherited - - contents = '\n'.join(contents) - if not contents: - return title + '\n' - return title + '\n' + self.indent(rstrip(contents), ' | ') + '\n' - - def formatvalue(self, object): - """Format an argument default value as text.""" - return '=' + self.repr(object) - - def docroutine(self, object, name=None, mod=None, cl=None): - """Produce text documentation for a function or method object.""" - realname = object.__name__ - name = name or realname - note = '' - skipdocs = 0 - if inspect.ismethod(object): - imclass = object.im_class - if cl: - if imclass is not cl: - note = ' from ' + classname(imclass, mod) - else: - if object.im_self is not None: - note = ' method of %s instance' % classname( - object.im_self.__class__, mod) - else: - note = ' unbound %s method' % classname(imclass,mod) - object = object.im_func - - if name == realname: - title = self.bold(realname) - else: - if (cl and realname in cl.__dict__ and - cl.__dict__[realname] is object): - skipdocs = 1 - title = self.bold(name) + ' = ' + realname - if inspect.isfunction(object): - args, varargs, varkw, defaults = inspect.getargspec(object) - argspec = inspect.formatargspec( - args, varargs, varkw, defaults, formatvalue=self.formatvalue) - if realname == '': - title = self.bold(name) + ' lambda ' - argspec = argspec[1:-1] # remove parentheses - else: - argspec = '(...)' - decl = title + argspec + note - - if skipdocs: - return decl + '\n' - else: - doc = getdoc(object) or '' - return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n') - - def _docdescriptor(self, name, value, mod): - results = [] - push = results.append - - if name: - push(self.bold(name)) - push('\n') - doc = getdoc(value) or '' - if doc: - push(self.indent(doc)) - push('\n') - return ''.join(results) - - def docproperty(self, object, name=None, mod=None, cl=None): - """Produce text documentation for a property.""" - return self._docdescriptor(name, object, mod) - - def docdata(self, object, name=None, mod=None, cl=None): - """Produce text documentation for a data descriptor.""" - return self._docdescriptor(name, object, mod) - - def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None): - """Produce text documentation for a data object.""" - repr = self.repr(object) - if maxlen: - line = (name and name + ' = ' or '') + repr - chop = maxlen - len(line) - if chop < 0: repr = repr[:chop] + '...' - line = (name and self.bold(name) + ' = ' or '') + repr - if doc is not None: - line += '\n' + self.indent(str(doc)) - return line - -# --------------------------------------------------------- user interfaces - -def pager(text): - """The first time this is called, determine what kind of pager to use.""" - global pager - pager = getpager() - pager(text) - -def getpager(): - """Decide what method to use for paging through text.""" - if type(sys.stdout) is not types.FileType: - return plainpager - if not sys.stdin.isatty() or not sys.stdout.isatty(): - return plainpager - if 'PAGER' in os.environ: - if sys.platform == 'win32': # pipes completely broken in Windows - return lambda text: tempfilepager(plain(text), os.environ['PAGER']) - elif sys.platform == 'uefi': - return lambda text: tempfilepager(plain(text), os.environ['PAGER']) - elif os.environ.get('TERM') in ('dumb', 'emacs'): - return lambda text: pipepager(plain(text), os.environ['PAGER']) - else: - return lambda text: pipepager(text, os.environ['PAGER']) - if os.environ.get('TERM') in ('dumb', 'emacs'): - return plainpager - if sys.platform == 'uefi': - return plainpager - if sys.platform == 'win32' or sys.platform.startswith('os2'): - return lambda text: tempfilepager(plain(text), 'more <') - if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0: - return lambda text: pipepager(text, 'less') - - import tempfile - (fd, filename) = tempfile.mkstemp() - os.close(fd) - try: - if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0: - return lambda text: pipepager(text, 'more') - else: - return ttypager - finally: - os.unlink(filename) - -def plain(text): - """Remove boldface formatting from text.""" - return re.sub('.\b', '', text) - -def pipepager(text, cmd): - """Page through text by feeding it to another program.""" - pipe = os.popen(cmd, 'w') - try: - pipe.write(text) - pipe.close() - except IOError: - pass # Ignore broken pipes caused by quitting the pager program. - -def tempfilepager(text, cmd): - """Page through text by invoking a program on a temporary file.""" - import tempfile - filename = tempfile.mktemp() - file = open(filename, 'w') - file.write(text) - file.close() - try: - os.system(cmd + ' "' + filename + '"') - finally: - os.unlink(filename) - -def ttypager(text): - """Page through text on a text terminal.""" - lines = split(plain(text), '\n') - try: - import tty - fd = sys.stdin.fileno() - old = tty.tcgetattr(fd) - tty.setcbreak(fd) - getchar = lambda: sys.stdin.read(1) - except (ImportError, AttributeError): - tty = None - getchar = lambda: sys.stdin.readline()[:-1][:1] - - try: - r = inc = os.environ.get('LINES', 25) - 1 - sys.stdout.write(join(lines[:inc], '\n') + '\n') - while lines[r:]: - sys.stdout.write('-- more --') - sys.stdout.flush() - c = getchar() - - if c in ('q', 'Q'): - sys.stdout.write('\r \r') - break - elif c in ('\r', '\n'): - sys.stdout.write('\r \r' + lines[r] + '\n') - r = r + 1 - continue - if c in ('b', 'B', '\x1b'): - r = r - inc - inc - if r < 0: r = 0 - sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n') - r = r + inc - - finally: - if tty: - tty.tcsetattr(fd, tty.TCSAFLUSH, old) - -def plainpager(text): - """Simply print unformatted text. This is the ultimate fallback.""" - sys.stdout.write(plain(text)) - -def describe(thing): - """Produce a short description of the given thing.""" - if inspect.ismodule(thing): - if thing.__name__ in sys.builtin_module_names: - return 'built-in module ' + thing.__name__ - if hasattr(thing, '__path__'): - return 'package ' + thing.__name__ - else: - return 'module ' + thing.__name__ - if inspect.isbuiltin(thing): - return 'built-in function ' + thing.__name__ - if inspect.isgetsetdescriptor(thing): - return 'getset descriptor %s.%s.%s' % ( - thing.__objclass__.__module__, thing.__objclass__.__name__, - thing.__name__) - if inspect.ismemberdescriptor(thing): - return 'member descriptor %s.%s.%s' % ( - thing.__objclass__.__module__, thing.__objclass__.__name__, - thing.__name__) - if inspect.isclass(thing): - return 'class ' + thing.__name__ - if inspect.isfunction(thing): - return 'function ' + thing.__name__ - if inspect.ismethod(thing): - return 'method ' + thing.__name__ - if type(thing) is types.InstanceType: - return 'instance of ' + thing.__class__.__name__ - return type(thing).__name__ - -def locate(path, forceload=0): - """Locate an object by name or dotted path, importing as necessary.""" - parts = [part for part in split(path, '.') if part] - module, n = None, 0 - while n < len(parts): - nextmodule = safeimport(join(parts[:n+1], '.'), forceload) - if nextmodule: module, n = nextmodule, n + 1 - else: break - if module: - object = module - for part in parts[n:]: - try: object = getattr(object, part) - except AttributeError: return None - return object - else: - if hasattr(__builtin__, path): - return getattr(__builtin__, path) - -# --------------------------------------- interactive interpreter interface - -text = TextDoc() -html = HTMLDoc() - -class _OldStyleClass: pass -_OLD_INSTANCE_TYPE = type(_OldStyleClass()) - -def resolve(thing, forceload=0): - """Given an object or a path to an object, get the object and its name.""" - if isinstance(thing, str): - object = locate(thing, forceload) - if not object: - raise ImportError, 'no Python documentation found for %r' % thing - return object, thing - else: - return thing, getattr(thing, '__name__', None) - -def render_doc(thing, title='Python Library Documentation: %s', forceload=0): - """Render text documentation, given an object or a path to an object.""" - object, name = resolve(thing, forceload) - desc = describe(object) - module = inspect.getmodule(object) - if name and '.' in name: - desc += ' in ' + name[:name.rfind('.')] - elif module and module is not object: - desc += ' in module ' + module.__name__ - if type(object) is _OLD_INSTANCE_TYPE: - # If the passed object is an instance of an old-style class, - # document its available methods instead of its value. - object = object.__class__ - elif not (inspect.ismodule(object) or - inspect.isclass(object) or - inspect.isroutine(object) or - inspect.isgetsetdescriptor(object) or - inspect.ismemberdescriptor(object) or - isinstance(object, property)): - # If the passed object is a piece of data or an instance, - # document its available methods instead of its value. - object = type(object) - desc += ' object' - return title % desc + '\n\n' + text.document(object, name) - -def doc(thing, title='Python Library Documentation: %s', forceload=0): - """Display text documentation, given an object or a path to an object.""" - try: - pager(render_doc(thing, title, forceload)) - except (ImportError, ErrorDuringImport), value: - print value - -def writedoc(thing, forceload=0): - """Write HTML documentation to a file in the current directory.""" - try: - object, name = resolve(thing, forceload) - page = html.page(describe(object), html.document(object, name)) - file = open(name + '.html', 'w') - file.write(page) - file.close() - print 'wrote', name + '.html' - except (ImportError, ErrorDuringImport), value: - print value - -def writedocs(dir, pkgpath='', done=None): - """Write out HTML documentation for all modules in a directory tree.""" - if done is None: done = {} - for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath): - writedoc(modname) - return - -class Helper: - - # These dictionaries map a topic name to either an alias, or a tuple - # (label, seealso-items). The "label" is the label of the corresponding - # section in the .rst file under Doc/ and an index into the dictionary - # in pydoc_data/topics.py. - # - # CAUTION: if you change one of these dictionaries, be sure to adapt the - # list of needed labels in Doc/tools/sphinxext/pyspecific.py and - # regenerate the pydoc_data/topics.py file by running - # make pydoc-topics - # in Doc/ and copying the output file into the Lib/ directory. - - keywords = { - 'and': 'BOOLEAN', - 'as': 'with', - 'assert': ('assert', ''), - 'break': ('break', 'while for'), - 'class': ('class', 'CLASSES SPECIALMETHODS'), - 'continue': ('continue', 'while for'), - 'def': ('function', ''), - 'del': ('del', 'BASICMETHODS'), - 'elif': 'if', - 'else': ('else', 'while for'), - 'except': 'try', - 'exec': ('exec', ''), - 'finally': 'try', - 'for': ('for', 'break continue while'), - 'from': 'import', - 'global': ('global', 'NAMESPACES'), - 'if': ('if', 'TRUTHVALUE'), - 'import': ('import', 'MODULES'), - 'in': ('in', 'SEQUENCEMETHODS2'), - 'is': 'COMPARISON', - 'lambda': ('lambda', 'FUNCTIONS'), - 'not': 'BOOLEAN', - 'or': 'BOOLEAN', - 'pass': ('pass', ''), - 'print': ('print', ''), - 'raise': ('raise', 'EXCEPTIONS'), - 'return': ('return', 'FUNCTIONS'), - 'try': ('try', 'EXCEPTIONS'), - 'while': ('while', 'break continue if TRUTHVALUE'), - 'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'), - 'yield': ('yield', ''), - } - # Either add symbols to this dictionary or to the symbols dictionary - # directly: Whichever is easier. They are merged later. - _symbols_inverse = { - 'STRINGS' : ("'", "'''", "r'", "u'", '"""', '"', 'r"', 'u"'), - 'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&', - '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'), - 'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'), - 'UNARY' : ('-', '~'), - 'AUGMENTEDASSIGNMENT' : ('+=', '-=', '*=', '/=', '%=', '&=', '|=', - '^=', '<<=', '>>=', '**=', '//='), - 'BITWISE' : ('<<', '>>', '&', '|', '^', '~'), - 'COMPLEX' : ('j', 'J') - } - symbols = { - '%': 'OPERATORS FORMATTING', - '**': 'POWER', - ',': 'TUPLES LISTS FUNCTIONS', - '.': 'ATTRIBUTES FLOAT MODULES OBJECTS', - '...': 'ELLIPSIS', - ':': 'SLICINGS DICTIONARYLITERALS', - '@': 'def class', - '\\': 'STRINGS', - '_': 'PRIVATENAMES', - '__': 'PRIVATENAMES SPECIALMETHODS', - '`': 'BACKQUOTES', - '(': 'TUPLES FUNCTIONS CALLS', - ')': 'TUPLES FUNCTIONS CALLS', - '[': 'LISTS SUBSCRIPTS SLICINGS', - ']': 'LISTS SUBSCRIPTS SLICINGS' - } - for topic, symbols_ in _symbols_inverse.iteritems(): - for symbol in symbols_: - topics = symbols.get(symbol, topic) - if topic not in topics: - topics = topics + ' ' + topic - symbols[symbol] = topics - - topics = { - 'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS ' - 'FUNCTIONS CLASSES MODULES FILES inspect'), - 'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING ' - 'TYPES'), - 'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'), - 'FORMATTING': ('formatstrings', 'OPERATORS'), - 'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS ' - 'FORMATTING TYPES'), - 'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'), - 'INTEGER': ('integers', 'int range'), - 'FLOAT': ('floating', 'float math'), - 'COMPLEX': ('imaginary', 'complex cmath'), - 'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'), - 'MAPPINGS': 'DICTIONARIES', - 'FUNCTIONS': ('typesfunctions', 'def TYPES'), - 'METHODS': ('typesmethods', 'class def CLASSES TYPES'), - 'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'), - 'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'), - 'FRAMEOBJECTS': 'TYPES', - 'TRACEBACKS': 'TYPES', - 'NONE': ('bltin-null-object', ''), - 'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'), - 'FILES': ('bltin-file-objects', ''), - 'SPECIALATTRIBUTES': ('specialattrs', ''), - 'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'), - 'MODULES': ('typesmodules', 'import'), - 'PACKAGES': 'import', - 'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN ' - 'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER ' - 'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES ' - 'LISTS DICTIONARIES BACKQUOTES'), - 'OPERATORS': 'EXPRESSIONS', - 'PRECEDENCE': 'EXPRESSIONS', - 'OBJECTS': ('objects', 'TYPES'), - 'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS ' - 'CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS ' - 'SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'), - 'BASICMETHODS': ('customization', 'cmp hash repr str SPECIALMETHODS'), - 'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'), - 'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'), - 'SEQUENCEMETHODS1': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS2 ' - 'SPECIALMETHODS'), - 'SEQUENCEMETHODS2': ('sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 ' - 'SPECIALMETHODS'), - 'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'), - 'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT ' - 'SPECIALMETHODS'), - 'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'), - 'NAMESPACES': ('naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'), - 'DYNAMICFEATURES': ('dynamic-features', ''), - 'SCOPING': 'NAMESPACES', - 'FRAMES': 'NAMESPACES', - 'EXCEPTIONS': ('exceptions', 'try except finally raise'), - 'COERCIONS': ('coercion-rules','CONVERSIONS'), - 'CONVERSIONS': ('conversions', 'COERCIONS'), - 'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'), - 'SPECIALIDENTIFIERS': ('id-classes', ''), - 'PRIVATENAMES': ('atom-identifiers', ''), - 'LITERALS': ('atom-literals', 'STRINGS BACKQUOTES NUMBERS ' - 'TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'), - 'TUPLES': 'SEQUENCES', - 'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'), - 'LISTS': ('typesseq-mutable', 'LISTLITERALS'), - 'LISTLITERALS': ('lists', 'LISTS LITERALS'), - 'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'), - 'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'), - 'BACKQUOTES': ('string-conversions', 'repr str STRINGS LITERALS'), - 'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr ' - 'ATTRIBUTEMETHODS'), - 'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS1'), - 'SLICINGS': ('slicings', 'SEQUENCEMETHODS2'), - 'CALLS': ('calls', 'EXPRESSIONS'), - 'POWER': ('power', 'EXPRESSIONS'), - 'UNARY': ('unary', 'EXPRESSIONS'), - 'BINARY': ('binary', 'EXPRESSIONS'), - 'SHIFTING': ('shifting', 'EXPRESSIONS'), - 'BITWISE': ('bitwise', 'EXPRESSIONS'), - 'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'), - 'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'), - 'ASSERTION': 'assert', - 'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'), - 'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'), - 'DELETION': 'del', - 'PRINTING': 'print', - 'RETURNING': 'return', - 'IMPORTING': 'import', - 'CONDITIONAL': 'if', - 'LOOPING': ('compound', 'for while break continue'), - 'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'), - 'DEBUGGING': ('debugger', 'pdb'), - 'CONTEXTMANAGERS': ('context-managers', 'with'), - } - - def __init__(self, input=None, output=None): - self._input = input - self._output = output - - input = property(lambda self: self._input or sys.stdin) - output = property(lambda self: self._output or sys.stdout) - - def __repr__(self): - if inspect.stack()[1][3] == '?': - self() - return '' - return '' - - _GoInteractive = object() - def __call__(self, request=_GoInteractive): - if request is not self._GoInteractive: - self.help(request) - else: - self.intro() - self.interact() - self.output.write(''' -You are now leaving help and returning to the Python interpreter. -If you want to ask for help on a particular object directly from the -interpreter, you can type "help(object)". Executing "help('string')" -has the same effect as typing a particular string at the help> prompt. -''') - - def interact(self): - self.output.write('\n') - while True: - try: - request = self.getline('help> ') - if not request: break - except (KeyboardInterrupt, EOFError): - break - request = strip(replace(request, '"', '', "'", '')) - if lower(request) in ('q', 'quit'): break - self.help(request) - - def getline(self, prompt): - """Read one line, using raw_input when available.""" - if self.input is sys.stdin: - return raw_input(prompt) - else: - self.output.write(prompt) - self.output.flush() - return self.input.readline() - - def help(self, request): - if type(request) is type(''): - request = request.strip() - if request == 'help': self.intro() - elif request == 'keywords': self.listkeywords() - elif request == 'symbols': self.listsymbols() - elif request == 'topics': self.listtopics() - elif request == 'modules': self.listmodules() - elif request[:8] == 'modules ': - self.listmodules(split(request)[1]) - elif request in self.symbols: self.showsymbol(request) - elif request in self.keywords: self.showtopic(request) - elif request in self.topics: self.showtopic(request) - elif request: doc(request, 'Help on %s:') - elif isinstance(request, Helper): self() - else: doc(request, 'Help on %s:') - self.output.write('\n') - - def intro(self): - self.output.write(''' -Welcome to Python %s! This is the online help utility. - -If this is your first time using Python, you should definitely check out -the tutorial on the Internet at http://docs.python.org/tutorial/. - -Enter the name of any module, keyword, or topic to get help on writing -Python programs and using Python modules. To quit this help utility and -return to the interpreter, just type "quit". - -To get a list of available modules, keywords, or topics, type "modules", -"keywords", or "topics". Each module also comes with a one-line summary -of what it does; to list the modules whose summaries contain a given word -such as "spam", type "modules spam". -''' % sys.version[:3]) - - def list(self, items, columns=4, width=80): - items = items[:] - items.sort() - colw = width / columns - rows = (len(items) + columns - 1) / columns - for row in range(rows): - for col in range(columns): - i = col * rows + row - if i < len(items): - self.output.write(items[i]) - if col < columns - 1: - self.output.write(' ' + ' ' * (colw-1 - len(items[i]))) - self.output.write('\n') - - def listkeywords(self): - self.output.write(''' -Here is a list of the Python keywords. Enter any keyword to get more help. - -''') - self.list(self.keywords.keys()) - - def listsymbols(self): - self.output.write(''' -Here is a list of the punctuation symbols which Python assigns special meaning -to. Enter any symbol to get more help. - -''') - self.list(self.symbols.keys()) - - def listtopics(self): - self.output.write(''' -Here is a list of available topics. Enter any topic name to get more help. - -''') - self.list(self.topics.keys()) - - def showtopic(self, topic, more_xrefs=''): - try: - import pydoc_data.topics - except ImportError: - self.output.write(''' -Sorry, topic and keyword documentation is not available because the -module "pydoc_data.topics" could not be found. -''') - return - target = self.topics.get(topic, self.keywords.get(topic)) - if not target: - self.output.write('no documentation found for %s\n' % repr(topic)) - return - if type(target) is type(''): - return self.showtopic(target, more_xrefs) - - label, xrefs = target - try: - doc = pydoc_data.topics.topics[label] - except KeyError: - self.output.write('no documentation found for %s\n' % repr(topic)) - return - pager(strip(doc) + '\n') - if more_xrefs: - xrefs = (xrefs or '') + ' ' + more_xrefs - if xrefs: - import StringIO, formatter - buffer = StringIO.StringIO() - formatter.DumbWriter(buffer).send_flowing_data( - 'Related help topics: ' + join(split(xrefs), ', ') + '\n') - self.output.write('\n%s\n' % buffer.getvalue()) - - def showsymbol(self, symbol): - target = self.symbols[symbol] - topic, _, xrefs = target.partition(' ') - self.showtopic(topic, xrefs) - - def listmodules(self, key=''): - if key: - self.output.write(''' -Here is a list of matching modules. Enter any module name to get more help. - -''') - apropos(key) - else: - self.output.write(''' -Please wait a moment while I gather a list of all available modules... - -''') - modules = {} - def callback(path, modname, desc, modules=modules): - if modname and modname[-9:] == '.__init__': - modname = modname[:-9] + ' (package)' - if find(modname, '.') < 0: - modules[modname] = 1 - def onerror(modname): - callback(None, modname, None) - ModuleScanner().run(callback, onerror=onerror) - self.list(modules.keys()) - self.output.write(''' -Enter any module name to get more help. Or, type "modules spam" to search -for modules whose descriptions contain the word "spam". -''') - -help = Helper() - -class Scanner: - """A generic tree iterator.""" - def __init__(self, roots, children, descendp): - self.roots = roots[:] - self.state = [] - self.children = children - self.descendp = descendp - - def next(self): - if not self.state: - if not self.roots: - return None - root = self.roots.pop(0) - self.state = [(root, self.children(root))] - node, children = self.state[-1] - if not children: - self.state.pop() - return self.next() - child = children.pop(0) - if self.descendp(child): - self.state.append((child, self.children(child))) - return child - - -class ModuleScanner: - """An interruptible scanner that searches module synopses.""" - - def run(self, callback, key=None, completer=None, onerror=None): - if key: key = lower(key) - self.quit = False - seen = {} - - for modname in sys.builtin_module_names: - if modname != '__main__': - seen[modname] = 1 - if key is None: - callback(None, modname, '') - else: - desc = split(__import__(modname).__doc__ or '', '\n')[0] - if find(lower(modname + ' - ' + desc), key) >= 0: - callback(None, modname, desc) - - for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror): - if self.quit: - break - if key is None: - callback(None, modname, '') - else: - loader = importer.find_module(modname) - if hasattr(loader,'get_source'): - import StringIO - desc = source_synopsis( - StringIO.StringIO(loader.get_source(modname)) - ) or '' - if hasattr(loader,'get_filename'): - path = loader.get_filename(modname) - else: - path = None - else: - module = loader.load_module(modname) - desc = (module.__doc__ or '').splitlines()[0] - path = getattr(module,'__file__',None) - if find(lower(modname + ' - ' + desc), key) >= 0: - callback(path, modname, desc) - - if completer: - completer() - -def apropos(key): - """Print all the one-line module summaries that contain a substring.""" - def callback(path, modname, desc): - if modname[-9:] == '.__init__': - modname = modname[:-9] + ' (package)' - print modname, desc and '- ' + desc - try: import warnings - except ImportError: pass - else: warnings.filterwarnings('ignore') # ignore problems during import - ModuleScanner().run(callback, key) - -# --------------------------------------------------- web browser interface - -def serve(port, callback=None, completer=None): - import BaseHTTPServer, mimetools, select - - # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded. - class Message(mimetools.Message): - def __init__(self, fp, seekable=1): - Message = self.__class__ - Message.__bases__[0].__bases__[0].__init__(self, fp, seekable) - self.encodingheader = self.getheader('content-transfer-encoding') - self.typeheader = self.getheader('content-type') - self.parsetype() - self.parseplist() - - class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler): - def send_document(self, title, contents): - try: - self.send_response(200) - self.send_header('Content-Type', 'text/html') - self.end_headers() - self.wfile.write(html.page(title, contents)) - except IOError: pass - - def do_GET(self): - path = self.path - if path[-5:] == '.html': path = path[:-5] - if path[:1] == '/': path = path[1:] - if path and path != '.': - try: - obj = locate(path, forceload=1) - except ErrorDuringImport, value: - self.send_document(path, html.escape(str(value))) - return - if obj: - self.send_document(describe(obj), html.document(obj, path)) - else: - self.send_document(path, -'no Python documentation found for %s' % repr(path)) - else: - heading = html.heading( -'Python: Index of Modules', -'#ffffff', '#7799ee') - def bltinlink(name): - return '%s' % (name, name) - names = filter(lambda x: x != '__main__', - sys.builtin_module_names) - contents = html.multicolumn(names, bltinlink) - indices = ['

' + html.bigsection( - 'Built-in Modules', '#ffffff', '#ee77aa', contents)] - - seen = {} - for dir in sys.path: - indices.append(html.index(dir, seen)) - contents = heading + join(indices) + '''

- -pydoc by Ka-Ping Yee <ping@lfw.org>''' - self.send_document('Index of Modules', contents) - - def log_message(self, *args): pass - - class DocServer(BaseHTTPServer.HTTPServer): - def __init__(self, port, callback): - host = 'localhost' - self.address = (host, port) - self.url = 'http://%s:%d/' % (host, port) - self.callback = callback - self.base.__init__(self, self.address, self.handler) - - def serve_until_quit(self): - import select - self.quit = False - while not self.quit: - rd, wr, ex = select.select([self.socket.fileno()], [], [], 1) - if rd: self.handle_request() - - def server_activate(self): - self.base.server_activate(self) - if self.callback: self.callback(self) - - DocServer.base = BaseHTTPServer.HTTPServer - DocServer.handler = DocHandler - DocHandler.MessageClass = Message - try: - try: - DocServer(port, callback).serve_until_quit() - except (KeyboardInterrupt, select.error): - pass - finally: - if completer: completer() - -# ----------------------------------------------------- graphical interface - -def gui(): - """Graphical interface (starts web server and pops up a control window).""" - class GUI: - def __init__(self, window, port=7464): - self.window = window - self.server = None - self.scanner = None - - import Tkinter - self.server_frm = Tkinter.Frame(window) - self.title_lbl = Tkinter.Label(self.server_frm, - text='Starting server...\n ') - self.open_btn = Tkinter.Button(self.server_frm, - text='open browser', command=self.open, state='disabled') - self.quit_btn = Tkinter.Button(self.server_frm, - text='quit serving', command=self.quit, state='disabled') - - self.search_frm = Tkinter.Frame(window) - self.search_lbl = Tkinter.Label(self.search_frm, text='Search for') - self.search_ent = Tkinter.Entry(self.search_frm) - self.search_ent.bind('', self.search) - self.stop_btn = Tkinter.Button(self.search_frm, - text='stop', pady=0, command=self.stop, state='disabled') - if sys.platform == 'win32': - # Trying to hide and show this button crashes under Windows. - self.stop_btn.pack(side='right') - - self.window.title('pydoc') - self.window.protocol('WM_DELETE_WINDOW', self.quit) - self.title_lbl.pack(side='top', fill='x') - self.open_btn.pack(side='left', fill='x', expand=1) - self.quit_btn.pack(side='right', fill='x', expand=1) - self.server_frm.pack(side='top', fill='x') - - self.search_lbl.pack(side='left') - self.search_ent.pack(side='right', fill='x', expand=1) - self.search_frm.pack(side='top', fill='x') - self.search_ent.focus_set() - - font = ('helvetica', sys.platform == 'win32' and 8 or 10) - self.result_lst = Tkinter.Listbox(window, font=font, height=6) - self.result_lst.bind('', self.select) - self.result_lst.bind('', self.goto) - self.result_scr = Tkinter.Scrollbar(window, - orient='vertical', command=self.result_lst.yview) - self.result_lst.config(yscrollcommand=self.result_scr.set) - - self.result_frm = Tkinter.Frame(window) - self.goto_btn = Tkinter.Button(self.result_frm, - text='go to selected', command=self.goto) - self.hide_btn = Tkinter.Button(self.result_frm, - text='hide results', command=self.hide) - self.goto_btn.pack(side='left', fill='x', expand=1) - self.hide_btn.pack(side='right', fill='x', expand=1) - - self.window.update() - self.minwidth = self.window.winfo_width() - self.minheight = self.window.winfo_height() - self.bigminheight = (self.server_frm.winfo_reqheight() + - self.search_frm.winfo_reqheight() + - self.result_lst.winfo_reqheight() + - self.result_frm.winfo_reqheight()) - self.bigwidth, self.bigheight = self.minwidth, self.bigminheight - self.expanded = 0 - self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight)) - self.window.wm_minsize(self.minwidth, self.minheight) - self.window.tk.willdispatch() - - import threading - threading.Thread( - target=serve, args=(port, self.ready, self.quit)).start() - - def ready(self, server): - self.server = server - self.title_lbl.config( - text='Python documentation server at\n' + server.url) - self.open_btn.config(state='normal') - self.quit_btn.config(state='normal') - - def open(self, event=None, url=None): - url = url or self.server.url - try: - import webbrowser - webbrowser.open(url) - except ImportError: # pre-webbrowser.py compatibility - if sys.platform == 'win32': - os.system('start "%s"' % url) - else: - rc = os.system('netscape -remote "openURL(%s)" &' % url) - if rc: os.system('netscape "%s" &' % url) - - def quit(self, event=None): - if self.server: - self.server.quit = 1 - self.window.quit() - - def search(self, event=None): - key = self.search_ent.get() - self.stop_btn.pack(side='right') - self.stop_btn.config(state='normal') - self.search_lbl.config(text='Searching for "%s"...' % key) - self.search_ent.forget() - self.search_lbl.pack(side='left') - self.result_lst.delete(0, 'end') - self.goto_btn.config(state='disabled') - self.expand() - - import threading - if self.scanner: - self.scanner.quit = 1 - self.scanner = ModuleScanner() - threading.Thread(target=self.scanner.run, - args=(self.update, key, self.done)).start() - - def update(self, path, modname, desc): - if modname[-9:] == '.__init__': - modname = modname[:-9] + ' (package)' - self.result_lst.insert('end', - modname + ' - ' + (desc or '(no description)')) - - def stop(self, event=None): - if self.scanner: - self.scanner.quit = 1 - self.scanner = None - - def done(self): - self.scanner = None - self.search_lbl.config(text='Search for') - self.search_lbl.pack(side='left') - self.search_ent.pack(side='right', fill='x', expand=1) - if sys.platform != 'win32': self.stop_btn.forget() - self.stop_btn.config(state='disabled') - - def select(self, event=None): - self.goto_btn.config(state='normal') - - def goto(self, event=None): - selection = self.result_lst.curselection() - if selection: - modname = split(self.result_lst.get(selection[0]))[0] - self.open(url=self.server.url + modname + '.html') - - def collapse(self): - if not self.expanded: return - self.result_frm.forget() - self.result_scr.forget() - self.result_lst.forget() - self.bigwidth = self.window.winfo_width() - self.bigheight = self.window.winfo_height() - self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight)) - self.window.wm_minsize(self.minwidth, self.minheight) - self.expanded = 0 - - def expand(self): - if self.expanded: return - self.result_frm.pack(side='bottom', fill='x') - self.result_scr.pack(side='right', fill='y') - self.result_lst.pack(side='top', fill='both', expand=1) - self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight)) - self.window.wm_minsize(self.minwidth, self.bigminheight) - self.expanded = 1 - - def hide(self, event=None): - self.stop() - self.collapse() - - import Tkinter - try: - root = Tkinter.Tk() - # Tk will crash if pythonw.exe has an XP .manifest - # file and the root has is not destroyed explicitly. - # If the problem is ever fixed in Tk, the explicit - # destroy can go. - try: - gui = GUI(root) - root.mainloop() - finally: - root.destroy() - except KeyboardInterrupt: - pass - -# -------------------------------------------------- command-line interface - -def ispath(x): - return isinstance(x, str) and find(x, os.sep) >= 0 - -def cli(): - """Command-line interface (looks at sys.argv to decide what to do).""" - import getopt - class BadUsage: pass - - # Scripts don't get the current directory in their path by default - # unless they are run with the '-m' switch - if '' not in sys.path: - scriptdir = os.path.dirname(sys.argv[0]) - if scriptdir in sys.path: - sys.path.remove(scriptdir) - sys.path.insert(0, '.') - - try: - opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w') - writing = 0 - - for opt, val in opts: - if opt == '-g': - gui() - return - if opt == '-k': - apropos(val) - return - if opt == '-p': - try: - port = int(val) - except ValueError: - raise BadUsage - def ready(server): - print 'pydoc server ready at %s' % server.url - def stopped(): - print 'pydoc server stopped' - serve(port, ready, stopped) - return - if opt == '-w': - writing = 1 - - if not args: raise BadUsage - for arg in args: - if ispath(arg) and not os.path.exists(arg): - print 'file %r does not exist' % arg - break - try: - if ispath(arg) and os.path.isfile(arg): - arg = importfile(arg) - if writing: - if ispath(arg) and os.path.isdir(arg): - writedocs(arg) - else: - writedoc(arg) - else: - help.help(arg) - except ErrorDuringImport, value: - print value - - except (getopt.error, BadUsage): - cmd = os.path.basename(sys.argv[0]) - print """pydoc - the Python documentation tool - -%s ... - Show text documentation on something. may be the name of a - Python keyword, topic, function, module, or package, or a dotted - reference to a class or function within a module or module in a - package. If contains a '%s', it is used as the path to a - Python source file to document. If name is 'keywords', 'topics', - or 'modules', a listing of these things is displayed. - -%s -k - Search for a keyword in the synopsis lines of all available modules. - -%s -p - Start an HTTP server on the given port on the local machine. - -%s -g - Pop up a graphical interface for finding and serving documentation. - -%s -w ... - Write out the HTML documentation for a module to a file in the current - directory. If contains a '%s', it is treated as a filename; if - it names a directory, documentation is written for all the contents. -""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep) - -if __name__ == '__main__': cli() diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Lib/site.py b/AppPkg/Applications/Python/PyMod-2.7.2/Lib/site.py deleted file mode 100644 index 5525d4a..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Lib/site.py +++ /dev/null @@ -1,537 +0,0 @@ -"""Append module search paths for third-party packages to sys.path. - -**************************************************************** -* This module is automatically imported during initialization. * -**************************************************************** - -This is a UEFI-specific version of site.py. - -In earlier versions of Python (up to 1.5a3), scripts or modules that -needed to use site-specific modules would place ``import site'' -somewhere near the top of their code. Because of the automatic -import, this is no longer necessary (but code that does it still -works). - -This will append site-specific paths to the module search path. It -starts with sys.prefix and sys.exec_prefix (if different) and appends -lib/python/site-packages as well as lib/site-python. -The resulting directories, if they exist, are appended to sys.path, -and also inspected for path configuration files. - -A path configuration file is a file whose name has the form -.pth; its contents are additional directories (one per line) -to be added to sys.path. Non-existing directories (or -non-directories) are never added to sys.path; no directory is added to -sys.path more than once. Blank lines and lines beginning with -'#' are skipped. Lines starting with 'import' are executed. - -For example, suppose sys.prefix and sys.exec_prefix are set to -/Efi/StdLib and there is a directory /Efi/StdLib/lib/python2.7/site-packages -with three subdirectories, foo, bar and spam, and two path -configuration files, foo.pth and bar.pth. Assume foo.pth contains the -following: - - # foo package configuration - foo - bar - bletch - -and bar.pth contains: - - # bar package configuration - bar - -Then the following directories are added to sys.path, in this order: - - /Efi/StdLib/lib/python2.7/site-packages/bar - /Efi/StdLib/lib/python2.7/site-packages/foo - -Note that bletch is omitted because it doesn't exist; bar precedes foo -because bar.pth comes alphabetically before foo.pth; and spam is -omitted because it is not mentioned in either path configuration file. - -After these path manipulations, an attempt is made to import a module -named sitecustomize, which can perform arbitrary additional -site-specific customizations. If this import fails with an -ImportError exception, it is silently ignored. - -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. -""" - -import sys -import os -import __builtin__ -import traceback - -# Prefixes for site-packages; add additional prefixes like /usr/local here -PREFIXES = [sys.prefix, sys.exec_prefix] -# Enable per user site-packages directory -# set it to False to disable the feature or True to force the feature -ENABLE_USER_SITE = False - -# for distutils.commands.install -# These values are initialized by the getuserbase() and getusersitepackages() -# functions, through the main() function when Python starts. -USER_SITE = None -USER_BASE = None - - -def makepath(*paths): - dir = os.path.join(*paths) - try: - dir = os.path.abspath(dir) - except OSError: - pass - return dir, os.path.normcase(dir) - - -def abs__file__(): - """Set all module' __file__ attribute to an absolute path""" - for m in sys.modules.values(): - if hasattr(m, '__loader__'): - continue # don't mess with a PEP 302-supplied __file__ - try: - m.__file__ = os.path.abspath(m.__file__) - except (AttributeError, OSError): - pass - - -def removeduppaths(): - """ Remove duplicate entries from sys.path along with making them - absolute""" - # This ensures that the initial path provided by the interpreter contains - # only absolute pathnames, even if we're running from the build directory. - L = [] - known_paths = set() - for dir in sys.path: - # Filter out duplicate paths (on case-insensitive file systems also - # if they only differ in case); turn relative paths into absolute - # paths. - dir, dircase = makepath(dir) - if not dircase in known_paths: - L.append(dir) - known_paths.add(dircase) - sys.path[:] = L - return known_paths - - -def _init_pathinfo(): - """Return a set containing all existing directory entries from sys.path""" - d = set() - for dir in sys.path: - try: - if os.path.isdir(dir): - dir, dircase = makepath(dir) - d.add(dircase) - except TypeError: - continue - return d - - -def addpackage(sitedir, name, known_paths): - """Process a .pth file within the site-packages directory: - For each line in the file, either combine it with sitedir to a path - and add that to known_paths, or execute it if it starts with 'import '. - """ - if known_paths is None: - _init_pathinfo() - reset = 1 - else: - reset = 0 - fullname = os.path.join(sitedir, name) - try: - f = open(fullname, "rU") - except IOError: - return - with f: - for n, line in enumerate(f): - if line.startswith("#"): - continue - try: - if line.startswith(("import ", "import\t")): - exec line - continue - line = line.rstrip() - dir, dircase = makepath(sitedir, line) - if not dircase in known_paths and os.path.exists(dir): - sys.path.append(dir) - known_paths.add(dircase) - except Exception as err: - print >>sys.stderr, "Error processing line {:d} of {}:\n".format( - n+1, fullname) - for record in traceback.format_exception(*sys.exc_info()): - for line in record.splitlines(): - print >>sys.stderr, ' '+line - print >>sys.stderr, "\nRemainder of file ignored" - break - if reset: - known_paths = None - return known_paths - - -def addsitedir(sitedir, known_paths=None): - """Add 'sitedir' argument to sys.path if missing and handle .pth files in - 'sitedir'""" - if known_paths is None: - known_paths = _init_pathinfo() - reset = 1 - else: - reset = 0 - sitedir, sitedircase = makepath(sitedir) - if not sitedircase in known_paths: - sys.path.append(sitedir) # Add path component - try: - names = os.listdir(sitedir) - except os.error: - return - dotpth = os.extsep + "pth" - names = [name for name in names if name.endswith(dotpth)] - for name in sorted(names): - addpackage(sitedir, name, known_paths) - if reset: - known_paths = None - return known_paths - - -def check_enableusersite(): - """Check if user site directory is safe for inclusion - - The function tests for the command line flag (including environment var), - process uid/gid equal to effective uid/gid. - - None: Disabled for security reasons - False: Disabled by user (command line option) - True: Safe and enabled - """ - if sys.flags.no_user_site: - return False - - if hasattr(os, "getuid") and hasattr(os, "geteuid"): - # check process uid == effective uid - if os.geteuid() != os.getuid(): - return None - if hasattr(os, "getgid") and hasattr(os, "getegid"): - # check process gid == effective gid - if os.getegid() != os.getgid(): - return None - - return True - -def getuserbase(): - """Returns the `user base` directory path. - - The `user base` directory can be used to store data. If the global - variable ``USER_BASE`` is not initialized yet, this function will also set - it. - """ - global USER_BASE - if USER_BASE is not None: - return USER_BASE - from sysconfig import get_config_var - USER_BASE = get_config_var('userbase') - return USER_BASE - -def getusersitepackages(): - """Returns the user-specific site-packages directory path. - - If the global variable ``USER_SITE`` is not initialized yet, this - function will also set it. - """ - global USER_SITE - user_base = getuserbase() # this will also set USER_BASE - - if USER_SITE is not None: - return USER_SITE - - from sysconfig import get_path - import os - - USER_SITE = get_path('purelib', '%s_user' % os.name) - return USER_SITE - -def addusersitepackages(known_paths): - """Add a per user site-package to sys.path - - Each user has its own python directory with site-packages in the - home directory. - """ - # get the per user site-package path - # this call will also make sure USER_BASE and USER_SITE are set - user_site = getusersitepackages() - - if ENABLE_USER_SITE and os.path.isdir(user_site): - addsitedir(user_site, known_paths) - return known_paths - -def getsitepackages(): - """Returns a list containing all global site-packages directories - (and possibly site-python). - - For each directory present in the global ``PREFIXES``, this function - will find its `site-packages` subdirectory depending on the system - environment, and will return a list of full paths. - """ - sitepackages = [] - seen = set() - - for prefix in PREFIXES: - if not prefix or prefix in seen: - continue - seen.add(prefix) - - sitepackages.append(os.path.join(prefix, "lib", - "python." + sys.version[0] + sys.version[2], - "site-packages")) - sitepackages.append(os.path.join(prefix, "lib", "site-python")) - return sitepackages - -def addsitepackages(known_paths): - """Add site-packages (and possibly site-python) to sys.path""" - for sitedir in getsitepackages(): - if os.path.isdir(sitedir): - addsitedir(sitedir, known_paths) - - return known_paths - -def setBEGINLIBPATH(): - """The UEFI port has optional extension modules that do double duty - as DLLs (even though they have .efi file extensions) for other extensions. - The library search path needs to be amended so these will be found - during module import. Use BEGINLIBPATH so that these are at the start - of the library search path. - - """ - dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload") - libpath = os.environ['BEGINLIBPATH'].split(os.path.pathsep) - if libpath[-1]: - libpath.append(dllpath) - else: - libpath[-1] = dllpath - os.environ['BEGINLIBPATH'] = os.path.pathsep.join(libpath) - - -def setquit(): - """Define new builtins 'quit' and 'exit'. - - These are objects which make the interpreter exit when called. - The repr of each object contains a hint at how it works. - - """ - eof = 'Ctrl-D (i.e. EOF)' - - class Quitter(object): - def __init__(self, name): - self.name = name - def __repr__(self): - return 'Use %s() or %s to exit' % (self.name, eof) - def __call__(self, code=None): - # Shells like IDLE catch the SystemExit, but listen when their - # stdin wrapper is closed. - try: - sys.stdin.close() - except: - pass - raise SystemExit(code) - __builtin__.quit = Quitter('quit') - __builtin__.exit = Quitter('exit') - - -class _Printer(object): - """interactive prompt objects for printing the license text, a list of - contributors and the copyright notice.""" - - MAXLINES = 23 - - def __init__(self, name, data, files=(), dirs=()): - self.__name = name - self.__data = data - self.__files = files - self.__dirs = dirs - self.__lines = None - - def __setup(self): - if self.__lines: - return - data = None - for dir in self.__dirs: - for filename in self.__files: - filename = os.path.join(dir, filename) - try: - fp = file(filename, "rU") - data = fp.read() - fp.close() - break - except IOError: - pass - if data: - break - if not data: - data = self.__data - self.__lines = data.split('\n') - self.__linecnt = len(self.__lines) - - def __repr__(self): - self.__setup() - if len(self.__lines) <= self.MAXLINES: - return "\n".join(self.__lines) - else: - return "Type %s() to see the full %s text" % ((self.__name,)*2) - - def __call__(self): - self.__setup() - prompt = 'Hit Return for more, or q (and Return) to quit: ' - lineno = 0 - while 1: - try: - for i in range(lineno, lineno + self.MAXLINES): - print self.__lines[i] - except IndexError: - break - else: - lineno += self.MAXLINES - key = None - while key is None: - key = raw_input(prompt) - if key not in ('', 'q'): - key = None - if key == 'q': - break - -def setcopyright(): - """Set 'copyright' and 'credits' in __builtin__""" - __builtin__.copyright = _Printer("copyright", sys.copyright) - __builtin__.credits = _Printer("credits", """\ - Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands - for supporting Python development. See www.python.org for more information.""") - here = os.path.dirname(os.__file__) - __builtin__.license = _Printer( - "license", "See http://www.python.org/%.3s/license.html" % sys.version, - ["LICENSE.txt", "LICENSE"], - [os.path.join(here, os.pardir), here, os.curdir]) - - -class _Helper(object): - """Define the builtin 'help'. - This is a wrapper around pydoc.help (with a twist). - - """ - - def __repr__(self): - return "Type help() for interactive help, " \ - "or help(object) for help about object." - - def __call__(self, *args, **kwds): - import pydoc - return pydoc.help(*args, **kwds) - -def sethelper(): - __builtin__.help = _Helper() - -#### -# Keep around for future mbcs support. -#### -#def aliasmbcs(): -# """On Windows, some default encodings are not provided by Python, -# while they are always available as "mbcs" in each locale. Make -# them usable by aliasing to "mbcs" in such a case.""" -# if sys.platform == 'win32': -# import locale, codecs -# enc = locale.getdefaultlocale()[1] -# if enc.startswith('cp'): # "cp***" ? -# try: -# codecs.lookup(enc) -# except LookupError: -# import encodings -# encodings._cache[enc] = encodings._unknown -# encodings.aliases.aliases[enc] = 'mbcs' - -def setencoding(): - """Set the string encoding used by the Unicode implementation. The - default is 'ascii', but if you're willing to experiment, you can - change this.""" - encoding = "ascii" # Default value set by _PyUnicode_Init() - if 0: - # Enable to support locale aware default string encodings. - import locale - loc = locale.getdefaultlocale() - if loc[1]: - encoding = loc[1] - if 0: - # Enable to switch off string to Unicode coercion and implicit - # Unicode to string conversion. - encoding = "undefined" - if encoding != "ascii": - # On Non-Unicode builds this will raise an AttributeError... - sys.setdefaultencoding(encoding) # Needs Python Unicode build ! - - -def execsitecustomize(): - """Run custom site specific code, if available.""" - try: - import sitecustomize - except ImportError: - pass - except Exception: - if sys.flags.verbose: - sys.excepthook(*sys.exc_info()) - else: - print >>sys.stderr, \ - "'import sitecustomize' failed; use -v for traceback" - - -def execusercustomize(): - """Run custom user specific code, if available.""" - try: - import usercustomize - except ImportError: - pass - except Exception: - if sys.flags.verbose: - sys.excepthook(*sys.exc_info()) - else: - print>>sys.stderr, \ - "'import usercustomize' failed; use -v for traceback" - - -def main(): - abs__file__() - known_paths = removeduppaths() - known_paths = addsitepackages(known_paths) - setquit() - setcopyright() - sethelper() -# aliasmbcs() - setencoding() - execsitecustomize() - # Remove sys.setdefaultencoding() so that users cannot change the - # encoding after initialization. The test for presence is needed when - # this module is run as a script, because this code is executed twice. - if hasattr(sys, "setdefaultencoding"): - del sys.setdefaultencoding - -main() - -def _script(): - help = """\ - %s - - Path elements are normally separated by '%s'. - """ - print "sys.path = [" - for dir in sys.path: - print " %r," % (dir,) - print "]" - - import textwrap - print textwrap.dedent(help % (sys.argv[0], os.pathsep)) - sys.exit(0) - -if __name__ == '__main__': - _script() diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/_sre.c b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/_sre.c deleted file mode 100644 index 3bad991..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/_sre.c +++ /dev/null @@ -1,3921 +0,0 @@ -/* - * Secret Labs' Regular Expression Engine - * - * regular expression matching engine - - 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. - * - * partial history: - * 1999-10-24 fl created (based on existing template matcher code) - * 2000-03-06 fl first alpha, sort of - * 2000-08-01 fl fixes for 1.6b1 - * 2000-08-07 fl use PyOS_CheckStack() if available - * 2000-09-20 fl added expand method - * 2001-03-20 fl lots of fixes for 2.1b2 - * 2001-04-15 fl export copyright as Python attribute, not global - * 2001-04-28 fl added __copy__ methods (work in progress) - * 2001-05-14 fl fixes for 1.5.2 compatibility - * 2001-07-01 fl added BIGCHARSET support (from Martin von Loewis) - * 2001-10-18 fl fixed group reset issue (from Matthew Mueller) - * 2001-10-20 fl added split primitive; reenable unicode for 1.6/2.0/2.1 - * 2001-10-21 fl added sub/subn primitive - * 2001-10-24 fl added finditer primitive (for 2.2 only) - * 2001-12-07 fl fixed memory leak in sub/subn (Guido van Rossum) - * 2002-11-09 fl fixed empty sub/subn return type - * 2003-04-18 mvl fully support 4-byte codes - * 2003-10-17 gn implemented non recursive scheme - * - * Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved. - * - * This version of the SRE library can be redistributed under CNRI's - * Python 1.6 license. For any other use, please contact Secret Labs - * AB (info@pythonware.com). - * - * Portions of this engine have been developed in cooperation with - * CNRI. Hewlett-Packard provided funding for 1.6 integration and - * other compatibility work. - */ - -/* Get rid of these macros to prevent collisions between EFI and Python in this file. */ -#undef RETURN_ERROR -#undef RETURN_SUCCESS - -#ifndef SRE_RECURSIVE - -static char copyright[] = - " SRE 2.2.2 Copyright (c) 1997-2002 by Secret Labs AB "; - -#define PY_SSIZE_T_CLEAN - -#include "Python.h" -#include "structmember.h" /* offsetof */ - -#include "sre.h" - -#include - -/* name of this module, minus the leading underscore */ -#if !defined(SRE_MODULE) -#define SRE_MODULE "sre" -#endif - -#define SRE_PY_MODULE "re" - -/* defining this one enables tracing */ -#undef VERBOSE - -#if PY_VERSION_HEX >= 0x01060000 -#if PY_VERSION_HEX < 0x02020000 || defined(Py_USING_UNICODE) -/* defining this enables unicode support (default under 1.6a1 and later) */ -#define HAVE_UNICODE -#endif -#endif - -/* -------------------------------------------------------------------- */ -/* optional features */ - -/* enables fast searching */ -#define USE_FAST_SEARCH - -/* enables aggressive inlining (always on for Visual C) */ -#undef USE_INLINE - -/* enables copy/deepcopy handling (work in progress) */ -#undef USE_BUILTIN_COPY - -#if PY_VERSION_HEX < 0x01060000 -#define PyObject_DEL(op) PyMem_DEL((op)) -#endif - -/* -------------------------------------------------------------------- */ - -#if defined(_MSC_VER) -#pragma optimize("gt", on) /* doesn't seem to make much difference... */ -#pragma warning(disable: 4710) /* who cares if functions are not inlined ;-) */ -/* fastest possible local call under MSVC */ -#define LOCAL(type) static __inline type __fastcall -#elif defined(USE_INLINE) -#define LOCAL(type) static inline type -#else -#define LOCAL(type) static type -#endif - -/* error codes */ -#define SRE_ERROR_ILLEGAL -1 /* illegal opcode */ -#define SRE_ERROR_STATE -2 /* illegal state */ -#define SRE_ERROR_RECURSION_LIMIT -3 /* runaway recursion */ -#define SRE_ERROR_MEMORY -9 /* out of memory */ -#define SRE_ERROR_INTERRUPTED -10 /* signal handler raised exception */ - -#if defined(VERBOSE) -#define TRACE(v) printf v -#else -#define TRACE(v) -#endif - -/* -------------------------------------------------------------------- */ -/* search engine state */ - -/* default character predicates (run sre_chars.py to regenerate tables) */ - -#define SRE_DIGIT_MASK 1 -#define SRE_SPACE_MASK 2 -#define SRE_LINEBREAK_MASK 4 -#define SRE_ALNUM_MASK 8 -#define SRE_WORD_MASK 16 - -/* FIXME: this assumes ASCII. create tables in init_sre() instead */ - -static char sre_char_info[128] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 2, -2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 25, 25, 25, 25, 25, 25, 25, -25, 25, 0, 0, 0, 0, 0, 0, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, -24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, -0, 0, 16, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, -24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 0, 0, 0 }; - -static char sre_char_lower[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, -27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, -44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, -61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, -108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, -122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, -106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, -120, 121, 122, 123, 124, 125, 126, 127 }; - -#define SRE_IS_DIGIT(ch)\ - ((ch) < 128 ? (sre_char_info[(ch)] & SRE_DIGIT_MASK) : 0) -#define SRE_IS_SPACE(ch)\ - ((ch) < 128 ? (sre_char_info[(ch)] & SRE_SPACE_MASK) : 0) -#define SRE_IS_LINEBREAK(ch)\ - ((ch) < 128 ? (sre_char_info[(ch)] & SRE_LINEBREAK_MASK) : 0) -#define SRE_IS_ALNUM(ch)\ - ((ch) < 128 ? (sre_char_info[(ch)] & SRE_ALNUM_MASK) : 0) -#define SRE_IS_WORD(ch)\ - ((ch) < 128 ? (sre_char_info[(ch)] & SRE_WORD_MASK) : 0) - -static unsigned int sre_lower(unsigned int ch) -{ - return ((ch) < 128 ? (unsigned int)sre_char_lower[ch] : ch); -} - -/* locale-specific character predicates */ -/* !(c & ~N) == (c < N+1) for any unsigned c, this avoids - * warnings when c's type supports only numbers < N+1 */ -#define SRE_LOC_IS_DIGIT(ch) (!((ch) & ~255) ? isdigit((ch)) : 0) -#define SRE_LOC_IS_SPACE(ch) (!((ch) & ~255) ? isspace((ch)) : 0) -#define SRE_LOC_IS_LINEBREAK(ch) ((ch) == '\n') -#define SRE_LOC_IS_ALNUM(ch) (!((ch) & ~255) ? isalnum((ch)) : 0) -#define SRE_LOC_IS_WORD(ch) (SRE_LOC_IS_ALNUM((ch)) || (ch) == '_') - -static unsigned int sre_lower_locale(unsigned int ch) -{ - return ((ch) < 256 ? (unsigned int)tolower((ch)) : ch); -} - -/* unicode-specific character predicates */ - -#if defined(HAVE_UNICODE) - -#define SRE_UNI_IS_DIGIT(ch) Py_UNICODE_ISDECIMAL((Py_UNICODE)(ch)) -#define SRE_UNI_IS_SPACE(ch) Py_UNICODE_ISSPACE((Py_UNICODE)(ch)) -#define SRE_UNI_IS_LINEBREAK(ch) Py_UNICODE_ISLINEBREAK((Py_UNICODE)(ch)) -#define SRE_UNI_IS_ALNUM(ch) Py_UNICODE_ISALNUM((Py_UNICODE)(ch)) -#define SRE_UNI_IS_WORD(ch) (SRE_UNI_IS_ALNUM((ch)) || (ch) == '_') - -static unsigned int sre_lower_unicode(unsigned int ch) -{ - return (unsigned int) Py_UNICODE_TOLOWER((Py_UNICODE)(ch)); -} - -#endif - -LOCAL(int) -sre_category(SRE_CODE category, unsigned int ch) -{ - switch (category) { - - case SRE_CATEGORY_DIGIT: - return SRE_IS_DIGIT(ch); - case SRE_CATEGORY_NOT_DIGIT: - return !SRE_IS_DIGIT(ch); - case SRE_CATEGORY_SPACE: - return SRE_IS_SPACE(ch); - case SRE_CATEGORY_NOT_SPACE: - return !SRE_IS_SPACE(ch); - case SRE_CATEGORY_WORD: - return SRE_IS_WORD(ch); - case SRE_CATEGORY_NOT_WORD: - return !SRE_IS_WORD(ch); - case SRE_CATEGORY_LINEBREAK: - return SRE_IS_LINEBREAK(ch); - case SRE_CATEGORY_NOT_LINEBREAK: - return !SRE_IS_LINEBREAK(ch); - - case SRE_CATEGORY_LOC_WORD: - return SRE_LOC_IS_WORD(ch); - case SRE_CATEGORY_LOC_NOT_WORD: - return !SRE_LOC_IS_WORD(ch); - -#if defined(HAVE_UNICODE) - case SRE_CATEGORY_UNI_DIGIT: - return SRE_UNI_IS_DIGIT(ch); - case SRE_CATEGORY_UNI_NOT_DIGIT: - return !SRE_UNI_IS_DIGIT(ch); - case SRE_CATEGORY_UNI_SPACE: - return SRE_UNI_IS_SPACE(ch); - case SRE_CATEGORY_UNI_NOT_SPACE: - return !SRE_UNI_IS_SPACE(ch); - case SRE_CATEGORY_UNI_WORD: - return SRE_UNI_IS_WORD(ch); - case SRE_CATEGORY_UNI_NOT_WORD: - return !SRE_UNI_IS_WORD(ch); - case SRE_CATEGORY_UNI_LINEBREAK: - return SRE_UNI_IS_LINEBREAK(ch); - case SRE_CATEGORY_UNI_NOT_LINEBREAK: - return !SRE_UNI_IS_LINEBREAK(ch); -#else - case SRE_CATEGORY_UNI_DIGIT: - return SRE_IS_DIGIT(ch); - case SRE_CATEGORY_UNI_NOT_DIGIT: - return !SRE_IS_DIGIT(ch); - case SRE_CATEGORY_UNI_SPACE: - return SRE_IS_SPACE(ch); - case SRE_CATEGORY_UNI_NOT_SPACE: - return !SRE_IS_SPACE(ch); - case SRE_CATEGORY_UNI_WORD: - return SRE_LOC_IS_WORD(ch); - case SRE_CATEGORY_UNI_NOT_WORD: - return !SRE_LOC_IS_WORD(ch); - case SRE_CATEGORY_UNI_LINEBREAK: - return SRE_IS_LINEBREAK(ch); - case SRE_CATEGORY_UNI_NOT_LINEBREAK: - return !SRE_IS_LINEBREAK(ch); -#endif - } - return 0; -} - -/* helpers */ - -static void -data_stack_dealloc(SRE_STATE* state) -{ - if (state->data_stack) { - PyMem_FREE(state->data_stack); - state->data_stack = NULL; - } - state->data_stack_size = state->data_stack_base = 0; -} - -static int -data_stack_grow(SRE_STATE* state, Py_ssize_t size) -{ - Py_ssize_t minsize, cursize; - minsize = state->data_stack_base+size; - cursize = state->data_stack_size; - if (cursize < minsize) { - void* stack; - cursize = minsize+minsize/4+1024; - TRACE(("allocate/grow stack %d\n", cursize)); - stack = PyMem_REALLOC(state->data_stack, cursize); - if (!stack) { - data_stack_dealloc(state); - return SRE_ERROR_MEMORY; - } - state->data_stack = (char *)stack; - state->data_stack_size = cursize; - } - return 0; -} - -/* generate 8-bit version */ - -#define SRE_CHAR unsigned char -#define SRE_AT sre_at -#define SRE_COUNT sre_count -#define SRE_CHARSET sre_charset -#define SRE_INFO sre_info -#define SRE_MATCH sre_match -#define SRE_MATCH_CONTEXT sre_match_context -#define SRE_SEARCH sre_search -#define SRE_LITERAL_TEMPLATE sre_literal_template - -#if defined(HAVE_UNICODE) - -#define SRE_RECURSIVE -#include "_sre.c" -#undef SRE_RECURSIVE - -#undef SRE_LITERAL_TEMPLATE -#undef SRE_SEARCH -#undef SRE_MATCH -#undef SRE_MATCH_CONTEXT -#undef SRE_INFO -#undef SRE_CHARSET -#undef SRE_COUNT -#undef SRE_AT -#undef SRE_CHAR - -/* generate 16-bit unicode version */ - -#define SRE_CHAR Py_UNICODE -#define SRE_AT sre_uat -#define SRE_COUNT sre_ucount -#define SRE_CHARSET sre_ucharset -#define SRE_INFO sre_uinfo -#define SRE_MATCH sre_umatch -#define SRE_MATCH_CONTEXT sre_umatch_context -#define SRE_SEARCH sre_usearch -#define SRE_LITERAL_TEMPLATE sre_uliteral_template -#endif - -#endif /* SRE_RECURSIVE */ - -/* -------------------------------------------------------------------- */ -/* String matching engine */ - -/* the following section is compiled twice, with different character - settings */ - -LOCAL(int) -SRE_AT(SRE_STATE* state, SRE_CHAR* ptr, SRE_CODE at) -{ - /* check if pointer is at given position */ - - Py_ssize_t thisp, thatp; - - switch (at) { - - case SRE_AT_BEGINNING: - case SRE_AT_BEGINNING_STRING: - return ((void*) ptr == state->beginning); - - case SRE_AT_BEGINNING_LINE: - return ((void*) ptr == state->beginning || - SRE_IS_LINEBREAK((int) ptr[-1])); - - case SRE_AT_END: - return (((void*) (ptr+1) == state->end && - SRE_IS_LINEBREAK((int) ptr[0])) || - ((void*) ptr == state->end)); - - case SRE_AT_END_LINE: - return ((void*) ptr == state->end || - SRE_IS_LINEBREAK((int) ptr[0])); - - case SRE_AT_END_STRING: - return ((void*) ptr == state->end); - - case SRE_AT_BOUNDARY: - if (state->beginning == state->end) - return 0; - thatp = ((void*) ptr > state->beginning) ? - SRE_IS_WORD((int) ptr[-1]) : 0; - thisp = ((void*) ptr < state->end) ? - SRE_IS_WORD((int) ptr[0]) : 0; - return thisp != thatp; - - case SRE_AT_NON_BOUNDARY: - if (state->beginning == state->end) - return 0; - thatp = ((void*) ptr > state->beginning) ? - SRE_IS_WORD((int) ptr[-1]) : 0; - thisp = ((void*) ptr < state->end) ? - SRE_IS_WORD((int) ptr[0]) : 0; - return thisp == thatp; - - case SRE_AT_LOC_BOUNDARY: - if (state->beginning == state->end) - return 0; - thatp = ((void*) ptr > state->beginning) ? - SRE_LOC_IS_WORD((int) ptr[-1]) : 0; - thisp = ((void*) ptr < state->end) ? - SRE_LOC_IS_WORD((int) ptr[0]) : 0; - return thisp != thatp; - - case SRE_AT_LOC_NON_BOUNDARY: - if (state->beginning == state->end) - return 0; - thatp = ((void*) ptr > state->beginning) ? - SRE_LOC_IS_WORD((int) ptr[-1]) : 0; - thisp = ((void*) ptr < state->end) ? - SRE_LOC_IS_WORD((int) ptr[0]) : 0; - return thisp == thatp; - -#if defined(HAVE_UNICODE) - case SRE_AT_UNI_BOUNDARY: - if (state->beginning == state->end) - return 0; - thatp = ((void*) ptr > state->beginning) ? - SRE_UNI_IS_WORD((int) ptr[-1]) : 0; - thisp = ((void*) ptr < state->end) ? - SRE_UNI_IS_WORD((int) ptr[0]) : 0; - return thisp != thatp; - - case SRE_AT_UNI_NON_BOUNDARY: - if (state->beginning == state->end) - return 0; - thatp = ((void*) ptr > state->beginning) ? - SRE_UNI_IS_WORD((int) ptr[-1]) : 0; - thisp = ((void*) ptr < state->end) ? - SRE_UNI_IS_WORD((int) ptr[0]) : 0; - return thisp == thatp; -#endif - - } - - return 0; -} - -LOCAL(int) -SRE_CHARSET(SRE_CODE* set, SRE_CODE ch) -{ - /* check if character is a member of the given set */ - - int ok = 1; - - for (;;) { - switch (*set++) { - - case SRE_OP_FAILURE: - return !ok; - - case SRE_OP_LITERAL: - /* */ - if (ch == set[0]) - return ok; - set++; - break; - - case SRE_OP_CATEGORY: - /* */ - if (sre_category(set[0], (int) ch)) - return ok; - set += 1; - break; - - case SRE_OP_CHARSET: - if (sizeof(SRE_CODE) == 2) { - /* (16 bits per code word) */ - if (ch < 256 && (set[ch >> 4] & (1 << (ch & 15)))) - return ok; - set += 16; - } - else { - /* (32 bits per code word) */ - if (ch < 256 && (set[ch >> 5] & (1 << (ch & 31)))) - return ok; - set += 8; - } - break; - - case SRE_OP_RANGE: - /* */ - if (set[0] <= ch && ch <= set[1]) - return ok; - set += 2; - break; - - case SRE_OP_NEGATE: - ok = !ok; - break; - - case SRE_OP_BIGCHARSET: - /* <256 blockindices> */ - { - Py_ssize_t count, block; - count = *(set++); - - if (sizeof(SRE_CODE) == 2) { - block = ((unsigned char*)set)[ch >> 8]; - set += 128; - if (set[block*16 + ((ch & 255)>>4)] & (1 << (ch & 15))) - return ok; - set += count*16; - } - else { - /* !(c & ~N) == (c < N+1) for any unsigned c, this avoids - * warnings when c's type supports only numbers < N+1 */ - if (!(ch & ~65535)) - block = ((unsigned char*)set)[ch >> 8]; - else - block = -1; - set += 64; - if (block >=0 && - (set[block*8 + ((ch & 255)>>5)] & (1 << (ch & 31)))) - return ok; - set += count*8; - } - break; - } - - default: - /* internal error -- there's not much we can do about it - here, so let's just pretend it didn't match... */ - return 0; - } - } -} - -LOCAL(Py_ssize_t) SRE_MATCH(SRE_STATE* state, SRE_CODE* pattern); - -LOCAL(Py_ssize_t) -SRE_COUNT(SRE_STATE* state, SRE_CODE* pattern, Py_ssize_t maxcount) -{ - SRE_CODE chr; - SRE_CHAR* ptr = (SRE_CHAR *)state->ptr; - SRE_CHAR* end = (SRE_CHAR *)state->end; - Py_ssize_t i; - - /* adjust end */ - if (maxcount < end - ptr && maxcount != 65535) - end = ptr + maxcount; - - switch (pattern[0]) { - - case SRE_OP_IN: - /* repeated set */ - TRACE(("|%p|%p|COUNT IN\n", pattern, ptr)); - while (ptr < end && SRE_CHARSET(pattern + 2, *ptr)) - ptr++; - break; - - case SRE_OP_ANY: - /* repeated dot wildcard. */ - TRACE(("|%p|%p|COUNT ANY\n", pattern, ptr)); - while (ptr < end && !SRE_IS_LINEBREAK(*ptr)) - ptr++; - break; - - case SRE_OP_ANY_ALL: - /* repeated dot wildcard. skip to the end of the target - string, and backtrack from there */ - TRACE(("|%p|%p|COUNT ANY_ALL\n", pattern, ptr)); - ptr = end; - break; - - case SRE_OP_LITERAL: - /* repeated literal */ - chr = pattern[1]; - TRACE(("|%p|%p|COUNT LITERAL %d\n", pattern, ptr, chr)); - while (ptr < end && (SRE_CODE) *ptr == chr) - ptr++; - break; - - case SRE_OP_LITERAL_IGNORE: - /* repeated literal */ - chr = pattern[1]; - TRACE(("|%p|%p|COUNT LITERAL_IGNORE %d\n", pattern, ptr, chr)); - while (ptr < end && (SRE_CODE) state->lower(*ptr) == chr) - ptr++; - break; - - case SRE_OP_NOT_LITERAL: - /* repeated non-literal */ - chr = pattern[1]; - TRACE(("|%p|%p|COUNT NOT_LITERAL %d\n", pattern, ptr, chr)); - while (ptr < end && (SRE_CODE) *ptr != chr) - ptr++; - break; - - case SRE_OP_NOT_LITERAL_IGNORE: - /* repeated non-literal */ - chr = pattern[1]; - TRACE(("|%p|%p|COUNT NOT_LITERAL_IGNORE %d\n", pattern, ptr, chr)); - while (ptr < end && (SRE_CODE) state->lower(*ptr) != chr) - ptr++; - break; - - default: - /* repeated single character pattern */ - TRACE(("|%p|%p|COUNT SUBPATTERN\n", pattern, ptr)); - while ((SRE_CHAR*) state->ptr < end) { - i = SRE_MATCH(state, pattern); - if (i < 0) - return i; - if (!i) - break; - } - TRACE(("|%p|%p|COUNT %d\n", pattern, ptr, - (SRE_CHAR*) state->ptr - ptr)); - return (SRE_CHAR*) state->ptr - ptr; - } - - TRACE(("|%p|%p|COUNT %d\n", pattern, ptr, ptr - (SRE_CHAR*) state->ptr)); - return ptr - (SRE_CHAR*) state->ptr; -} - -#if 0 /* not used in this release */ -LOCAL(int) -SRE_INFO(SRE_STATE* state, SRE_CODE* pattern) -{ - /* check if an SRE_OP_INFO block matches at the current position. - returns the number of SRE_CODE objects to skip if successful, 0 - if no match */ - - SRE_CHAR* end = state->end; - SRE_CHAR* ptr = state->ptr; - Py_ssize_t i; - - /* check minimal length */ - if (pattern[3] && (end - ptr) < pattern[3]) - return 0; - - /* check known prefix */ - if (pattern[2] & SRE_INFO_PREFIX && pattern[5] > 1) { - /* */ - for (i = 0; i < pattern[5]; i++) - if ((SRE_CODE) ptr[i] != pattern[7 + i]) - return 0; - return pattern[0] + 2 * pattern[6]; - } - return pattern[0]; -} -#endif - -/* The macros below should be used to protect recursive SRE_MATCH() - * calls that *failed* and do *not* return immediately (IOW, those - * that will backtrack). Explaining: - * - * - Recursive SRE_MATCH() returned true: that's usually a success - * (besides atypical cases like ASSERT_NOT), therefore there's no - * reason to restore lastmark; - * - * - Recursive SRE_MATCH() returned false but the current SRE_MATCH() - * is returning to the caller: If the current SRE_MATCH() is the - * top function of the recursion, returning false will be a matching - * failure, and it doesn't matter where lastmark is pointing to. - * If it's *not* the top function, it will be a recursive SRE_MATCH() - * failure by itself, and the calling SRE_MATCH() will have to deal - * with the failure by the same rules explained here (it will restore - * lastmark by itself if necessary); - * - * - Recursive SRE_MATCH() returned false, and will continue the - * outside 'for' loop: must be protected when breaking, since the next - * OP could potentially depend on lastmark; - * - * - Recursive SRE_MATCH() returned false, and will be called again - * inside a local for/while loop: must be protected between each - * loop iteration, since the recursive SRE_MATCH() could do anything, - * and could potentially depend on lastmark. - * - * For more information, check the discussion at SF patch #712900. - */ -#define LASTMARK_SAVE() \ - do { \ - ctx->lastmark = state->lastmark; \ - ctx->lastindex = state->lastindex; \ - } while (0) -#define LASTMARK_RESTORE() \ - do { \ - state->lastmark = ctx->lastmark; \ - state->lastindex = ctx->lastindex; \ - } while (0) - -#define RETURN_ERROR(i) do { return i; } while(0) -#define RETURN_FAILURE do { ret = 0; goto exit; } while(0) -#define RETURN_SUCCESS do { ret = 1; goto exit; } while(0) - -#define RETURN_ON_ERROR(i) \ - do { if (i < 0) RETURN_ERROR(i); } while (0) -#define RETURN_ON_SUCCESS(i) \ - do { RETURN_ON_ERROR(i); if (i > 0) RETURN_SUCCESS; } while (0) -#define RETURN_ON_FAILURE(i) \ - do { RETURN_ON_ERROR(i); if (i == 0) RETURN_FAILURE; } while (0) - -#define SFY(x) #x - -#define DATA_STACK_ALLOC(state, type, ptr) \ -do { \ - alloc_pos = state->data_stack_base; \ - TRACE(("allocating %s in %d (%d)\n", \ - SFY(type), alloc_pos, sizeof(type))); \ - if (state->data_stack_size < alloc_pos+sizeof(type)) { \ - int j = data_stack_grow(state, sizeof(type)); \ - if (j < 0) return j; \ - if (ctx_pos != -1) \ - DATA_STACK_LOOKUP_AT(state, SRE_MATCH_CONTEXT, ctx, ctx_pos); \ - } \ - ptr = (type*)(state->data_stack+alloc_pos); \ - state->data_stack_base += sizeof(type); \ -} while (0) - -#define DATA_STACK_LOOKUP_AT(state, type, ptr, pos) \ -do { \ - TRACE(("looking up %s at %d\n", SFY(type), pos)); \ - ptr = (type*)(state->data_stack+pos); \ -} while (0) - -#define DATA_STACK_PUSH(state, data, size) \ -do { \ - TRACE(("copy data in %p to %d (%d)\n", \ - data, state->data_stack_base, size)); \ - if (state->data_stack_size < state->data_stack_base+size) { \ - int j = data_stack_grow(state, size); \ - if (j < 0) return j; \ - if (ctx_pos != -1) \ - DATA_STACK_LOOKUP_AT(state, SRE_MATCH_CONTEXT, ctx, ctx_pos); \ - } \ - memcpy(state->data_stack+state->data_stack_base, data, size); \ - state->data_stack_base += size; \ -} while (0) - -#define DATA_STACK_POP(state, data, size, discard) \ -do { \ - TRACE(("copy data to %p from %d (%d)\n", \ - data, state->data_stack_base-size, size)); \ - memcpy(data, state->data_stack+state->data_stack_base-size, size); \ - if (discard) \ - state->data_stack_base -= size; \ -} while (0) - -#define DATA_STACK_POP_DISCARD(state, size) \ -do { \ - TRACE(("discard data from %d (%d)\n", \ - state->data_stack_base-size, size)); \ - state->data_stack_base -= size; \ -} while(0) - -#define DATA_PUSH(x) \ - DATA_STACK_PUSH(state, (x), sizeof(*(x))) -#define DATA_POP(x) \ - DATA_STACK_POP(state, (x), sizeof(*(x)), 1) -#define DATA_POP_DISCARD(x) \ - DATA_STACK_POP_DISCARD(state, sizeof(*(x))) -#define DATA_ALLOC(t,p) \ - DATA_STACK_ALLOC(state, t, p) -#define DATA_LOOKUP_AT(t,p,pos) \ - DATA_STACK_LOOKUP_AT(state,t,p,pos) - -#define MARK_PUSH(lastmark) \ - do if (lastmark > 0) { \ - i = lastmark; /* ctx->lastmark may change if reallocated */ \ - DATA_STACK_PUSH(state, state->mark, (i+1)*sizeof(void*)); \ - } while (0) -#define MARK_POP(lastmark) \ - do if (lastmark > 0) { \ - DATA_STACK_POP(state, state->mark, (lastmark+1)*sizeof(void*), 1); \ - } while (0) -#define MARK_POP_KEEP(lastmark) \ - do if (lastmark > 0) { \ - DATA_STACK_POP(state, state->mark, (lastmark+1)*sizeof(void*), 0); \ - } while (0) -#define MARK_POP_DISCARD(lastmark) \ - do if (lastmark > 0) { \ - DATA_STACK_POP_DISCARD(state, (lastmark+1)*sizeof(void*)); \ - } while (0) - -#define JUMP_NONE 0 -#define JUMP_MAX_UNTIL_1 1 -#define JUMP_MAX_UNTIL_2 2 -#define JUMP_MAX_UNTIL_3 3 -#define JUMP_MIN_UNTIL_1 4 -#define JUMP_MIN_UNTIL_2 5 -#define JUMP_MIN_UNTIL_3 6 -#define JUMP_REPEAT 7 -#define JUMP_REPEAT_ONE_1 8 -#define JUMP_REPEAT_ONE_2 9 -#define JUMP_MIN_REPEAT_ONE 10 -#define JUMP_BRANCH 11 -#define JUMP_ASSERT 12 -#define JUMP_ASSERT_NOT 13 - -#define DO_JUMP(jumpvalue, jumplabel, nextpattern) \ - DATA_ALLOC(SRE_MATCH_CONTEXT, nextctx); \ - nextctx->last_ctx_pos = ctx_pos; \ - nextctx->jump = jumpvalue; \ - nextctx->pattern = nextpattern; \ - ctx_pos = alloc_pos; \ - ctx = nextctx; \ - goto entrance; \ - jumplabel: \ - while (0) /* gcc doesn't like labels at end of scopes */ \ - -typedef struct { - Py_ssize_t last_ctx_pos; - Py_ssize_t jump; - SRE_CHAR* ptr; - SRE_CODE* pattern; - Py_ssize_t count; - Py_ssize_t lastmark; - Py_ssize_t lastindex; - union { - SRE_CODE chr; - SRE_REPEAT* rep; - } u; -} SRE_MATCH_CONTEXT; - -/* check if string matches the given pattern. returns <0 for - error, 0 for failure, and 1 for success */ -LOCAL(Py_ssize_t) -SRE_MATCH(SRE_STATE* state, SRE_CODE* pattern) -{ - SRE_CHAR* end = (SRE_CHAR *)state->end; - Py_ssize_t alloc_pos, ctx_pos = -1; - Py_ssize_t i, ret = 0; - Py_ssize_t jump; - unsigned int sigcount=0; - - SRE_MATCH_CONTEXT* ctx; - SRE_MATCH_CONTEXT* nextctx; - - TRACE(("|%p|%p|ENTER\n", pattern, state->ptr)); - - DATA_ALLOC(SRE_MATCH_CONTEXT, ctx); - ctx->last_ctx_pos = -1; - ctx->jump = JUMP_NONE; - ctx->pattern = pattern; - ctx_pos = alloc_pos; - -entrance: - - ctx->ptr = (SRE_CHAR *)state->ptr; - - if (ctx->pattern[0] == SRE_OP_INFO) { - /* optimization info block */ - /* <1=skip> <2=flags> <3=min> ... */ - if (ctx->pattern[3] && (end - ctx->ptr) < ctx->pattern[3]) { - TRACE(("reject (got %d chars, need %d)\n", - (end - ctx->ptr), ctx->pattern[3])); - RETURN_FAILURE; - } - ctx->pattern += ctx->pattern[1] + 1; - } - - for (;;) { - ++sigcount; - if ((0 == (sigcount & 0xfff)) && PyErr_CheckSignals()) - RETURN_ERROR(SRE_ERROR_INTERRUPTED); - - switch (*ctx->pattern++) { - - case SRE_OP_MARK: - /* set mark */ - /* */ - TRACE(("|%p|%p|MARK %d\n", ctx->pattern, - ctx->ptr, ctx->pattern[0])); - i = ctx->pattern[0]; - if (i & 1) - state->lastindex = i/2 + 1; - if (i > state->lastmark) { - /* state->lastmark is the highest valid index in the - state->mark array. If it is increased by more than 1, - the intervening marks must be set to NULL to signal - that these marks have not been encountered. */ - Py_ssize_t j = state->lastmark + 1; - while (j < i) - state->mark[j++] = NULL; - state->lastmark = i; - } - state->mark[i] = ctx->ptr; - ctx->pattern++; - break; - - case SRE_OP_LITERAL: - /* match literal string */ - /* */ - TRACE(("|%p|%p|LITERAL %d\n", ctx->pattern, - ctx->ptr, *ctx->pattern)); - if (ctx->ptr >= end || (SRE_CODE) ctx->ptr[0] != ctx->pattern[0]) - RETURN_FAILURE; - ctx->pattern++; - ctx->ptr++; - break; - - case SRE_OP_NOT_LITERAL: - /* match anything that is not literal character */ - /* */ - TRACE(("|%p|%p|NOT_LITERAL %d\n", ctx->pattern, - ctx->ptr, *ctx->pattern)); - if (ctx->ptr >= end || (SRE_CODE) ctx->ptr[0] == ctx->pattern[0]) - RETURN_FAILURE; - ctx->pattern++; - ctx->ptr++; - break; - - case SRE_OP_SUCCESS: - /* end of pattern */ - TRACE(("|%p|%p|SUCCESS\n", ctx->pattern, ctx->ptr)); - state->ptr = ctx->ptr; - RETURN_SUCCESS; - - case SRE_OP_AT: - /* match at given position */ - /* */ - TRACE(("|%p|%p|AT %d\n", ctx->pattern, ctx->ptr, *ctx->pattern)); - if (!SRE_AT(state, ctx->ptr, *ctx->pattern)) - RETURN_FAILURE; - ctx->pattern++; - break; - - case SRE_OP_CATEGORY: - /* match at given category */ - /* */ - TRACE(("|%p|%p|CATEGORY %d\n", ctx->pattern, - ctx->ptr, *ctx->pattern)); - if (ctx->ptr >= end || !sre_category(ctx->pattern[0], ctx->ptr[0])) - RETURN_FAILURE; - ctx->pattern++; - ctx->ptr++; - break; - - case SRE_OP_ANY: - /* match anything (except a newline) */ - /* */ - TRACE(("|%p|%p|ANY\n", ctx->pattern, ctx->ptr)); - if (ctx->ptr >= end || SRE_IS_LINEBREAK(ctx->ptr[0])) - RETURN_FAILURE; - ctx->ptr++; - break; - - case SRE_OP_ANY_ALL: - /* match anything */ - /* */ - TRACE(("|%p|%p|ANY_ALL\n", ctx->pattern, ctx->ptr)); - if (ctx->ptr >= end) - RETURN_FAILURE; - ctx->ptr++; - break; - - case SRE_OP_IN: - /* match set member (or non_member) */ - /* */ - TRACE(("|%p|%p|IN\n", ctx->pattern, ctx->ptr)); - if (ctx->ptr >= end || !SRE_CHARSET(ctx->pattern + 1, *ctx->ptr)) - RETURN_FAILURE; - ctx->pattern += ctx->pattern[0]; - ctx->ptr++; - break; - - case SRE_OP_LITERAL_IGNORE: - TRACE(("|%p|%p|LITERAL_IGNORE %d\n", - ctx->pattern, ctx->ptr, ctx->pattern[0])); - if (ctx->ptr >= end || - state->lower(*ctx->ptr) != state->lower(*ctx->pattern)) - RETURN_FAILURE; - ctx->pattern++; - ctx->ptr++; - break; - - case SRE_OP_NOT_LITERAL_IGNORE: - TRACE(("|%p|%p|NOT_LITERAL_IGNORE %d\n", - ctx->pattern, ctx->ptr, *ctx->pattern)); - if (ctx->ptr >= end || - state->lower(*ctx->ptr) == state->lower(*ctx->pattern)) - RETURN_FAILURE; - ctx->pattern++; - ctx->ptr++; - break; - - case SRE_OP_IN_IGNORE: - TRACE(("|%p|%p|IN_IGNORE\n", ctx->pattern, ctx->ptr)); - if (ctx->ptr >= end - || !SRE_CHARSET(ctx->pattern+1, - (SRE_CODE)state->lower(*ctx->ptr))) - RETURN_FAILURE; - ctx->pattern += ctx->pattern[0]; - ctx->ptr++; - break; - - case SRE_OP_JUMP: - case SRE_OP_INFO: - /* jump forward */ - /* */ - TRACE(("|%p|%p|JUMP %d\n", ctx->pattern, - ctx->ptr, ctx->pattern[0])); - ctx->pattern += ctx->pattern[0]; - break; - - case SRE_OP_BRANCH: - /* alternation */ - /* <0=skip> code ... */ - TRACE(("|%p|%p|BRANCH\n", ctx->pattern, ctx->ptr)); - LASTMARK_SAVE(); - ctx->u.rep = state->repeat; - if (ctx->u.rep) - MARK_PUSH(ctx->lastmark); - for (; ctx->pattern[0]; ctx->pattern += ctx->pattern[0]) { - if (ctx->pattern[1] == SRE_OP_LITERAL && - (ctx->ptr >= end || - (SRE_CODE) *ctx->ptr != ctx->pattern[2])) - continue; - if (ctx->pattern[1] == SRE_OP_IN && - (ctx->ptr >= end || - !SRE_CHARSET(ctx->pattern + 3, (SRE_CODE) *ctx->ptr))) - continue; - state->ptr = ctx->ptr; - DO_JUMP(JUMP_BRANCH, jump_branch, ctx->pattern+1); - if (ret) { - if (ctx->u.rep) - MARK_POP_DISCARD(ctx->lastmark); - RETURN_ON_ERROR(ret); - RETURN_SUCCESS; - } - if (ctx->u.rep) - MARK_POP_KEEP(ctx->lastmark); - LASTMARK_RESTORE(); - } - if (ctx->u.rep) - MARK_POP_DISCARD(ctx->lastmark); - RETURN_FAILURE; - - case SRE_OP_REPEAT_ONE: - /* match repeated sequence (maximizing regexp) */ - - /* this operator only works if the repeated item is - exactly one character wide, and we're not already - collecting backtracking points. for other cases, - use the MAX_REPEAT operator */ - - /* <1=min> <2=max> item tail */ - - TRACE(("|%p|%p|REPEAT_ONE %d %d\n", ctx->pattern, ctx->ptr, - ctx->pattern[1], ctx->pattern[2])); - - if (ctx->ptr + ctx->pattern[1] > end) - RETURN_FAILURE; /* cannot match */ - - state->ptr = ctx->ptr; - - ret = SRE_COUNT(state, ctx->pattern+3, ctx->pattern[2]); - RETURN_ON_ERROR(ret); - DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos); - ctx->count = ret; - ctx->ptr += ctx->count; - - /* when we arrive here, count contains the number of - matches, and ctx->ptr points to the tail of the target - string. check if the rest of the pattern matches, - and backtrack if not. */ - - if (ctx->count < (Py_ssize_t) ctx->pattern[1]) - RETURN_FAILURE; - - if (ctx->pattern[ctx->pattern[0]] == SRE_OP_SUCCESS) { - /* tail is empty. we're finished */ - state->ptr = ctx->ptr; - RETURN_SUCCESS; - } - - LASTMARK_SAVE(); - - if (ctx->pattern[ctx->pattern[0]] == SRE_OP_LITERAL) { - /* tail starts with a literal. skip positions where - the rest of the pattern cannot possibly match */ - ctx->u.chr = ctx->pattern[ctx->pattern[0]+1]; - for (;;) { - while (ctx->count >= (Py_ssize_t) ctx->pattern[1] && - (ctx->ptr >= end || *ctx->ptr != ctx->u.chr)) { - ctx->ptr--; - ctx->count--; - } - if (ctx->count < (Py_ssize_t) ctx->pattern[1]) - break; - state->ptr = ctx->ptr; - DO_JUMP(JUMP_REPEAT_ONE_1, jump_repeat_one_1, - ctx->pattern+ctx->pattern[0]); - if (ret) { - RETURN_ON_ERROR(ret); - RETURN_SUCCESS; - } - - LASTMARK_RESTORE(); - - ctx->ptr--; - ctx->count--; - } - - } else { - /* general case */ - while (ctx->count >= (Py_ssize_t) ctx->pattern[1]) { - state->ptr = ctx->ptr; - DO_JUMP(JUMP_REPEAT_ONE_2, jump_repeat_one_2, - ctx->pattern+ctx->pattern[0]); - if (ret) { - RETURN_ON_ERROR(ret); - RETURN_SUCCESS; - } - ctx->ptr--; - ctx->count--; - LASTMARK_RESTORE(); - } - } - RETURN_FAILURE; - - case SRE_OP_MIN_REPEAT_ONE: - /* match repeated sequence (minimizing regexp) */ - - /* this operator only works if the repeated item is - exactly one character wide, and we're not already - collecting backtracking points. for other cases, - use the MIN_REPEAT operator */ - - /* <1=min> <2=max> item tail */ - - TRACE(("|%p|%p|MIN_REPEAT_ONE %d %d\n", ctx->pattern, ctx->ptr, - ctx->pattern[1], ctx->pattern[2])); - - if (ctx->ptr + ctx->pattern[1] > end) - RETURN_FAILURE; /* cannot match */ - - state->ptr = ctx->ptr; - - if (ctx->pattern[1] == 0) - ctx->count = 0; - else { - /* count using pattern min as the maximum */ - ret = SRE_COUNT(state, ctx->pattern+3, ctx->pattern[1]); - RETURN_ON_ERROR(ret); - DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos); - if (ret < (Py_ssize_t) ctx->pattern[1]) - /* didn't match minimum number of times */ - RETURN_FAILURE; - /* advance past minimum matches of repeat */ - ctx->count = ret; - ctx->ptr += ctx->count; - } - - if (ctx->pattern[ctx->pattern[0]] == SRE_OP_SUCCESS) { - /* tail is empty. we're finished */ - state->ptr = ctx->ptr; - RETURN_SUCCESS; - - } else { - /* general case */ - LASTMARK_SAVE(); - while ((Py_ssize_t)ctx->pattern[2] == 65535 - || ctx->count <= (Py_ssize_t)ctx->pattern[2]) { - state->ptr = ctx->ptr; - DO_JUMP(JUMP_MIN_REPEAT_ONE,jump_min_repeat_one, - ctx->pattern+ctx->pattern[0]); - if (ret) { - RETURN_ON_ERROR(ret); - RETURN_SUCCESS; - } - state->ptr = ctx->ptr; - ret = SRE_COUNT(state, ctx->pattern+3, 1); - RETURN_ON_ERROR(ret); - DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos); - if (ret == 0) - break; - assert(ret == 1); - ctx->ptr++; - ctx->count++; - LASTMARK_RESTORE(); - } - } - RETURN_FAILURE; - - case SRE_OP_REPEAT: - /* create repeat context. all the hard work is done - by the UNTIL operator (MAX_UNTIL, MIN_UNTIL) */ - /* <1=min> <2=max> item tail */ - TRACE(("|%p|%p|REPEAT %d %d\n", ctx->pattern, ctx->ptr, - ctx->pattern[1], ctx->pattern[2])); - - /* install new repeat context */ - ctx->u.rep = (SRE_REPEAT*) PyObject_MALLOC(sizeof(*ctx->u.rep)); - if (!ctx->u.rep) { - PyErr_NoMemory(); - RETURN_FAILURE; - } - ctx->u.rep->count = -1; - ctx->u.rep->pattern = ctx->pattern; - ctx->u.rep->prev = state->repeat; - ctx->u.rep->last_ptr = NULL; - state->repeat = ctx->u.rep; - - state->ptr = ctx->ptr; - DO_JUMP(JUMP_REPEAT, jump_repeat, ctx->pattern+ctx->pattern[0]); - state->repeat = ctx->u.rep->prev; - PyObject_FREE(ctx->u.rep); - - if (ret) { - RETURN_ON_ERROR(ret); - RETURN_SUCCESS; - } - RETURN_FAILURE; - - case SRE_OP_MAX_UNTIL: - /* maximizing repeat */ - /* <1=min> <2=max> item tail */ - - /* FIXME: we probably need to deal with zero-width - matches in here... */ - - ctx->u.rep = state->repeat; - if (!ctx->u.rep) - RETURN_ERROR(SRE_ERROR_STATE); - - state->ptr = ctx->ptr; - - ctx->count = ctx->u.rep->count+1; - - TRACE(("|%p|%p|MAX_UNTIL %d\n", ctx->pattern, - ctx->ptr, ctx->count)); - - if (ctx->count < ctx->u.rep->pattern[1]) { - /* not enough matches */ - ctx->u.rep->count = ctx->count; - DO_JUMP(JUMP_MAX_UNTIL_1, jump_max_until_1, - ctx->u.rep->pattern+3); - if (ret) { - RETURN_ON_ERROR(ret); - RETURN_SUCCESS; - } - ctx->u.rep->count = ctx->count-1; - state->ptr = ctx->ptr; - RETURN_FAILURE; - } - - if ((ctx->count < ctx->u.rep->pattern[2] || - ctx->u.rep->pattern[2] == 65535) && - state->ptr != ctx->u.rep->last_ptr) { - /* we may have enough matches, but if we can - match another item, do so */ - ctx->u.rep->count = ctx->count; - LASTMARK_SAVE(); - MARK_PUSH(ctx->lastmark); - /* zero-width match protection */ - DATA_PUSH(&ctx->u.rep->last_ptr); - ctx->u.rep->last_ptr = state->ptr; - DO_JUMP(JUMP_MAX_UNTIL_2, jump_max_until_2, - ctx->u.rep->pattern+3); - DATA_POP(&ctx->u.rep->last_ptr); - if (ret) { - MARK_POP_DISCARD(ctx->lastmark); - RETURN_ON_ERROR(ret); - RETURN_SUCCESS; - } - MARK_POP(ctx->lastmark); - LASTMARK_RESTORE(); - ctx->u.rep->count = ctx->count-1; - state->ptr = ctx->ptr; - } - - /* cannot match more repeated items here. make sure the - tail matches */ - state->repeat = ctx->u.rep->prev; - DO_JUMP(JUMP_MAX_UNTIL_3, jump_max_until_3, ctx->pattern); - RETURN_ON_SUCCESS(ret); - state->repeat = ctx->u.rep; - state->ptr = ctx->ptr; - RETURN_FAILURE; - - case SRE_OP_MIN_UNTIL: - /* minimizing repeat */ - /* <1=min> <2=max> item tail */ - - ctx->u.rep = state->repeat; - if (!ctx->u.rep) - RETURN_ERROR(SRE_ERROR_STATE); - - state->ptr = ctx->ptr; - - ctx->count = ctx->u.rep->count+1; - - TRACE(("|%p|%p|MIN_UNTIL %d %p\n", ctx->pattern, - ctx->ptr, ctx->count, ctx->u.rep->pattern)); - - if (ctx->count < ctx->u.rep->pattern[1]) { - /* not enough matches */ - ctx->u.rep->count = ctx->count; - DO_JUMP(JUMP_MIN_UNTIL_1, jump_min_until_1, - ctx->u.rep->pattern+3); - if (ret) { - RETURN_ON_ERROR(ret); - RETURN_SUCCESS; - } - ctx->u.rep->count = ctx->count-1; - state->ptr = ctx->ptr; - RETURN_FAILURE; - } - - LASTMARK_SAVE(); - - /* see if the tail matches */ - state->repeat = ctx->u.rep->prev; - DO_JUMP(JUMP_MIN_UNTIL_2, jump_min_until_2, ctx->pattern); - if (ret) { - RETURN_ON_ERROR(ret); - RETURN_SUCCESS; - } - - state->repeat = ctx->u.rep; - state->ptr = ctx->ptr; - - LASTMARK_RESTORE(); - - if (ctx->count >= ctx->u.rep->pattern[2] - && ctx->u.rep->pattern[2] != 65535) - RETURN_FAILURE; - - ctx->u.rep->count = ctx->count; - DO_JUMP(JUMP_MIN_UNTIL_3,jump_min_until_3, - ctx->u.rep->pattern+3); - if (ret) { - RETURN_ON_ERROR(ret); - RETURN_SUCCESS; - } - ctx->u.rep->count = ctx->count-1; - state->ptr = ctx->ptr; - RETURN_FAILURE; - - case SRE_OP_GROUPREF: - /* match backreference */ - TRACE(("|%p|%p|GROUPREF %d\n", ctx->pattern, - ctx->ptr, ctx->pattern[0])); - i = ctx->pattern[0]; - { - Py_ssize_t groupref = i+i; - if (groupref >= state->lastmark) { - RETURN_FAILURE; - } else { - SRE_CHAR* p = (SRE_CHAR*) state->mark[groupref]; - SRE_CHAR* e = (SRE_CHAR*) state->mark[groupref+1]; - if (!p || !e || e < p) - RETURN_FAILURE; - while (p < e) { - if (ctx->ptr >= end || *ctx->ptr != *p) - RETURN_FAILURE; - p++; ctx->ptr++; - } - } - } - ctx->pattern++; - break; - - case SRE_OP_GROUPREF_IGNORE: - /* match backreference */ - TRACE(("|%p|%p|GROUPREF_IGNORE %d\n", ctx->pattern, - ctx->ptr, ctx->pattern[0])); - i = ctx->pattern[0]; - { - Py_ssize_t groupref = i+i; - if (groupref >= state->lastmark) { - RETURN_FAILURE; - } else { - SRE_CHAR* p = (SRE_CHAR*) state->mark[groupref]; - SRE_CHAR* e = (SRE_CHAR*) state->mark[groupref+1]; - if (!p || !e || e < p) - RETURN_FAILURE; - while (p < e) { - if (ctx->ptr >= end || - state->lower(*ctx->ptr) != state->lower(*p)) - RETURN_FAILURE; - p++; ctx->ptr++; - } - } - } - ctx->pattern++; - break; - - case SRE_OP_GROUPREF_EXISTS: - TRACE(("|%p|%p|GROUPREF_EXISTS %d\n", ctx->pattern, - ctx->ptr, ctx->pattern[0])); - /* codeyes codeno ... */ - i = ctx->pattern[0]; - { - Py_ssize_t groupref = i+i; - if (groupref >= state->lastmark) { - ctx->pattern += ctx->pattern[1]; - break; - } else { - SRE_CHAR* p = (SRE_CHAR*) state->mark[groupref]; - SRE_CHAR* e = (SRE_CHAR*) state->mark[groupref+1]; - if (!p || !e || e < p) { - ctx->pattern += ctx->pattern[1]; - break; - } - } - } - ctx->pattern += 2; - break; - - case SRE_OP_ASSERT: - /* assert subpattern */ - /* */ - TRACE(("|%p|%p|ASSERT %d\n", ctx->pattern, - ctx->ptr, ctx->pattern[1])); - state->ptr = ctx->ptr - ctx->pattern[1]; - if (state->ptr < state->beginning) - RETURN_FAILURE; - DO_JUMP(JUMP_ASSERT, jump_assert, ctx->pattern+2); - RETURN_ON_FAILURE(ret); - ctx->pattern += ctx->pattern[0]; - break; - - case SRE_OP_ASSERT_NOT: - /* assert not subpattern */ - /* */ - TRACE(("|%p|%p|ASSERT_NOT %d\n", ctx->pattern, - ctx->ptr, ctx->pattern[1])); - state->ptr = ctx->ptr - ctx->pattern[1]; - if (state->ptr >= state->beginning) { - DO_JUMP(JUMP_ASSERT_NOT, jump_assert_not, ctx->pattern+2); - if (ret) { - RETURN_ON_ERROR(ret); - RETURN_FAILURE; - } - } - ctx->pattern += ctx->pattern[0]; - break; - - case SRE_OP_FAILURE: - /* immediate failure */ - TRACE(("|%p|%p|FAILURE\n", ctx->pattern, ctx->ptr)); - RETURN_FAILURE; - - default: - TRACE(("|%p|%p|UNKNOWN %d\n", ctx->pattern, ctx->ptr, - ctx->pattern[-1])); - RETURN_ERROR(SRE_ERROR_ILLEGAL); - } - } - -exit: - ctx_pos = ctx->last_ctx_pos; - jump = ctx->jump; - DATA_POP_DISCARD(ctx); - if (ctx_pos == -1) - return ret; - DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos); - - switch (jump) { - case JUMP_MAX_UNTIL_2: - TRACE(("|%p|%p|JUMP_MAX_UNTIL_2\n", ctx->pattern, ctx->ptr)); - goto jump_max_until_2; - case JUMP_MAX_UNTIL_3: - TRACE(("|%p|%p|JUMP_MAX_UNTIL_3\n", ctx->pattern, ctx->ptr)); - goto jump_max_until_3; - case JUMP_MIN_UNTIL_2: - TRACE(("|%p|%p|JUMP_MIN_UNTIL_2\n", ctx->pattern, ctx->ptr)); - goto jump_min_until_2; - case JUMP_MIN_UNTIL_3: - TRACE(("|%p|%p|JUMP_MIN_UNTIL_3\n", ctx->pattern, ctx->ptr)); - goto jump_min_until_3; - case JUMP_BRANCH: - TRACE(("|%p|%p|JUMP_BRANCH\n", ctx->pattern, ctx->ptr)); - goto jump_branch; - case JUMP_MAX_UNTIL_1: - TRACE(("|%p|%p|JUMP_MAX_UNTIL_1\n", ctx->pattern, ctx->ptr)); - goto jump_max_until_1; - case JUMP_MIN_UNTIL_1: - TRACE(("|%p|%p|JUMP_MIN_UNTIL_1\n", ctx->pattern, ctx->ptr)); - goto jump_min_until_1; - case JUMP_REPEAT: - TRACE(("|%p|%p|JUMP_REPEAT\n", ctx->pattern, ctx->ptr)); - goto jump_repeat; - case JUMP_REPEAT_ONE_1: - TRACE(("|%p|%p|JUMP_REPEAT_ONE_1\n", ctx->pattern, ctx->ptr)); - goto jump_repeat_one_1; - case JUMP_REPEAT_ONE_2: - TRACE(("|%p|%p|JUMP_REPEAT_ONE_2\n", ctx->pattern, ctx->ptr)); - goto jump_repeat_one_2; - case JUMP_MIN_REPEAT_ONE: - TRACE(("|%p|%p|JUMP_MIN_REPEAT_ONE\n", ctx->pattern, ctx->ptr)); - goto jump_min_repeat_one; - case JUMP_ASSERT: - TRACE(("|%p|%p|JUMP_ASSERT\n", ctx->pattern, ctx->ptr)); - goto jump_assert; - case JUMP_ASSERT_NOT: - TRACE(("|%p|%p|JUMP_ASSERT_NOT\n", ctx->pattern, ctx->ptr)); - goto jump_assert_not; - case JUMP_NONE: - TRACE(("|%p|%p|RETURN %d\n", ctx->pattern, ctx->ptr, ret)); - break; - } - - return ret; /* should never get here */ -} - -LOCAL(Py_ssize_t) -SRE_SEARCH(SRE_STATE* state, SRE_CODE* pattern) -{ - SRE_CHAR* ptr = (SRE_CHAR *)state->start; - SRE_CHAR* end = (SRE_CHAR *)state->end; - Py_ssize_t status = 0; - Py_ssize_t prefix_len = 0; - Py_ssize_t prefix_skip = 0; - SRE_CODE* prefix = NULL; - SRE_CODE* charset = NULL; - SRE_CODE* overlap = NULL; - int flags = 0; - - if (pattern[0] == SRE_OP_INFO) { - /* optimization info block */ - /* <1=skip> <2=flags> <3=min> <4=max> <5=prefix info> */ - - flags = pattern[2]; - - if (pattern[3] > 1) { - /* adjust end point (but make sure we leave at least one - character in there, so literal search will work) */ - end -= pattern[3]-1; - if (end <= ptr) - end = ptr+1; - } - - if (flags & SRE_INFO_PREFIX) { - /* pattern starts with a known prefix */ - /* */ - prefix_len = pattern[5]; - prefix_skip = pattern[6]; - prefix = pattern + 7; - overlap = prefix + prefix_len - 1; - } else if (flags & SRE_INFO_CHARSET) - /* pattern starts with a character from a known set */ - /* */ - charset = pattern + 5; - - pattern += 1 + pattern[1]; - } - - TRACE(("prefix = %p %d %d\n", prefix, prefix_len, prefix_skip)); - TRACE(("charset = %p\n", charset)); - -#if defined(USE_FAST_SEARCH) - if (prefix_len > 1) { - /* pattern starts with a known prefix. use the overlap - table to skip forward as fast as we possibly can */ - Py_ssize_t i = 0; - end = (SRE_CHAR *)state->end; - while (ptr < end) { - for (;;) { - if ((SRE_CODE) ptr[0] != prefix[i]) { - if (!i) - break; - else - i = overlap[i]; - } else { - if (++i == prefix_len) { - /* found a potential match */ - TRACE(("|%p|%p|SEARCH SCAN\n", pattern, ptr)); - state->start = ptr + 1 - prefix_len; - state->ptr = ptr + 1 - prefix_len + prefix_skip; - if (flags & SRE_INFO_LITERAL) - return 1; /* we got all of it */ - status = SRE_MATCH(state, pattern + 2*prefix_skip); - if (status != 0) - return status; - /* close but no cigar -- try again */ - i = overlap[i]; - } - break; - } - } - ptr++; - } - return 0; - } -#endif - - if (pattern[0] == SRE_OP_LITERAL) { - /* pattern starts with a literal character. this is used - for short prefixes, and if fast search is disabled */ - SRE_CODE chr = pattern[1]; - end = (SRE_CHAR *)state->end; - for (;;) { - while (ptr < end && (SRE_CODE) ptr[0] != chr) - ptr++; - if (ptr >= end) - return 0; - TRACE(("|%p|%p|SEARCH LITERAL\n", pattern, ptr)); - state->start = ptr; - state->ptr = ++ptr; - if (flags & SRE_INFO_LITERAL) - return 1; /* we got all of it */ - status = SRE_MATCH(state, pattern + 2); - if (status != 0) - break; - } - } else if (charset) { - /* pattern starts with a character from a known set */ - end = (SRE_CHAR *)state->end; - for (;;) { - while (ptr < end && !SRE_CHARSET(charset, ptr[0])) - ptr++; - if (ptr >= end) - return 0; - TRACE(("|%p|%p|SEARCH CHARSET\n", pattern, ptr)); - state->start = ptr; - state->ptr = ptr; - status = SRE_MATCH(state, pattern); - if (status != 0) - break; - ptr++; - } - } else - /* general case */ - while (ptr <= end) { - TRACE(("|%p|%p|SEARCH\n", pattern, ptr)); - state->start = state->ptr = ptr++; - status = SRE_MATCH(state, pattern); - if (status != 0) - break; - } - - return status; -} - -LOCAL(int) -SRE_LITERAL_TEMPLATE(SRE_CHAR* ptr, Py_ssize_t len) -{ - /* check if given string is a literal template (i.e. no escapes) */ - while (len-- > 0) - if (*ptr++ == '\\') - return 0; - return 1; -} - -#if !defined(SRE_RECURSIVE) - -/* -------------------------------------------------------------------- */ -/* factories and destructors */ - -/* see sre.h for object declarations */ -static PyObject*pattern_new_match(PatternObject*, SRE_STATE*, int); -static PyObject*pattern_scanner(PatternObject*, PyObject*); - -static PyObject * -sre_codesize(PyObject* self, PyObject *unused) -{ - return Py_BuildValue("l", sizeof(SRE_CODE)); -} - -static PyObject * -sre_getlower(PyObject* self, PyObject* args) -{ - int character, flags; - if (!PyArg_ParseTuple(args, "ii", &character, &flags)) - return NULL; - if (flags & SRE_FLAG_LOCALE) - return Py_BuildValue("i", sre_lower_locale(character)); - if (flags & SRE_FLAG_UNICODE) -#if defined(HAVE_UNICODE) - return Py_BuildValue("i", sre_lower_unicode(character)); -#else - return Py_BuildValue("i", sre_lower_locale(character)); -#endif - return Py_BuildValue("i", sre_lower(character)); -} - -LOCAL(void) -state_reset(SRE_STATE* state) -{ - /* FIXME: dynamic! */ - /*memset(state->mark, 0, sizeof(*state->mark) * SRE_MARK_SIZE);*/ - - state->lastmark = -1; - state->lastindex = -1; - - state->repeat = NULL; - - data_stack_dealloc(state); -} - -static void* -getstring(PyObject* string, Py_ssize_t* p_length, int* p_charsize) -{ - /* given a python object, return a data pointer, a length (in - characters), and a character size. return NULL if the object - is not a string (or not compatible) */ - - PyBufferProcs *buffer; - Py_ssize_t size, bytes; - int charsize; - void* ptr; - -#if defined(HAVE_UNICODE) - if (PyUnicode_Check(string)) { - /* unicode strings doesn't always support the buffer interface */ - ptr = (void*) PyUnicode_AS_DATA(string); - /* bytes = PyUnicode_GET_DATA_SIZE(string); */ - size = PyUnicode_GET_SIZE(string); - charsize = sizeof(Py_UNICODE); - - } else { -#endif - - /* get pointer to string buffer */ - buffer = Py_TYPE(string)->tp_as_buffer; - if (!buffer || !buffer->bf_getreadbuffer || !buffer->bf_getsegcount || - buffer->bf_getsegcount(string, NULL) != 1) { - PyErr_SetString(PyExc_TypeError, "expected string or buffer"); - return NULL; - } - - /* determine buffer size */ - bytes = buffer->bf_getreadbuffer(string, 0, &ptr); - if (bytes < 0) { - PyErr_SetString(PyExc_TypeError, "buffer has negative size"); - return NULL; - } - - /* determine character size */ -#if PY_VERSION_HEX >= 0x01060000 - size = PyObject_Size(string); -#else - size = PyObject_Length(string); -#endif - - if (PyString_Check(string) || bytes == size) - charsize = 1; -#if defined(HAVE_UNICODE) - else if (bytes == (Py_ssize_t) (size * sizeof(Py_UNICODE))) - charsize = sizeof(Py_UNICODE); -#endif - else { - PyErr_SetString(PyExc_TypeError, "buffer size mismatch"); - return NULL; - } - -#if defined(HAVE_UNICODE) - } -#endif - - *p_length = size; - *p_charsize = charsize; - - return ptr; -} - -LOCAL(PyObject*) -state_init(SRE_STATE* state, PatternObject* pattern, PyObject* string, - Py_ssize_t start, Py_ssize_t end) -{ - /* prepare state object */ - - Py_ssize_t length; - int charsize; - void* ptr; - - memset(state, 0, sizeof(SRE_STATE)); - - state->lastmark = -1; - state->lastindex = -1; - - ptr = getstring(string, &length, &charsize); - if (!ptr) - return NULL; - - /* adjust boundaries */ - if (start < 0) - start = 0; - else if (start > length) - start = length; - - if (end < 0) - end = 0; - else if (end > length) - end = length; - - state->charsize = charsize; - - state->beginning = ptr; - - state->start = (void*) ((char*) ptr + start * state->charsize); - state->end = (void*) ((char*) ptr + end * state->charsize); - - Py_INCREF(string); - state->string = string; - state->pos = start; - state->endpos = end; - - if (pattern->flags & SRE_FLAG_LOCALE) - state->lower = sre_lower_locale; - else if (pattern->flags & SRE_FLAG_UNICODE) -#if defined(HAVE_UNICODE) - state->lower = sre_lower_unicode; -#else - state->lower = sre_lower_locale; -#endif - else - state->lower = sre_lower; - - return string; -} - -LOCAL(void) -state_fini(SRE_STATE* state) -{ - Py_XDECREF(state->string); - data_stack_dealloc(state); -} - -/* calculate offset from start of string */ -#define STATE_OFFSET(state, member)\ - (((char*)(member) - (char*)(state)->beginning) / (state)->charsize) - -LOCAL(PyObject*) -state_getslice(SRE_STATE* state, Py_ssize_t index, PyObject* string, int empty) -{ - Py_ssize_t i, j; - - index = (index - 1) * 2; - - if (string == Py_None || index >= state->lastmark || !state->mark[index] || !state->mark[index+1]) { - if (empty) - /* want empty string */ - i = j = 0; - else { - Py_INCREF(Py_None); - return Py_None; - } - } else { - i = STATE_OFFSET(state, state->mark[index]); - j = STATE_OFFSET(state, state->mark[index+1]); - } - - return PySequence_GetSlice(string, i, j); -} - -static void -pattern_error(int status) -{ - switch (status) { - case SRE_ERROR_RECURSION_LIMIT: - PyErr_SetString( - PyExc_RuntimeError, - "maximum recursion limit exceeded" - ); - break; - case SRE_ERROR_MEMORY: - PyErr_NoMemory(); - break; - case SRE_ERROR_INTERRUPTED: - /* An exception has already been raised, so let it fly */ - break; - default: - /* other error codes indicate compiler/engine bugs */ - PyErr_SetString( - PyExc_RuntimeError, - "internal error in regular expression engine" - ); - } -} - -static void -pattern_dealloc(PatternObject* self) -{ - if (self->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) self); - Py_XDECREF(self->pattern); - Py_XDECREF(self->groupindex); - Py_XDECREF(self->indexgroup); - PyObject_DEL(self); -} - -static PyObject* -pattern_match(PatternObject* self, PyObject* args, PyObject* kw) -{ - SRE_STATE state; - int status; - - PyObject* string; - Py_ssize_t start = 0; - Py_ssize_t end = PY_SSIZE_T_MAX; - static char* kwlist[] = { "pattern", "pos", "endpos", NULL }; - if (!PyArg_ParseTupleAndKeywords(args, kw, "O|nn:match", kwlist, - &string, &start, &end)) - return NULL; - - string = state_init(&state, self, string, start, end); - if (!string) - return NULL; - - state.ptr = state.start; - - TRACE(("|%p|%p|MATCH\n", PatternObject_GetCode(self), state.ptr)); - - if (state.charsize == 1) { - status = sre_match(&state, PatternObject_GetCode(self)); - } else { -#if defined(HAVE_UNICODE) - status = sre_umatch(&state, PatternObject_GetCode(self)); -#endif - } - - TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr)); - if (PyErr_Occurred()) - return NULL; - - state_fini(&state); - - return pattern_new_match(self, &state, status); -} - -static PyObject* -pattern_search(PatternObject* self, PyObject* args, PyObject* kw) -{ - SRE_STATE state; - int status; - - PyObject* string; - Py_ssize_t start = 0; - Py_ssize_t end = PY_SSIZE_T_MAX; - static char* kwlist[] = { "pattern", "pos", "endpos", NULL }; - if (!PyArg_ParseTupleAndKeywords(args, kw, "O|nn:search", kwlist, - &string, &start, &end)) - return NULL; - - string = state_init(&state, self, string, start, end); - if (!string) - return NULL; - - TRACE(("|%p|%p|SEARCH\n", PatternObject_GetCode(self), state.ptr)); - - if (state.charsize == 1) { - status = sre_search(&state, PatternObject_GetCode(self)); - } else { -#if defined(HAVE_UNICODE) - status = sre_usearch(&state, PatternObject_GetCode(self)); -#endif - } - - TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr)); - - state_fini(&state); - - if (PyErr_Occurred()) - return NULL; - - return pattern_new_match(self, &state, status); -} - -static PyObject* -call(char* module, char* function, PyObject* args) -{ - PyObject* name; - PyObject* mod; - PyObject* func; - PyObject* result; - - if (!args) - return NULL; - name = PyString_FromString(module); - if (!name) - return NULL; - mod = PyImport_Import(name); - Py_DECREF(name); - if (!mod) - return NULL; - func = PyObject_GetAttrString(mod, function); - Py_DECREF(mod); - if (!func) - return NULL; - result = PyObject_CallObject(func, args); - Py_DECREF(func); - Py_DECREF(args); - return result; -} - -#ifdef USE_BUILTIN_COPY -static int -deepcopy(PyObject** object, PyObject* memo) -{ - PyObject* copy; - - copy = call( - "copy", "deepcopy", - PyTuple_Pack(2, *object, memo) - ); - if (!copy) - return 0; - - Py_DECREF(*object); - *object = copy; - - return 1; /* success */ -} -#endif - -static PyObject* -join_list(PyObject* list, PyObject* string) -{ - /* join list elements */ - - PyObject* joiner; -#if PY_VERSION_HEX >= 0x01060000 - PyObject* function; - PyObject* args; -#endif - PyObject* result; - - joiner = PySequence_GetSlice(string, 0, 0); - if (!joiner) - return NULL; - - if (PyList_GET_SIZE(list) == 0) { - Py_DECREF(list); - return joiner; - } - -#if PY_VERSION_HEX >= 0x01060000 - function = PyObject_GetAttrString(joiner, "join"); - if (!function) { - Py_DECREF(joiner); - return NULL; - } - args = PyTuple_New(1); - if (!args) { - Py_DECREF(function); - Py_DECREF(joiner); - return NULL; - } - PyTuple_SET_ITEM(args, 0, list); - result = PyObject_CallObject(function, args); - Py_DECREF(args); /* also removes list */ - Py_DECREF(function); -#else - result = call( - "string", "join", - PyTuple_Pack(2, list, joiner) - ); -#endif - Py_DECREF(joiner); - - return result; -} - -static PyObject* -pattern_findall(PatternObject* self, PyObject* args, PyObject* kw) -{ - SRE_STATE state; - PyObject* list; - int status; - Py_ssize_t i, b, e; - - PyObject* string; - Py_ssize_t start = 0; - Py_ssize_t end = PY_SSIZE_T_MAX; - static char* kwlist[] = { "source", "pos", "endpos", NULL }; - if (!PyArg_ParseTupleAndKeywords(args, kw, "O|nn:findall", kwlist, - &string, &start, &end)) - return NULL; - - string = state_init(&state, self, string, start, end); - if (!string) - return NULL; - - list = PyList_New(0); - if (!list) { - state_fini(&state); - return NULL; - } - - while (state.start <= state.end) { - - PyObject* item; - - state_reset(&state); - - state.ptr = state.start; - - if (state.charsize == 1) { - status = sre_search(&state, PatternObject_GetCode(self)); - } else { -#if defined(HAVE_UNICODE) - status = sre_usearch(&state, PatternObject_GetCode(self)); -#endif - } - - if (PyErr_Occurred()) - goto error; - - if (status <= 0) { - if (status == 0) - break; - pattern_error(status); - goto error; - } - - /* don't bother to build a match object */ - switch (self->groups) { - case 0: - b = STATE_OFFSET(&state, state.start); - e = STATE_OFFSET(&state, state.ptr); - item = PySequence_GetSlice(string, b, e); - if (!item) - goto error; - break; - case 1: - item = state_getslice(&state, 1, string, 1); - if (!item) - goto error; - break; - default: - item = PyTuple_New(self->groups); - if (!item) - goto error; - for (i = 0; i < self->groups; i++) { - PyObject* o = state_getslice(&state, i+1, string, 1); - if (!o) { - Py_DECREF(item); - goto error; - } - PyTuple_SET_ITEM(item, i, o); - } - break; - } - - status = PyList_Append(list, item); - Py_DECREF(item); - if (status < 0) - goto error; - - if (state.ptr == state.start) - state.start = (void*) ((char*) state.ptr + state.charsize); - else - state.start = state.ptr; - - } - - state_fini(&state); - return list; - -error: - Py_DECREF(list); - state_fini(&state); - return NULL; - -} - -#if PY_VERSION_HEX >= 0x02020000 -static PyObject* -pattern_finditer(PatternObject* pattern, PyObject* args) -{ - PyObject* scanner; - PyObject* search; - PyObject* iterator; - - scanner = pattern_scanner(pattern, args); - if (!scanner) - return NULL; - - search = PyObject_GetAttrString(scanner, "search"); - Py_DECREF(scanner); - if (!search) - return NULL; - - iterator = PyCallIter_New(search, Py_None); - Py_DECREF(search); - - return iterator; -} -#endif - -static PyObject* -pattern_split(PatternObject* self, PyObject* args, PyObject* kw) -{ - SRE_STATE state; - PyObject* list; - PyObject* item; - int status; - Py_ssize_t n; - Py_ssize_t i; - void* last; - - PyObject* string; - Py_ssize_t maxsplit = 0; - static char* kwlist[] = { "source", "maxsplit", NULL }; - if (!PyArg_ParseTupleAndKeywords(args, kw, "O|n:split", kwlist, - &string, &maxsplit)) - return NULL; - - string = state_init(&state, self, string, 0, PY_SSIZE_T_MAX); - if (!string) - return NULL; - - list = PyList_New(0); - if (!list) { - state_fini(&state); - return NULL; - } - - n = 0; - last = state.start; - - while (!maxsplit || n < maxsplit) { - - state_reset(&state); - - state.ptr = state.start; - - if (state.charsize == 1) { - status = sre_search(&state, PatternObject_GetCode(self)); - } else { -#if defined(HAVE_UNICODE) - status = sre_usearch(&state, PatternObject_GetCode(self)); -#endif - } - - if (PyErr_Occurred()) - goto error; - - if (status <= 0) { - if (status == 0) - break; - pattern_error(status); - goto error; - } - - if (state.start == state.ptr) { - if (last == state.end) - break; - /* skip one character */ - state.start = (void*) ((char*) state.ptr + state.charsize); - continue; - } - - /* get segment before this match */ - item = PySequence_GetSlice( - string, STATE_OFFSET(&state, last), - STATE_OFFSET(&state, state.start) - ); - if (!item) - goto error; - status = PyList_Append(list, item); - Py_DECREF(item); - if (status < 0) - goto error; - - /* add groups (if any) */ - for (i = 0; i < self->groups; i++) { - item = state_getslice(&state, i+1, string, 0); - if (!item) - goto error; - status = PyList_Append(list, item); - Py_DECREF(item); - if (status < 0) - goto error; - } - - n = n + 1; - - last = state.start = state.ptr; - - } - - /* get segment following last match (even if empty) */ - item = PySequence_GetSlice( - string, STATE_OFFSET(&state, last), state.endpos - ); - if (!item) - goto error; - status = PyList_Append(list, item); - Py_DECREF(item); - if (status < 0) - goto error; - - state_fini(&state); - return list; - -error: - Py_DECREF(list); - state_fini(&state); - return NULL; - -} - -static PyObject* -pattern_subx(PatternObject* self, PyObject* ptemplate, PyObject* string, - Py_ssize_t count, Py_ssize_t subn) -{ - SRE_STATE state; - PyObject* list; - PyObject* item; - PyObject* filter; - PyObject* args; - PyObject* match; - void* ptr; - int status; - Py_ssize_t n; - Py_ssize_t i, b, e; - int bint; - int filter_is_callable; - - if (PyCallable_Check(ptemplate)) { - /* sub/subn takes either a function or a template */ - filter = ptemplate; - Py_INCREF(filter); - filter_is_callable = 1; - } else { - /* if not callable, check if it's a literal string */ - int literal; - ptr = getstring(ptemplate, &n, &bint); - b = bint; - if (ptr) { - if (b == 1) { - literal = sre_literal_template((unsigned char *)ptr, n); - } else { -#if defined(HAVE_UNICODE) - literal = sre_uliteral_template((Py_UNICODE *)ptr, n); -#endif - } - } else { - PyErr_Clear(); - literal = 0; - } - if (literal) { - filter = ptemplate; - Py_INCREF(filter); - filter_is_callable = 0; - } else { - /* not a literal; hand it over to the template compiler */ - filter = call( - SRE_PY_MODULE, "_subx", - PyTuple_Pack(2, self, ptemplate) - ); - if (!filter) - return NULL; - filter_is_callable = PyCallable_Check(filter); - } - } - - string = state_init(&state, self, string, 0, PY_SSIZE_T_MAX); - if (!string) { - Py_DECREF(filter); - return NULL; - } - - list = PyList_New(0); - if (!list) { - Py_DECREF(filter); - state_fini(&state); - return NULL; - } - - n = i = 0; - - while (!count || n < count) { - - state_reset(&state); - - state.ptr = state.start; - - if (state.charsize == 1) { - status = sre_search(&state, PatternObject_GetCode(self)); - } else { -#if defined(HAVE_UNICODE) - status = sre_usearch(&state, PatternObject_GetCode(self)); -#endif - } - - if (PyErr_Occurred()) - goto error; - - if (status <= 0) { - if (status == 0) - break; - pattern_error(status); - goto error; - } - - b = STATE_OFFSET(&state, state.start); - e = STATE_OFFSET(&state, state.ptr); - - if (i < b) { - /* get segment before this match */ - item = PySequence_GetSlice(string, i, b); - if (!item) - goto error; - status = PyList_Append(list, item); - Py_DECREF(item); - if (status < 0) - goto error; - - } else if (i == b && i == e && n > 0) - /* ignore empty match on latest position */ - goto next; - - if (filter_is_callable) { - /* pass match object through filter */ - match = pattern_new_match(self, &state, 1); - if (!match) - goto error; - args = PyTuple_Pack(1, match); - if (!args) { - Py_DECREF(match); - goto error; - } - item = PyObject_CallObject(filter, args); - Py_DECREF(args); - Py_DECREF(match); - if (!item) - goto error; - } else { - /* filter is literal string */ - item = filter; - Py_INCREF(item); - } - - /* add to list */ - if (item != Py_None) { - status = PyList_Append(list, item); - Py_DECREF(item); - if (status < 0) - goto error; - } - - i = e; - n = n + 1; - -next: - /* move on */ - if (state.ptr == state.start) - state.start = (void*) ((char*) state.ptr + state.charsize); - else - state.start = state.ptr; - - } - - /* get segment following last match */ - if (i < state.endpos) { - item = PySequence_GetSlice(string, i, state.endpos); - if (!item) - goto error; - status = PyList_Append(list, item); - Py_DECREF(item); - if (status < 0) - goto error; - } - - state_fini(&state); - - Py_DECREF(filter); - - /* convert list to single string (also removes list) */ - item = join_list(list, string); - - if (!item) - return NULL; - - if (subn) - return Py_BuildValue("Ni", item, n); - - return item; - -error: - Py_DECREF(list); - state_fini(&state); - Py_DECREF(filter); - return NULL; - -} - -static PyObject* -pattern_sub(PatternObject* self, PyObject* args, PyObject* kw) -{ - PyObject* ptemplate; - PyObject* string; - Py_ssize_t count = 0; - static char* kwlist[] = { "repl", "string", "count", NULL }; - if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|n:sub", kwlist, - &ptemplate, &string, &count)) - return NULL; - - return pattern_subx(self, ptemplate, string, count, 0); -} - -static PyObject* -pattern_subn(PatternObject* self, PyObject* args, PyObject* kw) -{ - PyObject* ptemplate; - PyObject* string; - Py_ssize_t count = 0; - static char* kwlist[] = { "repl", "string", "count", NULL }; - if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|n:subn", kwlist, - &ptemplate, &string, &count)) - return NULL; - - return pattern_subx(self, ptemplate, string, count, 1); -} - -static PyObject* -pattern_copy(PatternObject* self, PyObject *unused) -{ -#ifdef USE_BUILTIN_COPY - PatternObject* copy; - int offset; - - copy = PyObject_NEW_VAR(PatternObject, &Pattern_Type, self->codesize); - if (!copy) - return NULL; - - offset = offsetof(PatternObject, groups); - - Py_XINCREF(self->groupindex); - Py_XINCREF(self->indexgroup); - Py_XINCREF(self->pattern); - - memcpy((char*) copy + offset, (char*) self + offset, - sizeof(PatternObject) + self->codesize * sizeof(SRE_CODE) - offset); - copy->weakreflist = NULL; - - return (PyObject*) copy; -#else - PyErr_SetString(PyExc_TypeError, "cannot copy this pattern object"); - return NULL; -#endif -} - -static PyObject* -pattern_deepcopy(PatternObject* self, PyObject* memo) -{ -#ifdef USE_BUILTIN_COPY - PatternObject* copy; - - copy = (PatternObject*) pattern_copy(self); - if (!copy) - return NULL; - - if (!deepcopy(©->groupindex, memo) || - !deepcopy(©->indexgroup, memo) || - !deepcopy(©->pattern, memo)) { - Py_DECREF(copy); - return NULL; - } - -#else - PyErr_SetString(PyExc_TypeError, "cannot deepcopy this pattern object"); - return NULL; -#endif -} - -PyDoc_STRVAR(pattern_match_doc, -"match(string[, pos[, endpos]]) --> match object or None.\n\ - Matches zero or more characters at the beginning of the string"); - -PyDoc_STRVAR(pattern_search_doc, -"search(string[, pos[, endpos]]) --> match object or None.\n\ - Scan through string looking for a match, and return a corresponding\n\ - MatchObject instance. Return None if no position in the string matches."); - -PyDoc_STRVAR(pattern_split_doc, -"split(string[, maxsplit = 0]) --> list.\n\ - Split string by the occurrences of pattern."); - -PyDoc_STRVAR(pattern_findall_doc, -"findall(string[, pos[, endpos]]) --> list.\n\ - Return a list of all non-overlapping matches of pattern in string."); - -PyDoc_STRVAR(pattern_finditer_doc, -"finditer(string[, pos[, endpos]]) --> iterator.\n\ - Return an iterator over all non-overlapping matches for the \n\ - RE pattern in string. For each match, the iterator returns a\n\ - match object."); - -PyDoc_STRVAR(pattern_sub_doc, -"sub(repl, string[, count = 0]) --> newstring\n\ - Return the string obtained by replacing the leftmost non-overlapping\n\ - occurrences of pattern in string by the replacement repl."); - -PyDoc_STRVAR(pattern_subn_doc, -"subn(repl, string[, count = 0]) --> (newstring, number of subs)\n\ - Return the tuple (new_string, number_of_subs_made) found by replacing\n\ - the leftmost non-overlapping occurrences of pattern with the\n\ - replacement repl."); - -PyDoc_STRVAR(pattern_doc, "Compiled regular expression objects"); - -static PyMethodDef pattern_methods[] = { - {"match", (PyCFunction) pattern_match, METH_VARARGS|METH_KEYWORDS, - pattern_match_doc}, - {"search", (PyCFunction) pattern_search, METH_VARARGS|METH_KEYWORDS, - pattern_search_doc}, - {"sub", (PyCFunction) pattern_sub, METH_VARARGS|METH_KEYWORDS, - pattern_sub_doc}, - {"subn", (PyCFunction) pattern_subn, METH_VARARGS|METH_KEYWORDS, - pattern_subn_doc}, - {"split", (PyCFunction) pattern_split, METH_VARARGS|METH_KEYWORDS, - pattern_split_doc}, - {"findall", (PyCFunction) pattern_findall, METH_VARARGS|METH_KEYWORDS, - pattern_findall_doc}, -#if PY_VERSION_HEX >= 0x02020000 - {"finditer", (PyCFunction) pattern_finditer, METH_VARARGS, - pattern_finditer_doc}, -#endif - {"scanner", (PyCFunction) pattern_scanner, METH_VARARGS}, - {"__copy__", (PyCFunction) pattern_copy, METH_NOARGS}, - {"__deepcopy__", (PyCFunction) pattern_deepcopy, METH_O}, - {NULL, NULL} -}; - -#define PAT_OFF(x) offsetof(PatternObject, x) -static PyMemberDef pattern_members[] = { - {"pattern", T_OBJECT, PAT_OFF(pattern), READONLY}, - {"flags", T_INT, PAT_OFF(flags), READONLY}, - {"groups", T_PYSSIZET, PAT_OFF(groups), READONLY}, - {"groupindex", T_OBJECT, PAT_OFF(groupindex), READONLY}, - {NULL} /* Sentinel */ -}; - -statichere PyTypeObject Pattern_Type = { - PyObject_HEAD_INIT(NULL) - 0, "_" SRE_MODULE ".SRE_Pattern", - sizeof(PatternObject), sizeof(SRE_CODE), - (destructor)pattern_dealloc, /*tp_dealloc*/ - 0, /* tp_print */ - 0, /* tp_getattrn */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - pattern_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(PatternObject, weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - pattern_methods, /* tp_methods */ - pattern_members, /* tp_members */ -}; - -static int _validate(PatternObject *self); /* Forward */ - -static PyObject * -_compile(PyObject* self_, PyObject* args) -{ - /* "compile" pattern descriptor to pattern object */ - - PatternObject* self; - Py_ssize_t i, n; - - PyObject* pattern; - int flags = 0; - PyObject* code; - Py_ssize_t groups = 0; - PyObject* groupindex = NULL; - PyObject* indexgroup = NULL; - if (!PyArg_ParseTuple(args, "OiO!|nOO", &pattern, &flags, - &PyList_Type, &code, &groups, - &groupindex, &indexgroup)) - return NULL; - - n = PyList_GET_SIZE(code); - /* coverity[ampersand_in_size] */ - self = PyObject_NEW_VAR(PatternObject, &Pattern_Type, n); - if (!self) - return NULL; - self->weakreflist = NULL; - self->pattern = NULL; - self->groupindex = NULL; - self->indexgroup = NULL; - - self->codesize = n; - - for (i = 0; i < n; i++) { - PyObject *o = PyList_GET_ITEM(code, i); - unsigned long value = PyInt_Check(o) ? (unsigned long)PyInt_AsLong(o) - : PyLong_AsUnsignedLong(o); - self->code[i] = (SRE_CODE) value; - if ((unsigned long) self->code[i] != value) { - PyErr_SetString(PyExc_OverflowError, - "regular expression code size limit exceeded"); - break; - } - } - - if (PyErr_Occurred()) { - Py_DECREF(self); - return NULL; - } - - Py_INCREF(pattern); - self->pattern = pattern; - - self->flags = flags; - - self->groups = groups; - - Py_XINCREF(groupindex); - self->groupindex = groupindex; - - Py_XINCREF(indexgroup); - self->indexgroup = indexgroup; - - self->weakreflist = NULL; - - if (!_validate(self)) { - Py_DECREF(self); - return NULL; - } - - return (PyObject*) self; -} - -/* -------------------------------------------------------------------- */ -/* Code validation */ - -/* To learn more about this code, have a look at the _compile() function in - Lib/sre_compile.py. The validation functions below checks the code array - for conformance with the code patterns generated there. - - The nice thing about the generated code is that it is position-independent: - all jumps are relative jumps forward. Also, jumps don't cross each other: - the target of a later jump is always earlier than the target of an earlier - jump. IOW, this is okay: - - J---------J-------T--------T - \ \_____/ / - \______________________/ - - but this is not: - - J---------J-------T--------T - \_________\_____/ / - \____________/ - - It also helps that SRE_CODE is always an unsigned type, either 2 bytes or 4 - bytes wide (the latter if Python is compiled for "wide" unicode support). -*/ - -/* Defining this one enables tracing of the validator */ -#undef VVERBOSE - -/* Trace macro for the validator */ -#if defined(VVERBOSE) -#define VTRACE(v) printf v -#else -#define VTRACE(v) -#endif - -/* Report failure */ -#define FAIL do { VTRACE(("FAIL: %d\n", __LINE__)); return 0; } while (0) - -/* Extract opcode, argument, or skip count from code array */ -#define GET_OP \ - do { \ - VTRACE(("%p: ", code)); \ - if (code >= end) FAIL; \ - op = *code++; \ - VTRACE(("%lu (op)\n", (unsigned long)op)); \ - } while (0) -#define GET_ARG \ - do { \ - VTRACE(("%p= ", code)); \ - if (code >= end) FAIL; \ - arg = *code++; \ - VTRACE(("%lu (arg)\n", (unsigned long)arg)); \ - } while (0) -#define GET_SKIP_ADJ(adj) \ - do { \ - VTRACE(("%p= ", code)); \ - if (code >= end) FAIL; \ - skip = *code; \ - VTRACE(("%lu (skip to %p)\n", \ - (unsigned long)skip, code+skip)); \ - if (code+skip-adj < code || code+skip-adj > end)\ - FAIL; \ - code++; \ - } while (0) -#define GET_SKIP GET_SKIP_ADJ(0) - -static int -_validate_charset(SRE_CODE *code, SRE_CODE *end) -{ - /* Some variables are manipulated by the macros above */ - SRE_CODE op; - SRE_CODE arg; - SRE_CODE offset; - int i; - - while (code < end) { - GET_OP; - switch (op) { - - case SRE_OP_NEGATE: - break; - - case SRE_OP_LITERAL: - GET_ARG; - break; - - case SRE_OP_RANGE: - GET_ARG; - GET_ARG; - break; - - case SRE_OP_CHARSET: - offset = 32/sizeof(SRE_CODE); /* 32-byte bitmap */ - if (code+offset < code || code+offset > end) - FAIL; - code += offset; - break; - - case SRE_OP_BIGCHARSET: - GET_ARG; /* Number of blocks */ - offset = 256/sizeof(SRE_CODE); /* 256-byte table */ - if (code+offset < code || code+offset > end) - FAIL; - /* Make sure that each byte points to a valid block */ - for (i = 0; i < 256; i++) { - if (((unsigned char *)code)[i] >= arg) - FAIL; - } - code += offset; - offset = arg * 32/sizeof(SRE_CODE); /* 32-byte bitmap times arg */ - if (code+offset < code || code+offset > end) - FAIL; - code += offset; - break; - - case SRE_OP_CATEGORY: - GET_ARG; - switch (arg) { - case SRE_CATEGORY_DIGIT: - case SRE_CATEGORY_NOT_DIGIT: - case SRE_CATEGORY_SPACE: - case SRE_CATEGORY_NOT_SPACE: - case SRE_CATEGORY_WORD: - case SRE_CATEGORY_NOT_WORD: - case SRE_CATEGORY_LINEBREAK: - case SRE_CATEGORY_NOT_LINEBREAK: - case SRE_CATEGORY_LOC_WORD: - case SRE_CATEGORY_LOC_NOT_WORD: - case SRE_CATEGORY_UNI_DIGIT: - case SRE_CATEGORY_UNI_NOT_DIGIT: - case SRE_CATEGORY_UNI_SPACE: - case SRE_CATEGORY_UNI_NOT_SPACE: - case SRE_CATEGORY_UNI_WORD: - case SRE_CATEGORY_UNI_NOT_WORD: - case SRE_CATEGORY_UNI_LINEBREAK: - case SRE_CATEGORY_UNI_NOT_LINEBREAK: - break; - default: - FAIL; - } - break; - - default: - FAIL; - - } - } - - return 1; -} - -static int -_validate_inner(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups) -{ - /* Some variables are manipulated by the macros above */ - SRE_CODE op; - SRE_CODE arg; - SRE_CODE skip; - - VTRACE(("code=%p, end=%p\n", code, end)); - - if (code > end) - FAIL; - - while (code < end) { - GET_OP; - switch (op) { - - case SRE_OP_MARK: - /* We don't check whether marks are properly nested; the - sre_match() code is robust even if they don't, and the worst - you can get is nonsensical match results. */ - GET_ARG; - if (arg > 2*groups+1) { - VTRACE(("arg=%d, groups=%d\n", (int)arg, (int)groups)); - FAIL; - } - break; - - case SRE_OP_LITERAL: - case SRE_OP_NOT_LITERAL: - case SRE_OP_LITERAL_IGNORE: - case SRE_OP_NOT_LITERAL_IGNORE: - GET_ARG; - /* The arg is just a character, nothing to check */ - break; - - case SRE_OP_SUCCESS: - case SRE_OP_FAILURE: - /* Nothing to check; these normally end the matching process */ - break; - - case SRE_OP_AT: - GET_ARG; - switch (arg) { - case SRE_AT_BEGINNING: - case SRE_AT_BEGINNING_STRING: - case SRE_AT_BEGINNING_LINE: - case SRE_AT_END: - case SRE_AT_END_LINE: - case SRE_AT_END_STRING: - case SRE_AT_BOUNDARY: - case SRE_AT_NON_BOUNDARY: - case SRE_AT_LOC_BOUNDARY: - case SRE_AT_LOC_NON_BOUNDARY: - case SRE_AT_UNI_BOUNDARY: - case SRE_AT_UNI_NON_BOUNDARY: - break; - default: - FAIL; - } - break; - - case SRE_OP_ANY: - case SRE_OP_ANY_ALL: - /* These have no operands */ - break; - - case SRE_OP_IN: - case SRE_OP_IN_IGNORE: - GET_SKIP; - /* Stop 1 before the end; we check the FAILURE below */ - if (!_validate_charset(code, code+skip-2)) - FAIL; - if (code[skip-2] != SRE_OP_FAILURE) - FAIL; - code += skip-1; - break; - - case SRE_OP_INFO: - { - /* A minimal info field is - <1=skip> <2=flags> <3=min> <4=max>; - If SRE_INFO_PREFIX or SRE_INFO_CHARSET is in the flags, - more follows. */ - SRE_CODE flags, i; - SRE_CODE *newcode; - GET_SKIP; - newcode = code+skip-1; - GET_ARG; flags = arg; - GET_ARG; /* min */ - GET_ARG; /* max */ - /* Check that only valid flags are present */ - if ((flags & ~(SRE_INFO_PREFIX | - SRE_INFO_LITERAL | - SRE_INFO_CHARSET)) != 0) - FAIL; - /* PREFIX and CHARSET are mutually exclusive */ - if ((flags & SRE_INFO_PREFIX) && - (flags & SRE_INFO_CHARSET)) - FAIL; - /* LITERAL implies PREFIX */ - if ((flags & SRE_INFO_LITERAL) && - !(flags & SRE_INFO_PREFIX)) - FAIL; - /* Validate the prefix */ - if (flags & SRE_INFO_PREFIX) { - SRE_CODE prefix_len; - GET_ARG; prefix_len = arg; - GET_ARG; /* prefix skip */ - /* Here comes the prefix string */ - if (code+prefix_len < code || code+prefix_len > newcode) - FAIL; - code += prefix_len; - /* And here comes the overlap table */ - if (code+prefix_len < code || code+prefix_len > newcode) - FAIL; - /* Each overlap value should be < prefix_len */ - for (i = 0; i < prefix_len; i++) { - if (code[i] >= prefix_len) - FAIL; - } - code += prefix_len; - } - /* Validate the charset */ - if (flags & SRE_INFO_CHARSET) { - if (!_validate_charset(code, newcode-1)) - FAIL; - if (newcode[-1] != SRE_OP_FAILURE) - FAIL; - code = newcode; - } - else if (code != newcode) { - VTRACE(("code=%p, newcode=%p\n", code, newcode)); - FAIL; - } - } - break; - - case SRE_OP_BRANCH: - { - SRE_CODE *target = NULL; - for (;;) { - GET_SKIP; - if (skip == 0) - break; - /* Stop 2 before the end; we check the JUMP below */ - if (!_validate_inner(code, code+skip-3, groups)) - FAIL; - code += skip-3; - /* Check that it ends with a JUMP, and that each JUMP - has the same target */ - GET_OP; - if (op != SRE_OP_JUMP) - FAIL; - GET_SKIP; - if (target == NULL) - target = code+skip-1; - else if (code+skip-1 != target) - FAIL; - } - } - break; - - case SRE_OP_REPEAT_ONE: - case SRE_OP_MIN_REPEAT_ONE: - { - SRE_CODE min, max; - GET_SKIP; - GET_ARG; min = arg; - GET_ARG; max = arg; - if (min > max) - FAIL; -#ifdef Py_UNICODE_WIDE - if (max > 65535) - FAIL; -#endif - if (!_validate_inner(code, code+skip-4, groups)) - FAIL; - code += skip-4; - GET_OP; - if (op != SRE_OP_SUCCESS) - FAIL; - } - break; - - case SRE_OP_REPEAT: - { - SRE_CODE min, max; - GET_SKIP; - GET_ARG; min = arg; - GET_ARG; max = arg; - if (min > max) - FAIL; -#ifdef Py_UNICODE_WIDE - if (max > 65535) - FAIL; -#endif - if (!_validate_inner(code, code+skip-3, groups)) - FAIL; - code += skip-3; - GET_OP; - if (op != SRE_OP_MAX_UNTIL && op != SRE_OP_MIN_UNTIL) - FAIL; - } - break; - - case SRE_OP_GROUPREF: - case SRE_OP_GROUPREF_IGNORE: - GET_ARG; - if (arg >= groups) - FAIL; - break; - - case SRE_OP_GROUPREF_EXISTS: - /* The regex syntax for this is: '(?(group)then|else)', where - 'group' is either an integer group number or a group name, - 'then' and 'else' are sub-regexes, and 'else' is optional. */ - GET_ARG; - if (arg >= groups) - FAIL; - GET_SKIP_ADJ(1); - code--; /* The skip is relative to the first arg! */ - /* There are two possibilities here: if there is both a 'then' - part and an 'else' part, the generated code looks like: - - GROUPREF_EXISTS - - - ...then part... - JUMP - - ( jumps here) - ...else part... - ( jumps here) - - If there is only a 'then' part, it looks like: - - GROUPREF_EXISTS - - - ...then part... - ( jumps here) - - There is no direct way to decide which it is, and we don't want - to allow arbitrary jumps anywhere in the code; so we just look - for a JUMP opcode preceding our skip target. - */ - if (skip >= 3 && code+skip-3 >= code && - code[skip-3] == SRE_OP_JUMP) - { - VTRACE(("both then and else parts present\n")); - if (!_validate_inner(code+1, code+skip-3, groups)) - FAIL; - code += skip-2; /* Position after JUMP, at */ - GET_SKIP; - if (!_validate_inner(code, code+skip-1, groups)) - FAIL; - code += skip-1; - } - else { - VTRACE(("only a then part present\n")); - if (!_validate_inner(code+1, code+skip-1, groups)) - FAIL; - code += skip-1; - } - break; - - case SRE_OP_ASSERT: - case SRE_OP_ASSERT_NOT: - GET_SKIP; - GET_ARG; /* 0 for lookahead, width for lookbehind */ - code--; /* Back up over arg to simplify math below */ - if (arg & 0x80000000) - FAIL; /* Width too large */ - /* Stop 1 before the end; we check the SUCCESS below */ - if (!_validate_inner(code+1, code+skip-2, groups)) - FAIL; - code += skip-2; - GET_OP; - if (op != SRE_OP_SUCCESS) - FAIL; - break; - - default: - FAIL; - - } - } - - VTRACE(("okay\n")); - return 1; -} - -static int -_validate_outer(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups) -{ - if (groups < 0 || groups > 100 || code >= end || end[-1] != SRE_OP_SUCCESS) - FAIL; - if (groups == 0) /* fix for simplejson */ - groups = 100; /* 100 groups should always be safe */ - return _validate_inner(code, end-1, groups); -} - -static int -_validate(PatternObject *self) -{ - if (!_validate_outer(self->code, self->code+self->codesize, self->groups)) - { - PyErr_SetString(PyExc_RuntimeError, "invalid SRE code"); - return 0; - } - else - VTRACE(("Success!\n")); - return 1; -} - -/* -------------------------------------------------------------------- */ -/* match methods */ - -static void -match_dealloc(MatchObject* self) -{ - Py_XDECREF(self->regs); - Py_XDECREF(self->string); - Py_DECREF(self->pattern); - PyObject_DEL(self); -} - -static PyObject* -match_getslice_by_index(MatchObject* self, Py_ssize_t index, PyObject* def) -{ - if (index < 0 || index >= self->groups) { - /* raise IndexError if we were given a bad group number */ - PyErr_SetString( - PyExc_IndexError, - "no such group" - ); - return NULL; - } - - index *= 2; - - if (self->string == Py_None || self->mark[index] < 0) { - /* return default value if the string or group is undefined */ - Py_INCREF(def); - return def; - } - - return PySequence_GetSlice( - self->string, self->mark[index], self->mark[index+1] - ); -} - -static Py_ssize_t -match_getindex(MatchObject* self, PyObject* index) -{ - Py_ssize_t i; - - if (PyInt_Check(index)) - return PyInt_AsSsize_t(index); - - i = -1; - - if (self->pattern->groupindex) { - index = PyObject_GetItem(self->pattern->groupindex, index); - if (index) { - if (PyInt_Check(index) || PyLong_Check(index)) - i = PyInt_AsSsize_t(index); - Py_DECREF(index); - } else - PyErr_Clear(); - } - - return i; -} - -static PyObject* -match_getslice(MatchObject* self, PyObject* index, PyObject* def) -{ - return match_getslice_by_index(self, match_getindex(self, index), def); -} - -static PyObject* -match_expand(MatchObject* self, PyObject* ptemplate) -{ - /* delegate to Python code */ - return call( - SRE_PY_MODULE, "_expand", - PyTuple_Pack(3, self->pattern, self, ptemplate) - ); -} - -static PyObject* -match_group(MatchObject* self, PyObject* args) -{ - PyObject* result; - Py_ssize_t i, size; - - size = PyTuple_GET_SIZE(args); - - switch (size) { - case 0: - result = match_getslice(self, Py_False, Py_None); - break; - case 1: - result = match_getslice(self, PyTuple_GET_ITEM(args, 0), Py_None); - break; - default: - /* fetch multiple items */ - result = PyTuple_New(size); - if (!result) - return NULL; - for (i = 0; i < size; i++) { - PyObject* item = match_getslice( - self, PyTuple_GET_ITEM(args, i), Py_None - ); - if (!item) { - Py_DECREF(result); - return NULL; - } - PyTuple_SET_ITEM(result, i, item); - } - break; - } - return result; -} - -static PyObject* -match_groups(MatchObject* self, PyObject* args, PyObject* kw) -{ - PyObject* result; - Py_ssize_t index; - - PyObject* def = Py_None; - static char* kwlist[] = { "default", NULL }; - if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:groups", kwlist, &def)) - return NULL; - - result = PyTuple_New(self->groups-1); - if (!result) - return NULL; - - for (index = 1; index < self->groups; index++) { - PyObject* item; - item = match_getslice_by_index(self, index, def); - if (!item) { - Py_DECREF(result); - return NULL; - } - PyTuple_SET_ITEM(result, index-1, item); - } - - return result; -} - -static PyObject* -match_groupdict(MatchObject* self, PyObject* args, PyObject* kw) -{ - PyObject* result; - PyObject* keys; - Py_ssize_t index; - - PyObject* def = Py_None; - static char* kwlist[] = { "default", NULL }; - if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:groupdict", kwlist, &def)) - return NULL; - - result = PyDict_New(); - if (!result || !self->pattern->groupindex) - return result; - - keys = PyMapping_Keys(self->pattern->groupindex); - if (!keys) - goto failed; - - for (index = 0; index < PyList_GET_SIZE(keys); index++) { - int status; - PyObject* key; - PyObject* value; - key = PyList_GET_ITEM(keys, index); - if (!key) - goto failed; - value = match_getslice(self, key, def); - if (!value) { - Py_DECREF(key); - goto failed; - } - status = PyDict_SetItem(result, key, value); - Py_DECREF(value); - if (status < 0) - goto failed; - } - - Py_DECREF(keys); - - return result; - -failed: - Py_XDECREF(keys); - Py_DECREF(result); - return NULL; -} - -static PyObject* -match_start(MatchObject* self, PyObject* args) -{ - Py_ssize_t index; - - PyObject* index_ = Py_False; /* zero */ - if (!PyArg_UnpackTuple(args, "start", 0, 1, &index_)) - return NULL; - - index = match_getindex(self, index_); - - if (index < 0 || index >= self->groups) { - PyErr_SetString( - PyExc_IndexError, - "no such group" - ); - return NULL; - } - - /* mark is -1 if group is undefined */ - return Py_BuildValue("i", self->mark[index*2]); -} - -static PyObject* -match_end(MatchObject* self, PyObject* args) -{ - Py_ssize_t index; - - PyObject* index_ = Py_False; /* zero */ - if (!PyArg_UnpackTuple(args, "end", 0, 1, &index_)) - return NULL; - - index = match_getindex(self, index_); - - if (index < 0 || index >= self->groups) { - PyErr_SetString( - PyExc_IndexError, - "no such group" - ); - return NULL; - } - - /* mark is -1 if group is undefined */ - return Py_BuildValue("i", self->mark[index*2+1]); -} - -LOCAL(PyObject*) -_pair(Py_ssize_t i1, Py_ssize_t i2) -{ - PyObject* pair; - PyObject* item; - - pair = PyTuple_New(2); - if (!pair) - return NULL; - - item = PyInt_FromSsize_t(i1); - if (!item) - goto error; - PyTuple_SET_ITEM(pair, 0, item); - - item = PyInt_FromSsize_t(i2); - if (!item) - goto error; - PyTuple_SET_ITEM(pair, 1, item); - - return pair; - - error: - Py_DECREF(pair); - return NULL; -} - -static PyObject* -match_span(MatchObject* self, PyObject* args) -{ - Py_ssize_t index; - - PyObject* index_ = Py_False; /* zero */ - if (!PyArg_UnpackTuple(args, "span", 0, 1, &index_)) - return NULL; - - index = match_getindex(self, index_); - - if (index < 0 || index >= self->groups) { - PyErr_SetString( - PyExc_IndexError, - "no such group" - ); - return NULL; - } - - /* marks are -1 if group is undefined */ - return _pair(self->mark[index*2], self->mark[index*2+1]); -} - -static PyObject* -match_regs(MatchObject* self) -{ - PyObject* regs; - PyObject* item; - Py_ssize_t index; - - regs = PyTuple_New(self->groups); - if (!regs) - return NULL; - - for (index = 0; index < self->groups; index++) { - item = _pair(self->mark[index*2], self->mark[index*2+1]); - if (!item) { - Py_DECREF(regs); - return NULL; - } - PyTuple_SET_ITEM(regs, index, item); - } - - Py_INCREF(regs); - self->regs = regs; - - return regs; -} - -static PyObject* -match_copy(MatchObject* self, PyObject *unused) -{ -#ifdef USE_BUILTIN_COPY - MatchObject* copy; - Py_ssize_t slots, offset; - - slots = 2 * (self->pattern->groups+1); - - copy = PyObject_NEW_VAR(MatchObject, &Match_Type, slots); - if (!copy) - return NULL; - - /* this value a constant, but any compiler should be able to - figure that out all by itself */ - offset = offsetof(MatchObject, string); - - Py_XINCREF(self->pattern); - Py_XINCREF(self->string); - Py_XINCREF(self->regs); - - memcpy((char*) copy + offset, (char*) self + offset, - sizeof(MatchObject) + slots * sizeof(Py_ssize_t) - offset); - - return (PyObject*) copy; -#else - PyErr_SetString(PyExc_TypeError, "cannot copy this match object"); - return NULL; -#endif -} - -static PyObject* -match_deepcopy(MatchObject* self, PyObject* memo) -{ -#ifdef USE_BUILTIN_COPY - MatchObject* copy; - - copy = (MatchObject*) match_copy(self); - if (!copy) - return NULL; - - if (!deepcopy((PyObject**) ©->pattern, memo) || - !deepcopy(©->string, memo) || - !deepcopy(©->regs, memo)) { - Py_DECREF(copy); - return NULL; - } - -#else - PyErr_SetString(PyExc_TypeError, "cannot deepcopy this match object"); - return NULL; -#endif -} - -static struct PyMethodDef match_methods[] = { - {"group", (PyCFunction) match_group, METH_VARARGS}, - {"start", (PyCFunction) match_start, METH_VARARGS}, - {"end", (PyCFunction) match_end, METH_VARARGS}, - {"span", (PyCFunction) match_span, METH_VARARGS}, - {"groups", (PyCFunction) match_groups, METH_VARARGS|METH_KEYWORDS}, - {"groupdict", (PyCFunction) match_groupdict, METH_VARARGS|METH_KEYWORDS}, - {"expand", (PyCFunction) match_expand, METH_O}, - {"__copy__", (PyCFunction) match_copy, METH_NOARGS}, - {"__deepcopy__", (PyCFunction) match_deepcopy, METH_O}, - {NULL, NULL} -}; - -static PyObject * -match_lastindex_get(MatchObject *self) -{ - if (self->lastindex >= 0) - return Py_BuildValue("i", self->lastindex); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -match_lastgroup_get(MatchObject *self) -{ - if (self->pattern->indexgroup && self->lastindex >= 0) { - PyObject* result = PySequence_GetItem( - self->pattern->indexgroup, self->lastindex - ); - if (result) - return result; - PyErr_Clear(); - } - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -match_regs_get(MatchObject *self) -{ - if (self->regs) { - Py_INCREF(self->regs); - return self->regs; - } else - return match_regs(self); -} - -static PyGetSetDef match_getset[] = { - {"lastindex", (getter)match_lastindex_get, (setter)NULL}, - {"lastgroup", (getter)match_lastgroup_get, (setter)NULL}, - {"regs", (getter)match_regs_get, (setter)NULL}, - {NULL} -}; - -#define MATCH_OFF(x) offsetof(MatchObject, x) -static PyMemberDef match_members[] = { - {"string", T_OBJECT, MATCH_OFF(string), READONLY}, - {"re", T_OBJECT, MATCH_OFF(pattern), READONLY}, - {"pos", T_PYSSIZET, MATCH_OFF(pos), READONLY}, - {"endpos", T_PYSSIZET, MATCH_OFF(endpos), READONLY}, - {NULL} -}; - - -/* FIXME: implement setattr("string", None) as a special case (to - detach the associated string, if any */ - -static PyTypeObject Match_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_" SRE_MODULE ".SRE_Match", - sizeof(MatchObject), sizeof(Py_ssize_t), - (destructor)match_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - match_methods, /* tp_methods */ - match_members, /* tp_members */ - match_getset, /* tp_getset */ -}; - -static PyObject* -pattern_new_match(PatternObject* pattern, SRE_STATE* state, int status) -{ - /* create match object (from state object) */ - - MatchObject* match; - Py_ssize_t i, j; - char* base; - int n; - - if (status > 0) { - - /* create match object (with room for extra group marks) */ - /* coverity[ampersand_in_size] */ - match = PyObject_NEW_VAR(MatchObject, &Match_Type, - 2*(pattern->groups+1)); - if (!match) - return NULL; - - Py_INCREF(pattern); - match->pattern = pattern; - - Py_INCREF(state->string); - match->string = state->string; - - match->regs = NULL; - match->groups = pattern->groups+1; - - /* fill in group slices */ - - base = (char*) state->beginning; - n = state->charsize; - - match->mark[0] = ((char*) state->start - base) / n; - match->mark[1] = ((char*) state->ptr - base) / n; - - for (i = j = 0; i < pattern->groups; i++, j+=2) - if (j+1 <= state->lastmark && state->mark[j] && state->mark[j+1]) { - match->mark[j+2] = ((char*) state->mark[j] - base) / n; - match->mark[j+3] = ((char*) state->mark[j+1] - base) / n; - } else - match->mark[j+2] = match->mark[j+3] = -1; /* undefined */ - - match->pos = state->pos; - match->endpos = state->endpos; - - match->lastindex = state->lastindex; - - return (PyObject*) match; - - } else if (status == 0) { - - /* no match */ - Py_INCREF(Py_None); - return Py_None; - - } - - /* internal error */ - pattern_error(status); - return NULL; -} - - -/* -------------------------------------------------------------------- */ -/* scanner methods (experimental) */ - -static void -scanner_dealloc(ScannerObject* self) -{ - state_fini(&self->state); - Py_XDECREF(self->pattern); - PyObject_DEL(self); -} - -static PyObject* -scanner_match(ScannerObject* self, PyObject *unused) -{ - SRE_STATE* state = &self->state; - PyObject* match; - int status; - - state_reset(state); - - state->ptr = state->start; - - if (state->charsize == 1) { - status = sre_match(state, PatternObject_GetCode(self->pattern)); - } else { -#if defined(HAVE_UNICODE) - status = sre_umatch(state, PatternObject_GetCode(self->pattern)); -#endif - } - if (PyErr_Occurred()) - return NULL; - - match = pattern_new_match((PatternObject*) self->pattern, - state, status); - - if (status == 0 || state->ptr == state->start) - state->start = (void*) ((char*) state->ptr + state->charsize); - else - state->start = state->ptr; - - return match; -} - - -static PyObject* -scanner_search(ScannerObject* self, PyObject *unused) -{ - SRE_STATE* state = &self->state; - PyObject* match; - int status; - - state_reset(state); - - state->ptr = state->start; - - if (state->charsize == 1) { - status = sre_search(state, PatternObject_GetCode(self->pattern)); - } else { -#if defined(HAVE_UNICODE) - status = sre_usearch(state, PatternObject_GetCode(self->pattern)); -#endif - } - if (PyErr_Occurred()) - return NULL; - - match = pattern_new_match((PatternObject*) self->pattern, - state, status); - - if (status == 0 || state->ptr == state->start) - state->start = (void*) ((char*) state->ptr + state->charsize); - else - state->start = state->ptr; - - return match; -} - -static PyMethodDef scanner_methods[] = { - {"match", (PyCFunction) scanner_match, METH_NOARGS}, - {"search", (PyCFunction) scanner_search, METH_NOARGS}, - {NULL, NULL} -}; - -#define SCAN_OFF(x) offsetof(ScannerObject, x) -static PyMemberDef scanner_members[] = { - {"pattern", T_OBJECT, SCAN_OFF(pattern), READONLY}, - {NULL} /* Sentinel */ -}; - -statichere PyTypeObject Scanner_Type = { - PyObject_HEAD_INIT(NULL) - 0, "_" SRE_MODULE ".SRE_Scanner", - sizeof(ScannerObject), 0, - (destructor)scanner_dealloc, /*tp_dealloc*/ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - scanner_methods, /* tp_methods */ - scanner_members, /* tp_members */ - 0, /* tp_getset */ -}; - -static PyObject* -pattern_scanner(PatternObject* pattern, PyObject* args) -{ - /* create search state object */ - - ScannerObject* self; - - PyObject* string; - Py_ssize_t start = 0; - Py_ssize_t end = PY_SSIZE_T_MAX; - if (!PyArg_ParseTuple(args, "O|nn:scanner", &string, &start, &end)) - return NULL; - - /* create scanner object */ - self = PyObject_NEW(ScannerObject, &Scanner_Type); - if (!self) - return NULL; - self->pattern = NULL; - - string = state_init(&self->state, pattern, string, start, end); - if (!string) { - Py_DECREF(self); - return NULL; - } - - Py_INCREF(pattern); - self->pattern = (PyObject*) pattern; - - return (PyObject*) self; -} - -static PyMethodDef _functions[] = { - {"compile", _compile, METH_VARARGS}, - {"getcodesize", sre_codesize, METH_NOARGS}, - {"getlower", sre_getlower, METH_VARARGS}, - {NULL, NULL} -}; - -#if PY_VERSION_HEX < 0x02030000 -DL_EXPORT(void) init_sre(void) -#else -PyMODINIT_FUNC init_sre(void) -#endif -{ - PyObject* m; - PyObject* d; - PyObject* x; - - /* Patch object types */ - if (PyType_Ready(&Pattern_Type) || PyType_Ready(&Match_Type) || - PyType_Ready(&Scanner_Type)) - return; - - m = Py_InitModule("_" SRE_MODULE, _functions); - if (m == NULL) - return; - d = PyModule_GetDict(m); - - x = PyInt_FromLong(SRE_MAGIC); - if (x) { - PyDict_SetItemString(d, "MAGIC", x); - Py_DECREF(x); - } - - x = PyInt_FromLong(sizeof(SRE_CODE)); - if (x) { - PyDict_SetItemString(d, "CODESIZE", x); - Py_DECREF(x); - } - - x = PyString_FromString(copyright); - if (x) { - PyDict_SetItemString(d, "copyright", x); - Py_DECREF(x); - } -} - -#endif /* !defined(SRE_RECURSIVE) */ - -/* vim:ts=4:sw=4:et -*/ diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/addrinfo.h b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/addrinfo.h deleted file mode 100644 index 2b35385..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/addrinfo.h +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the project nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#ifndef HAVE_GETADDRINFO - -/* - * Error return codes from getaddrinfo() - */ -#ifdef EAI_ADDRFAMILY -/* If this is defined, there is a conflicting implementation - in the C library, which can't be used for some reason. - Make sure it won't interfere with this emulation. */ - -#undef EAI_ADDRFAMILY -#undef EAI_AGAIN -#undef EAI_BADFLAGS -#undef EAI_FAIL -#undef EAI_FAMILY -#undef EAI_MEMORY -#undef EAI_NODATA -#undef EAI_NONAME -#undef EAI_SERVICE -#undef EAI_SOCKTYPE -#undef EAI_SYSTEM -#undef EAI_BADHINTS -#undef EAI_PROTOCOL -#undef EAI_MAX -#undef getaddrinfo -#define getaddrinfo fake_getaddrinfo -#endif /* EAI_ADDRFAMILY */ - -#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */ -#define EAI_AGAIN 2 /* temporary failure in name resolution */ -#define EAI_BADFLAGS 3 /* invalid value for ai_flags */ -#define EAI_FAIL 4 /* non-recoverable failure in name resolution */ -#define EAI_FAMILY 5 /* ai_family not supported */ -#define EAI_MEMORY 6 /* memory allocation failure */ -#define EAI_NODATA 7 /* no address associated with hostname */ -#define EAI_NONAME 8 /* hostname nor servname provided, or not known */ -#define EAI_SERVICE 9 /* servname not supported for ai_socktype */ -#define EAI_SOCKTYPE 10 /* ai_socktype not supported */ -#define EAI_SYSTEM 11 /* system error returned in errno */ -#define EAI_BADHINTS 12 -#define EAI_PROTOCOL 13 -#define EAI_MAX 14 - -/* - * Flag values for getaddrinfo() - */ -#ifdef AI_PASSIVE -#undef AI_PASSIVE -#undef AI_CANONNAME -#undef AI_NUMERICHOST -#undef AI_MASK -#undef AI_ALL -#undef AI_V4MAPPED_CFG -#undef AI_ADDRCONFIG -#undef AI_V4MAPPED -#undef AI_DEFAULT -#endif /* AI_PASSIVE */ - -#define AI_PASSIVE 0x00000001 /* get address to use bind() */ -#define AI_CANONNAME 0x00000002 /* fill ai_canonname */ -#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */ -/* valid flags for addrinfo */ -#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST) - -#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */ -#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */ -#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */ -#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */ -/* special recommended flags for getipnodebyname */ -#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG) - -#endif /* !HAVE_GETADDRINFO */ - -#ifndef HAVE_GETNAMEINFO - -/* - * Constants for getnameinfo() - */ -#ifndef NI_MAXHOST -#define NI_MAXHOST 1025 -#define NI_MAXSERV 32 -#endif /* !NI_MAXHOST */ - -/* - * Flag values for getnameinfo() - */ -#ifndef NI_NOFQDN -#define NI_NOFQDN 0x00000001 -#define NI_NUMERICHOST 0x00000002 -#define NI_NAMEREQD 0x00000004 -#define NI_NUMERICSERV 0x00000008 -#define NI_DGRAM 0x00000010 -#endif /* !NI_NOFQDN */ - -#endif /* !HAVE_GETNAMEINFO */ - -#ifndef _SYS_SOCKET_H_ - #ifndef HAVE_ADDRINFO - struct addrinfo { - int ai_flags; /* AI_PASSIVE, AI_CANONNAME */ - int ai_family; /* PF_xxx */ - int ai_socktype; /* SOCK_xxx */ - int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */ - size_t ai_addrlen; /* length of ai_addr */ - char *ai_canonname; /* canonical name for hostname */ - struct sockaddr *ai_addr; /* binary address */ - struct addrinfo *ai_next; /* next structure in linked list */ - }; - #endif /* !HAVE_ADDRINFO */ - - #ifndef HAVE_SOCKADDR_STORAGE - /* - * RFC 2553: protocol-independent placeholder for socket addresses - */ - #define _SS_MAXSIZE 128 - #ifdef HAVE_LONG_LONG - #define _SS_ALIGNSIZE (sizeof(PY_LONG_LONG)) - #else - #define _SS_ALIGNSIZE (sizeof(double)) - #endif /* HAVE_LONG_LONG */ - #define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(u_char) * 2) - #define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(u_char) * 2 - \ - _SS_PAD1SIZE - _SS_ALIGNSIZE) - - struct sockaddr_storage { - #ifdef HAVE_SOCKADDR_SA_LEN - unsigned char ss_len; /* address length */ - unsigned char ss_family; /* address family */ - #else - unsigned short ss_family; /* address family */ - #endif /* HAVE_SOCKADDR_SA_LEN */ - char __ss_pad1[_SS_PAD1SIZE]; - #ifdef HAVE_LONG_LONG - PY_LONG_LONG __ss_align; /* force desired structure storage alignment */ - #else - double __ss_align; /* force desired structure storage alignment */ - #endif /* HAVE_LONG_LONG */ - char __ss_pad2[_SS_PAD2SIZE]; - }; - #endif /* !HAVE_SOCKADDR_STORAGE */ -#endif /* _SYS_SOCKET_H_ */ - -#ifdef __cplusplus -extern "C" { -#endif -extern void freehostent Py_PROTO((struct hostent *)); -#ifdef __cplusplus -} -#endif diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/errnomodule.c b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/errnomodule.c deleted file mode 100644 index a325389..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/errnomodule.c +++ /dev/null @@ -1,845 +0,0 @@ - -/* Errno module - - 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. -*/ - -#include "Python.h" - -/* Windows socket errors (WSA*) */ -#ifdef MS_WINDOWS -#include -#endif - -/* - * Pull in the system error definitions - */ - -static PyMethodDef errno_methods[] = { - {NULL, NULL} -}; - -/* Helper function doing the dictionary inserting */ - -static void -_inscode(PyObject *d, PyObject *de, char *name, int code) -{ - PyObject *u = PyString_FromString(name); - PyObject *v = PyInt_FromLong((long) code); - - /* Don't bother checking for errors; they'll be caught at the end - * of the module initialization function by the caller of - * initerrno(). - */ - if (u && v) { - /* insert in modules dict */ - PyDict_SetItem(d, u, v); - /* insert in errorcode dict */ - PyDict_SetItem(de, v, u); - } - Py_XDECREF(u); - Py_XDECREF(v); -} - -PyDoc_STRVAR(errno__doc__, -"This module makes available standard errno system symbols.\n\ -\n\ -The value of each symbol is the corresponding integer value,\n\ -e.g., on most systems, errno.ENOENT equals the integer 2.\n\ -\n\ -The dictionary errno.errorcode maps numeric codes to symbol names,\n\ -e.g., errno.errorcode[2] could be the string 'ENOENT'.\n\ -\n\ -Symbols that are not relevant to the underlying system are not defined.\n\ -\n\ -To map error codes to error messages, use the function os.strerror(),\n\ -e.g. os.strerror(2) could return 'No such file or directory'."); - -PyMODINIT_FUNC -initerrno(void) -{ - PyObject *m, *d, *de; - m = Py_InitModule3("errno", errno_methods, errno__doc__); - if (m == NULL) - return; - d = PyModule_GetDict(m); - de = PyDict_New(); - if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0) - return; - -/* Macro so I don't have to edit each and every line below... */ -#define inscode(d, ds, de, name, code, comment) _inscode(d, de, name, code) - - /* - * The names and comments are borrowed from linux/include/errno.h, - * which should be pretty all-inclusive - */ - -#ifdef ENODEV - inscode(d, ds, de, "ENODEV", ENODEV, "No such device"); -#endif -#ifdef ENOCSI - inscode(d, ds, de, "ENOCSI", ENOCSI, "No CSI structure available"); -#endif -#ifdef EHOSTUNREACH - inscode(d, ds, de, "EHOSTUNREACH", EHOSTUNREACH, "No route to host"); -#else -#ifdef WSAEHOSTUNREACH - inscode(d, ds, de, "EHOSTUNREACH", WSAEHOSTUNREACH, "No route to host"); -#endif -#endif -#ifdef ENOMSG - inscode(d, ds, de, "ENOMSG", ENOMSG, "No message of desired type"); -#endif -#ifdef EUCLEAN - inscode(d, ds, de, "EUCLEAN", EUCLEAN, "Structure needs cleaning"); -#endif -#ifdef EL2NSYNC - inscode(d, ds, de, "EL2NSYNC", EL2NSYNC, "Level 2 not synchronized"); -#endif -#ifdef EL2HLT - inscode(d, ds, de, "EL2HLT", EL2HLT, "Level 2 halted"); -#endif -#ifdef ENODATA - inscode(d, ds, de, "ENODATA", ENODATA, "No data available"); -#endif -#ifdef ENOTBLK - inscode(d, ds, de, "ENOTBLK", ENOTBLK, "Block device required"); -#endif -#ifdef ENOSYS - inscode(d, ds, de, "ENOSYS", ENOSYS, "Function not implemented"); -#endif -#ifdef EPIPE - inscode(d, ds, de, "EPIPE", EPIPE, "Broken pipe"); -#endif -#ifdef EINVAL - inscode(d, ds, de, "EINVAL", EINVAL, "Invalid argument"); -#else -#ifdef WSAEINVAL - inscode(d, ds, de, "EINVAL", WSAEINVAL, "Invalid argument"); -#endif -#endif -#ifdef EOVERFLOW - inscode(d, ds, de, "EOVERFLOW", EOVERFLOW, "Value too large for defined data type"); -#endif -#ifdef EADV - inscode(d, ds, de, "EADV", EADV, "Advertise error"); -#endif -#ifdef EINTR - inscode(d, ds, de, "EINTR", EINTR, "Interrupted system call"); -#else -#ifdef WSAEINTR - inscode(d, ds, de, "EINTR", WSAEINTR, "Interrupted system call"); -#endif -#endif -#ifdef EUSERS - inscode(d, ds, de, "EUSERS", EUSERS, "Too many users"); -#else -#ifdef WSAEUSERS - inscode(d, ds, de, "EUSERS", WSAEUSERS, "Too many users"); -#endif -#endif -#ifdef ENOTEMPTY - inscode(d, ds, de, "ENOTEMPTY", ENOTEMPTY, "Directory not empty"); -#else -#ifdef WSAENOTEMPTY - inscode(d, ds, de, "ENOTEMPTY", WSAENOTEMPTY, "Directory not empty"); -#endif -#endif -#ifdef ENOBUFS - inscode(d, ds, de, "ENOBUFS", ENOBUFS, "No buffer space available"); -#else -#ifdef WSAENOBUFS - inscode(d, ds, de, "ENOBUFS", WSAENOBUFS, "No buffer space available"); -#endif -#endif -#ifdef EPROTO - inscode(d, ds, de, "EPROTO", EPROTO, "Protocol error"); -#endif -#ifdef EREMOTE - inscode(d, ds, de, "EREMOTE", EREMOTE, "Object is remote"); -#else -#ifdef WSAEREMOTE - inscode(d, ds, de, "EREMOTE", WSAEREMOTE, "Object is remote"); -#endif -#endif -#ifdef ENAVAIL - inscode(d, ds, de, "ENAVAIL", ENAVAIL, "No XENIX semaphores available"); -#endif -#ifdef ECHILD - inscode(d, ds, de, "ECHILD", ECHILD, "No child processes"); -#endif -#ifdef ELOOP - inscode(d, ds, de, "ELOOP", ELOOP, "Too many symbolic links encountered"); -#else -#ifdef WSAELOOP - inscode(d, ds, de, "ELOOP", WSAELOOP, "Too many symbolic links encountered"); -#endif -#endif -#ifdef EXDEV - inscode(d, ds, de, "EXDEV", EXDEV, "Cross-device link"); -#endif -#ifdef E2BIG - inscode(d, ds, de, "E2BIG", E2BIG, "Arg list too long"); -#endif -#ifdef ESRCH - inscode(d, ds, de, "ESRCH", ESRCH, "No such process"); -#endif -#ifdef EMSGSIZE - inscode(d, ds, de, "EMSGSIZE", EMSGSIZE, "Message too long"); -#else -#ifdef WSAEMSGSIZE - inscode(d, ds, de, "EMSGSIZE", WSAEMSGSIZE, "Message too long"); -#endif -#endif -#ifdef EAFNOSUPPORT - inscode(d, ds, de, "EAFNOSUPPORT", EAFNOSUPPORT, "Address family not supported by protocol"); -#else -#ifdef WSAEAFNOSUPPORT - inscode(d, ds, de, "EAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol"); -#endif -#endif -#ifdef EBADR - inscode(d, ds, de, "EBADR", EBADR, "Invalid request descriptor"); -#endif -#ifdef EHOSTDOWN - inscode(d, ds, de, "EHOSTDOWN", EHOSTDOWN, "Host is down"); -#else -#ifdef WSAEHOSTDOWN - inscode(d, ds, de, "EHOSTDOWN", WSAEHOSTDOWN, "Host is down"); -#endif -#endif -#ifdef EPFNOSUPPORT - inscode(d, ds, de, "EPFNOSUPPORT", EPFNOSUPPORT, "Protocol family not supported"); -#else -#ifdef WSAEPFNOSUPPORT - inscode(d, ds, de, "EPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported"); -#endif -#endif -#ifdef ENOPROTOOPT - inscode(d, ds, de, "ENOPROTOOPT", ENOPROTOOPT, "Protocol not available"); -#else -#ifdef WSAENOPROTOOPT - inscode(d, ds, de, "ENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available"); -#endif -#endif -#ifdef EBUSY - inscode(d, ds, de, "EBUSY", EBUSY, "Device or resource busy"); -#endif -#ifdef EWOULDBLOCK - inscode(d, ds, de, "EWOULDBLOCK", EWOULDBLOCK, "Operation would block"); -#else -#ifdef WSAEWOULDBLOCK - inscode(d, ds, de, "EWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block"); -#endif -#endif -#ifdef EBADFD - inscode(d, ds, de, "EBADFD", EBADFD, "File descriptor in bad state"); -#endif -#ifdef EDOTDOT - inscode(d, ds, de, "EDOTDOT", EDOTDOT, "RFS specific error"); -#endif -#ifdef EISCONN - inscode(d, ds, de, "EISCONN", EISCONN, "Transport endpoint is already connected"); -#else -#ifdef WSAEISCONN - inscode(d, ds, de, "EISCONN", WSAEISCONN, "Transport endpoint is already connected"); -#endif -#endif -#ifdef ENOANO - inscode(d, ds, de, "ENOANO", ENOANO, "No anode"); -#endif -#ifdef ESHUTDOWN - inscode(d, ds, de, "ESHUTDOWN", ESHUTDOWN, "Cannot send after transport endpoint shutdown"); -#else -#ifdef WSAESHUTDOWN - inscode(d, ds, de, "ESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown"); -#endif -#endif -#ifdef ECHRNG - inscode(d, ds, de, "ECHRNG", ECHRNG, "Channel number out of range"); -#endif -#ifdef ELIBBAD - inscode(d, ds, de, "ELIBBAD", ELIBBAD, "Accessing a corrupted shared library"); -#endif -#ifdef ENONET - inscode(d, ds, de, "ENONET", ENONET, "Machine is not on the network"); -#endif -#ifdef EBADE - inscode(d, ds, de, "EBADE", EBADE, "Invalid exchange"); -#endif -#ifdef EBADF - inscode(d, ds, de, "EBADF", EBADF, "Bad file number"); -#else -#ifdef WSAEBADF - inscode(d, ds, de, "EBADF", WSAEBADF, "Bad file number"); -#endif -#endif -#ifdef EMULTIHOP - inscode(d, ds, de, "EMULTIHOP", EMULTIHOP, "Multihop attempted"); -#endif -#ifdef EIO - inscode(d, ds, de, "EIO", EIO, "I/O error"); -#endif -#ifdef EUNATCH - inscode(d, ds, de, "EUNATCH", EUNATCH, "Protocol driver not attached"); -#endif -#ifdef EPROTOTYPE - inscode(d, ds, de, "EPROTOTYPE", EPROTOTYPE, "Protocol wrong type for socket"); -#else -#ifdef WSAEPROTOTYPE - inscode(d, ds, de, "EPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket"); -#endif -#endif -#ifdef ENOSPC - inscode(d, ds, de, "ENOSPC", ENOSPC, "No space left on device"); -#endif -#ifdef ENOEXEC - inscode(d, ds, de, "ENOEXEC", ENOEXEC, "Exec format error"); -#endif -#ifdef EALREADY - inscode(d, ds, de, "EALREADY", EALREADY, "Operation already in progress"); -#else -#ifdef WSAEALREADY - inscode(d, ds, de, "EALREADY", WSAEALREADY, "Operation already in progress"); -#endif -#endif -#ifdef ENETDOWN - inscode(d, ds, de, "ENETDOWN", ENETDOWN, "Network is down"); -#else -#ifdef WSAENETDOWN - inscode(d, ds, de, "ENETDOWN", WSAENETDOWN, "Network is down"); -#endif -#endif -#ifdef ENOTNAM - inscode(d, ds, de, "ENOTNAM", ENOTNAM, "Not a XENIX named type file"); -#endif -#ifdef EACCES - inscode(d, ds, de, "EACCES", EACCES, "Permission denied"); -#else -#ifdef WSAEACCES - inscode(d, ds, de, "EACCES", WSAEACCES, "Permission denied"); -#endif -#endif -#ifdef ELNRNG - inscode(d, ds, de, "ELNRNG", ELNRNG, "Link number out of range"); -#endif -#ifdef EILSEQ - inscode(d, ds, de, "EILSEQ", EILSEQ, "Illegal byte sequence"); -#endif -#ifdef ENOTDIR - inscode(d, ds, de, "ENOTDIR", ENOTDIR, "Not a directory"); -#endif -#ifdef ENOTUNIQ - inscode(d, ds, de, "ENOTUNIQ", ENOTUNIQ, "Name not unique on network"); -#endif -#ifdef EPERM - inscode(d, ds, de, "EPERM", EPERM, "Operation not permitted"); -#endif -#ifdef EDOM - inscode(d, ds, de, "EDOM", EDOM, "Math argument out of domain of func"); -#endif -#ifdef EXFULL - inscode(d, ds, de, "EXFULL", EXFULL, "Exchange full"); -#endif -#ifdef ECONNREFUSED - inscode(d, ds, de, "ECONNREFUSED", ECONNREFUSED, "Connection refused"); -#else -#ifdef WSAECONNREFUSED - inscode(d, ds, de, "ECONNREFUSED", WSAECONNREFUSED, "Connection refused"); -#endif -#endif -#ifdef EISDIR - inscode(d, ds, de, "EISDIR", EISDIR, "Is a directory"); -#endif -#ifdef EPROTONOSUPPORT - inscode(d, ds, de, "EPROTONOSUPPORT", EPROTONOSUPPORT, "Protocol not supported"); -#else -#ifdef WSAEPROTONOSUPPORT - inscode(d, ds, de, "EPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported"); -#endif -#endif -#ifdef EROFS - inscode(d, ds, de, "EROFS", EROFS, "Read-only file system"); -#endif -#ifdef EADDRNOTAVAIL - inscode(d, ds, de, "EADDRNOTAVAIL", EADDRNOTAVAIL, "Cannot assign requested address"); -#else -#ifdef WSAEADDRNOTAVAIL - inscode(d, ds, de, "EADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address"); -#endif -#endif -#ifdef EIDRM - inscode(d, ds, de, "EIDRM", EIDRM, "Identifier removed"); -#endif -#ifdef ECOMM - inscode(d, ds, de, "ECOMM", ECOMM, "Communication error on send"); -#endif -#ifdef ESRMNT - inscode(d, ds, de, "ESRMNT", ESRMNT, "Srmount error"); -#endif -#ifdef EREMOTEIO - inscode(d, ds, de, "EREMOTEIO", EREMOTEIO, "Remote I/O error"); -#endif -#ifdef EL3RST - inscode(d, ds, de, "EL3RST", EL3RST, "Level 3 reset"); -#endif -#ifdef EBADMSG - inscode(d, ds, de, "EBADMSG", EBADMSG, "Not a data message"); -#endif -#ifdef ENFILE - inscode(d, ds, de, "ENFILE", ENFILE, "File table overflow"); -#endif -#ifdef ELIBMAX - inscode(d, ds, de, "ELIBMAX", ELIBMAX, "Attempting to link in too many shared libraries"); -#endif -#ifdef ESPIPE - inscode(d, ds, de, "ESPIPE", ESPIPE, "Illegal seek"); -#endif -#ifdef ENOLINK - inscode(d, ds, de, "ENOLINK", ENOLINK, "Link has been severed"); -#endif -#ifdef ENETRESET - inscode(d, ds, de, "ENETRESET", ENETRESET, "Network dropped connection because of reset"); -#else -#ifdef WSAENETRESET - inscode(d, ds, de, "ENETRESET", WSAENETRESET, "Network dropped connection because of reset"); -#endif -#endif -#ifdef ETIMEDOUT - inscode(d, ds, de, "ETIMEDOUT", ETIMEDOUT, "Connection timed out"); -#else -#ifdef WSAETIMEDOUT - inscode(d, ds, de, "ETIMEDOUT", WSAETIMEDOUT, "Connection timed out"); -#endif -#endif -#ifdef ENOENT - inscode(d, ds, de, "ENOENT", ENOENT, "No such file or directory"); -#endif -#ifdef EEXIST - inscode(d, ds, de, "EEXIST", EEXIST, "File exists"); -#endif -#ifdef EDQUOT - inscode(d, ds, de, "EDQUOT", EDQUOT, "Quota exceeded"); -#else -#ifdef WSAEDQUOT - inscode(d, ds, de, "EDQUOT", WSAEDQUOT, "Quota exceeded"); -#endif -#endif -#ifdef ENOSTR - inscode(d, ds, de, "ENOSTR", ENOSTR, "Device not a stream"); -#endif -#ifdef EBADSLT - inscode(d, ds, de, "EBADSLT", EBADSLT, "Invalid slot"); -#endif -#ifdef EBADRQC - inscode(d, ds, de, "EBADRQC", EBADRQC, "Invalid request code"); -#endif -#ifdef ELIBACC - inscode(d, ds, de, "ELIBACC", ELIBACC, "Can not access a needed shared library"); -#endif -#ifdef EFAULT - inscode(d, ds, de, "EFAULT", EFAULT, "Bad address"); -#else -#ifdef WSAEFAULT - inscode(d, ds, de, "EFAULT", WSAEFAULT, "Bad address"); -#endif -#endif -#ifdef EFBIG - inscode(d, ds, de, "EFBIG", EFBIG, "File too large"); -#endif -#ifdef EDEADLK - inscode(d, ds, de, "EDEADLK", EDEADLK, "Resource deadlock would occur"); -#endif -#ifdef ENOTCONN - inscode(d, ds, de, "ENOTCONN", ENOTCONN, "Transport endpoint is not connected"); -#else -#ifdef WSAENOTCONN - inscode(d, ds, de, "ENOTCONN", WSAENOTCONN, "Transport endpoint is not connected"); -#endif -#endif -#ifdef EDESTADDRREQ - inscode(d, ds, de, "EDESTADDRREQ", EDESTADDRREQ, "Destination address required"); -#else -#ifdef WSAEDESTADDRREQ - inscode(d, ds, de, "EDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required"); -#endif -#endif -#ifdef ELIBSCN - inscode(d, ds, de, "ELIBSCN", ELIBSCN, ".lib section in a.out corrupted"); -#endif -#ifdef ENOLCK - inscode(d, ds, de, "ENOLCK", ENOLCK, "No record locks available"); -#endif -#ifdef EISNAM - inscode(d, ds, de, "EISNAM", EISNAM, "Is a named type file"); -#endif -#ifdef ECONNABORTED - inscode(d, ds, de, "ECONNABORTED", ECONNABORTED, "Software caused connection abort"); -#else -#ifdef WSAECONNABORTED - inscode(d, ds, de, "ECONNABORTED", WSAECONNABORTED, "Software caused connection abort"); -#endif -#endif -#ifdef ENETUNREACH - inscode(d, ds, de, "ENETUNREACH", ENETUNREACH, "Network is unreachable"); -#else -#ifdef WSAENETUNREACH - inscode(d, ds, de, "ENETUNREACH", WSAENETUNREACH, "Network is unreachable"); -#endif -#endif -#ifdef ESTALE - inscode(d, ds, de, "ESTALE", ESTALE, "Stale NFS file handle"); -#else -#ifdef WSAESTALE - inscode(d, ds, de, "ESTALE", WSAESTALE, "Stale NFS file handle"); -#endif -#endif -#ifdef ENOSR - inscode(d, ds, de, "ENOSR", ENOSR, "Out of streams resources"); -#endif -#ifdef ENOMEM - inscode(d, ds, de, "ENOMEM", ENOMEM, "Out of memory"); -#endif -#ifdef ENOTSOCK - inscode(d, ds, de, "ENOTSOCK", ENOTSOCK, "Socket operation on non-socket"); -#else -#ifdef WSAENOTSOCK - inscode(d, ds, de, "ENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket"); -#endif -#endif -#ifdef ESTRPIPE - inscode(d, ds, de, "ESTRPIPE", ESTRPIPE, "Streams pipe error"); -#endif -#ifdef EMLINK - inscode(d, ds, de, "EMLINK", EMLINK, "Too many links"); -#endif -#ifdef ERANGE - inscode(d, ds, de, "ERANGE", ERANGE, "Math result not representable"); -#endif -#ifdef ELIBEXEC - inscode(d, ds, de, "ELIBEXEC", ELIBEXEC, "Cannot exec a shared library directly"); -#endif -#ifdef EL3HLT - inscode(d, ds, de, "EL3HLT", EL3HLT, "Level 3 halted"); -#endif -#ifdef ECONNRESET - inscode(d, ds, de, "ECONNRESET", ECONNRESET, "Connection reset by peer"); -#else -#ifdef WSAECONNRESET - inscode(d, ds, de, "ECONNRESET", WSAECONNRESET, "Connection reset by peer"); -#endif -#endif -#ifdef EADDRINUSE - inscode(d, ds, de, "EADDRINUSE", EADDRINUSE, "Address already in use"); -#else -#ifdef WSAEADDRINUSE - inscode(d, ds, de, "EADDRINUSE", WSAEADDRINUSE, "Address already in use"); -#endif -#endif -#ifdef EOPNOTSUPP - inscode(d, ds, de, "EOPNOTSUPP", EOPNOTSUPP, "Operation not supported on transport endpoint"); -#else -#ifdef WSAEOPNOTSUPP - inscode(d, ds, de, "EOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint"); -#endif -#endif -#ifdef EREMCHG - inscode(d, ds, de, "EREMCHG", EREMCHG, "Remote address changed"); -#endif -#ifdef EAGAIN - inscode(d, ds, de, "EAGAIN", EAGAIN, "Try again"); -#endif -#ifdef ENAMETOOLONG - inscode(d, ds, de, "ENAMETOOLONG", ENAMETOOLONG, "File name too long"); -#else -#ifdef WSAENAMETOOLONG - inscode(d, ds, de, "ENAMETOOLONG", WSAENAMETOOLONG, "File name too long"); -#endif -#endif -#ifdef ENOTTY - inscode(d, ds, de, "ENOTTY", ENOTTY, "Not a typewriter"); -#endif -#ifdef ERESTART - inscode(d, ds, de, "ERESTART", ERESTART, "Interrupted system call should be restarted"); -#endif -#ifdef ESOCKTNOSUPPORT - inscode(d, ds, de, "ESOCKTNOSUPPORT", ESOCKTNOSUPPORT, "Socket type not supported"); -#else -#ifdef WSAESOCKTNOSUPPORT - inscode(d, ds, de, "ESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported"); -#endif -#endif -#ifdef ETIME - inscode(d, ds, de, "ETIME", ETIME, "Timer expired"); -#endif -#ifdef EBFONT - inscode(d, ds, de, "EBFONT", EBFONT, "Bad font file format"); -#endif -#ifdef EDEADLOCK - inscode(d, ds, de, "EDEADLOCK", EDEADLOCK, "Error EDEADLOCK"); -#endif -#ifdef ETOOMANYREFS - inscode(d, ds, de, "ETOOMANYREFS", ETOOMANYREFS, "Too many references: cannot splice"); -#else -#ifdef WSAETOOMANYREFS - inscode(d, ds, de, "ETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice"); -#endif -#endif -#ifdef EMFILE - inscode(d, ds, de, "EMFILE", EMFILE, "Too many open files"); -#else -#ifdef WSAEMFILE - inscode(d, ds, de, "EMFILE", WSAEMFILE, "Too many open files"); -#endif -#endif -#ifdef ETXTBSY - inscode(d, ds, de, "ETXTBSY", ETXTBSY, "Text file busy"); -#endif -#ifdef EINPROGRESS - inscode(d, ds, de, "EINPROGRESS", EINPROGRESS, "Operation now in progress"); -#else -#ifdef WSAEINPROGRESS - inscode(d, ds, de, "EINPROGRESS", WSAEINPROGRESS, "Operation now in progress"); -#endif -#endif -#ifdef ENXIO - inscode(d, ds, de, "ENXIO", ENXIO, "No such device or address"); -#endif -#ifdef ENOPKG - inscode(d, ds, de, "ENOPKG", ENOPKG, "Package not installed"); -#endif -#ifdef WSASY - inscode(d, ds, de, "WSASY", WSASY, "Error WSASY"); -#endif -#ifdef WSAEHOSTDOWN - inscode(d, ds, de, "WSAEHOSTDOWN", WSAEHOSTDOWN, "Host is down"); -#endif -#ifdef WSAENETDOWN - inscode(d, ds, de, "WSAENETDOWN", WSAENETDOWN, "Network is down"); -#endif -#ifdef WSAENOTSOCK - inscode(d, ds, de, "WSAENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket"); -#endif -#ifdef WSAEHOSTUNREACH - inscode(d, ds, de, "WSAEHOSTUNREACH", WSAEHOSTUNREACH, "No route to host"); -#endif -#ifdef WSAELOOP - inscode(d, ds, de, "WSAELOOP", WSAELOOP, "Too many symbolic links encountered"); -#endif -#ifdef WSAEMFILE - inscode(d, ds, de, "WSAEMFILE", WSAEMFILE, "Too many open files"); -#endif -#ifdef WSAESTALE - inscode(d, ds, de, "WSAESTALE", WSAESTALE, "Stale NFS file handle"); -#endif -#ifdef WSAVERNOTSUPPORTED - inscode(d, ds, de, "WSAVERNOTSUPPORTED", WSAVERNOTSUPPORTED, "Error WSAVERNOTSUPPORTED"); -#endif -#ifdef WSAENETUNREACH - inscode(d, ds, de, "WSAENETUNREACH", WSAENETUNREACH, "Network is unreachable"); -#endif -#ifdef WSAEPROCLIM - inscode(d, ds, de, "WSAEPROCLIM", WSAEPROCLIM, "Error WSAEPROCLIM"); -#endif -#ifdef WSAEFAULT - inscode(d, ds, de, "WSAEFAULT", WSAEFAULT, "Bad address"); -#endif -#ifdef WSANOTINITIALISED - inscode(d, ds, de, "WSANOTINITIALISED", WSANOTINITIALISED, "Error WSANOTINITIALISED"); -#endif -#ifdef WSAEUSERS - inscode(d, ds, de, "WSAEUSERS", WSAEUSERS, "Too many users"); -#endif -#ifdef WSAMAKEASYNCREPL - inscode(d, ds, de, "WSAMAKEASYNCREPL", WSAMAKEASYNCREPL, "Error WSAMAKEASYNCREPL"); -#endif -#ifdef WSAENOPROTOOPT - inscode(d, ds, de, "WSAENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available"); -#endif -#ifdef WSAECONNABORTED - inscode(d, ds, de, "WSAECONNABORTED", WSAECONNABORTED, "Software caused connection abort"); -#endif -#ifdef WSAENAMETOOLONG - inscode(d, ds, de, "WSAENAMETOOLONG", WSAENAMETOOLONG, "File name too long"); -#endif -#ifdef WSAENOTEMPTY - inscode(d, ds, de, "WSAENOTEMPTY", WSAENOTEMPTY, "Directory not empty"); -#endif -#ifdef WSAESHUTDOWN - inscode(d, ds, de, "WSAESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown"); -#endif -#ifdef WSAEAFNOSUPPORT - inscode(d, ds, de, "WSAEAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol"); -#endif -#ifdef WSAETOOMANYREFS - inscode(d, ds, de, "WSAETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice"); -#endif -#ifdef WSAEACCES - inscode(d, ds, de, "WSAEACCES", WSAEACCES, "Permission denied"); -#endif -#ifdef WSATR - inscode(d, ds, de, "WSATR", WSATR, "Error WSATR"); -#endif -#ifdef WSABASEERR - inscode(d, ds, de, "WSABASEERR", WSABASEERR, "Error WSABASEERR"); -#endif -#ifdef WSADESCRIPTIO - inscode(d, ds, de, "WSADESCRIPTIO", WSADESCRIPTIO, "Error WSADESCRIPTIO"); -#endif -#ifdef WSAEMSGSIZE - inscode(d, ds, de, "WSAEMSGSIZE", WSAEMSGSIZE, "Message too long"); -#endif -#ifdef WSAEBADF - inscode(d, ds, de, "WSAEBADF", WSAEBADF, "Bad file number"); -#endif -#ifdef WSAECONNRESET - inscode(d, ds, de, "WSAECONNRESET", WSAECONNRESET, "Connection reset by peer"); -#endif -#ifdef WSAGETSELECTERRO - inscode(d, ds, de, "WSAGETSELECTERRO", WSAGETSELECTERRO, "Error WSAGETSELECTERRO"); -#endif -#ifdef WSAETIMEDOUT - inscode(d, ds, de, "WSAETIMEDOUT", WSAETIMEDOUT, "Connection timed out"); -#endif -#ifdef WSAENOBUFS - inscode(d, ds, de, "WSAENOBUFS", WSAENOBUFS, "No buffer space available"); -#endif -#ifdef WSAEDISCON - inscode(d, ds, de, "WSAEDISCON", WSAEDISCON, "Error WSAEDISCON"); -#endif -#ifdef WSAEINTR - inscode(d, ds, de, "WSAEINTR", WSAEINTR, "Interrupted system call"); -#endif -#ifdef WSAEPROTOTYPE - inscode(d, ds, de, "WSAEPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket"); -#endif -#ifdef WSAHOS - inscode(d, ds, de, "WSAHOS", WSAHOS, "Error WSAHOS"); -#endif -#ifdef WSAEADDRINUSE - inscode(d, ds, de, "WSAEADDRINUSE", WSAEADDRINUSE, "Address already in use"); -#endif -#ifdef WSAEADDRNOTAVAIL - inscode(d, ds, de, "WSAEADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address"); -#endif -#ifdef WSAEALREADY - inscode(d, ds, de, "WSAEALREADY", WSAEALREADY, "Operation already in progress"); -#endif -#ifdef WSAEPROTONOSUPPORT - inscode(d, ds, de, "WSAEPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported"); -#endif -#ifdef WSASYSNOTREADY - inscode(d, ds, de, "WSASYSNOTREADY", WSASYSNOTREADY, "Error WSASYSNOTREADY"); -#endif -#ifdef WSAEWOULDBLOCK - inscode(d, ds, de, "WSAEWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block"); -#endif -#ifdef WSAEPFNOSUPPORT - inscode(d, ds, de, "WSAEPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported"); -#endif -#ifdef WSAEOPNOTSUPP - inscode(d, ds, de, "WSAEOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint"); -#endif -#ifdef WSAEISCONN - inscode(d, ds, de, "WSAEISCONN", WSAEISCONN, "Transport endpoint is already connected"); -#endif -#ifdef WSAEDQUOT - inscode(d, ds, de, "WSAEDQUOT", WSAEDQUOT, "Quota exceeded"); -#endif -#ifdef WSAENOTCONN - inscode(d, ds, de, "WSAENOTCONN", WSAENOTCONN, "Transport endpoint is not connected"); -#endif -#ifdef WSAEREMOTE - inscode(d, ds, de, "WSAEREMOTE", WSAEREMOTE, "Object is remote"); -#endif -#ifdef WSAEINVAL - inscode(d, ds, de, "WSAEINVAL", WSAEINVAL, "Invalid argument"); -#endif -#ifdef WSAEINPROGRESS - inscode(d, ds, de, "WSAEINPROGRESS", WSAEINPROGRESS, "Operation now in progress"); -#endif -#ifdef WSAGETSELECTEVEN - inscode(d, ds, de, "WSAGETSELECTEVEN", WSAGETSELECTEVEN, "Error WSAGETSELECTEVEN"); -#endif -#ifdef WSAESOCKTNOSUPPORT - inscode(d, ds, de, "WSAESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported"); -#endif -#ifdef WSAGETASYNCERRO - inscode(d, ds, de, "WSAGETASYNCERRO", WSAGETASYNCERRO, "Error WSAGETASYNCERRO"); -#endif -#ifdef WSAMAKESELECTREPL - inscode(d, ds, de, "WSAMAKESELECTREPL", WSAMAKESELECTREPL, "Error WSAMAKESELECTREPL"); -#endif -#ifdef WSAGETASYNCBUFLE - inscode(d, ds, de, "WSAGETASYNCBUFLE", WSAGETASYNCBUFLE, "Error WSAGETASYNCBUFLE"); -#endif -#ifdef WSAEDESTADDRREQ - inscode(d, ds, de, "WSAEDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required"); -#endif -#ifdef WSAECONNREFUSED - inscode(d, ds, de, "WSAECONNREFUSED", WSAECONNREFUSED, "Connection refused"); -#endif -#ifdef WSAENETRESET - inscode(d, ds, de, "WSAENETRESET", WSAENETRESET, "Network dropped connection because of reset"); -#endif -#ifdef WSAN - inscode(d, ds, de, "WSAN", WSAN, "Error WSAN"); -#endif - -/* These symbols are added for EDK II support. */ -#ifdef EMINERRORVAL - inscode(d, ds, de, "EMINERRORVAL", EMINERRORVAL, "Lowest valid error value"); -#endif -#ifdef ENOTSUP - inscode(d, ds, de, "ENOTSUP", ENOTSUP, "Operation not supported"); -#endif -#ifdef EBADRPC - inscode(d, ds, de, "EBADRPC", EBADRPC, "RPC struct is bad"); -#endif -#ifdef ERPCMISMATCH - inscode(d, ds, de, "ERPCMISMATCH", ERPCMISMATCH, "RPC version wrong"); -#endif -#ifdef EPROGUNAVAIL - inscode(d, ds, de, "EPROGUNAVAIL", EPROGUNAVAIL, "RPC prog. not avail"); -#endif -#ifdef EPROGMISMATCH - inscode(d, ds, de, "EPROGMISMATCH", EPROGMISMATCH, "Program version wrong"); -#endif -#ifdef EPROCUNAVAIL - inscode(d, ds, de, "EPROCUNAVAIL", EPROCUNAVAIL, "Bad procedure for program"); -#endif -#ifdef EFTYPE - inscode(d, ds, de, "EFTYPE", EFTYPE, "Inappropriate file type or format"); -#endif -#ifdef EAUTH - inscode(d, ds, de, "EAUTH", EAUTH, "Authentication error"); -#endif -#ifdef ENEEDAUTH - inscode(d, ds, de, "ENEEDAUTH", ENEEDAUTH, "Need authenticator"); -#endif -#ifdef ECANCELED - inscode(d, ds, de, "ECANCELED", ECANCELED, "Operation canceled"); -#endif -#ifdef ENOATTR - inscode(d, ds, de, "ENOATTR", ENOATTR, "Attribute not found"); -#endif -#ifdef EDOOFUS - inscode(d, ds, de, "EDOOFUS", EDOOFUS, "Programming Error"); -#endif -#ifdef EBUFSIZE - inscode(d, ds, de, "EBUFSIZE", EBUFSIZE, "Buffer too small to hold result"); -#endif -#ifdef EMAXERRORVAL - inscode(d, ds, de, "EMAXERRORVAL", EMAXERRORVAL, "One more than the highest defined error value"); -#endif - - Py_DECREF(de); -} diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/expat_external.h b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/expat_external.h deleted file mode 100644 index b739595..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/expat_external.h +++ /dev/null @@ -1,121 +0,0 @@ -/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. -*/ - -#ifndef Expat_External_INCLUDED -#define Expat_External_INCLUDED 1 - -/* External API definitions */ - -/* Namespace external symbols to allow multiple libexpat version to - co-exist. */ -#if !defined(UEFI_C_SOURCE) - #include "pyexpatns.h" -#endif - -#if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__) -#define XML_USE_MSC_EXTENSIONS 1 -#endif - -/* Expat tries very hard to make the API boundary very specifically - defined. There are two macros defined to control this boundary; - each of these can be defined before including this header to - achieve some different behavior, but doing so it not recommended or - tested frequently. - - XMLCALL - The calling convention to use for all calls across the - "library boundary." This will default to cdecl, and - try really hard to tell the compiler that's what we - want. - - XMLIMPORT - Whatever magic is needed to note that a function is - to be imported from a dynamically loaded library - (.dll, .so, or .sl, depending on your platform). - - The XMLCALL macro was added in Expat 1.95.7. The only one which is - expected to be directly useful in client code is XMLCALL. - - Note that on at least some Unix versions, the Expat library must be - compiled with the cdecl calling convention as the default since - system headers may assume the cdecl convention. -*/ -#ifndef XMLCALL -#if defined(XML_USE_MSC_EXTENSIONS) -#define XMLCALL __cdecl -#elif defined(__GNUC__) && defined(__i386) -#define XMLCALL __attribute__((cdecl)) -#else -/* For any platform which uses this definition and supports more than - one calling convention, we need to extend this definition to - declare the convention used on that platform, if it's possible to - do so. - - If this is the case for your platform, please file a bug report - with information on how to identify your platform via the C - pre-processor and how to specify the same calling convention as the - platform's malloc() implementation. -*/ -#define XMLCALL -#endif -#endif /* not defined XMLCALL */ - - -#if !defined(XML_STATIC) && !defined(XMLIMPORT) -#ifndef XML_BUILDING_EXPAT -/* using Expat from an application */ - -#ifdef XML_USE_MSC_EXTENSIONS -#define XMLIMPORT __declspec(dllimport) -#endif - -#endif -#endif /* not defined XML_STATIC */ - - -/* If we didn't define it above, define it away: */ -#ifndef XMLIMPORT -#define XMLIMPORT -#endif - - -#define XMLPARSEAPI(type) XMLIMPORT type XMLCALL - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef XML_UNICODE_WCHAR_T -#define XML_UNICODE -#endif - -#ifdef XML_UNICODE /* Information is UTF-16 encoded. */ -#ifdef XML_UNICODE_WCHAR_T -typedef wchar_t XML_Char; -typedef wchar_t XML_LChar; -#else -typedef unsigned short XML_Char; -typedef char XML_LChar; -#endif /* XML_UNICODE_WCHAR_T */ -#else /* Information is UTF-8 encoded. */ -typedef char XML_Char; -typedef char XML_LChar; -#endif /* XML_UNICODE */ - -#ifdef XML_LARGE_SIZE /* Use large integers for file/stream positions. */ -#if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400 -typedef __int64 XML_Index; -typedef unsigned __int64 XML_Size; -#else -typedef long long XML_Index; -typedef unsigned long long XML_Size; -#endif -#else -typedef long XML_Index; -typedef unsigned long XML_Size; -#endif /* XML_LARGE_SIZE */ - -#ifdef __cplusplus -} -#endif - -#endif /* not Expat_External_INCLUDED */ diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/xmlparse.c b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/xmlparse.c deleted file mode 100644 index e303c7a..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/xmlparse.c +++ /dev/null @@ -1,6279 +0,0 @@ -/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. -*/ - -#define XML_BUILDING_EXPAT 1 - -#ifdef COMPILED_FROM_DSP -#include "winconfig.h" -#elif defined(MACOS_CLASSIC) -#include "macconfig.h" -#elif defined(__amigaos4__) -#include "amigaconfig.h" -#elif defined(HAVE_EXPAT_CONFIG_H) -#include -#endif /* ndef COMPILED_FROM_DSP */ - -#include -#include /* memset(), memcpy() */ -#include - -#if defined(UEFI_C_SOURCE) - #include -#else - #include "expat.h" -#endif - -#ifdef XML_UNICODE -#define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX -#define XmlConvert XmlUtf16Convert -#define XmlGetInternalEncoding XmlGetUtf16InternalEncoding -#define XmlGetInternalEncodingNS XmlGetUtf16InternalEncodingNS -#define XmlEncode XmlUtf16Encode -#define MUST_CONVERT(enc, s) (!(enc)->isUtf16 || (((unsigned long)s) & 1)) -typedef unsigned short ICHAR; -#else -#define XML_ENCODE_MAX XML_UTF8_ENCODE_MAX -#define XmlConvert XmlUtf8Convert -#define XmlGetInternalEncoding XmlGetUtf8InternalEncoding -#define XmlGetInternalEncodingNS XmlGetUtf8InternalEncodingNS -#define XmlEncode XmlUtf8Encode -#define MUST_CONVERT(enc, s) (!(enc)->isUtf8) -typedef char ICHAR; -#endif - - -#ifndef XML_NS - -#define XmlInitEncodingNS XmlInitEncoding -#define XmlInitUnknownEncodingNS XmlInitUnknownEncoding -#undef XmlGetInternalEncodingNS -#define XmlGetInternalEncodingNS XmlGetInternalEncoding -#define XmlParseXmlDeclNS XmlParseXmlDecl - -#endif - -#ifdef XML_UNICODE - -#ifdef XML_UNICODE_WCHAR_T -#define XML_T(x) (const wchar_t)x -#define XML_L(x) L ## x -#else -#define XML_T(x) (const unsigned short)x -#define XML_L(x) x -#endif - -#else - -#define XML_T(x) x -#define XML_L(x) x - -#endif - -/* Round up n to be a multiple of sz, where sz is a power of 2. */ -#define ROUND_UP(n, sz) (((n) + ((sz) - 1)) & ~((sz) - 1)) - -/* Handle the case where memmove() doesn't exist. */ -#ifndef HAVE_MEMMOVE -#ifdef HAVE_BCOPY -#define memmove(d,s,l) bcopy((s),(d),(l)) -#else -#error memmove does not exist on this platform, nor is a substitute available -#endif /* HAVE_BCOPY */ -#endif /* HAVE_MEMMOVE */ - -#include "internal.h" -#include "xmltok.h" -#include "xmlrole.h" - -typedef const XML_Char *KEY; - -typedef struct { - KEY name; -} NAMED; - -typedef struct { - NAMED **v; - unsigned char power; - size_t size; - size_t used; - const XML_Memory_Handling_Suite *mem; -} HASH_TABLE; - -/* Basic character hash algorithm, taken from Python's string hash: - h = h * 1000003 ^ character, the constant being a prime number. - -*/ -#ifdef XML_UNICODE -#define CHAR_HASH(h, c) \ - (((h) * 0xF4243) ^ (unsigned short)(c)) -#else -#define CHAR_HASH(h, c) \ - (((h) * 0xF4243) ^ (unsigned char)(c)) -#endif - -/* For probing (after a collision) we need a step size relative prime - to the hash table size, which is a power of 2. We use double-hashing, - since we can calculate a second hash value cheaply by taking those bits - of the first hash value that were discarded (masked out) when the table - index was calculated: index = hash & mask, where mask = table->size - 1. - We limit the maximum step size to table->size / 4 (mask >> 2) and make - it odd, since odd numbers are always relative prime to a power of 2. -*/ -#define SECOND_HASH(hash, mask, power) \ - ((((hash) & ~(mask)) >> ((power) - 1)) & ((mask) >> 2)) -#define PROBE_STEP(hash, mask, power) \ - ((unsigned char)((SECOND_HASH(hash, mask, power)) | 1)) - -typedef struct { - NAMED **p; - NAMED **end; -} HASH_TABLE_ITER; - -#define INIT_TAG_BUF_SIZE 32 /* must be a multiple of sizeof(XML_Char) */ -#define INIT_DATA_BUF_SIZE 1024 -#define INIT_ATTS_SIZE 16 -#define INIT_ATTS_VERSION 0xFFFFFFFF -#define INIT_BLOCK_SIZE 1024 -#define INIT_BUFFER_SIZE 1024 - -#define EXPAND_SPARE 24 - -typedef struct binding { - struct prefix *prefix; - struct binding *nextTagBinding; - struct binding *prevPrefixBinding; - const struct attribute_id *attId; - XML_Char *uri; - int uriLen; - int uriAlloc; -} BINDING; - -typedef struct prefix { - const XML_Char *name; - BINDING *binding; -} PREFIX; - -typedef struct { - const XML_Char *str; - const XML_Char *localPart; - const XML_Char *prefix; - int strLen; - int uriLen; - int prefixLen; -} TAG_NAME; - -/* TAG represents an open element. - The name of the element is stored in both the document and API - encodings. The memory buffer 'buf' is a separately-allocated - memory area which stores the name. During the XML_Parse()/ - XMLParseBuffer() when the element is open, the memory for the 'raw' - version of the name (in the document encoding) is shared with the - document buffer. If the element is open across calls to - XML_Parse()/XML_ParseBuffer(), the buffer is re-allocated to - contain the 'raw' name as well. - - A parser re-uses these structures, maintaining a list of allocated - TAG objects in a free list. -*/ -typedef struct tag { - struct tag *parent; /* parent of this element */ - const char *rawName; /* tagName in the original encoding */ - int rawNameLength; - TAG_NAME name; /* tagName in the API encoding */ - char *buf; /* buffer for name components */ - char *bufEnd; /* end of the buffer */ - BINDING *bindings; -} TAG; - -typedef struct { - const XML_Char *name; - const XML_Char *textPtr; - int textLen; /* length in XML_Chars */ - int processed; /* # of processed bytes - when suspended */ - const XML_Char *systemId; - const XML_Char *base; - const XML_Char *publicId; - const XML_Char *notation; - XML_Bool open; - XML_Bool is_param; - XML_Bool is_internal; /* true if declared in internal subset outside PE */ -} ENTITY; - -typedef struct { - enum XML_Content_Type type; - enum XML_Content_Quant quant; - const XML_Char * name; - int firstchild; - int lastchild; - int childcnt; - int nextsib; -} CONTENT_SCAFFOLD; - -#define INIT_SCAFFOLD_ELEMENTS 32 - -typedef struct block { - struct block *next; - int size; - XML_Char s[1]; -} BLOCK; - -typedef struct { - BLOCK *blocks; - BLOCK *freeBlocks; - const XML_Char *end; - XML_Char *ptr; - XML_Char *start; - const XML_Memory_Handling_Suite *mem; -} STRING_POOL; - -/* The XML_Char before the name is used to determine whether - an attribute has been specified. */ -typedef struct attribute_id { - XML_Char *name; - PREFIX *prefix; - XML_Bool maybeTokenized; - XML_Bool xmlns; -} ATTRIBUTE_ID; - -typedef struct { - const ATTRIBUTE_ID *id; - XML_Bool isCdata; - const XML_Char *value; -} DEFAULT_ATTRIBUTE; - -typedef struct { - unsigned long version; - unsigned long hash; - const XML_Char *uriName; -} NS_ATT; - -typedef struct { - const XML_Char *name; - PREFIX *prefix; - const ATTRIBUTE_ID *idAtt; - int nDefaultAtts; - int allocDefaultAtts; - DEFAULT_ATTRIBUTE *defaultAtts; -} ELEMENT_TYPE; - -typedef struct { - HASH_TABLE generalEntities; - HASH_TABLE elementTypes; - HASH_TABLE attributeIds; - HASH_TABLE prefixes; - STRING_POOL pool; - STRING_POOL entityValuePool; - /* false once a parameter entity reference has been skipped */ - XML_Bool keepProcessing; - /* true once an internal or external PE reference has been encountered; - this includes the reference to an external subset */ - XML_Bool hasParamEntityRefs; - XML_Bool standalone; -#ifdef XML_DTD - /* indicates if external PE has been read */ - XML_Bool paramEntityRead; - HASH_TABLE paramEntities; -#endif /* XML_DTD */ - PREFIX defaultPrefix; - /* === scaffolding for building content model === */ - XML_Bool in_eldecl; - CONTENT_SCAFFOLD *scaffold; - unsigned contentStringLen; - unsigned scaffSize; - unsigned scaffCount; - int scaffLevel; - int *scaffIndex; -} DTD; - -typedef struct open_internal_entity { - const char *internalEventPtr; - const char *internalEventEndPtr; - struct open_internal_entity *next; - ENTITY *entity; - int startTagLevel; - XML_Bool betweenDecl; /* WFC: PE Between Declarations */ -} OPEN_INTERNAL_ENTITY; - -typedef enum XML_Error PTRCALL Processor(XML_Parser parser, - const char *start, - const char *end, - const char **endPtr); - -static Processor prologProcessor; -static Processor prologInitProcessor; -static Processor contentProcessor; -static Processor cdataSectionProcessor; -#ifdef XML_DTD -static Processor ignoreSectionProcessor; -static Processor externalParEntProcessor; -static Processor externalParEntInitProcessor; -static Processor entityValueProcessor; -static Processor entityValueInitProcessor; -#endif /* XML_DTD */ -static Processor epilogProcessor; -static Processor errorProcessor; -static Processor externalEntityInitProcessor; -static Processor externalEntityInitProcessor2; -static Processor externalEntityInitProcessor3; -static Processor externalEntityContentProcessor; -static Processor internalEntityProcessor; - -static enum XML_Error -handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName); -static enum XML_Error -processXmlDecl(XML_Parser parser, int isGeneralTextEntity, - const char *s, const char *next); -static enum XML_Error -initializeEncoding(XML_Parser parser); -static enum XML_Error -doProlog(XML_Parser parser, const ENCODING *enc, const char *s, - const char *end, int tok, const char *next, const char **nextPtr, - XML_Bool haveMore); -static enum XML_Error -processInternalEntity(XML_Parser parser, ENTITY *entity, - XML_Bool betweenDecl); -static enum XML_Error -doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc, - const char *start, const char *end, const char **endPtr, - XML_Bool haveMore); -static enum XML_Error -doCdataSection(XML_Parser parser, const ENCODING *, const char **startPtr, - const char *end, const char **nextPtr, XML_Bool haveMore); -#ifdef XML_DTD -static enum XML_Error -doIgnoreSection(XML_Parser parser, const ENCODING *, const char **startPtr, - const char *end, const char **nextPtr, XML_Bool haveMore); -#endif /* XML_DTD */ - -static enum XML_Error -storeAtts(XML_Parser parser, const ENCODING *, const char *s, - TAG_NAME *tagNamePtr, BINDING **bindingsPtr); -static enum XML_Error -addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, - const XML_Char *uri, BINDING **bindingsPtr); -static int -defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *, XML_Bool isCdata, - XML_Bool isId, const XML_Char *dfltValue, XML_Parser parser); -static enum XML_Error -storeAttributeValue(XML_Parser parser, const ENCODING *, XML_Bool isCdata, - const char *, const char *, STRING_POOL *); -static enum XML_Error -appendAttributeValue(XML_Parser parser, const ENCODING *, XML_Bool isCdata, - const char *, const char *, STRING_POOL *); -static ATTRIBUTE_ID * -getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start, - const char *end); -static int -setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *); -static enum XML_Error -storeEntityValue(XML_Parser parser, const ENCODING *enc, const char *start, - const char *end); -static int -reportProcessingInstruction(XML_Parser parser, const ENCODING *enc, - const char *start, const char *end); -static int -reportComment(XML_Parser parser, const ENCODING *enc, const char *start, - const char *end); -static void -reportDefault(XML_Parser parser, const ENCODING *enc, const char *start, - const char *end); - -static const XML_Char * getContext(XML_Parser parser); -static XML_Bool -setContext(XML_Parser parser, const XML_Char *context); - -static void FASTCALL normalizePublicId(XML_Char *s); - -static DTD * dtdCreate(const XML_Memory_Handling_Suite *ms); -/* do not call if parentParser != NULL */ -static void dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms); -static void -dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms); -static int -dtdCopy(DTD *newDtd, const DTD *oldDtd, const XML_Memory_Handling_Suite *ms); -static int -copyEntityTable(HASH_TABLE *, STRING_POOL *, const HASH_TABLE *); - -static NAMED * -lookup(HASH_TABLE *table, KEY name, size_t createSize); -static void FASTCALL -hashTableInit(HASH_TABLE *, const XML_Memory_Handling_Suite *ms); -static void FASTCALL hashTableClear(HASH_TABLE *); -static void FASTCALL hashTableDestroy(HASH_TABLE *); -static void FASTCALL -hashTableIterInit(HASH_TABLE_ITER *, const HASH_TABLE *); -static NAMED * FASTCALL hashTableIterNext(HASH_TABLE_ITER *); - -static void FASTCALL -poolInit(STRING_POOL *, const XML_Memory_Handling_Suite *ms); -static void FASTCALL poolClear(STRING_POOL *); -static void FASTCALL poolDestroy(STRING_POOL *); -static XML_Char * -poolAppend(STRING_POOL *pool, const ENCODING *enc, - const char *ptr, const char *end); -static XML_Char * -poolStoreString(STRING_POOL *pool, const ENCODING *enc, - const char *ptr, const char *end); -static XML_Bool FASTCALL poolGrow(STRING_POOL *pool); -static const XML_Char * FASTCALL -poolCopyString(STRING_POOL *pool, const XML_Char *s); -static const XML_Char * -poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n); -static const XML_Char * FASTCALL -poolAppendString(STRING_POOL *pool, const XML_Char *s); - -static int FASTCALL nextScaffoldPart(XML_Parser parser); -static XML_Content * build_model(XML_Parser parser); -static ELEMENT_TYPE * -getElementType(XML_Parser parser, const ENCODING *enc, - const char *ptr, const char *end); - -static XML_Parser -parserCreate(const XML_Char *encodingName, - const XML_Memory_Handling_Suite *memsuite, - const XML_Char *nameSep, - DTD *dtd); -static void -parserInit(XML_Parser parser, const XML_Char *encodingName); - -#define poolStart(pool) ((pool)->start) -#define poolEnd(pool) ((pool)->ptr) -#define poolLength(pool) ((pool)->ptr - (pool)->start) -#define poolChop(pool) ((void)--(pool->ptr)) -#define poolLastChar(pool) (((pool)->ptr)[-1]) -#define poolDiscard(pool) ((pool)->ptr = (pool)->start) -#define poolFinish(pool) ((pool)->start = (pool)->ptr) -#define poolAppendChar(pool, c) \ - (((pool)->ptr == (pool)->end && !poolGrow(pool)) \ - ? 0 \ - : ((*((pool)->ptr)++ = c), 1)) - -struct XML_ParserStruct { - /* The first member must be userData so that the XML_GetUserData - macro works. */ - void *m_userData; - void *m_handlerArg; - char *m_buffer; - const XML_Memory_Handling_Suite m_mem; - /* first character to be parsed */ - const char *m_bufferPtr; - /* past last character to be parsed */ - char *m_bufferEnd; - /* allocated end of buffer */ - const char *m_bufferLim; - XML_Index m_parseEndByteIndex; - const char *m_parseEndPtr; - XML_Char *m_dataBuf; - XML_Char *m_dataBufEnd; - XML_StartElementHandler m_startElementHandler; - XML_EndElementHandler m_endElementHandler; - XML_CharacterDataHandler m_characterDataHandler; - XML_ProcessingInstructionHandler m_processingInstructionHandler; - XML_CommentHandler m_commentHandler; - XML_StartCdataSectionHandler m_startCdataSectionHandler; - XML_EndCdataSectionHandler m_endCdataSectionHandler; - XML_DefaultHandler m_defaultHandler; - XML_StartDoctypeDeclHandler m_startDoctypeDeclHandler; - XML_EndDoctypeDeclHandler m_endDoctypeDeclHandler; - XML_UnparsedEntityDeclHandler m_unparsedEntityDeclHandler; - XML_NotationDeclHandler m_notationDeclHandler; - XML_StartNamespaceDeclHandler m_startNamespaceDeclHandler; - XML_EndNamespaceDeclHandler m_endNamespaceDeclHandler; - XML_NotStandaloneHandler m_notStandaloneHandler; - XML_ExternalEntityRefHandler m_externalEntityRefHandler; - XML_Parser m_externalEntityRefHandlerArg; - XML_SkippedEntityHandler m_skippedEntityHandler; - XML_UnknownEncodingHandler m_unknownEncodingHandler; - XML_ElementDeclHandler m_elementDeclHandler; - XML_AttlistDeclHandler m_attlistDeclHandler; - XML_EntityDeclHandler m_entityDeclHandler; - XML_XmlDeclHandler m_xmlDeclHandler; - const ENCODING *m_encoding; - INIT_ENCODING m_initEncoding; - const ENCODING *m_internalEncoding; - const XML_Char *m_protocolEncodingName; - XML_Bool m_ns; - XML_Bool m_ns_triplets; - void *m_unknownEncodingMem; - void *m_unknownEncodingData; - void *m_unknownEncodingHandlerData; - void (XMLCALL *m_unknownEncodingRelease)(void *); - PROLOG_STATE m_prologState; - Processor *m_processor; - enum XML_Error m_errorCode; - const char *m_eventPtr; - const char *m_eventEndPtr; - const char *m_positionPtr; - OPEN_INTERNAL_ENTITY *m_openInternalEntities; - OPEN_INTERNAL_ENTITY *m_freeInternalEntities; - XML_Bool m_defaultExpandInternalEntities; - int m_tagLevel; - ENTITY *m_declEntity; - const XML_Char *m_doctypeName; - const XML_Char *m_doctypeSysid; - const XML_Char *m_doctypePubid; - const XML_Char *m_declAttributeType; - const XML_Char *m_declNotationName; - const XML_Char *m_declNotationPublicId; - ELEMENT_TYPE *m_declElementType; - ATTRIBUTE_ID *m_declAttributeId; - XML_Bool m_declAttributeIsCdata; - XML_Bool m_declAttributeIsId; - DTD *m_dtd; - const XML_Char *m_curBase; - TAG *m_tagStack; - TAG *m_freeTagList; - BINDING *m_inheritedBindings; - BINDING *m_freeBindingList; - int m_attsSize; - int m_nSpecifiedAtts; - int m_idAttIndex; - ATTRIBUTE *m_atts; - NS_ATT *m_nsAtts; - unsigned long m_nsAttsVersion; - unsigned char m_nsAttsPower; - POSITION m_position; - STRING_POOL m_tempPool; - STRING_POOL m_temp2Pool; - char *m_groupConnector; - unsigned int m_groupSize; - XML_Char m_namespaceSeparator; - XML_Parser m_parentParser; - XML_ParsingStatus m_parsingStatus; -#ifdef XML_DTD - XML_Bool m_isParamEntity; - XML_Bool m_useForeignDTD; - enum XML_ParamEntityParsing m_paramEntityParsing; -#endif -}; - -#define MALLOC(s) (parser->m_mem.malloc_fcn((s))) -#define REALLOC(p,s) (parser->m_mem.realloc_fcn((p),(s))) -#define FREE(p) (parser->m_mem.free_fcn((p))) - -#define userData (parser->m_userData) -#define handlerArg (parser->m_handlerArg) -#define startElementHandler (parser->m_startElementHandler) -#define endElementHandler (parser->m_endElementHandler) -#define characterDataHandler (parser->m_characterDataHandler) -#define processingInstructionHandler \ - (parser->m_processingInstructionHandler) -#define commentHandler (parser->m_commentHandler) -#define startCdataSectionHandler \ - (parser->m_startCdataSectionHandler) -#define endCdataSectionHandler (parser->m_endCdataSectionHandler) -#define defaultHandler (parser->m_defaultHandler) -#define startDoctypeDeclHandler (parser->m_startDoctypeDeclHandler) -#define endDoctypeDeclHandler (parser->m_endDoctypeDeclHandler) -#define unparsedEntityDeclHandler \ - (parser->m_unparsedEntityDeclHandler) -#define notationDeclHandler (parser->m_notationDeclHandler) -#define startNamespaceDeclHandler \ - (parser->m_startNamespaceDeclHandler) -#define endNamespaceDeclHandler (parser->m_endNamespaceDeclHandler) -#define notStandaloneHandler (parser->m_notStandaloneHandler) -#define externalEntityRefHandler \ - (parser->m_externalEntityRefHandler) -#define externalEntityRefHandlerArg \ - (parser->m_externalEntityRefHandlerArg) -#define internalEntityRefHandler \ - (parser->m_internalEntityRefHandler) -#define skippedEntityHandler (parser->m_skippedEntityHandler) -#define unknownEncodingHandler (parser->m_unknownEncodingHandler) -#define elementDeclHandler (parser->m_elementDeclHandler) -#define attlistDeclHandler (parser->m_attlistDeclHandler) -#define entityDeclHandler (parser->m_entityDeclHandler) -#define xmlDeclHandler (parser->m_xmlDeclHandler) -#define encoding (parser->m_encoding) -#define initEncoding (parser->m_initEncoding) -#define internalEncoding (parser->m_internalEncoding) -#define unknownEncodingMem (parser->m_unknownEncodingMem) -#define unknownEncodingData (parser->m_unknownEncodingData) -#define unknownEncodingHandlerData \ - (parser->m_unknownEncodingHandlerData) -#define unknownEncodingRelease (parser->m_unknownEncodingRelease) -#define protocolEncodingName (parser->m_protocolEncodingName) -#define ns (parser->m_ns) -#define ns_triplets (parser->m_ns_triplets) -#define prologState (parser->m_prologState) -#define processor (parser->m_processor) -#define errorCode (parser->m_errorCode) -#define eventPtr (parser->m_eventPtr) -#define eventEndPtr (parser->m_eventEndPtr) -#define positionPtr (parser->m_positionPtr) -#define position (parser->m_position) -#define openInternalEntities (parser->m_openInternalEntities) -#define freeInternalEntities (parser->m_freeInternalEntities) -#define defaultExpandInternalEntities \ - (parser->m_defaultExpandInternalEntities) -#define tagLevel (parser->m_tagLevel) -#define buffer (parser->m_buffer) -#define bufferPtr (parser->m_bufferPtr) -#define bufferEnd (parser->m_bufferEnd) -#define parseEndByteIndex (parser->m_parseEndByteIndex) -#define parseEndPtr (parser->m_parseEndPtr) -#define bufferLim (parser->m_bufferLim) -#define dataBuf (parser->m_dataBuf) -#define dataBufEnd (parser->m_dataBufEnd) -#define _dtd (parser->m_dtd) -#define curBase (parser->m_curBase) -#define declEntity (parser->m_declEntity) -#define doctypeName (parser->m_doctypeName) -#define doctypeSysid (parser->m_doctypeSysid) -#define doctypePubid (parser->m_doctypePubid) -#define declAttributeType (parser->m_declAttributeType) -#define declNotationName (parser->m_declNotationName) -#define declNotationPublicId (parser->m_declNotationPublicId) -#define declElementType (parser->m_declElementType) -#define declAttributeId (parser->m_declAttributeId) -#define declAttributeIsCdata (parser->m_declAttributeIsCdata) -#define declAttributeIsId (parser->m_declAttributeIsId) -#define freeTagList (parser->m_freeTagList) -#define freeBindingList (parser->m_freeBindingList) -#define inheritedBindings (parser->m_inheritedBindings) -#define tagStack (parser->m_tagStack) -#define atts (parser->m_atts) -#define attsSize (parser->m_attsSize) -#define nSpecifiedAtts (parser->m_nSpecifiedAtts) -#define idAttIndex (parser->m_idAttIndex) -#define nsAtts (parser->m_nsAtts) -#define nsAttsVersion (parser->m_nsAttsVersion) -#define nsAttsPower (parser->m_nsAttsPower) -#define tempPool (parser->m_tempPool) -#define temp2Pool (parser->m_temp2Pool) -#define groupConnector (parser->m_groupConnector) -#define groupSize (parser->m_groupSize) -#define namespaceSeparator (parser->m_namespaceSeparator) -#define parentParser (parser->m_parentParser) -#define ps_parsing (parser->m_parsingStatus.parsing) -#define ps_finalBuffer (parser->m_parsingStatus.finalBuffer) -#ifdef XML_DTD -#define isParamEntity (parser->m_isParamEntity) -#define useForeignDTD (parser->m_useForeignDTD) -#define paramEntityParsing (parser->m_paramEntityParsing) -#endif /* XML_DTD */ - -XML_Parser XMLCALL -XML_ParserCreate(const XML_Char *encodingName) -{ - return XML_ParserCreate_MM(encodingName, NULL, NULL); -} - -XML_Parser XMLCALL -XML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep) -{ - XML_Char tmp[2]; - *tmp = nsSep; - return XML_ParserCreate_MM(encodingName, NULL, tmp); -} - -static const XML_Char implicitContext[] = { - 'x', 'm', 'l', '=', 'h', 't', 't', 'p', ':', '/', '/', - 'w', 'w', 'w', '.', 'w', '3', '.', 'o', 'r', 'g', '/', - 'X', 'M', 'L', '/', '1', '9', '9', '8', '/', - 'n', 'a', 'm', 'e', 's', 'p', 'a', 'c', 'e', '\0' -}; - -XML_Parser XMLCALL -XML_ParserCreate_MM(const XML_Char *encodingName, - const XML_Memory_Handling_Suite *memsuite, - const XML_Char *nameSep) -{ - XML_Parser parser = parserCreate(encodingName, memsuite, nameSep, NULL); - if (parser != NULL && ns) { - /* implicit context only set for root parser, since child - parsers (i.e. external entity parsers) will inherit it - */ - if (!setContext(parser, implicitContext)) { - XML_ParserFree(parser); - return NULL; - } - } - return parser; -} - -static XML_Parser -parserCreate(const XML_Char *encodingName, - const XML_Memory_Handling_Suite *memsuite, - const XML_Char *nameSep, - DTD *dtd) -{ - XML_Parser parser; - - if (memsuite) { - XML_Memory_Handling_Suite *mtemp; - parser = (XML_Parser) - memsuite->malloc_fcn(sizeof(struct XML_ParserStruct)); - if (parser != NULL) { - mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem); - mtemp->malloc_fcn = memsuite->malloc_fcn; - mtemp->realloc_fcn = memsuite->realloc_fcn; - mtemp->free_fcn = memsuite->free_fcn; - } - } - else { - XML_Memory_Handling_Suite *mtemp; - parser = (XML_Parser)malloc(sizeof(struct XML_ParserStruct)); - if (parser != NULL) { - mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem); - mtemp->malloc_fcn = malloc; - mtemp->realloc_fcn = realloc; - mtemp->free_fcn = free; - } - } - - if (!parser) - return parser; - - buffer = NULL; - bufferLim = NULL; - - attsSize = INIT_ATTS_SIZE; - atts = (ATTRIBUTE *)MALLOC(attsSize * sizeof(ATTRIBUTE)); - if (atts == NULL) { - FREE(parser); - return NULL; - } - dataBuf = (XML_Char *)MALLOC(INIT_DATA_BUF_SIZE * sizeof(XML_Char)); - if (dataBuf == NULL) { - FREE(atts); - FREE(parser); - return NULL; - } - dataBufEnd = dataBuf + INIT_DATA_BUF_SIZE; - - if (dtd) - _dtd = dtd; - else { - _dtd = dtdCreate(&parser->m_mem); - if (_dtd == NULL) { - FREE(dataBuf); - FREE(atts); - FREE(parser); - return NULL; - } - } - - freeBindingList = NULL; - freeTagList = NULL; - freeInternalEntities = NULL; - - groupSize = 0; - groupConnector = NULL; - - unknownEncodingHandler = NULL; - unknownEncodingHandlerData = NULL; - - namespaceSeparator = '!'; - ns = XML_FALSE; - ns_triplets = XML_FALSE; - - nsAtts = NULL; - nsAttsVersion = 0; - nsAttsPower = 0; - - poolInit(&tempPool, &(parser->m_mem)); - poolInit(&temp2Pool, &(parser->m_mem)); - parserInit(parser, encodingName); - - if (encodingName && !protocolEncodingName) { - XML_ParserFree(parser); - return NULL; - } - - if (nameSep) { - ns = XML_TRUE; - internalEncoding = XmlGetInternalEncodingNS(); - namespaceSeparator = *nameSep; - } - else { - internalEncoding = XmlGetInternalEncoding(); - } - - return parser; -} - -static void -parserInit(XML_Parser parser, const XML_Char *encodingName) -{ - processor = prologInitProcessor; - XmlPrologStateInit(&prologState); - protocolEncodingName = (encodingName != NULL - ? poolCopyString(&tempPool, encodingName) - : NULL); - curBase = NULL; - XmlInitEncoding(&initEncoding, &encoding, 0); - userData = NULL; - handlerArg = NULL; - startElementHandler = NULL; - endElementHandler = NULL; - characterDataHandler = NULL; - processingInstructionHandler = NULL; - commentHandler = NULL; - startCdataSectionHandler = NULL; - endCdataSectionHandler = NULL; - defaultHandler = NULL; - startDoctypeDeclHandler = NULL; - endDoctypeDeclHandler = NULL; - unparsedEntityDeclHandler = NULL; - notationDeclHandler = NULL; - startNamespaceDeclHandler = NULL; - endNamespaceDeclHandler = NULL; - notStandaloneHandler = NULL; - externalEntityRefHandler = NULL; - externalEntityRefHandlerArg = parser; - skippedEntityHandler = NULL; - elementDeclHandler = NULL; - attlistDeclHandler = NULL; - entityDeclHandler = NULL; - xmlDeclHandler = NULL; - bufferPtr = buffer; - bufferEnd = buffer; - parseEndByteIndex = 0; - parseEndPtr = NULL; - declElementType = NULL; - declAttributeId = NULL; - declEntity = NULL; - doctypeName = NULL; - doctypeSysid = NULL; - doctypePubid = NULL; - declAttributeType = NULL; - declNotationName = NULL; - declNotationPublicId = NULL; - declAttributeIsCdata = XML_FALSE; - declAttributeIsId = XML_FALSE; - memset(&position, 0, sizeof(POSITION)); - errorCode = XML_ERROR_NONE; - eventPtr = NULL; - eventEndPtr = NULL; - positionPtr = NULL; - openInternalEntities = NULL; - defaultExpandInternalEntities = XML_TRUE; - tagLevel = 0; - tagStack = NULL; - inheritedBindings = NULL; - nSpecifiedAtts = 0; - unknownEncodingMem = NULL; - unknownEncodingRelease = NULL; - unknownEncodingData = NULL; - parentParser = NULL; - ps_parsing = XML_INITIALIZED; -#ifdef XML_DTD - isParamEntity = XML_FALSE; - useForeignDTD = XML_FALSE; - paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER; -#endif -} - -/* moves list of bindings to freeBindingList */ -static void FASTCALL -moveToFreeBindingList(XML_Parser parser, BINDING *bindings) -{ - while (bindings) { - BINDING *b = bindings; - bindings = bindings->nextTagBinding; - b->nextTagBinding = freeBindingList; - freeBindingList = b; - } -} - -XML_Bool XMLCALL -XML_ParserReset(XML_Parser parser, const XML_Char *encodingName) -{ - TAG *tStk; - OPEN_INTERNAL_ENTITY *openEntityList; - if (parentParser) - return XML_FALSE; - /* move tagStack to freeTagList */ - tStk = tagStack; - while (tStk) { - TAG *tag = tStk; - tStk = tStk->parent; - tag->parent = freeTagList; - moveToFreeBindingList(parser, tag->bindings); - tag->bindings = NULL; - freeTagList = tag; - } - /* move openInternalEntities to freeInternalEntities */ - openEntityList = openInternalEntities; - while (openEntityList) { - OPEN_INTERNAL_ENTITY *openEntity = openEntityList; - openEntityList = openEntity->next; - openEntity->next = freeInternalEntities; - freeInternalEntities = openEntity; - } - moveToFreeBindingList(parser, inheritedBindings); - FREE(unknownEncodingMem); - if (unknownEncodingRelease) - unknownEncodingRelease(unknownEncodingData); - poolClear(&tempPool); - poolClear(&temp2Pool); - parserInit(parser, encodingName); - dtdReset(_dtd, &parser->m_mem); - return setContext(parser, implicitContext); -} - -enum XML_Status XMLCALL -XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName) -{ - /* Block after XML_Parse()/XML_ParseBuffer() has been called. - XXX There's no way for the caller to determine which of the - XXX possible error cases caused the XML_STATUS_ERROR return. - */ - if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED) - return XML_STATUS_ERROR; - if (encodingName == NULL) - protocolEncodingName = NULL; - else { - protocolEncodingName = poolCopyString(&tempPool, encodingName); - if (!protocolEncodingName) - return XML_STATUS_ERROR; - } - return XML_STATUS_OK; -} - -XML_Parser XMLCALL -XML_ExternalEntityParserCreate(XML_Parser oldParser, - const XML_Char *context, - const XML_Char *encodingName) -{ - XML_Parser parser = oldParser; - DTD *newDtd = NULL; - DTD *oldDtd = _dtd; - XML_StartElementHandler oldStartElementHandler = startElementHandler; - XML_EndElementHandler oldEndElementHandler = endElementHandler; - XML_CharacterDataHandler oldCharacterDataHandler = characterDataHandler; - XML_ProcessingInstructionHandler oldProcessingInstructionHandler - = processingInstructionHandler; - XML_CommentHandler oldCommentHandler = commentHandler; - XML_StartCdataSectionHandler oldStartCdataSectionHandler - = startCdataSectionHandler; - XML_EndCdataSectionHandler oldEndCdataSectionHandler - = endCdataSectionHandler; - XML_DefaultHandler oldDefaultHandler = defaultHandler; - XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler - = unparsedEntityDeclHandler; - XML_NotationDeclHandler oldNotationDeclHandler = notationDeclHandler; - XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler - = startNamespaceDeclHandler; - XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler - = endNamespaceDeclHandler; - XML_NotStandaloneHandler oldNotStandaloneHandler = notStandaloneHandler; - XML_ExternalEntityRefHandler oldExternalEntityRefHandler - = externalEntityRefHandler; - XML_SkippedEntityHandler oldSkippedEntityHandler = skippedEntityHandler; - XML_UnknownEncodingHandler oldUnknownEncodingHandler - = unknownEncodingHandler; - XML_ElementDeclHandler oldElementDeclHandler = elementDeclHandler; - XML_AttlistDeclHandler oldAttlistDeclHandler = attlistDeclHandler; - XML_EntityDeclHandler oldEntityDeclHandler = entityDeclHandler; - XML_XmlDeclHandler oldXmlDeclHandler = xmlDeclHandler; - ELEMENT_TYPE * oldDeclElementType = declElementType; - - void *oldUserData = userData; - void *oldHandlerArg = handlerArg; - XML_Bool oldDefaultExpandInternalEntities = defaultExpandInternalEntities; - XML_Parser oldExternalEntityRefHandlerArg = externalEntityRefHandlerArg; -#ifdef XML_DTD - enum XML_ParamEntityParsing oldParamEntityParsing = paramEntityParsing; - int oldInEntityValue = prologState.inEntityValue; -#endif - XML_Bool oldns_triplets = ns_triplets; - -#ifdef XML_DTD - if (!context) - newDtd = oldDtd; -#endif /* XML_DTD */ - - /* Note that the magical uses of the pre-processor to make field - access look more like C++ require that `parser' be overwritten - here. This makes this function more painful to follow than it - would be otherwise. - */ - if (ns) { - XML_Char tmp[2]; - *tmp = namespaceSeparator; - parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd); - } - else { - parser = parserCreate(encodingName, &parser->m_mem, NULL, newDtd); - } - - if (!parser) - return NULL; - - startElementHandler = oldStartElementHandler; - endElementHandler = oldEndElementHandler; - characterDataHandler = oldCharacterDataHandler; - processingInstructionHandler = oldProcessingInstructionHandler; - commentHandler = oldCommentHandler; - startCdataSectionHandler = oldStartCdataSectionHandler; - endCdataSectionHandler = oldEndCdataSectionHandler; - defaultHandler = oldDefaultHandler; - unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler; - notationDeclHandler = oldNotationDeclHandler; - startNamespaceDeclHandler = oldStartNamespaceDeclHandler; - endNamespaceDeclHandler = oldEndNamespaceDeclHandler; - notStandaloneHandler = oldNotStandaloneHandler; - externalEntityRefHandler = oldExternalEntityRefHandler; - skippedEntityHandler = oldSkippedEntityHandler; - unknownEncodingHandler = oldUnknownEncodingHandler; - elementDeclHandler = oldElementDeclHandler; - attlistDeclHandler = oldAttlistDeclHandler; - entityDeclHandler = oldEntityDeclHandler; - xmlDeclHandler = oldXmlDeclHandler; - declElementType = oldDeclElementType; - userData = oldUserData; - if (oldUserData == oldHandlerArg) - handlerArg = userData; - else - handlerArg = parser; - if (oldExternalEntityRefHandlerArg != oldParser) - externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg; - defaultExpandInternalEntities = oldDefaultExpandInternalEntities; - ns_triplets = oldns_triplets; - parentParser = oldParser; -#ifdef XML_DTD - paramEntityParsing = oldParamEntityParsing; - prologState.inEntityValue = oldInEntityValue; - if (context) { -#endif /* XML_DTD */ - if (!dtdCopy(_dtd, oldDtd, &parser->m_mem) - || !setContext(parser, context)) { - XML_ParserFree(parser); - return NULL; - } - processor = externalEntityInitProcessor; -#ifdef XML_DTD - } - else { - /* The DTD instance referenced by _dtd is shared between the document's - root parser and external PE parsers, therefore one does not need to - call setContext. In addition, one also *must* not call setContext, - because this would overwrite existing prefix->binding pointers in - _dtd with ones that get destroyed with the external PE parser. - This would leave those prefixes with dangling pointers. - */ - isParamEntity = XML_TRUE; - XmlPrologStateInitExternalEntity(&prologState); - processor = externalParEntInitProcessor; - } -#endif /* XML_DTD */ - return parser; -} - -static void FASTCALL -destroyBindings(BINDING *bindings, XML_Parser parser) -{ - for (;;) { - BINDING *b = bindings; - if (!b) - break; - bindings = b->nextTagBinding; - FREE(b->uri); - FREE(b); - } -} - -void XMLCALL -XML_ParserFree(XML_Parser parser) -{ - TAG *tagList; - OPEN_INTERNAL_ENTITY *entityList; - if (parser == NULL) - return; - /* free tagStack and freeTagList */ - tagList = tagStack; - for (;;) { - TAG *p; - if (tagList == NULL) { - if (freeTagList == NULL) - break; - tagList = freeTagList; - freeTagList = NULL; - } - p = tagList; - tagList = tagList->parent; - FREE(p->buf); - destroyBindings(p->bindings, parser); - FREE(p); - } - /* free openInternalEntities and freeInternalEntities */ - entityList = openInternalEntities; - for (;;) { - OPEN_INTERNAL_ENTITY *openEntity; - if (entityList == NULL) { - if (freeInternalEntities == NULL) - break; - entityList = freeInternalEntities; - freeInternalEntities = NULL; - } - openEntity = entityList; - entityList = entityList->next; - FREE(openEntity); - } - - destroyBindings(freeBindingList, parser); - destroyBindings(inheritedBindings, parser); - poolDestroy(&tempPool); - poolDestroy(&temp2Pool); -#ifdef XML_DTD - /* external parameter entity parsers share the DTD structure - parser->m_dtd with the root parser, so we must not destroy it - */ - if (!isParamEntity && _dtd) -#else - if (_dtd) -#endif /* XML_DTD */ - dtdDestroy(_dtd, (XML_Bool)!parentParser, &parser->m_mem); - FREE((void *)atts); - FREE(groupConnector); - FREE(buffer); - FREE(dataBuf); - FREE(nsAtts); - FREE(unknownEncodingMem); - if (unknownEncodingRelease) - unknownEncodingRelease(unknownEncodingData); - FREE(parser); -} - -void XMLCALL -XML_UseParserAsHandlerArg(XML_Parser parser) -{ - handlerArg = parser; -} - -enum XML_Error XMLCALL -XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD) -{ -#ifdef XML_DTD - /* block after XML_Parse()/XML_ParseBuffer() has been called */ - if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED) - return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING; - useForeignDTD = useDTD; - return XML_ERROR_NONE; -#else - return XML_ERROR_FEATURE_REQUIRES_XML_DTD; -#endif -} - -void XMLCALL -XML_SetReturnNSTriplet(XML_Parser parser, int do_nst) -{ - /* block after XML_Parse()/XML_ParseBuffer() has been called */ - if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED) - return; - ns_triplets = do_nst ? XML_TRUE : XML_FALSE; -} - -void XMLCALL -XML_SetUserData(XML_Parser parser, void *p) -{ - if (handlerArg == userData) - handlerArg = userData = p; - else - userData = p; -} - -enum XML_Status XMLCALL -XML_SetBase(XML_Parser parser, const XML_Char *p) -{ - if (p) { - p = poolCopyString(&_dtd->pool, p); - if (!p) - return XML_STATUS_ERROR; - curBase = p; - } - else - curBase = NULL; - return XML_STATUS_OK; -} - -const XML_Char * XMLCALL -XML_GetBase(XML_Parser parser) -{ - return curBase; -} - -int XMLCALL -XML_GetSpecifiedAttributeCount(XML_Parser parser) -{ - return nSpecifiedAtts; -} - -int XMLCALL -XML_GetIdAttributeIndex(XML_Parser parser) -{ - return idAttIndex; -} - -void XMLCALL -XML_SetElementHandler(XML_Parser parser, - XML_StartElementHandler start, - XML_EndElementHandler end) -{ - startElementHandler = start; - endElementHandler = end; -} - -void XMLCALL -XML_SetStartElementHandler(XML_Parser parser, - XML_StartElementHandler start) { - startElementHandler = start; -} - -void XMLCALL -XML_SetEndElementHandler(XML_Parser parser, - XML_EndElementHandler end) { - endElementHandler = end; -} - -void XMLCALL -XML_SetCharacterDataHandler(XML_Parser parser, - XML_CharacterDataHandler handler) -{ - characterDataHandler = handler; -} - -void XMLCALL -XML_SetProcessingInstructionHandler(XML_Parser parser, - XML_ProcessingInstructionHandler handler) -{ - processingInstructionHandler = handler; -} - -void XMLCALL -XML_SetCommentHandler(XML_Parser parser, - XML_CommentHandler handler) -{ - commentHandler = handler; -} - -void XMLCALL -XML_SetCdataSectionHandler(XML_Parser parser, - XML_StartCdataSectionHandler start, - XML_EndCdataSectionHandler end) -{ - startCdataSectionHandler = start; - endCdataSectionHandler = end; -} - -void XMLCALL -XML_SetStartCdataSectionHandler(XML_Parser parser, - XML_StartCdataSectionHandler start) { - startCdataSectionHandler = start; -} - -void XMLCALL -XML_SetEndCdataSectionHandler(XML_Parser parser, - XML_EndCdataSectionHandler end) { - endCdataSectionHandler = end; -} - -void XMLCALL -XML_SetDefaultHandler(XML_Parser parser, - XML_DefaultHandler handler) -{ - defaultHandler = handler; - defaultExpandInternalEntities = XML_FALSE; -} - -void XMLCALL -XML_SetDefaultHandlerExpand(XML_Parser parser, - XML_DefaultHandler handler) -{ - defaultHandler = handler; - defaultExpandInternalEntities = XML_TRUE; -} - -void XMLCALL -XML_SetDoctypeDeclHandler(XML_Parser parser, - XML_StartDoctypeDeclHandler start, - XML_EndDoctypeDeclHandler end) -{ - startDoctypeDeclHandler = start; - endDoctypeDeclHandler = end; -} - -void XMLCALL -XML_SetStartDoctypeDeclHandler(XML_Parser parser, - XML_StartDoctypeDeclHandler start) { - startDoctypeDeclHandler = start; -} - -void XMLCALL -XML_SetEndDoctypeDeclHandler(XML_Parser parser, - XML_EndDoctypeDeclHandler end) { - endDoctypeDeclHandler = end; -} - -void XMLCALL -XML_SetUnparsedEntityDeclHandler(XML_Parser parser, - XML_UnparsedEntityDeclHandler handler) -{ - unparsedEntityDeclHandler = handler; -} - -void XMLCALL -XML_SetNotationDeclHandler(XML_Parser parser, - XML_NotationDeclHandler handler) -{ - notationDeclHandler = handler; -} - -void XMLCALL -XML_SetNamespaceDeclHandler(XML_Parser parser, - XML_StartNamespaceDeclHandler start, - XML_EndNamespaceDeclHandler end) -{ - startNamespaceDeclHandler = start; - endNamespaceDeclHandler = end; -} - -void XMLCALL -XML_SetStartNamespaceDeclHandler(XML_Parser parser, - XML_StartNamespaceDeclHandler start) { - startNamespaceDeclHandler = start; -} - -void XMLCALL -XML_SetEndNamespaceDeclHandler(XML_Parser parser, - XML_EndNamespaceDeclHandler end) { - endNamespaceDeclHandler = end; -} - -void XMLCALL -XML_SetNotStandaloneHandler(XML_Parser parser, - XML_NotStandaloneHandler handler) -{ - notStandaloneHandler = handler; -} - -void XMLCALL -XML_SetExternalEntityRefHandler(XML_Parser parser, - XML_ExternalEntityRefHandler handler) -{ - externalEntityRefHandler = handler; -} - -void XMLCALL -XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg) -{ - if (arg) - externalEntityRefHandlerArg = (XML_Parser)arg; - else - externalEntityRefHandlerArg = parser; -} - -void XMLCALL -XML_SetSkippedEntityHandler(XML_Parser parser, - XML_SkippedEntityHandler handler) -{ - skippedEntityHandler = handler; -} - -void XMLCALL -XML_SetUnknownEncodingHandler(XML_Parser parser, - XML_UnknownEncodingHandler handler, - void *data) -{ - unknownEncodingHandler = handler; - unknownEncodingHandlerData = data; -} - -void XMLCALL -XML_SetElementDeclHandler(XML_Parser parser, - XML_ElementDeclHandler eldecl) -{ - elementDeclHandler = eldecl; -} - -void XMLCALL -XML_SetAttlistDeclHandler(XML_Parser parser, - XML_AttlistDeclHandler attdecl) -{ - attlistDeclHandler = attdecl; -} - -void XMLCALL -XML_SetEntityDeclHandler(XML_Parser parser, - XML_EntityDeclHandler handler) -{ - entityDeclHandler = handler; -} - -void XMLCALL -XML_SetXmlDeclHandler(XML_Parser parser, - XML_XmlDeclHandler handler) { - xmlDeclHandler = handler; -} - -int XMLCALL -XML_SetParamEntityParsing(XML_Parser parser, - enum XML_ParamEntityParsing peParsing) -{ - /* block after XML_Parse()/XML_ParseBuffer() has been called */ - if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED) - return 0; -#ifdef XML_DTD - paramEntityParsing = peParsing; - return 1; -#else - return peParsing == XML_PARAM_ENTITY_PARSING_NEVER; -#endif -} - -enum XML_Status XMLCALL -XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) -{ - switch (ps_parsing) { - case XML_SUSPENDED: - errorCode = XML_ERROR_SUSPENDED; - return XML_STATUS_ERROR; - case XML_FINISHED: - errorCode = XML_ERROR_FINISHED; - return XML_STATUS_ERROR; - default: - ps_parsing = XML_PARSING; - } - - if (len == 0) { - ps_finalBuffer = (XML_Bool)isFinal; - if (!isFinal) - return XML_STATUS_OK; - positionPtr = bufferPtr; - parseEndPtr = bufferEnd; - - /* If data are left over from last buffer, and we now know that these - data are the final chunk of input, then we have to check them again - to detect errors based on that fact. - */ - errorCode = processor(parser, bufferPtr, parseEndPtr, &bufferPtr); - - if (errorCode == XML_ERROR_NONE) { - switch (ps_parsing) { - case XML_SUSPENDED: - XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position); - positionPtr = bufferPtr; - return XML_STATUS_SUSPENDED; - case XML_INITIALIZED: - case XML_PARSING: - ps_parsing = XML_FINISHED; - /* fall through */ - default: - return XML_STATUS_OK; - } - } - eventEndPtr = eventPtr; - processor = errorProcessor; - return XML_STATUS_ERROR; - } -#ifndef XML_CONTEXT_BYTES - else if (bufferPtr == bufferEnd) { - const char *end; - int nLeftOver; - enum XML_Error result; - parseEndByteIndex += len; - positionPtr = s; - ps_finalBuffer = (XML_Bool)isFinal; - - errorCode = processor(parser, s, parseEndPtr = s + len, &end); - - if (errorCode != XML_ERROR_NONE) { - eventEndPtr = eventPtr; - processor = errorProcessor; - return XML_STATUS_ERROR; - } - else { - switch (ps_parsing) { - case XML_SUSPENDED: - result = XML_STATUS_SUSPENDED; - break; - case XML_INITIALIZED: - case XML_PARSING: - result = XML_STATUS_OK; - if (isFinal) { - ps_parsing = XML_FINISHED; - return result; - } - break; - default: - /* XML_FINISHED case required by compiler - but not tested - djv */ - return XML_STATUS_OK; - } - } - - XmlUpdatePosition(encoding, positionPtr, end, &position); - nLeftOver = s + len - end; - if (nLeftOver) { - if (buffer == NULL || nLeftOver > bufferLim - buffer) { - /* FIXME avoid integer overflow */ - char *temp; - temp = (buffer == NULL - ? (char *)MALLOC(len * 2) - : (char *)REALLOC(buffer, len * 2)); - if (temp == NULL) { - errorCode = XML_ERROR_NO_MEMORY; - return XML_STATUS_ERROR; - } - buffer = temp; - if (!buffer) { - errorCode = XML_ERROR_NO_MEMORY; - eventPtr = eventEndPtr = NULL; - processor = errorProcessor; - return XML_STATUS_ERROR; - } - bufferLim = buffer + len * 2; - } - memcpy(buffer, end, nLeftOver); - } - bufferPtr = buffer; - bufferEnd = buffer + nLeftOver; - positionPtr = bufferPtr; - parseEndPtr = bufferEnd; - eventPtr = bufferPtr; - eventEndPtr = bufferPtr; - return result; - } -#endif /* not defined XML_CONTEXT_BYTES */ - else { - void *buff = XML_GetBuffer(parser, len); - if (buff == NULL) - return XML_STATUS_ERROR; - else { - memcpy(buff, s, len); - return XML_ParseBuffer(parser, len, isFinal); - } - } -} - -enum XML_Status XMLCALL -XML_ParseBuffer(XML_Parser parser, int len, int isFinal) -{ - const char *start; - enum XML_Status result = XML_STATUS_OK; - - switch (ps_parsing) { - case XML_SUSPENDED: - errorCode = XML_ERROR_SUSPENDED; - return XML_STATUS_ERROR; - case XML_FINISHED: - errorCode = XML_ERROR_FINISHED; - return XML_STATUS_ERROR; - default: - ps_parsing = XML_PARSING; - } - - start = bufferPtr; - positionPtr = start; - bufferEnd += len; - parseEndPtr = bufferEnd; - parseEndByteIndex += len; - ps_finalBuffer = (XML_Bool)isFinal; - - errorCode = processor(parser, start, parseEndPtr, &bufferPtr); - - if (errorCode != XML_ERROR_NONE) { - eventEndPtr = eventPtr; - processor = errorProcessor; - return XML_STATUS_ERROR; - } - else { - switch (ps_parsing) { - case XML_SUSPENDED: - result = XML_STATUS_SUSPENDED; - break; - case XML_INITIALIZED: - case XML_PARSING: - if (isFinal) { - ps_parsing = XML_FINISHED; - return result; - } - default: ; /* should not happen */ - } - } - - XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position); - positionPtr = bufferPtr; - return result; -} - -void * XMLCALL -XML_GetBuffer(XML_Parser parser, int len) -{ - switch (ps_parsing) { - case XML_SUSPENDED: - errorCode = XML_ERROR_SUSPENDED; - return NULL; - case XML_FINISHED: - errorCode = XML_ERROR_FINISHED; - return NULL; - default: ; - } - - if (len > bufferLim - bufferEnd) { - /* FIXME avoid integer overflow */ - int neededSize = len + (int)(bufferEnd - bufferPtr); -#ifdef XML_CONTEXT_BYTES - int keep = (int)(bufferPtr - buffer); - - if (keep > XML_CONTEXT_BYTES) - keep = XML_CONTEXT_BYTES; - neededSize += keep; -#endif /* defined XML_CONTEXT_BYTES */ - if (neededSize <= bufferLim - buffer) { -#ifdef XML_CONTEXT_BYTES - if (keep < bufferPtr - buffer) { - int offset = (int)(bufferPtr - buffer) - keep; - memmove(buffer, &buffer[offset], bufferEnd - bufferPtr + keep); - bufferEnd -= offset; - bufferPtr -= offset; - } -#else - memmove(buffer, bufferPtr, bufferEnd - bufferPtr); - bufferEnd = buffer + (bufferEnd - bufferPtr); - bufferPtr = buffer; -#endif /* not defined XML_CONTEXT_BYTES */ - } - else { - char *newBuf; - int bufferSize = (int)(bufferLim - bufferPtr); - if (bufferSize == 0) - bufferSize = INIT_BUFFER_SIZE; - do { - bufferSize *= 2; - } while (bufferSize < neededSize); - newBuf = (char *)MALLOC(bufferSize); - if (newBuf == 0) { - errorCode = XML_ERROR_NO_MEMORY; - return NULL; - } - bufferLim = newBuf + bufferSize; -#ifdef XML_CONTEXT_BYTES - if (bufferPtr) { - int keep = (int)(bufferPtr - buffer); - if (keep > XML_CONTEXT_BYTES) - keep = XML_CONTEXT_BYTES; - memcpy(newBuf, &bufferPtr[-keep], bufferEnd - bufferPtr + keep); - FREE(buffer); - buffer = newBuf; - bufferEnd = buffer + (bufferEnd - bufferPtr) + keep; - bufferPtr = buffer + keep; - } - else { - bufferEnd = newBuf + (bufferEnd - bufferPtr); - bufferPtr = buffer = newBuf; - } -#else - if (bufferPtr) { - memcpy(newBuf, bufferPtr, bufferEnd - bufferPtr); - FREE(buffer); - } - bufferEnd = newBuf + (bufferEnd - bufferPtr); - bufferPtr = buffer = newBuf; -#endif /* not defined XML_CONTEXT_BYTES */ - } - } - return bufferEnd; -} - -enum XML_Status XMLCALL -XML_StopParser(XML_Parser parser, XML_Bool resumable) -{ - switch (ps_parsing) { - case XML_SUSPENDED: - if (resumable) { - errorCode = XML_ERROR_SUSPENDED; - return XML_STATUS_ERROR; - } - ps_parsing = XML_FINISHED; - break; - case XML_FINISHED: - errorCode = XML_ERROR_FINISHED; - return XML_STATUS_ERROR; - default: - if (resumable) { -#ifdef XML_DTD - if (isParamEntity) { - errorCode = XML_ERROR_SUSPEND_PE; - return XML_STATUS_ERROR; - } -#endif - ps_parsing = XML_SUSPENDED; - } - else - ps_parsing = XML_FINISHED; - } - return XML_STATUS_OK; -} - -enum XML_Status XMLCALL -XML_ResumeParser(XML_Parser parser) -{ - enum XML_Status result = XML_STATUS_OK; - - if (ps_parsing != XML_SUSPENDED) { - errorCode = XML_ERROR_NOT_SUSPENDED; - return XML_STATUS_ERROR; - } - ps_parsing = XML_PARSING; - - errorCode = processor(parser, bufferPtr, parseEndPtr, &bufferPtr); - - if (errorCode != XML_ERROR_NONE) { - eventEndPtr = eventPtr; - processor = errorProcessor; - return XML_STATUS_ERROR; - } - else { - switch (ps_parsing) { - case XML_SUSPENDED: - result = XML_STATUS_SUSPENDED; - break; - case XML_INITIALIZED: - case XML_PARSING: - if (ps_finalBuffer) { - ps_parsing = XML_FINISHED; - return result; - } - default: ; - } - } - - XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position); - positionPtr = bufferPtr; - return result; -} - -void XMLCALL -XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status) -{ - assert(status != NULL); - *status = parser->m_parsingStatus; -} - -enum XML_Error XMLCALL -XML_GetErrorCode(XML_Parser parser) -{ - return errorCode; -} - -XML_Index XMLCALL -XML_GetCurrentByteIndex(XML_Parser parser) -{ - if (eventPtr) - return parseEndByteIndex - (parseEndPtr - eventPtr); - return -1; -} - -int XMLCALL -XML_GetCurrentByteCount(XML_Parser parser) -{ - if (eventEndPtr && eventPtr) - return (int)(eventEndPtr - eventPtr); - return 0; -} - -const char * XMLCALL -XML_GetInputContext(XML_Parser parser, int *offset, int *size) -{ -#ifdef XML_CONTEXT_BYTES - if (eventPtr && buffer) { - *offset = (int)(eventPtr - buffer); - *size = (int)(bufferEnd - buffer); - return buffer; - } -#endif /* defined XML_CONTEXT_BYTES */ - return (char *) 0; -} - -XML_Size XMLCALL -XML_GetCurrentLineNumber(XML_Parser parser) -{ - if (eventPtr && eventPtr >= positionPtr) { - XmlUpdatePosition(encoding, positionPtr, eventPtr, &position); - positionPtr = eventPtr; - } - return position.lineNumber + 1; -} - -XML_Size XMLCALL -XML_GetCurrentColumnNumber(XML_Parser parser) -{ - if (eventPtr && eventPtr >= positionPtr) { - XmlUpdatePosition(encoding, positionPtr, eventPtr, &position); - positionPtr = eventPtr; - } - return position.columnNumber; -} - -void XMLCALL -XML_FreeContentModel(XML_Parser parser, XML_Content *model) -{ - FREE(model); -} - -void * XMLCALL -XML_MemMalloc(XML_Parser parser, size_t size) -{ - return MALLOC(size); -} - -void * XMLCALL -XML_MemRealloc(XML_Parser parser, void *ptr, size_t size) -{ - return REALLOC(ptr, size); -} - -void XMLCALL -XML_MemFree(XML_Parser parser, void *ptr) -{ - FREE(ptr); -} - -void XMLCALL -XML_DefaultCurrent(XML_Parser parser) -{ - if (defaultHandler) { - if (openInternalEntities) - reportDefault(parser, - internalEncoding, - openInternalEntities->internalEventPtr, - openInternalEntities->internalEventEndPtr); - else - reportDefault(parser, encoding, eventPtr, eventEndPtr); - } -} - -const XML_LChar * XMLCALL -XML_ErrorString(enum XML_Error code) -{ - static const XML_LChar* const message[] = { - 0, - XML_L("out of memory"), - XML_L("syntax error"), - XML_L("no element found"), - XML_L("not well-formed (invalid token)"), - XML_L("unclosed token"), - XML_L("partial character"), - XML_L("mismatched tag"), - XML_L("duplicate attribute"), - XML_L("junk after document element"), - XML_L("illegal parameter entity reference"), - XML_L("undefined entity"), - XML_L("recursive entity reference"), - XML_L("asynchronous entity"), - XML_L("reference to invalid character number"), - XML_L("reference to binary entity"), - XML_L("reference to external entity in attribute"), - XML_L("XML or text declaration not at start of entity"), - XML_L("unknown encoding"), - XML_L("encoding specified in XML declaration is incorrect"), - XML_L("unclosed CDATA section"), - XML_L("error in processing external entity reference"), - XML_L("document is not standalone"), - XML_L("unexpected parser state - please send a bug report"), - XML_L("entity declared in parameter entity"), - XML_L("requested feature requires XML_DTD support in Expat"), - XML_L("cannot change setting once parsing has begun"), - XML_L("unbound prefix"), - XML_L("must not undeclare prefix"), - XML_L("incomplete markup in parameter entity"), - XML_L("XML declaration not well-formed"), - XML_L("text declaration not well-formed"), - XML_L("illegal character(s) in public id"), - XML_L("parser suspended"), - XML_L("parser not suspended"), - XML_L("parsing aborted"), - XML_L("parsing finished"), - XML_L("cannot suspend in external parameter entity"), - XML_L("reserved prefix (xml) must not be undeclared or bound to another namespace name"), - XML_L("reserved prefix (xmlns) must not be declared or undeclared"), - XML_L("prefix must not be bound to one of the reserved namespace names") - }; - if (code > 0 && code < sizeof(message)/sizeof(message[0])) - return message[code]; - return NULL; -} - -const XML_LChar * XMLCALL -XML_ExpatVersion(void) { - - /* V1 is used to string-ize the version number. However, it would - string-ize the actual version macro *names* unless we get them - substituted before being passed to V1. CPP is defined to expand - a macro, then rescan for more expansions. Thus, we use V2 to expand - the version macros, then CPP will expand the resulting V1() macro - with the correct numerals. */ - /* ### I'm assuming cpp is portable in this respect... */ - -#define V1(a,b,c) XML_L(#a)XML_L(".")XML_L(#b)XML_L(".")XML_L(#c) -#define V2(a,b,c) XML_L("expat_")V1(a,b,c) - - return V2(XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION); - -#undef V1 -#undef V2 -} - -XML_Expat_Version XMLCALL -XML_ExpatVersionInfo(void) -{ - XML_Expat_Version version; - - version.major = XML_MAJOR_VERSION; - version.minor = XML_MINOR_VERSION; - version.micro = XML_MICRO_VERSION; - - return version; -} - -const XML_Feature * XMLCALL -XML_GetFeatureList(void) -{ - static const XML_Feature features[] = { - {XML_FEATURE_SIZEOF_XML_CHAR, XML_L("sizeof(XML_Char)"), - sizeof(XML_Char)}, - {XML_FEATURE_SIZEOF_XML_LCHAR, XML_L("sizeof(XML_LChar)"), - sizeof(XML_LChar)}, -#ifdef XML_UNICODE - {XML_FEATURE_UNICODE, XML_L("XML_UNICODE"), 0}, -#endif -#ifdef XML_UNICODE_WCHAR_T - {XML_FEATURE_UNICODE_WCHAR_T, XML_L("XML_UNICODE_WCHAR_T"), 0}, -#endif -#ifdef XML_DTD - {XML_FEATURE_DTD, XML_L("XML_DTD"), 0}, -#endif -#ifdef XML_CONTEXT_BYTES - {XML_FEATURE_CONTEXT_BYTES, XML_L("XML_CONTEXT_BYTES"), - XML_CONTEXT_BYTES}, -#endif -#ifdef XML_MIN_SIZE - {XML_FEATURE_MIN_SIZE, XML_L("XML_MIN_SIZE"), 0}, -#endif -#ifdef XML_NS - {XML_FEATURE_NS, XML_L("XML_NS"), 0}, -#endif - {XML_FEATURE_END, NULL, 0} - }; - - return features; -} - -/* Initially tag->rawName always points into the parse buffer; - for those TAG instances opened while the current parse buffer was - processed, and not yet closed, we need to store tag->rawName in a more - permanent location, since the parse buffer is about to be discarded. -*/ -static XML_Bool -storeRawNames(XML_Parser parser) -{ - TAG *tag = tagStack; - while (tag) { - int bufSize; - int nameLen = sizeof(XML_Char) * (tag->name.strLen + 1); - char *rawNameBuf = tag->buf + nameLen; - /* Stop if already stored. Since tagStack is a stack, we can stop - at the first entry that has already been copied; everything - below it in the stack is already been accounted for in a - previous call to this function. - */ - if (tag->rawName == rawNameBuf) - break; - /* For re-use purposes we need to ensure that the - size of tag->buf is a multiple of sizeof(XML_Char). - */ - bufSize = nameLen + ROUND_UP(tag->rawNameLength, sizeof(XML_Char)); - if (bufSize > tag->bufEnd - tag->buf) { - char *temp = (char *)REALLOC(tag->buf, bufSize); - if (temp == NULL) - return XML_FALSE; - /* if tag->name.str points to tag->buf (only when namespace - processing is off) then we have to update it - */ - if (tag->name.str == (XML_Char *)tag->buf) - tag->name.str = (XML_Char *)temp; - /* if tag->name.localPart is set (when namespace processing is on) - then update it as well, since it will always point into tag->buf - */ - if (tag->name.localPart) - tag->name.localPart = (XML_Char *)temp + (tag->name.localPart - - (XML_Char *)tag->buf); - tag->buf = temp; - tag->bufEnd = temp + bufSize; - rawNameBuf = temp + nameLen; - } - memcpy(rawNameBuf, tag->rawName, tag->rawNameLength); - tag->rawName = rawNameBuf; - tag = tag->parent; - } - return XML_TRUE; -} - -static enum XML_Error PTRCALL -contentProcessor(XML_Parser parser, - const char *start, - const char *end, - const char **endPtr) -{ - enum XML_Error result = doContent(parser, 0, encoding, start, end, - endPtr, (XML_Bool)!ps_finalBuffer); - if (result == XML_ERROR_NONE) { - if (!storeRawNames(parser)) - return XML_ERROR_NO_MEMORY; - } - return result; -} - -static enum XML_Error PTRCALL -externalEntityInitProcessor(XML_Parser parser, - const char *start, - const char *end, - const char **endPtr) -{ - enum XML_Error result = initializeEncoding(parser); - if (result != XML_ERROR_NONE) - return result; - processor = externalEntityInitProcessor2; - return externalEntityInitProcessor2(parser, start, end, endPtr); -} - -static enum XML_Error PTRCALL -externalEntityInitProcessor2(XML_Parser parser, - const char *start, - const char *end, - const char **endPtr) -{ - const char *next = start; /* XmlContentTok doesn't always set the last arg */ - int tok = XmlContentTok(encoding, start, end, &next); - switch (tok) { - case XML_TOK_BOM: - /* If we are at the end of the buffer, this would cause the next stage, - i.e. externalEntityInitProcessor3, to pass control directly to - doContent (by detecting XML_TOK_NONE) without processing any xml text - declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent. - */ - if (next == end && !ps_finalBuffer) { - *endPtr = next; - return XML_ERROR_NONE; - } - start = next; - break; - case XML_TOK_PARTIAL: - if (!ps_finalBuffer) { - *endPtr = start; - return XML_ERROR_NONE; - } - eventPtr = start; - return XML_ERROR_UNCLOSED_TOKEN; - case XML_TOK_PARTIAL_CHAR: - if (!ps_finalBuffer) { - *endPtr = start; - return XML_ERROR_NONE; - } - eventPtr = start; - return XML_ERROR_PARTIAL_CHAR; - } - processor = externalEntityInitProcessor3; - return externalEntityInitProcessor3(parser, start, end, endPtr); -} - -static enum XML_Error PTRCALL -externalEntityInitProcessor3(XML_Parser parser, - const char *start, - const char *end, - const char **endPtr) -{ - int tok; - const char *next = start; /* XmlContentTok doesn't always set the last arg */ - eventPtr = start; - tok = XmlContentTok(encoding, start, end, &next); - eventEndPtr = next; - - switch (tok) { - case XML_TOK_XML_DECL: - { - enum XML_Error result; - result = processXmlDecl(parser, 1, start, next); - if (result != XML_ERROR_NONE) - return result; - switch (ps_parsing) { - case XML_SUSPENDED: - *endPtr = next; - return XML_ERROR_NONE; - case XML_FINISHED: - return XML_ERROR_ABORTED; - default: - start = next; - } - } - break; - case XML_TOK_PARTIAL: - if (!ps_finalBuffer) { - *endPtr = start; - return XML_ERROR_NONE; - } - return XML_ERROR_UNCLOSED_TOKEN; - case XML_TOK_PARTIAL_CHAR: - if (!ps_finalBuffer) { - *endPtr = start; - return XML_ERROR_NONE; - } - return XML_ERROR_PARTIAL_CHAR; - } - processor = externalEntityContentProcessor; - tagLevel = 1; - return externalEntityContentProcessor(parser, start, end, endPtr); -} - -static enum XML_Error PTRCALL -externalEntityContentProcessor(XML_Parser parser, - const char *start, - const char *end, - const char **endPtr) -{ - enum XML_Error result = doContent(parser, 1, encoding, start, end, - endPtr, (XML_Bool)!ps_finalBuffer); - if (result == XML_ERROR_NONE) { - if (!storeRawNames(parser)) - return XML_ERROR_NO_MEMORY; - } - return result; -} - -static enum XML_Error -doContent(XML_Parser parser, - int startTagLevel, - const ENCODING *enc, - const char *s, - const char *end, - const char **nextPtr, - XML_Bool haveMore) -{ - /* save one level of indirection */ - DTD * const dtd = _dtd; - - const char **eventPP; - const char **eventEndPP; - if (enc == encoding) { - eventPP = &eventPtr; - eventEndPP = &eventEndPtr; - } - else { - eventPP = &(openInternalEntities->internalEventPtr); - eventEndPP = &(openInternalEntities->internalEventEndPtr); - } - *eventPP = s; - - for (;;) { - const char *next = s; /* XmlContentTok doesn't always set the last arg */ - int tok = XmlContentTok(enc, s, end, &next); - *eventEndPP = next; - switch (tok) { - case XML_TOK_TRAILING_CR: - if (haveMore) { - *nextPtr = s; - return XML_ERROR_NONE; - } - *eventEndPP = end; - if (characterDataHandler) { - XML_Char c = 0xA; - characterDataHandler(handlerArg, &c, 1); - } - else if (defaultHandler) - reportDefault(parser, enc, s, end); - /* We are at the end of the final buffer, should we check for - XML_SUSPENDED, XML_FINISHED? - */ - if (startTagLevel == 0) - return XML_ERROR_NO_ELEMENTS; - if (tagLevel != startTagLevel) - return XML_ERROR_ASYNC_ENTITY; - *nextPtr = end; - return XML_ERROR_NONE; - case XML_TOK_NONE: - if (haveMore) { - *nextPtr = s; - return XML_ERROR_NONE; - } - if (startTagLevel > 0) { - if (tagLevel != startTagLevel) - return XML_ERROR_ASYNC_ENTITY; - *nextPtr = s; - return XML_ERROR_NONE; - } - return XML_ERROR_NO_ELEMENTS; - case XML_TOK_INVALID: - *eventPP = next; - return XML_ERROR_INVALID_TOKEN; - case XML_TOK_PARTIAL: - if (haveMore) { - *nextPtr = s; - return XML_ERROR_NONE; - } - return XML_ERROR_UNCLOSED_TOKEN; - case XML_TOK_PARTIAL_CHAR: - if (haveMore) { - *nextPtr = s; - return XML_ERROR_NONE; - } - return XML_ERROR_PARTIAL_CHAR; - case XML_TOK_ENTITY_REF: - { - const XML_Char *name; - ENTITY *entity; - XML_Char ch = (XML_Char) XmlPredefinedEntityName(enc, - s + enc->minBytesPerChar, - next - enc->minBytesPerChar); - if (ch) { - if (characterDataHandler) - characterDataHandler(handlerArg, &ch, 1); - else if (defaultHandler) - reportDefault(parser, enc, s, next); - break; - } - name = poolStoreString(&dtd->pool, enc, - s + enc->minBytesPerChar, - next - enc->minBytesPerChar); - if (!name) - return XML_ERROR_NO_MEMORY; - entity = (ENTITY *)lookup(&dtd->generalEntities, name, 0); - poolDiscard(&dtd->pool); - /* First, determine if a check for an existing declaration is needed; - if yes, check that the entity exists, and that it is internal, - otherwise call the skipped entity or default handler. - */ - if (!dtd->hasParamEntityRefs || dtd->standalone) { - if (!entity) - return XML_ERROR_UNDEFINED_ENTITY; - else if (!entity->is_internal) - return XML_ERROR_ENTITY_DECLARED_IN_PE; - } - else if (!entity) { - if (skippedEntityHandler) - skippedEntityHandler(handlerArg, name, 0); - else if (defaultHandler) - reportDefault(parser, enc, s, next); - break; - } - if (entity->open) - return XML_ERROR_RECURSIVE_ENTITY_REF; - if (entity->notation) - return XML_ERROR_BINARY_ENTITY_REF; - if (entity->textPtr) { - enum XML_Error result; - if (!defaultExpandInternalEntities) { - if (skippedEntityHandler) - skippedEntityHandler(handlerArg, entity->name, 0); - else if (defaultHandler) - reportDefault(parser, enc, s, next); - break; - } - result = processInternalEntity(parser, entity, XML_FALSE); - if (result != XML_ERROR_NONE) - return result; - } - else if (externalEntityRefHandler) { - const XML_Char *context; - entity->open = XML_TRUE; - context = getContext(parser); - entity->open = XML_FALSE; - if (!context) - return XML_ERROR_NO_MEMORY; - if (!externalEntityRefHandler(externalEntityRefHandlerArg, - context, - entity->base, - entity->systemId, - entity->publicId)) - return XML_ERROR_EXTERNAL_ENTITY_HANDLING; - poolDiscard(&tempPool); - } - else if (defaultHandler) - reportDefault(parser, enc, s, next); - break; - } - case XML_TOK_START_TAG_NO_ATTS: - /* fall through */ - case XML_TOK_START_TAG_WITH_ATTS: - { - TAG *tag; - enum XML_Error result; - XML_Char *toPtr; - if (freeTagList) { - tag = freeTagList; - freeTagList = freeTagList->parent; - } - else { - tag = (TAG *)MALLOC(sizeof(TAG)); - if (!tag) - return XML_ERROR_NO_MEMORY; - tag->buf = (char *)MALLOC(INIT_TAG_BUF_SIZE); - if (!tag->buf) { - FREE(tag); - return XML_ERROR_NO_MEMORY; - } - tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE; - } - tag->bindings = NULL; - tag->parent = tagStack; - tagStack = tag; - tag->name.localPart = NULL; - tag->name.prefix = NULL; - tag->rawName = s + enc->minBytesPerChar; - tag->rawNameLength = XmlNameLength(enc, tag->rawName); - ++tagLevel; - { - const char *rawNameEnd = tag->rawName + tag->rawNameLength; - const char *fromPtr = tag->rawName; - toPtr = (XML_Char *)tag->buf; - for (;;) { - int bufSize; - int convLen; - XmlConvert(enc, - &fromPtr, rawNameEnd, - (ICHAR **)&toPtr, (ICHAR *)tag->bufEnd - 1); - convLen = (int)(toPtr - (XML_Char *)tag->buf); - if (fromPtr == rawNameEnd) { - tag->name.strLen = convLen; - break; - } - bufSize = (int)(tag->bufEnd - tag->buf) << 1; - { - char *temp = (char *)REALLOC(tag->buf, bufSize); - if (temp == NULL) - return XML_ERROR_NO_MEMORY; - tag->buf = temp; - tag->bufEnd = temp + bufSize; - toPtr = (XML_Char *)temp + convLen; - } - } - } - tag->name.str = (XML_Char *)tag->buf; - *toPtr = XML_T('\0'); - result = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings)); - if (result) - return result; - if (startElementHandler) - startElementHandler(handlerArg, tag->name.str, - (const XML_Char **)atts); - else if (defaultHandler) - reportDefault(parser, enc, s, next); - poolClear(&tempPool); - break; - } - case XML_TOK_EMPTY_ELEMENT_NO_ATTS: - /* fall through */ - case XML_TOK_EMPTY_ELEMENT_WITH_ATTS: - { - const char *rawName = s + enc->minBytesPerChar; - enum XML_Error result; - BINDING *bindings = NULL; - XML_Bool noElmHandlers = XML_TRUE; - TAG_NAME name; - name.str = poolStoreString(&tempPool, enc, rawName, - rawName + XmlNameLength(enc, rawName)); - if (!name.str) - return XML_ERROR_NO_MEMORY; - poolFinish(&tempPool); - result = storeAtts(parser, enc, s, &name, &bindings); - if (result) - return result; - poolFinish(&tempPool); - if (startElementHandler) { - startElementHandler(handlerArg, name.str, (const XML_Char **)atts); - noElmHandlers = XML_FALSE; - } - if (endElementHandler) { - if (startElementHandler) - *eventPP = *eventEndPP; - endElementHandler(handlerArg, name.str); - noElmHandlers = XML_FALSE; - } - if (noElmHandlers && defaultHandler) - reportDefault(parser, enc, s, next); - poolClear(&tempPool); - while (bindings) { - BINDING *b = bindings; - if (endNamespaceDeclHandler) - endNamespaceDeclHandler(handlerArg, b->prefix->name); - bindings = bindings->nextTagBinding; - b->nextTagBinding = freeBindingList; - freeBindingList = b; - b->prefix->binding = b->prevPrefixBinding; - } - } - if (tagLevel == 0) - return epilogProcessor(parser, next, end, nextPtr); - break; - case XML_TOK_END_TAG: - if (tagLevel == startTagLevel) - return XML_ERROR_ASYNC_ENTITY; - else { - int len; - const char *rawName; - TAG *tag = tagStack; - tagStack = tag->parent; - tag->parent = freeTagList; - freeTagList = tag; - rawName = s + enc->minBytesPerChar*2; - len = XmlNameLength(enc, rawName); - if (len != tag->rawNameLength - || memcmp(tag->rawName, rawName, len) != 0) { - *eventPP = rawName; - return XML_ERROR_TAG_MISMATCH; - } - --tagLevel; - if (endElementHandler) { - const XML_Char *localPart; - const XML_Char *prefix; - XML_Char *uri; - localPart = tag->name.localPart; - if (ns && localPart) { - /* localPart and prefix may have been overwritten in - tag->name.str, since this points to the binding->uri - buffer which gets re-used; so we have to add them again - */ - uri = (XML_Char *)tag->name.str + tag->name.uriLen; - /* don't need to check for space - already done in storeAtts() */ - while (*localPart) *uri++ = *localPart++; - prefix = (XML_Char *)tag->name.prefix; - if (ns_triplets && prefix) { - *uri++ = namespaceSeparator; - while (*prefix) *uri++ = *prefix++; - } - *uri = XML_T('\0'); - } - endElementHandler(handlerArg, tag->name.str); - } - else if (defaultHandler) - reportDefault(parser, enc, s, next); - while (tag->bindings) { - BINDING *b = tag->bindings; - if (endNamespaceDeclHandler) - endNamespaceDeclHandler(handlerArg, b->prefix->name); - tag->bindings = tag->bindings->nextTagBinding; - b->nextTagBinding = freeBindingList; - freeBindingList = b; - b->prefix->binding = b->prevPrefixBinding; - } - if (tagLevel == 0) - return epilogProcessor(parser, next, end, nextPtr); - } - break; - case XML_TOK_CHAR_REF: - { - int n = XmlCharRefNumber(enc, s); - if (n < 0) - return XML_ERROR_BAD_CHAR_REF; - if (characterDataHandler) { - XML_Char buf[XML_ENCODE_MAX]; - characterDataHandler(handlerArg, buf, XmlEncode(n, (ICHAR *)buf)); - } - else if (defaultHandler) - reportDefault(parser, enc, s, next); - } - break; - case XML_TOK_XML_DECL: - return XML_ERROR_MISPLACED_XML_PI; - case XML_TOK_DATA_NEWLINE: - if (characterDataHandler) { - XML_Char c = 0xA; - characterDataHandler(handlerArg, &c, 1); - } - else if (defaultHandler) - reportDefault(parser, enc, s, next); - break; - case XML_TOK_CDATA_SECT_OPEN: - { - enum XML_Error result; - if (startCdataSectionHandler) - startCdataSectionHandler(handlerArg); -#if 0 - /* Suppose you doing a transformation on a document that involves - changing only the character data. You set up a defaultHandler - and a characterDataHandler. The defaultHandler simply copies - characters through. The characterDataHandler does the - transformation and writes the characters out escaping them as - necessary. This case will fail to work if we leave out the - following two lines (because & and < inside CDATA sections will - be incorrectly escaped). - - However, now we have a start/endCdataSectionHandler, so it seems - easier to let the user deal with this. - */ - else if (characterDataHandler) - characterDataHandler(handlerArg, dataBuf, 0); -#endif - else if (defaultHandler) - reportDefault(parser, enc, s, next); - result = doCdataSection(parser, enc, &next, end, nextPtr, haveMore); - if (result != XML_ERROR_NONE) - return result; - else if (!next) { - processor = cdataSectionProcessor; - return result; - } - } - break; - case XML_TOK_TRAILING_RSQB: - if (haveMore) { - *nextPtr = s; - return XML_ERROR_NONE; - } - if (characterDataHandler) { - if (MUST_CONVERT(enc, s)) { - ICHAR *dataPtr = (ICHAR *)dataBuf; - XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)dataBufEnd); - characterDataHandler(handlerArg, dataBuf, - (int)(dataPtr - (ICHAR *)dataBuf)); - } - else - characterDataHandler(handlerArg, - (XML_Char *)s, - (int)((XML_Char *)end - (XML_Char *)s)); - } - else if (defaultHandler) - reportDefault(parser, enc, s, end); - /* We are at the end of the final buffer, should we check for - XML_SUSPENDED, XML_FINISHED? - */ - if (startTagLevel == 0) { - *eventPP = end; - return XML_ERROR_NO_ELEMENTS; - } - if (tagLevel != startTagLevel) { - *eventPP = end; - return XML_ERROR_ASYNC_ENTITY; - } - *nextPtr = end; - return XML_ERROR_NONE; - case XML_TOK_DATA_CHARS: - if (characterDataHandler) { - if (MUST_CONVERT(enc, s)) { - for (;;) { - ICHAR *dataPtr = (ICHAR *)dataBuf; - XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd); - *eventEndPP = s; - characterDataHandler(handlerArg, dataBuf, - (int)(dataPtr - (ICHAR *)dataBuf)); - if (s == next) - break; - *eventPP = s; - } - } - else - characterDataHandler(handlerArg, - (XML_Char *)s, - (int)((XML_Char *)next - (XML_Char *)s)); - } - else if (defaultHandler) - reportDefault(parser, enc, s, next); - break; - case XML_TOK_PI: - if (!reportProcessingInstruction(parser, enc, s, next)) - return XML_ERROR_NO_MEMORY; - break; - case XML_TOK_COMMENT: - if (!reportComment(parser, enc, s, next)) - return XML_ERROR_NO_MEMORY; - break; - default: - if (defaultHandler) - reportDefault(parser, enc, s, next); - break; - } - *eventPP = s = next; - switch (ps_parsing) { - case XML_SUSPENDED: - *nextPtr = next; - return XML_ERROR_NONE; - case XML_FINISHED: - return XML_ERROR_ABORTED; - default: ; - } - } - /* not reached */ -} - -/* Precondition: all arguments must be non-NULL; - Purpose: - - normalize attributes - - check attributes for well-formedness - - generate namespace aware attribute names (URI, prefix) - - build list of attributes for startElementHandler - - default attributes - - process namespace declarations (check and report them) - - generate namespace aware element name (URI, prefix) -*/ -static enum XML_Error -storeAtts(XML_Parser parser, const ENCODING *enc, - const char *attStr, TAG_NAME *tagNamePtr, - BINDING **bindingsPtr) -{ - DTD * const dtd = _dtd; /* save one level of indirection */ - ELEMENT_TYPE *elementType; - int nDefaultAtts; - const XML_Char **appAtts; /* the attribute list for the application */ - int attIndex = 0; - int prefixLen; - int i; - int n; - XML_Char *uri; - int nPrefixes = 0; - BINDING *binding; - const XML_Char *localPart; - - /* lookup the element type name */ - elementType = (ELEMENT_TYPE *)lookup(&dtd->elementTypes, tagNamePtr->str,0); - if (!elementType) { - const XML_Char *name = poolCopyString(&dtd->pool, tagNamePtr->str); - if (!name) - return XML_ERROR_NO_MEMORY; - elementType = (ELEMENT_TYPE *)lookup(&dtd->elementTypes, name, - sizeof(ELEMENT_TYPE)); - if (!elementType) - return XML_ERROR_NO_MEMORY; - if (ns && !setElementTypePrefix(parser, elementType)) - return XML_ERROR_NO_MEMORY; - } - nDefaultAtts = elementType->nDefaultAtts; - - /* get the attributes from the tokenizer */ - n = XmlGetAttributes(enc, attStr, attsSize, atts); - if (n + nDefaultAtts > attsSize) { - int oldAttsSize = attsSize; - ATTRIBUTE *temp; - attsSize = n + nDefaultAtts + INIT_ATTS_SIZE; - temp = (ATTRIBUTE *)REALLOC((void *)atts, attsSize * sizeof(ATTRIBUTE)); - if (temp == NULL) - return XML_ERROR_NO_MEMORY; - atts = temp; - if (n > oldAttsSize) - XmlGetAttributes(enc, attStr, n, atts); - } - - appAtts = (const XML_Char **)atts; - for (i = 0; i < n; i++) { - /* add the name and value to the attribute list */ - ATTRIBUTE_ID *attId = getAttributeId(parser, enc, atts[i].name, - atts[i].name - + XmlNameLength(enc, atts[i].name)); - if (!attId) - return XML_ERROR_NO_MEMORY; - /* Detect duplicate attributes by their QNames. This does not work when - namespace processing is turned on and different prefixes for the same - namespace are used. For this case we have a check further down. - */ - if ((attId->name)[-1]) { - if (enc == encoding) - eventPtr = atts[i].name; - return XML_ERROR_DUPLICATE_ATTRIBUTE; - } - (attId->name)[-1] = 1; - appAtts[attIndex++] = attId->name; - if (!atts[i].normalized) { - enum XML_Error result; - XML_Bool isCdata = XML_TRUE; - - /* figure out whether declared as other than CDATA */ - if (attId->maybeTokenized) { - int j; - for (j = 0; j < nDefaultAtts; j++) { - if (attId == elementType->defaultAtts[j].id) { - isCdata = elementType->defaultAtts[j].isCdata; - break; - } - } - } - - /* normalize the attribute value */ - result = storeAttributeValue(parser, enc, isCdata, - atts[i].valuePtr, atts[i].valueEnd, - &tempPool); - if (result) - return result; - appAtts[attIndex] = poolStart(&tempPool); - poolFinish(&tempPool); - } - else { - /* the value did not need normalizing */ - appAtts[attIndex] = poolStoreString(&tempPool, enc, atts[i].valuePtr, - atts[i].valueEnd); - if (appAtts[attIndex] == 0) - return XML_ERROR_NO_MEMORY; - poolFinish(&tempPool); - } - /* handle prefixed attribute names */ - if (attId->prefix) { - if (attId->xmlns) { - /* deal with namespace declarations here */ - enum XML_Error result = addBinding(parser, attId->prefix, attId, - appAtts[attIndex], bindingsPtr); - if (result) - return result; - --attIndex; - } - else { - /* deal with other prefixed names later */ - attIndex++; - nPrefixes++; - (attId->name)[-1] = 2; - } - } - else - attIndex++; - } - - /* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */ - nSpecifiedAtts = attIndex; - if (elementType->idAtt && (elementType->idAtt->name)[-1]) { - for (i = 0; i < attIndex; i += 2) - if (appAtts[i] == elementType->idAtt->name) { - idAttIndex = i; - break; - } - } - else - idAttIndex = -1; - - /* do attribute defaulting */ - for (i = 0; i < nDefaultAtts; i++) { - const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + i; - if (!(da->id->name)[-1] && da->value) { - if (da->id->prefix) { - if (da->id->xmlns) { - enum XML_Error result = addBinding(parser, da->id->prefix, da->id, - da->value, bindingsPtr); - if (result) - return result; - } - else { - (da->id->name)[-1] = 2; - nPrefixes++; - appAtts[attIndex++] = da->id->name; - appAtts[attIndex++] = da->value; - } - } - else { - (da->id->name)[-1] = 1; - appAtts[attIndex++] = da->id->name; - appAtts[attIndex++] = da->value; - } - } - } - appAtts[attIndex] = 0; - - /* expand prefixed attribute names, check for duplicates, - and clear flags that say whether attributes were specified */ - i = 0; - if (nPrefixes) { - int j; /* hash table index */ - unsigned long version = nsAttsVersion; - int nsAttsSize = (int)1 << nsAttsPower; - /* size of hash table must be at least 2 * (# of prefixed attributes) */ - if ((nPrefixes << 1) >> nsAttsPower) { /* true for nsAttsPower = 0 */ - NS_ATT *temp; - /* hash table size must also be a power of 2 and >= 8 */ - while (nPrefixes >> nsAttsPower++); - if (nsAttsPower < 3) - nsAttsPower = 3; - nsAttsSize = (int)1 << nsAttsPower; - temp = (NS_ATT *)REALLOC(nsAtts, nsAttsSize * sizeof(NS_ATT)); - if (!temp) - return XML_ERROR_NO_MEMORY; - nsAtts = temp; - version = 0; /* force re-initialization of nsAtts hash table */ - } - /* using a version flag saves us from initializing nsAtts every time */ - if (!version) { /* initialize version flags when version wraps around */ - version = INIT_ATTS_VERSION; - for (j = nsAttsSize; j != 0; ) - nsAtts[--j].version = version; - } - nsAttsVersion = --version; - - /* expand prefixed names and check for duplicates */ - for (; i < attIndex; i += 2) { - const XML_Char *s = appAtts[i]; - if (s[-1] == 2) { /* prefixed */ - ATTRIBUTE_ID *id; - const BINDING *b; - unsigned long uriHash = 0; - ((XML_Char *)s)[-1] = 0; /* clear flag */ - id = (ATTRIBUTE_ID *)lookup(&dtd->attributeIds, s, 0); - if (!id) - return XML_ERROR_NO_MEMORY; - b = id->prefix->binding; - if (!b) - return XML_ERROR_UNBOUND_PREFIX; - - /* as we expand the name we also calculate its hash value */ - for (j = 0; j < b->uriLen; j++) { - const XML_Char c = b->uri[j]; - if (!poolAppendChar(&tempPool, c)) - return XML_ERROR_NO_MEMORY; - uriHash = CHAR_HASH(uriHash, c); - } - while (*s++ != XML_T(':')) - ; - do { /* copies null terminator */ - const XML_Char c = *s; - if (!poolAppendChar(&tempPool, *s)) - return XML_ERROR_NO_MEMORY; - uriHash = CHAR_HASH(uriHash, c); - } while (*s++); - - { /* Check hash table for duplicate of expanded name (uriName). - Derived from code in lookup(HASH_TABLE *table, ...). - */ - unsigned char step = 0; - unsigned long mask = nsAttsSize - 1; - j = uriHash & mask; /* index into hash table */ - while (nsAtts[j].version == version) { - /* for speed we compare stored hash values first */ - if (uriHash == nsAtts[j].hash) { - const XML_Char *s1 = poolStart(&tempPool); - const XML_Char *s2 = nsAtts[j].uriName; - /* s1 is null terminated, but not s2 */ - for (; *s1 == *s2 && *s1 != 0; s1++, s2++); - if (*s1 == 0) - return XML_ERROR_DUPLICATE_ATTRIBUTE; - } - if (!step) - step = PROBE_STEP(uriHash, mask, nsAttsPower); - j < step ? (j += nsAttsSize - step) : (j -= step); - } - } - - if (ns_triplets) { /* append namespace separator and prefix */ - tempPool.ptr[-1] = namespaceSeparator; - s = b->prefix->name; - do { - if (!poolAppendChar(&tempPool, *s)) - return XML_ERROR_NO_MEMORY; - } while (*s++); - } - - /* store expanded name in attribute list */ - s = poolStart(&tempPool); - poolFinish(&tempPool); - appAtts[i] = s; - - /* fill empty slot with new version, uriName and hash value */ - nsAtts[j].version = version; - nsAtts[j].hash = uriHash; - nsAtts[j].uriName = s; - - if (!--nPrefixes) { - i += 2; - break; - } - } - else /* not prefixed */ - ((XML_Char *)s)[-1] = 0; /* clear flag */ - } - } - /* clear flags for the remaining attributes */ - for (; i < attIndex; i += 2) - ((XML_Char *)(appAtts[i]))[-1] = 0; - for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding) - binding->attId->name[-1] = 0; - - if (!ns) - return XML_ERROR_NONE; - - /* expand the element type name */ - if (elementType->prefix) { - binding = elementType->prefix->binding; - if (!binding) - return XML_ERROR_UNBOUND_PREFIX; - localPart = tagNamePtr->str; - while (*localPart++ != XML_T(':')) - ; - } - else if (dtd->defaultPrefix.binding) { - binding = dtd->defaultPrefix.binding; - localPart = tagNamePtr->str; - } - else - return XML_ERROR_NONE; - prefixLen = 0; - if (ns_triplets && binding->prefix->name) { - for (; binding->prefix->name[prefixLen++];) - ; /* prefixLen includes null terminator */ - } - tagNamePtr->localPart = localPart; - tagNamePtr->uriLen = binding->uriLen; - tagNamePtr->prefix = binding->prefix->name; - tagNamePtr->prefixLen = prefixLen; - for (i = 0; localPart[i++];) - ; /* i includes null terminator */ - n = i + binding->uriLen + prefixLen; - if (n > binding->uriAlloc) { - TAG *p; - uri = (XML_Char *)MALLOC((n + EXPAND_SPARE) * sizeof(XML_Char)); - if (!uri) - return XML_ERROR_NO_MEMORY; - binding->uriAlloc = n + EXPAND_SPARE; - memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char)); - for (p = tagStack; p; p = p->parent) - if (p->name.str == binding->uri) - p->name.str = uri; - FREE(binding->uri); - binding->uri = uri; - } - /* if namespaceSeparator != '\0' then uri includes it already */ - uri = binding->uri + binding->uriLen; - memcpy(uri, localPart, i * sizeof(XML_Char)); - /* we always have a namespace separator between localPart and prefix */ - if (prefixLen) { - uri += i - 1; - *uri = namespaceSeparator; /* replace null terminator */ - memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char)); - } - tagNamePtr->str = binding->uri; - return XML_ERROR_NONE; -} - -/* addBinding() overwrites the value of prefix->binding without checking. - Therefore one must keep track of the old value outside of addBinding(). -*/ -static enum XML_Error -addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, - const XML_Char *uri, BINDING **bindingsPtr) -{ - static const XML_Char xmlNamespace[] = { - 'h', 't', 't', 'p', ':', '/', '/', - 'w', 'w', 'w', '.', 'w', '3', '.', 'o', 'r', 'g', '/', - 'X', 'M', 'L', '/', '1', '9', '9', '8', '/', - 'n', 'a', 'm', 'e', 's', 'p', 'a', 'c', 'e', '\0' - }; - static const int xmlLen = - (int)sizeof(xmlNamespace)/sizeof(XML_Char) - 1; - static const XML_Char xmlnsNamespace[] = { - 'h', 't', 't', 'p', ':', '/', '/', - 'w', 'w', 'w', '.', 'w', '3', '.', 'o', 'r', 'g', '/', - '2', '0', '0', '0', '/', 'x', 'm', 'l', 'n', 's', '/', '\0' - }; - static const int xmlnsLen = - (int)sizeof(xmlnsNamespace)/sizeof(XML_Char) - 1; - - XML_Bool mustBeXML = XML_FALSE; - XML_Bool isXML = XML_TRUE; - XML_Bool isXMLNS = XML_TRUE; - - BINDING *b; - int len; - - /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */ - if (*uri == XML_T('\0') && prefix->name) - return XML_ERROR_UNDECLARING_PREFIX; - - if (prefix->name - && prefix->name[0] == XML_T('x') - && prefix->name[1] == XML_T('m') - && prefix->name[2] == XML_T('l')) { - - /* Not allowed to bind xmlns */ - if (prefix->name[3] == XML_T('n') - && prefix->name[4] == XML_T('s') - && prefix->name[5] == XML_T('\0')) - return XML_ERROR_RESERVED_PREFIX_XMLNS; - - if (prefix->name[3] == XML_T('\0')) - mustBeXML = XML_TRUE; - } - - for (len = 0; uri[len]; len++) { - if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len])) - isXML = XML_FALSE; - - if (!mustBeXML && isXMLNS - && (len > xmlnsLen || uri[len] != xmlnsNamespace[len])) - isXMLNS = XML_FALSE; - } - isXML = isXML && len == xmlLen; - isXMLNS = isXMLNS && len == xmlnsLen; - - if (mustBeXML != isXML) - return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML - : XML_ERROR_RESERVED_NAMESPACE_URI; - - if (isXMLNS) - return XML_ERROR_RESERVED_NAMESPACE_URI; - - if (namespaceSeparator) - len++; - if (freeBindingList) { - b = freeBindingList; - if (len > b->uriAlloc) { - XML_Char *temp = (XML_Char *)REALLOC(b->uri, - sizeof(XML_Char) * (len + EXPAND_SPARE)); - if (temp == NULL) - return XML_ERROR_NO_MEMORY; - b->uri = temp; - b->uriAlloc = len + EXPAND_SPARE; - } - freeBindingList = b->nextTagBinding; - } - else { - b = (BINDING *)MALLOC(sizeof(BINDING)); - if (!b) - return XML_ERROR_NO_MEMORY; - b->uri = (XML_Char *)MALLOC(sizeof(XML_Char) * (len + EXPAND_SPARE)); - if (!b->uri) { - FREE(b); - return XML_ERROR_NO_MEMORY; - } - b->uriAlloc = len + EXPAND_SPARE; - } - b->uriLen = len; - memcpy(b->uri, uri, len * sizeof(XML_Char)); - if (namespaceSeparator) - b->uri[len - 1] = namespaceSeparator; - b->prefix = prefix; - b->attId = attId; - b->prevPrefixBinding = prefix->binding; - /* NULL binding when default namespace undeclared */ - if (*uri == XML_T('\0') && prefix == &_dtd->defaultPrefix) - prefix->binding = NULL; - else - prefix->binding = b; - b->nextTagBinding = *bindingsPtr; - *bindingsPtr = b; - /* if attId == NULL then we are not starting a namespace scope */ - if (attId && startNamespaceDeclHandler) - startNamespaceDeclHandler(handlerArg, prefix->name, - prefix->binding ? uri : 0); - return XML_ERROR_NONE; -} - -/* The idea here is to avoid using stack for each CDATA section when - the whole file is parsed with one call. -*/ -static enum XML_Error PTRCALL -cdataSectionProcessor(XML_Parser parser, - const char *start, - const char *end, - const char **endPtr) -{ - enum XML_Error result = doCdataSection(parser, encoding, &start, end, - endPtr, (XML_Bool)!ps_finalBuffer); - if (result != XML_ERROR_NONE) - return result; - if (start) { - if (parentParser) { /* we are parsing an external entity */ - processor = externalEntityContentProcessor; - return externalEntityContentProcessor(parser, start, end, endPtr); - } - else { - processor = contentProcessor; - return contentProcessor(parser, start, end, endPtr); - } - } - return result; -} - -/* startPtr gets set to non-null if the section is closed, and to null if - the section is not yet closed. -*/ -static enum XML_Error -doCdataSection(XML_Parser parser, - const ENCODING *enc, - const char **startPtr, - const char *end, - const char **nextPtr, - XML_Bool haveMore) -{ - const char *s = *startPtr; - const char **eventPP; - const char **eventEndPP; - if (enc == encoding) { - eventPP = &eventPtr; - *eventPP = s; - eventEndPP = &eventEndPtr; - } - else { - eventPP = &(openInternalEntities->internalEventPtr); - eventEndPP = &(openInternalEntities->internalEventEndPtr); - } - *eventPP = s; - *startPtr = NULL; - - for (;;) { - const char *next; - int tok = XmlCdataSectionTok(enc, s, end, &next); - *eventEndPP = next; - switch (tok) { - case XML_TOK_CDATA_SECT_CLOSE: - if (endCdataSectionHandler) - endCdataSectionHandler(handlerArg); -#if 0 - /* see comment under XML_TOK_CDATA_SECT_OPEN */ - else if (characterDataHandler) - characterDataHandler(handlerArg, dataBuf, 0); -#endif - else if (defaultHandler) - reportDefault(parser, enc, s, next); - *startPtr = next; - *nextPtr = next; - if (ps_parsing == XML_FINISHED) - return XML_ERROR_ABORTED; - else - return XML_ERROR_NONE; - case XML_TOK_DATA_NEWLINE: - if (characterDataHandler) { - XML_Char c = 0xA; - characterDataHandler(handlerArg, &c, 1); - } - else if (defaultHandler) - reportDefault(parser, enc, s, next); - break; - case XML_TOK_DATA_CHARS: - if (characterDataHandler) { - if (MUST_CONVERT(enc, s)) { - for (;;) { - ICHAR *dataPtr = (ICHAR *)dataBuf; - XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd); - *eventEndPP = next; - characterDataHandler(handlerArg, dataBuf, - (int)(dataPtr - (ICHAR *)dataBuf)); - if (s == next) - break; - *eventPP = s; - } - } - else - characterDataHandler(handlerArg, - (XML_Char *)s, - (int)((XML_Char *)next - (XML_Char *)s)); - } - else if (defaultHandler) - reportDefault(parser, enc, s, next); - break; - case XML_TOK_INVALID: - *eventPP = next; - return XML_ERROR_INVALID_TOKEN; - case XML_TOK_PARTIAL_CHAR: - if (haveMore) { - *nextPtr = s; - return XML_ERROR_NONE; - } - return XML_ERROR_PARTIAL_CHAR; - case XML_TOK_PARTIAL: - case XML_TOK_NONE: - if (haveMore) { - *nextPtr = s; - return XML_ERROR_NONE; - } - return XML_ERROR_UNCLOSED_CDATA_SECTION; - default: - *eventPP = next; - return XML_ERROR_UNEXPECTED_STATE; - } - - *eventPP = s = next; - switch (ps_parsing) { - case XML_SUSPENDED: - *nextPtr = next; - return XML_ERROR_NONE; - case XML_FINISHED: - return XML_ERROR_ABORTED; - default: ; - } - } - /* not reached */ -} - -#ifdef XML_DTD - -/* The idea here is to avoid using stack for each IGNORE section when - the whole file is parsed with one call. -*/ -static enum XML_Error PTRCALL -ignoreSectionProcessor(XML_Parser parser, - const char *start, - const char *end, - const char **endPtr) -{ - enum XML_Error result = doIgnoreSection(parser, encoding, &start, end, - endPtr, (XML_Bool)!ps_finalBuffer); - if (result != XML_ERROR_NONE) - return result; - if (start) { - processor = prologProcessor; - return prologProcessor(parser, start, end, endPtr); - } - return result; -} - -/* startPtr gets set to non-null is the section is closed, and to null - if the section is not yet closed. -*/ -static enum XML_Error -doIgnoreSection(XML_Parser parser, - const ENCODING *enc, - const char **startPtr, - const char *end, - const char **nextPtr, - XML_Bool haveMore) -{ - const char *next; - int tok; - const char *s = *startPtr; - const char **eventPP; - const char **eventEndPP; - if (enc == encoding) { - eventPP = &eventPtr; - *eventPP = s; - eventEndPP = &eventEndPtr; - } - else { - eventPP = &(openInternalEntities->internalEventPtr); - eventEndPP = &(openInternalEntities->internalEventEndPtr); - } - *eventPP = s; - *startPtr = NULL; - tok = XmlIgnoreSectionTok(enc, s, end, &next); - *eventEndPP = next; - switch (tok) { - case XML_TOK_IGNORE_SECT: - if (defaultHandler) - reportDefault(parser, enc, s, next); - *startPtr = next; - *nextPtr = next; - if (ps_parsing == XML_FINISHED) - return XML_ERROR_ABORTED; - else - return XML_ERROR_NONE; - case XML_TOK_INVALID: - *eventPP = next; - return XML_ERROR_INVALID_TOKEN; - case XML_TOK_PARTIAL_CHAR: - if (haveMore) { - *nextPtr = s; - return XML_ERROR_NONE; - } - return XML_ERROR_PARTIAL_CHAR; - case XML_TOK_PARTIAL: - case XML_TOK_NONE: - if (haveMore) { - *nextPtr = s; - return XML_ERROR_NONE; - } - return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */ - default: - *eventPP = next; - return XML_ERROR_UNEXPECTED_STATE; - } - /* not reached */ -} - -#endif /* XML_DTD */ - -static enum XML_Error -initializeEncoding(XML_Parser parser) -{ - const char *s; -#ifdef XML_UNICODE - char encodingBuf[128]; - if (!protocolEncodingName) - s = NULL; - else { - int i; - for (i = 0; protocolEncodingName[i]; i++) { - if (i == sizeof(encodingBuf) - 1 - || (protocolEncodingName[i] & ~0x7f) != 0) { - encodingBuf[0] = '\0'; - break; - } - encodingBuf[i] = (char)protocolEncodingName[i]; - } - encodingBuf[i] = '\0'; - s = encodingBuf; - } -#else - s = protocolEncodingName; -#endif - if ((ns ? XmlInitEncodingNS : XmlInitEncoding)(&initEncoding, &encoding, s)) - return XML_ERROR_NONE; - return handleUnknownEncoding(parser, protocolEncodingName); -} - -static enum XML_Error -processXmlDecl(XML_Parser parser, int isGeneralTextEntity, - const char *s, const char *next) -{ - const char *encodingName = NULL; - const XML_Char *storedEncName = NULL; - const ENCODING *newEncoding = NULL; - const char *version = NULL; - const char *versionend; - const XML_Char *storedversion = NULL; - int standalone = -1; - if (!(ns - ? XmlParseXmlDeclNS - : XmlParseXmlDecl)(isGeneralTextEntity, - encoding, - s, - next, - &eventPtr, - &version, - &versionend, - &encodingName, - &newEncoding, - &standalone)) { - if (isGeneralTextEntity) - return XML_ERROR_TEXT_DECL; - else - return XML_ERROR_XML_DECL; - } - if (!isGeneralTextEntity && standalone == 1) { - _dtd->standalone = XML_TRUE; -#ifdef XML_DTD - if (paramEntityParsing == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE) - paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER; -#endif /* XML_DTD */ - } - if (xmlDeclHandler) { - if (encodingName != NULL) { - storedEncName = poolStoreString(&temp2Pool, - encoding, - encodingName, - encodingName - + XmlNameLength(encoding, encodingName)); - if (!storedEncName) - return XML_ERROR_NO_MEMORY; - poolFinish(&temp2Pool); - } - if (version) { - storedversion = poolStoreString(&temp2Pool, - encoding, - version, - versionend - encoding->minBytesPerChar); - if (!storedversion) - return XML_ERROR_NO_MEMORY; - } - xmlDeclHandler(handlerArg, storedversion, storedEncName, standalone); - } - else if (defaultHandler) - reportDefault(parser, encoding, s, next); - if (protocolEncodingName == NULL) { - if (newEncoding) { - if (newEncoding->minBytesPerChar != encoding->minBytesPerChar) { - eventPtr = encodingName; - return XML_ERROR_INCORRECT_ENCODING; - } - encoding = newEncoding; - } - else if (encodingName) { - enum XML_Error result; - if (!storedEncName) { - storedEncName = poolStoreString( - &temp2Pool, encoding, encodingName, - encodingName + XmlNameLength(encoding, encodingName)); - if (!storedEncName) - return XML_ERROR_NO_MEMORY; - } - result = handleUnknownEncoding(parser, storedEncName); - poolClear(&temp2Pool); - if (result == XML_ERROR_UNKNOWN_ENCODING) - eventPtr = encodingName; - return result; - } - } - - if (storedEncName || storedversion) - poolClear(&temp2Pool); - - return XML_ERROR_NONE; -} - -static enum XML_Error -handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) -{ - if (unknownEncodingHandler) { - XML_Encoding info; - int i; - for (i = 0; i < 256; i++) - info.map[i] = -1; - info.convert = NULL; - info.data = NULL; - info.release = NULL; - if (unknownEncodingHandler(unknownEncodingHandlerData, encodingName, - &info)) { - ENCODING *enc; - unknownEncodingMem = MALLOC(XmlSizeOfUnknownEncoding()); - if (!unknownEncodingMem) { - if (info.release) - info.release(info.data); - return XML_ERROR_NO_MEMORY; - } - enc = (ns - ? XmlInitUnknownEncodingNS - : XmlInitUnknownEncoding)(unknownEncodingMem, - info.map, - info.convert, - info.data); - if (enc) { - unknownEncodingData = info.data; - unknownEncodingRelease = info.release; - encoding = enc; - return XML_ERROR_NONE; - } - } - if (info.release != NULL) - info.release(info.data); - } - return XML_ERROR_UNKNOWN_ENCODING; -} - -static enum XML_Error PTRCALL -prologInitProcessor(XML_Parser parser, - const char *s, - const char *end, - const char **nextPtr) -{ - enum XML_Error result = initializeEncoding(parser); - if (result != XML_ERROR_NONE) - return result; - processor = prologProcessor; - return prologProcessor(parser, s, end, nextPtr); -} - -#ifdef XML_DTD - -static enum XML_Error PTRCALL -externalParEntInitProcessor(XML_Parser parser, - const char *s, - const char *end, - const char **nextPtr) -{ - enum XML_Error result = initializeEncoding(parser); - if (result != XML_ERROR_NONE) - return result; - - /* we know now that XML_Parse(Buffer) has been called, - so we consider the external parameter entity read */ - _dtd->paramEntityRead = XML_TRUE; - - if (prologState.inEntityValue) { - processor = entityValueInitProcessor; - return entityValueInitProcessor(parser, s, end, nextPtr); - } - else { - processor = externalParEntProcessor; - return externalParEntProcessor(parser, s, end, nextPtr); - } -} - -static enum XML_Error PTRCALL -entityValueInitProcessor(XML_Parser parser, - const char *s, - const char *end, - const char **nextPtr) -{ - int tok; - const char *start = s; - const char *next = start; - eventPtr = start; - - for (;;) { - tok = XmlPrologTok(encoding, start, end, &next); - eventEndPtr = next; - if (tok <= 0) { - if (!ps_finalBuffer && tok != XML_TOK_INVALID) { - *nextPtr = s; - return XML_ERROR_NONE; - } - switch (tok) { - case XML_TOK_INVALID: - return XML_ERROR_INVALID_TOKEN; - case XML_TOK_PARTIAL: - return XML_ERROR_UNCLOSED_TOKEN; - case XML_TOK_PARTIAL_CHAR: - return XML_ERROR_PARTIAL_CHAR; - case XML_TOK_NONE: /* start == end */ - default: - break; - } - /* found end of entity value - can store it now */ - return storeEntityValue(parser, encoding, s, end); - } - else if (tok == XML_TOK_XML_DECL) { - enum XML_Error result; - result = processXmlDecl(parser, 0, start, next); - if (result != XML_ERROR_NONE) - return result; - switch (ps_parsing) { - case XML_SUSPENDED: - *nextPtr = next; - return XML_ERROR_NONE; - case XML_FINISHED: - return XML_ERROR_ABORTED; - default: - *nextPtr = next; - } - /* stop scanning for text declaration - we found one */ - processor = entityValueProcessor; - return entityValueProcessor(parser, next, end, nextPtr); - } - /* If we are at the end of the buffer, this would cause XmlPrologTok to - return XML_TOK_NONE on the next call, which would then cause the - function to exit with *nextPtr set to s - that is what we want for other - tokens, but not for the BOM - we would rather like to skip it; - then, when this routine is entered the next time, XmlPrologTok will - return XML_TOK_INVALID, since the BOM is still in the buffer - */ - else if (tok == XML_TOK_BOM && next == end && !ps_finalBuffer) { - *nextPtr = next; - return XML_ERROR_NONE; - } - start = next; - eventPtr = start; - } -} - -static enum XML_Error PTRCALL -externalParEntProcessor(XML_Parser parser, - const char *s, - const char *end, - const char **nextPtr) -{ - const char *next = s; - int tok; - - tok = XmlPrologTok(encoding, s, end, &next); - if (tok <= 0) { - if (!ps_finalBuffer && tok != XML_TOK_INVALID) { - *nextPtr = s; - return XML_ERROR_NONE; - } - switch (tok) { - case XML_TOK_INVALID: - return XML_ERROR_INVALID_TOKEN; - case XML_TOK_PARTIAL: - return XML_ERROR_UNCLOSED_TOKEN; - case XML_TOK_PARTIAL_CHAR: - return XML_ERROR_PARTIAL_CHAR; - case XML_TOK_NONE: /* start == end */ - default: - break; - } - } - /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM. - However, when parsing an external subset, doProlog will not accept a BOM - as valid, and report a syntax error, so we have to skip the BOM - */ - else if (tok == XML_TOK_BOM) { - s = next; - tok = XmlPrologTok(encoding, s, end, &next); - } - - processor = prologProcessor; - return doProlog(parser, encoding, s, end, tok, next, - nextPtr, (XML_Bool)!ps_finalBuffer); -} - -static enum XML_Error PTRCALL -entityValueProcessor(XML_Parser parser, - const char *s, - const char *end, - const char **nextPtr) -{ - const char *start = s; - const char *next = s; - const ENCODING *enc = encoding; - int tok; - - for (;;) { - tok = XmlPrologTok(enc, start, end, &next); - if (tok <= 0) { - if (!ps_finalBuffer && tok != XML_TOK_INVALID) { - *nextPtr = s; - return XML_ERROR_NONE; - } - switch (tok) { - case XML_TOK_INVALID: - return XML_ERROR_INVALID_TOKEN; - case XML_TOK_PARTIAL: - return XML_ERROR_UNCLOSED_TOKEN; - case XML_TOK_PARTIAL_CHAR: - return XML_ERROR_PARTIAL_CHAR; - case XML_TOK_NONE: /* start == end */ - default: - break; - } - /* found end of entity value - can store it now */ - return storeEntityValue(parser, enc, s, end); - } - start = next; - } -} - -#endif /* XML_DTD */ - -static enum XML_Error PTRCALL -prologProcessor(XML_Parser parser, - const char *s, - const char *end, - const char **nextPtr) -{ - const char *next = s; - int tok = XmlPrologTok(encoding, s, end, &next); - return doProlog(parser, encoding, s, end, tok, next, - nextPtr, (XML_Bool)!ps_finalBuffer); -} - -static enum XML_Error -doProlog(XML_Parser parser, - const ENCODING *enc, - const char *s, - const char *end, - int tok, - const char *next, - const char **nextPtr, - XML_Bool haveMore) -{ -#ifdef XML_DTD - static const XML_Char externalSubsetName[] = { '#' , '\0' }; -#endif /* XML_DTD */ - static const XML_Char atypeCDATA[] = { 'C', 'D', 'A', 'T', 'A', '\0' }; - static const XML_Char atypeID[] = { 'I', 'D', '\0' }; - static const XML_Char atypeIDREF[] = { 'I', 'D', 'R', 'E', 'F', '\0' }; - static const XML_Char atypeIDREFS[] = { 'I', 'D', 'R', 'E', 'F', 'S', '\0' }; - static const XML_Char atypeENTITY[] = { 'E', 'N', 'T', 'I', 'T', 'Y', '\0' }; - static const XML_Char atypeENTITIES[] = - { 'E', 'N', 'T', 'I', 'T', 'I', 'E', 'S', '\0' }; - static const XML_Char atypeNMTOKEN[] = { - 'N', 'M', 'T', 'O', 'K', 'E', 'N', '\0' }; - static const XML_Char atypeNMTOKENS[] = { - 'N', 'M', 'T', 'O', 'K', 'E', 'N', 'S', '\0' }; - static const XML_Char notationPrefix[] = { - 'N', 'O', 'T', 'A', 'T', 'I', 'O', 'N', '(', '\0' }; - static const XML_Char enumValueSep[] = { '|', '\0' }; - static const XML_Char enumValueStart[] = { '(', '\0' }; - - /* save one level of indirection */ - DTD * const dtd = _dtd; - - const char **eventPP; - const char **eventEndPP; - enum XML_Content_Quant quant; - - if (enc == encoding) { - eventPP = &eventPtr; - eventEndPP = &eventEndPtr; - } - else { - eventPP = &(openInternalEntities->internalEventPtr); - eventEndPP = &(openInternalEntities->internalEventEndPtr); - } - - for (;;) { - int role; - XML_Bool handleDefault = XML_TRUE; - *eventPP = s; - *eventEndPP = next; - if (tok <= 0) { - if (haveMore && tok != XML_TOK_INVALID) { - *nextPtr = s; - return XML_ERROR_NONE; - } - switch (tok) { - case XML_TOK_INVALID: - *eventPP = next; - return XML_ERROR_INVALID_TOKEN; - case XML_TOK_PARTIAL: - return XML_ERROR_UNCLOSED_TOKEN; - case XML_TOK_PARTIAL_CHAR: - return XML_ERROR_PARTIAL_CHAR; - case -XML_TOK_PROLOG_S: - tok = -tok; - break; - case XML_TOK_NONE: -#ifdef XML_DTD - /* for internal PE NOT referenced between declarations */ - if (enc != encoding && !openInternalEntities->betweenDecl) { - *nextPtr = s; - return XML_ERROR_NONE; - } - /* WFC: PE Between Declarations - must check that PE contains - complete markup, not only for external PEs, but also for - internal PEs if the reference occurs between declarations. - */ - if (isParamEntity || enc != encoding) { - if (XmlTokenRole(&prologState, XML_TOK_NONE, end, end, enc) - == XML_ROLE_ERROR) - return XML_ERROR_INCOMPLETE_PE; - *nextPtr = s; - return XML_ERROR_NONE; - } -#endif /* XML_DTD */ - return XML_ERROR_NO_ELEMENTS; - default: - tok = -tok; - next = end; - break; - } - } - role = XmlTokenRole(&prologState, tok, s, next, enc); - switch (role) { - case XML_ROLE_XML_DECL: - { - enum XML_Error result = processXmlDecl(parser, 0, s, next); - if (result != XML_ERROR_NONE) - return result; - enc = encoding; - handleDefault = XML_FALSE; - } - break; - case XML_ROLE_DOCTYPE_NAME: - if (startDoctypeDeclHandler) { - doctypeName = poolStoreString(&tempPool, enc, s, next); - if (!doctypeName) - return XML_ERROR_NO_MEMORY; - poolFinish(&tempPool); - doctypePubid = NULL; - handleDefault = XML_FALSE; - } - doctypeSysid = NULL; /* always initialize to NULL */ - break; - case XML_ROLE_DOCTYPE_INTERNAL_SUBSET: - if (startDoctypeDeclHandler) { - startDoctypeDeclHandler(handlerArg, doctypeName, doctypeSysid, - doctypePubid, 1); - doctypeName = NULL; - poolClear(&tempPool); - handleDefault = XML_FALSE; - } - break; -#ifdef XML_DTD - case XML_ROLE_TEXT_DECL: - { - enum XML_Error result = processXmlDecl(parser, 1, s, next); - if (result != XML_ERROR_NONE) - return result; - enc = encoding; - handleDefault = XML_FALSE; - } - break; -#endif /* XML_DTD */ - case XML_ROLE_DOCTYPE_PUBLIC_ID: -#ifdef XML_DTD - useForeignDTD = XML_FALSE; - declEntity = (ENTITY *)lookup(&dtd->paramEntities, - externalSubsetName, - sizeof(ENTITY)); - if (!declEntity) - return XML_ERROR_NO_MEMORY; -#endif /* XML_DTD */ - dtd->hasParamEntityRefs = XML_TRUE; - if (startDoctypeDeclHandler) { - if (!XmlIsPublicId(enc, s, next, eventPP)) - return XML_ERROR_PUBLICID; - doctypePubid = poolStoreString(&tempPool, enc, - s + enc->minBytesPerChar, - next - enc->minBytesPerChar); - if (!doctypePubid) - return XML_ERROR_NO_MEMORY; - normalizePublicId((XML_Char *)doctypePubid); - poolFinish(&tempPool); - handleDefault = XML_FALSE; - goto alreadyChecked; - } - /* fall through */ - case XML_ROLE_ENTITY_PUBLIC_ID: - if (!XmlIsPublicId(enc, s, next, eventPP)) - return XML_ERROR_PUBLICID; - alreadyChecked: - if (dtd->keepProcessing && declEntity) { - XML_Char *tem = poolStoreString(&dtd->pool, - enc, - s + enc->minBytesPerChar, - next - enc->minBytesPerChar); - if (!tem) - return XML_ERROR_NO_MEMORY; - normalizePublicId(tem); - declEntity->publicId = tem; - poolFinish(&dtd->pool); - if (entityDeclHandler) - handleDefault = XML_FALSE; - } - break; - case XML_ROLE_DOCTYPE_CLOSE: - if (doctypeName) { - startDoctypeDeclHandler(handlerArg, doctypeName, - doctypeSysid, doctypePubid, 0); - poolClear(&tempPool); - handleDefault = XML_FALSE; - } - /* doctypeSysid will be non-NULL in the case of a previous - XML_ROLE_DOCTYPE_SYSTEM_ID, even if startDoctypeDeclHandler - was not set, indicating an external subset - */ -#ifdef XML_DTD - if (doctypeSysid || useForeignDTD) { - XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs; - dtd->hasParamEntityRefs = XML_TRUE; - if (paramEntityParsing && externalEntityRefHandler) { - ENTITY *entity = (ENTITY *)lookup(&dtd->paramEntities, - externalSubsetName, - sizeof(ENTITY)); - if (!entity) - return XML_ERROR_NO_MEMORY; - if (useForeignDTD) - entity->base = curBase; - dtd->paramEntityRead = XML_FALSE; - if (!externalEntityRefHandler(externalEntityRefHandlerArg, - 0, - entity->base, - entity->systemId, - entity->publicId)) - return XML_ERROR_EXTERNAL_ENTITY_HANDLING; - if (dtd->paramEntityRead) { - if (!dtd->standalone && - notStandaloneHandler && - !notStandaloneHandler(handlerArg)) - return XML_ERROR_NOT_STANDALONE; - } - /* if we didn't read the foreign DTD then this means that there - is no external subset and we must reset dtd->hasParamEntityRefs - */ - else if (!doctypeSysid) - dtd->hasParamEntityRefs = hadParamEntityRefs; - /* end of DTD - no need to update dtd->keepProcessing */ - } - useForeignDTD = XML_FALSE; - } -#endif /* XML_DTD */ - if (endDoctypeDeclHandler) { - endDoctypeDeclHandler(handlerArg); - handleDefault = XML_FALSE; - } - break; - case XML_ROLE_INSTANCE_START: -#ifdef XML_DTD - /* if there is no DOCTYPE declaration then now is the - last chance to read the foreign DTD - */ - if (useForeignDTD) { - XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs; - dtd->hasParamEntityRefs = XML_TRUE; - if (paramEntityParsing && externalEntityRefHandler) { - ENTITY *entity = (ENTITY *)lookup(&dtd->paramEntities, - externalSubsetName, - sizeof(ENTITY)); - if (!entity) - return XML_ERROR_NO_MEMORY; - entity->base = curBase; - dtd->paramEntityRead = XML_FALSE; - if (!externalEntityRefHandler(externalEntityRefHandlerArg, - 0, - entity->base, - entity->systemId, - entity->publicId)) - return XML_ERROR_EXTERNAL_ENTITY_HANDLING; - if (dtd->paramEntityRead) { - if (!dtd->standalone && - notStandaloneHandler && - !notStandaloneHandler(handlerArg)) - return XML_ERROR_NOT_STANDALONE; - } - /* if we didn't read the foreign DTD then this means that there - is no external subset and we must reset dtd->hasParamEntityRefs - */ - else - dtd->hasParamEntityRefs = hadParamEntityRefs; - /* end of DTD - no need to update dtd->keepProcessing */ - } - } -#endif /* XML_DTD */ - processor = contentProcessor; - return contentProcessor(parser, s, end, nextPtr); - case XML_ROLE_ATTLIST_ELEMENT_NAME: - declElementType = getElementType(parser, enc, s, next); - if (!declElementType) - return XML_ERROR_NO_MEMORY; - goto checkAttListDeclHandler; - case XML_ROLE_ATTRIBUTE_NAME: - declAttributeId = getAttributeId(parser, enc, s, next); - if (!declAttributeId) - return XML_ERROR_NO_MEMORY; - declAttributeIsCdata = XML_FALSE; - declAttributeType = NULL; - declAttributeIsId = XML_FALSE; - goto checkAttListDeclHandler; - case XML_ROLE_ATTRIBUTE_TYPE_CDATA: - declAttributeIsCdata = XML_TRUE; - declAttributeType = atypeCDATA; - goto checkAttListDeclHandler; - case XML_ROLE_ATTRIBUTE_TYPE_ID: - declAttributeIsId = XML_TRUE; - declAttributeType = atypeID; - goto checkAttListDeclHandler; - case XML_ROLE_ATTRIBUTE_TYPE_IDREF: - declAttributeType = atypeIDREF; - goto checkAttListDeclHandler; - case XML_ROLE_ATTRIBUTE_TYPE_IDREFS: - declAttributeType = atypeIDREFS; - goto checkAttListDeclHandler; - case XML_ROLE_ATTRIBUTE_TYPE_ENTITY: - declAttributeType = atypeENTITY; - goto checkAttListDeclHandler; - case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES: - declAttributeType = atypeENTITIES; - goto checkAttListDeclHandler; - case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN: - declAttributeType = atypeNMTOKEN; - goto checkAttListDeclHandler; - case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS: - declAttributeType = atypeNMTOKENS; - checkAttListDeclHandler: - if (dtd->keepProcessing && attlistDeclHandler) - handleDefault = XML_FALSE; - break; - case XML_ROLE_ATTRIBUTE_ENUM_VALUE: - case XML_ROLE_ATTRIBUTE_NOTATION_VALUE: - if (dtd->keepProcessing && attlistDeclHandler) { - const XML_Char *prefix; - if (declAttributeType) { - prefix = enumValueSep; - } - else { - prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE - ? notationPrefix - : enumValueStart); - } - if (!poolAppendString(&tempPool, prefix)) - return XML_ERROR_NO_MEMORY; - if (!poolAppend(&tempPool, enc, s, next)) - return XML_ERROR_NO_MEMORY; - declAttributeType = tempPool.start; - handleDefault = XML_FALSE; - } - break; - case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE: - case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE: - if (dtd->keepProcessing) { - if (!defineAttribute(declElementType, declAttributeId, - declAttributeIsCdata, declAttributeIsId, - 0, parser)) - return XML_ERROR_NO_MEMORY; - if (attlistDeclHandler && declAttributeType) { - if (*declAttributeType == XML_T('(') - || (*declAttributeType == XML_T('N') - && declAttributeType[1] == XML_T('O'))) { - /* Enumerated or Notation type */ - if (!poolAppendChar(&tempPool, XML_T(')')) - || !poolAppendChar(&tempPool, XML_T('\0'))) - return XML_ERROR_NO_MEMORY; - declAttributeType = tempPool.start; - poolFinish(&tempPool); - } - *eventEndPP = s; - attlistDeclHandler(handlerArg, declElementType->name, - declAttributeId->name, declAttributeType, - 0, role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE); - poolClear(&tempPool); - handleDefault = XML_FALSE; - } - } - break; - case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE: - case XML_ROLE_FIXED_ATTRIBUTE_VALUE: - if (dtd->keepProcessing) { - const XML_Char *attVal; - enum XML_Error result = - storeAttributeValue(parser, enc, declAttributeIsCdata, - s + enc->minBytesPerChar, - next - enc->minBytesPerChar, - &dtd->pool); - if (result) - return result; - attVal = poolStart(&dtd->pool); - poolFinish(&dtd->pool); - /* ID attributes aren't allowed to have a default */ - if (!defineAttribute(declElementType, declAttributeId, - declAttributeIsCdata, XML_FALSE, attVal, parser)) - return XML_ERROR_NO_MEMORY; - if (attlistDeclHandler && declAttributeType) { - if (*declAttributeType == XML_T('(') - || (*declAttributeType == XML_T('N') - && declAttributeType[1] == XML_T('O'))) { - /* Enumerated or Notation type */ - if (!poolAppendChar(&tempPool, XML_T(')')) - || !poolAppendChar(&tempPool, XML_T('\0'))) - return XML_ERROR_NO_MEMORY; - declAttributeType = tempPool.start; - poolFinish(&tempPool); - } - *eventEndPP = s; - attlistDeclHandler(handlerArg, declElementType->name, - declAttributeId->name, declAttributeType, - attVal, - role == XML_ROLE_FIXED_ATTRIBUTE_VALUE); - poolClear(&tempPool); - handleDefault = XML_FALSE; - } - } - break; - case XML_ROLE_ENTITY_VALUE: - if (dtd->keepProcessing) { - enum XML_Error result = storeEntityValue(parser, enc, - s + enc->minBytesPerChar, - next - enc->minBytesPerChar); - if (declEntity) { - declEntity->textPtr = poolStart(&dtd->entityValuePool); - declEntity->textLen = (int)(poolLength(&dtd->entityValuePool)); - poolFinish(&dtd->entityValuePool); - if (entityDeclHandler) { - *eventEndPP = s; - entityDeclHandler(handlerArg, - declEntity->name, - declEntity->is_param, - declEntity->textPtr, - declEntity->textLen, - curBase, 0, 0, 0); - handleDefault = XML_FALSE; - } - } - else - poolDiscard(&dtd->entityValuePool); - if (result != XML_ERROR_NONE) - return result; - } - break; - case XML_ROLE_DOCTYPE_SYSTEM_ID: -#ifdef XML_DTD - useForeignDTD = XML_FALSE; -#endif /* XML_DTD */ - dtd->hasParamEntityRefs = XML_TRUE; - if (startDoctypeDeclHandler) { - doctypeSysid = poolStoreString(&tempPool, enc, - s + enc->minBytesPerChar, - next - enc->minBytesPerChar); - if (doctypeSysid == NULL) - return XML_ERROR_NO_MEMORY; - poolFinish(&tempPool); - handleDefault = XML_FALSE; - } -#ifdef XML_DTD - else - /* use externalSubsetName to make doctypeSysid non-NULL - for the case where no startDoctypeDeclHandler is set */ - doctypeSysid = externalSubsetName; -#endif /* XML_DTD */ - if (!dtd->standalone -#ifdef XML_DTD - && !paramEntityParsing -#endif /* XML_DTD */ - && notStandaloneHandler - && !notStandaloneHandler(handlerArg)) - return XML_ERROR_NOT_STANDALONE; -#ifndef XML_DTD - break; -#else /* XML_DTD */ - if (!declEntity) { - declEntity = (ENTITY *)lookup(&dtd->paramEntities, - externalSubsetName, - sizeof(ENTITY)); - if (!declEntity) - return XML_ERROR_NO_MEMORY; - declEntity->publicId = NULL; - } - /* fall through */ -#endif /* XML_DTD */ - case XML_ROLE_ENTITY_SYSTEM_ID: - if (dtd->keepProcessing && declEntity) { - declEntity->systemId = poolStoreString(&dtd->pool, enc, - s + enc->minBytesPerChar, - next - enc->minBytesPerChar); - if (!declEntity->systemId) - return XML_ERROR_NO_MEMORY; - declEntity->base = curBase; - poolFinish(&dtd->pool); - if (entityDeclHandler) - handleDefault = XML_FALSE; - } - break; - case XML_ROLE_ENTITY_COMPLETE: - if (dtd->keepProcessing && declEntity && entityDeclHandler) { - *eventEndPP = s; - entityDeclHandler(handlerArg, - declEntity->name, - declEntity->is_param, - 0,0, - declEntity->base, - declEntity->systemId, - declEntity->publicId, - 0); - handleDefault = XML_FALSE; - } - break; - case XML_ROLE_ENTITY_NOTATION_NAME: - if (dtd->keepProcessing && declEntity) { - declEntity->notation = poolStoreString(&dtd->pool, enc, s, next); - if (!declEntity->notation) - return XML_ERROR_NO_MEMORY; - poolFinish(&dtd->pool); - if (unparsedEntityDeclHandler) { - *eventEndPP = s; - unparsedEntityDeclHandler(handlerArg, - declEntity->name, - declEntity->base, - declEntity->systemId, - declEntity->publicId, - declEntity->notation); - handleDefault = XML_FALSE; - } - else if (entityDeclHandler) { - *eventEndPP = s; - entityDeclHandler(handlerArg, - declEntity->name, - 0,0,0, - declEntity->base, - declEntity->systemId, - declEntity->publicId, - declEntity->notation); - handleDefault = XML_FALSE; - } - } - break; - case XML_ROLE_GENERAL_ENTITY_NAME: - { - if (XmlPredefinedEntityName(enc, s, next)) { - declEntity = NULL; - break; - } - if (dtd->keepProcessing) { - const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next); - if (!name) - return XML_ERROR_NO_MEMORY; - declEntity = (ENTITY *)lookup(&dtd->generalEntities, name, - sizeof(ENTITY)); - if (!declEntity) - return XML_ERROR_NO_MEMORY; - if (declEntity->name != name) { - poolDiscard(&dtd->pool); - declEntity = NULL; - } - else { - poolFinish(&dtd->pool); - declEntity->publicId = NULL; - declEntity->is_param = XML_FALSE; - /* if we have a parent parser or are reading an internal parameter - entity, then the entity declaration is not considered "internal" - */ - declEntity->is_internal = !(parentParser || openInternalEntities); - if (entityDeclHandler) - handleDefault = XML_FALSE; - } - } - else { - poolDiscard(&dtd->pool); - declEntity = NULL; - } - } - break; - case XML_ROLE_PARAM_ENTITY_NAME: -#ifdef XML_DTD - if (dtd->keepProcessing) { - const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next); - if (!name) - return XML_ERROR_NO_MEMORY; - declEntity = (ENTITY *)lookup(&dtd->paramEntities, - name, sizeof(ENTITY)); - if (!declEntity) - return XML_ERROR_NO_MEMORY; - if (declEntity->name != name) { - poolDiscard(&dtd->pool); - declEntity = NULL; - } - else { - poolFinish(&dtd->pool); - declEntity->publicId = NULL; - declEntity->is_param = XML_TRUE; - /* if we have a parent parser or are reading an internal parameter - entity, then the entity declaration is not considered "internal" - */ - declEntity->is_internal = !(parentParser || openInternalEntities); - if (entityDeclHandler) - handleDefault = XML_FALSE; - } - } - else { - poolDiscard(&dtd->pool); - declEntity = NULL; - } -#else /* not XML_DTD */ - declEntity = NULL; -#endif /* XML_DTD */ - break; - case XML_ROLE_NOTATION_NAME: - declNotationPublicId = NULL; - declNotationName = NULL; - if (notationDeclHandler) { - declNotationName = poolStoreString(&tempPool, enc, s, next); - if (!declNotationName) - return XML_ERROR_NO_MEMORY; - poolFinish(&tempPool); - handleDefault = XML_FALSE; - } - break; - case XML_ROLE_NOTATION_PUBLIC_ID: - if (!XmlIsPublicId(enc, s, next, eventPP)) - return XML_ERROR_PUBLICID; - if (declNotationName) { /* means notationDeclHandler != NULL */ - XML_Char *tem = poolStoreString(&tempPool, - enc, - s + enc->minBytesPerChar, - next - enc->minBytesPerChar); - if (!tem) - return XML_ERROR_NO_MEMORY; - normalizePublicId(tem); - declNotationPublicId = tem; - poolFinish(&tempPool); - handleDefault = XML_FALSE; - } - break; - case XML_ROLE_NOTATION_SYSTEM_ID: - if (declNotationName && notationDeclHandler) { - const XML_Char *systemId - = poolStoreString(&tempPool, enc, - s + enc->minBytesPerChar, - next - enc->minBytesPerChar); - if (!systemId) - return XML_ERROR_NO_MEMORY; - *eventEndPP = s; - notationDeclHandler(handlerArg, - declNotationName, - curBase, - systemId, - declNotationPublicId); - handleDefault = XML_FALSE; - } - poolClear(&tempPool); - break; - case XML_ROLE_NOTATION_NO_SYSTEM_ID: - if (declNotationPublicId && notationDeclHandler) { - *eventEndPP = s; - notationDeclHandler(handlerArg, - declNotationName, - curBase, - 0, - declNotationPublicId); - handleDefault = XML_FALSE; - } - poolClear(&tempPool); - break; - case XML_ROLE_ERROR: - switch (tok) { - case XML_TOK_PARAM_ENTITY_REF: - /* PE references in internal subset are - not allowed within declarations. */ - return XML_ERROR_PARAM_ENTITY_REF; - case XML_TOK_XML_DECL: - return XML_ERROR_MISPLACED_XML_PI; - default: - return XML_ERROR_SYNTAX; - } -#ifdef XML_DTD - case XML_ROLE_IGNORE_SECT: - { - enum XML_Error result; - if (defaultHandler) - reportDefault(parser, enc, s, next); - handleDefault = XML_FALSE; - result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore); - if (result != XML_ERROR_NONE) - return result; - else if (!next) { - processor = ignoreSectionProcessor; - return result; - } - } - break; -#endif /* XML_DTD */ - case XML_ROLE_GROUP_OPEN: - if (prologState.level >= groupSize) { - if (groupSize) { - char *temp = (char *)REALLOC(groupConnector, groupSize *= 2); - if (temp == NULL) - return XML_ERROR_NO_MEMORY; - groupConnector = temp; - if (dtd->scaffIndex) { - int *temp = (int *)REALLOC(dtd->scaffIndex, - groupSize * sizeof(int)); - if (temp == NULL) - return XML_ERROR_NO_MEMORY; - dtd->scaffIndex = temp; - } - } - else { - groupConnector = (char *)MALLOC(groupSize = 32); - if (!groupConnector) - return XML_ERROR_NO_MEMORY; - } - } - groupConnector[prologState.level] = 0; - if (dtd->in_eldecl) { - int myindex = nextScaffoldPart(parser); - if (myindex < 0) - return XML_ERROR_NO_MEMORY; - dtd->scaffIndex[dtd->scaffLevel] = myindex; - dtd->scaffLevel++; - dtd->scaffold[myindex].type = XML_CTYPE_SEQ; - if (elementDeclHandler) - handleDefault = XML_FALSE; - } - break; - case XML_ROLE_GROUP_SEQUENCE: - if (groupConnector[prologState.level] == '|') - return XML_ERROR_SYNTAX; - groupConnector[prologState.level] = ','; - if (dtd->in_eldecl && elementDeclHandler) - handleDefault = XML_FALSE; - break; - case XML_ROLE_GROUP_CHOICE: - if (groupConnector[prologState.level] == ',') - return XML_ERROR_SYNTAX; - if (dtd->in_eldecl - && !groupConnector[prologState.level] - && (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type - != XML_CTYPE_MIXED) - ) { - dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type - = XML_CTYPE_CHOICE; - if (elementDeclHandler) - handleDefault = XML_FALSE; - } - groupConnector[prologState.level] = '|'; - break; - case XML_ROLE_PARAM_ENTITY_REF: -#ifdef XML_DTD - case XML_ROLE_INNER_PARAM_ENTITY_REF: - dtd->hasParamEntityRefs = XML_TRUE; - if (!paramEntityParsing) - dtd->keepProcessing = dtd->standalone; - else { - const XML_Char *name; - ENTITY *entity; - name = poolStoreString(&dtd->pool, enc, - s + enc->minBytesPerChar, - next - enc->minBytesPerChar); - if (!name) - return XML_ERROR_NO_MEMORY; - entity = (ENTITY *)lookup(&dtd->paramEntities, name, 0); - poolDiscard(&dtd->pool); - /* first, determine if a check for an existing declaration is needed; - if yes, check that the entity exists, and that it is internal, - otherwise call the skipped entity handler - */ - if (prologState.documentEntity && - (dtd->standalone - ? !openInternalEntities - : !dtd->hasParamEntityRefs)) { - if (!entity) - return XML_ERROR_UNDEFINED_ENTITY; - else if (!entity->is_internal) - return XML_ERROR_ENTITY_DECLARED_IN_PE; - } - else if (!entity) { - dtd->keepProcessing = dtd->standalone; - /* cannot report skipped entities in declarations */ - if ((role == XML_ROLE_PARAM_ENTITY_REF) && skippedEntityHandler) { - skippedEntityHandler(handlerArg, name, 1); - handleDefault = XML_FALSE; - } - break; - } - if (entity->open) - return XML_ERROR_RECURSIVE_ENTITY_REF; - if (entity->textPtr) { - enum XML_Error result; - XML_Bool betweenDecl = - (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE); - result = processInternalEntity(parser, entity, betweenDecl); - if (result != XML_ERROR_NONE) - return result; - handleDefault = XML_FALSE; - break; - } - if (externalEntityRefHandler) { - dtd->paramEntityRead = XML_FALSE; - entity->open = XML_TRUE; - if (!externalEntityRefHandler(externalEntityRefHandlerArg, - 0, - entity->base, - entity->systemId, - entity->publicId)) { - entity->open = XML_FALSE; - return XML_ERROR_EXTERNAL_ENTITY_HANDLING; - } - entity->open = XML_FALSE; - handleDefault = XML_FALSE; - if (!dtd->paramEntityRead) { - dtd->keepProcessing = dtd->standalone; - break; - } - } - else { - dtd->keepProcessing = dtd->standalone; - break; - } - } -#endif /* XML_DTD */ - if (!dtd->standalone && - notStandaloneHandler && - !notStandaloneHandler(handlerArg)) - return XML_ERROR_NOT_STANDALONE; - break; - - /* Element declaration stuff */ - - case XML_ROLE_ELEMENT_NAME: - if (elementDeclHandler) { - declElementType = getElementType(parser, enc, s, next); - if (!declElementType) - return XML_ERROR_NO_MEMORY; - dtd->scaffLevel = 0; - dtd->scaffCount = 0; - dtd->in_eldecl = XML_TRUE; - handleDefault = XML_FALSE; - } - break; - - case XML_ROLE_CONTENT_ANY: - case XML_ROLE_CONTENT_EMPTY: - if (dtd->in_eldecl) { - if (elementDeclHandler) { - XML_Content * content = (XML_Content *) MALLOC(sizeof(XML_Content)); - if (!content) - return XML_ERROR_NO_MEMORY; - content->quant = XML_CQUANT_NONE; - content->name = NULL; - content->numchildren = 0; - content->children = NULL; - content->type = ((role == XML_ROLE_CONTENT_ANY) ? - XML_CTYPE_ANY : - XML_CTYPE_EMPTY); - *eventEndPP = s; - elementDeclHandler(handlerArg, declElementType->name, content); - handleDefault = XML_FALSE; - } - dtd->in_eldecl = XML_FALSE; - } - break; - - case XML_ROLE_CONTENT_PCDATA: - if (dtd->in_eldecl) { - dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type - = XML_CTYPE_MIXED; - if (elementDeclHandler) - handleDefault = XML_FALSE; - } - break; - - case XML_ROLE_CONTENT_ELEMENT: - quant = XML_CQUANT_NONE; - goto elementContent; - case XML_ROLE_CONTENT_ELEMENT_OPT: - quant = XML_CQUANT_OPT; - goto elementContent; - case XML_ROLE_CONTENT_ELEMENT_REP: - quant = XML_CQUANT_REP; - goto elementContent; - case XML_ROLE_CONTENT_ELEMENT_PLUS: - quant = XML_CQUANT_PLUS; - elementContent: - if (dtd->in_eldecl) { - ELEMENT_TYPE *el; - const XML_Char *name; - int nameLen; - const char *nxt = (quant == XML_CQUANT_NONE - ? next - : next - enc->minBytesPerChar); - int myindex = nextScaffoldPart(parser); - if (myindex < 0) - return XML_ERROR_NO_MEMORY; - dtd->scaffold[myindex].type = XML_CTYPE_NAME; - dtd->scaffold[myindex].quant = quant; - el = getElementType(parser, enc, s, nxt); - if (!el) - return XML_ERROR_NO_MEMORY; - name = el->name; - dtd->scaffold[myindex].name = name; - nameLen = 0; - for (; name[nameLen++]; ); - dtd->contentStringLen += nameLen; - if (elementDeclHandler) - handleDefault = XML_FALSE; - } - break; - - case XML_ROLE_GROUP_CLOSE: - quant = XML_CQUANT_NONE; - goto closeGroup; - case XML_ROLE_GROUP_CLOSE_OPT: - quant = XML_CQUANT_OPT; - goto closeGroup; - case XML_ROLE_GROUP_CLOSE_REP: - quant = XML_CQUANT_REP; - goto closeGroup; - case XML_ROLE_GROUP_CLOSE_PLUS: - quant = XML_CQUANT_PLUS; - closeGroup: - if (dtd->in_eldecl) { - if (elementDeclHandler) - handleDefault = XML_FALSE; - dtd->scaffLevel--; - dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant; - if (dtd->scaffLevel == 0) { - if (!handleDefault) { - XML_Content *model = build_model(parser); - if (!model) - return XML_ERROR_NO_MEMORY; - *eventEndPP = s; - elementDeclHandler(handlerArg, declElementType->name, model); - } - dtd->in_eldecl = XML_FALSE; - dtd->contentStringLen = 0; - } - } - break; - /* End element declaration stuff */ - - case XML_ROLE_PI: - if (!reportProcessingInstruction(parser, enc, s, next)) - return XML_ERROR_NO_MEMORY; - handleDefault = XML_FALSE; - break; - case XML_ROLE_COMMENT: - if (!reportComment(parser, enc, s, next)) - return XML_ERROR_NO_MEMORY; - handleDefault = XML_FALSE; - break; - case XML_ROLE_NONE: - switch (tok) { - case XML_TOK_BOM: - handleDefault = XML_FALSE; - break; - } - break; - case XML_ROLE_DOCTYPE_NONE: - if (startDoctypeDeclHandler) - handleDefault = XML_FALSE; - break; - case XML_ROLE_ENTITY_NONE: - if (dtd->keepProcessing && entityDeclHandler) - handleDefault = XML_FALSE; - break; - case XML_ROLE_NOTATION_NONE: - if (notationDeclHandler) - handleDefault = XML_FALSE; - break; - case XML_ROLE_ATTLIST_NONE: - if (dtd->keepProcessing && attlistDeclHandler) - handleDefault = XML_FALSE; - break; - case XML_ROLE_ELEMENT_NONE: - if (elementDeclHandler) - handleDefault = XML_FALSE; - break; - } /* end of big switch */ - - if (handleDefault && defaultHandler) - reportDefault(parser, enc, s, next); - - switch (ps_parsing) { - case XML_SUSPENDED: - *nextPtr = next; - return XML_ERROR_NONE; - case XML_FINISHED: - return XML_ERROR_ABORTED; - default: - s = next; - tok = XmlPrologTok(enc, s, end, &next); - } - } - /* not reached */ -} - -static enum XML_Error PTRCALL -epilogProcessor(XML_Parser parser, - const char *s, - const char *end, - const char **nextPtr) -{ - processor = epilogProcessor; - eventPtr = s; - for (;;) { - const char *next = NULL; - int tok = XmlPrologTok(encoding, s, end, &next); - eventEndPtr = next; - switch (tok) { - /* report partial linebreak - it might be the last token */ - case -XML_TOK_PROLOG_S: - if (defaultHandler) { - reportDefault(parser, encoding, s, next); - if (ps_parsing == XML_FINISHED) - return XML_ERROR_ABORTED; - } - *nextPtr = next; - return XML_ERROR_NONE; - case XML_TOK_NONE: - *nextPtr = s; - return XML_ERROR_NONE; - case XML_TOK_PROLOG_S: - if (defaultHandler) - reportDefault(parser, encoding, s, next); - break; - case XML_TOK_PI: - if (!reportProcessingInstruction(parser, encoding, s, next)) - return XML_ERROR_NO_MEMORY; - break; - case XML_TOK_COMMENT: - if (!reportComment(parser, encoding, s, next)) - return XML_ERROR_NO_MEMORY; - break; - case XML_TOK_INVALID: - eventPtr = next; - return XML_ERROR_INVALID_TOKEN; - case XML_TOK_PARTIAL: - if (!ps_finalBuffer) { - *nextPtr = s; - return XML_ERROR_NONE; - } - return XML_ERROR_UNCLOSED_TOKEN; - case XML_TOK_PARTIAL_CHAR: - if (!ps_finalBuffer) { - *nextPtr = s; - return XML_ERROR_NONE; - } - return XML_ERROR_PARTIAL_CHAR; - default: - return XML_ERROR_JUNK_AFTER_DOC_ELEMENT; - } - eventPtr = s = next; - switch (ps_parsing) { - case XML_SUSPENDED: - *nextPtr = next; - return XML_ERROR_NONE; - case XML_FINISHED: - return XML_ERROR_ABORTED; - default: ; - } - } -} - -static enum XML_Error -processInternalEntity(XML_Parser parser, ENTITY *entity, - XML_Bool betweenDecl) -{ - const char *textStart, *textEnd; - const char *next; - enum XML_Error result; - OPEN_INTERNAL_ENTITY *openEntity; - - if (freeInternalEntities) { - openEntity = freeInternalEntities; - freeInternalEntities = openEntity->next; - } - else { - openEntity = (OPEN_INTERNAL_ENTITY *)MALLOC(sizeof(OPEN_INTERNAL_ENTITY)); - if (!openEntity) - return XML_ERROR_NO_MEMORY; - } - entity->open = XML_TRUE; - entity->processed = 0; - openEntity->next = openInternalEntities; - openInternalEntities = openEntity; - openEntity->entity = entity; - openEntity->startTagLevel = tagLevel; - openEntity->betweenDecl = betweenDecl; - openEntity->internalEventPtr = NULL; - openEntity->internalEventEndPtr = NULL; - textStart = (char *)entity->textPtr; - textEnd = (char *)(entity->textPtr + entity->textLen); - -#ifdef XML_DTD - if (entity->is_param) { - int tok = XmlPrologTok(internalEncoding, textStart, textEnd, &next); - result = doProlog(parser, internalEncoding, textStart, textEnd, tok, - next, &next, XML_FALSE); - } - else -#endif /* XML_DTD */ - result = doContent(parser, tagLevel, internalEncoding, textStart, - textEnd, &next, XML_FALSE); - - if (result == XML_ERROR_NONE) { - if (textEnd != next && ps_parsing == XML_SUSPENDED) { - entity->processed = (int)(next - textStart); - processor = internalEntityProcessor; - } - else { - entity->open = XML_FALSE; - openInternalEntities = openEntity->next; - /* put openEntity back in list of free instances */ - openEntity->next = freeInternalEntities; - freeInternalEntities = openEntity; - } - } - return result; -} - -static enum XML_Error PTRCALL -internalEntityProcessor(XML_Parser parser, - const char *s, - const char *end, - const char **nextPtr) -{ - ENTITY *entity; - const char *textStart, *textEnd; - const char *next; - enum XML_Error result; - OPEN_INTERNAL_ENTITY *openEntity = openInternalEntities; - if (!openEntity) - return XML_ERROR_UNEXPECTED_STATE; - - entity = openEntity->entity; - textStart = ((char *)entity->textPtr) + entity->processed; - textEnd = (char *)(entity->textPtr + entity->textLen); - -#ifdef XML_DTD - if (entity->is_param) { - int tok = XmlPrologTok(internalEncoding, textStart, textEnd, &next); - result = doProlog(parser, internalEncoding, textStart, textEnd, tok, - next, &next, XML_FALSE); - } - else -#endif /* XML_DTD */ - result = doContent(parser, openEntity->startTagLevel, internalEncoding, - textStart, textEnd, &next, XML_FALSE); - - if (result != XML_ERROR_NONE) - return result; - else if (textEnd != next && ps_parsing == XML_SUSPENDED) { - entity->processed = (int)(next - (char *)entity->textPtr); - return result; - } - else { - entity->open = XML_FALSE; - openInternalEntities = openEntity->next; - /* put openEntity back in list of free instances */ - openEntity->next = freeInternalEntities; - freeInternalEntities = openEntity; - } - -#ifdef XML_DTD - if (entity->is_param) { - int tok; - processor = prologProcessor; - tok = XmlPrologTok(encoding, s, end, &next); - return doProlog(parser, encoding, s, end, tok, next, nextPtr, - (XML_Bool)!ps_finalBuffer); - } - else -#endif /* XML_DTD */ - { - processor = contentProcessor; - /* see externalEntityContentProcessor vs contentProcessor */ - return doContent(parser, parentParser ? 1 : 0, encoding, s, end, - nextPtr, (XML_Bool)!ps_finalBuffer); - } -} - -static enum XML_Error PTRCALL -errorProcessor(XML_Parser parser, - const char *s, - const char *end, - const char **nextPtr) -{ - return errorCode; -} - -static enum XML_Error -storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, - const char *ptr, const char *end, - STRING_POOL *pool) -{ - enum XML_Error result = appendAttributeValue(parser, enc, isCdata, ptr, - end, pool); - if (result) - return result; - if (!isCdata && poolLength(pool) && poolLastChar(pool) == 0x20) - poolChop(pool); - if (!poolAppendChar(pool, XML_T('\0'))) - return XML_ERROR_NO_MEMORY; - return XML_ERROR_NONE; -} - -static enum XML_Error -appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, - const char *ptr, const char *end, - STRING_POOL *pool) -{ - DTD * const dtd = _dtd; /* save one level of indirection */ - for (;;) { - const char *next; - int tok = XmlAttributeValueTok(enc, ptr, end, &next); - switch (tok) { - case XML_TOK_NONE: - return XML_ERROR_NONE; - case XML_TOK_INVALID: - if (enc == encoding) - eventPtr = next; - return XML_ERROR_INVALID_TOKEN; - case XML_TOK_PARTIAL: - if (enc == encoding) - eventPtr = ptr; - return XML_ERROR_INVALID_TOKEN; - case XML_TOK_CHAR_REF: - { - XML_Char buf[XML_ENCODE_MAX]; - int i; - int n = XmlCharRefNumber(enc, ptr); - if (n < 0) { - if (enc == encoding) - eventPtr = ptr; - return XML_ERROR_BAD_CHAR_REF; - } - if (!isCdata - && n == 0x20 /* space */ - && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20)) - break; - n = XmlEncode(n, (ICHAR *)buf); - if (!n) { - if (enc == encoding) - eventPtr = ptr; - return XML_ERROR_BAD_CHAR_REF; - } - for (i = 0; i < n; i++) { - if (!poolAppendChar(pool, buf[i])) - return XML_ERROR_NO_MEMORY; - } - } - break; - case XML_TOK_DATA_CHARS: - if (!poolAppend(pool, enc, ptr, next)) - return XML_ERROR_NO_MEMORY; - break; - case XML_TOK_TRAILING_CR: - next = ptr + enc->minBytesPerChar; - /* fall through */ - case XML_TOK_ATTRIBUTE_VALUE_S: - case XML_TOK_DATA_NEWLINE: - if (!isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20)) - break; - if (!poolAppendChar(pool, 0x20)) - return XML_ERROR_NO_MEMORY; - break; - case XML_TOK_ENTITY_REF: - { - const XML_Char *name; - ENTITY *entity; - char checkEntityDecl; - XML_Char ch = (XML_Char) XmlPredefinedEntityName(enc, - ptr + enc->minBytesPerChar, - next - enc->minBytesPerChar); - if (ch) { - if (!poolAppendChar(pool, ch)) - return XML_ERROR_NO_MEMORY; - break; - } - name = poolStoreString(&temp2Pool, enc, - ptr + enc->minBytesPerChar, - next - enc->minBytesPerChar); - if (!name) - return XML_ERROR_NO_MEMORY; - entity = (ENTITY *)lookup(&dtd->generalEntities, name, 0); - poolDiscard(&temp2Pool); - /* First, determine if a check for an existing declaration is needed; - if yes, check that the entity exists, and that it is internal. - */ - if (pool == &dtd->pool) /* are we called from prolog? */ - checkEntityDecl = -#ifdef XML_DTD - prologState.documentEntity && -#endif /* XML_DTD */ - (dtd->standalone - ? !openInternalEntities - : !dtd->hasParamEntityRefs); - else /* if (pool == &tempPool): we are called from content */ - checkEntityDecl = !dtd->hasParamEntityRefs || dtd->standalone; - if (checkEntityDecl) { - if (!entity) - return XML_ERROR_UNDEFINED_ENTITY; - else if (!entity->is_internal) - return XML_ERROR_ENTITY_DECLARED_IN_PE; - } - else if (!entity) { - /* Cannot report skipped entity here - see comments on - skippedEntityHandler. - if (skippedEntityHandler) - skippedEntityHandler(handlerArg, name, 0); - */ - /* Cannot call the default handler because this would be - out of sync with the call to the startElementHandler. - if ((pool == &tempPool) && defaultHandler) - reportDefault(parser, enc, ptr, next); - */ - break; - } - if (entity->open) { - if (enc == encoding) - eventPtr = ptr; - return XML_ERROR_RECURSIVE_ENTITY_REF; - } - if (entity->notation) { - if (enc == encoding) - eventPtr = ptr; - return XML_ERROR_BINARY_ENTITY_REF; - } - if (!entity->textPtr) { - if (enc == encoding) - eventPtr = ptr; - return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF; - } - else { - enum XML_Error result; - const XML_Char *textEnd = entity->textPtr + entity->textLen; - entity->open = XML_TRUE; - result = appendAttributeValue(parser, internalEncoding, isCdata, - (char *)entity->textPtr, - (char *)textEnd, pool); - entity->open = XML_FALSE; - if (result) - return result; - } - } - break; - default: - if (enc == encoding) - eventPtr = ptr; - return XML_ERROR_UNEXPECTED_STATE; - } - ptr = next; - } - /* not reached */ -} - -static enum XML_Error -storeEntityValue(XML_Parser parser, - const ENCODING *enc, - const char *entityTextPtr, - const char *entityTextEnd) -{ - DTD * const dtd = _dtd; /* save one level of indirection */ - STRING_POOL *pool = &(dtd->entityValuePool); - enum XML_Error result = XML_ERROR_NONE; -#ifdef XML_DTD - int oldInEntityValue = prologState.inEntityValue; - prologState.inEntityValue = 1; -#endif /* XML_DTD */ - /* never return Null for the value argument in EntityDeclHandler, - since this would indicate an external entity; therefore we - have to make sure that entityValuePool.start is not null */ - if (!pool->blocks) { - if (!poolGrow(pool)) - return XML_ERROR_NO_MEMORY; - } - - for (;;) { - const char *next; - int tok = XmlEntityValueTok(enc, entityTextPtr, entityTextEnd, &next); - switch (tok) { - case XML_TOK_PARAM_ENTITY_REF: -#ifdef XML_DTD - if (isParamEntity || enc != encoding) { - const XML_Char *name; - ENTITY *entity; - name = poolStoreString(&tempPool, enc, - entityTextPtr + enc->minBytesPerChar, - next - enc->minBytesPerChar); - if (!name) { - result = XML_ERROR_NO_MEMORY; - goto endEntityValue; - } - entity = (ENTITY *)lookup(&dtd->paramEntities, name, 0); - poolDiscard(&tempPool); - if (!entity) { - /* not a well-formedness error - see XML 1.0: WFC Entity Declared */ - /* cannot report skipped entity here - see comments on - skippedEntityHandler - if (skippedEntityHandler) - skippedEntityHandler(handlerArg, name, 0); - */ - dtd->keepProcessing = dtd->standalone; - goto endEntityValue; - } - if (entity->open) { - if (enc == encoding) - eventPtr = entityTextPtr; - result = XML_ERROR_RECURSIVE_ENTITY_REF; - goto endEntityValue; - } - if (entity->systemId) { - if (externalEntityRefHandler) { - dtd->paramEntityRead = XML_FALSE; - entity->open = XML_TRUE; - if (!externalEntityRefHandler(externalEntityRefHandlerArg, - 0, - entity->base, - entity->systemId, - entity->publicId)) { - entity->open = XML_FALSE; - result = XML_ERROR_EXTERNAL_ENTITY_HANDLING; - goto endEntityValue; - } - entity->open = XML_FALSE; - if (!dtd->paramEntityRead) - dtd->keepProcessing = dtd->standalone; - } - else - dtd->keepProcessing = dtd->standalone; - } - else { - entity->open = XML_TRUE; - result = storeEntityValue(parser, - internalEncoding, - (char *)entity->textPtr, - (char *)(entity->textPtr - + entity->textLen)); - entity->open = XML_FALSE; - if (result) - goto endEntityValue; - } - break; - } -#endif /* XML_DTD */ - /* In the internal subset, PE references are not legal - within markup declarations, e.g entity values in this case. */ - eventPtr = entityTextPtr; - result = XML_ERROR_PARAM_ENTITY_REF; - goto endEntityValue; - case XML_TOK_NONE: - result = XML_ERROR_NONE; - goto endEntityValue; - case XML_TOK_ENTITY_REF: - case XML_TOK_DATA_CHARS: - if (!poolAppend(pool, enc, entityTextPtr, next)) { - result = XML_ERROR_NO_MEMORY; - goto endEntityValue; - } - break; - case XML_TOK_TRAILING_CR: - next = entityTextPtr + enc->minBytesPerChar; - /* fall through */ - case XML_TOK_DATA_NEWLINE: - if (pool->end == pool->ptr && !poolGrow(pool)) { - result = XML_ERROR_NO_MEMORY; - goto endEntityValue; - } - *(pool->ptr)++ = 0xA; - break; - case XML_TOK_CHAR_REF: - { - XML_Char buf[XML_ENCODE_MAX]; - int i; - int n = XmlCharRefNumber(enc, entityTextPtr); - if (n < 0) { - if (enc == encoding) - eventPtr = entityTextPtr; - result = XML_ERROR_BAD_CHAR_REF; - goto endEntityValue; - } - n = XmlEncode(n, (ICHAR *)buf); - if (!n) { - if (enc == encoding) - eventPtr = entityTextPtr; - result = XML_ERROR_BAD_CHAR_REF; - goto endEntityValue; - } - for (i = 0; i < n; i++) { - if (pool->end == pool->ptr && !poolGrow(pool)) { - result = XML_ERROR_NO_MEMORY; - goto endEntityValue; - } - *(pool->ptr)++ = buf[i]; - } - } - break; - case XML_TOK_PARTIAL: - if (enc == encoding) - eventPtr = entityTextPtr; - result = XML_ERROR_INVALID_TOKEN; - goto endEntityValue; - case XML_TOK_INVALID: - if (enc == encoding) - eventPtr = next; - result = XML_ERROR_INVALID_TOKEN; - goto endEntityValue; - default: - if (enc == encoding) - eventPtr = entityTextPtr; - result = XML_ERROR_UNEXPECTED_STATE; - goto endEntityValue; - } - entityTextPtr = next; - } -endEntityValue: -#ifdef XML_DTD - prologState.inEntityValue = oldInEntityValue; -#endif /* XML_DTD */ - return result; -} - -static void FASTCALL -normalizeLines(XML_Char *s) -{ - XML_Char *p; - for (;; s++) { - if (*s == XML_T('\0')) - return; - if (*s == 0xD) - break; - } - p = s; - do { - if (*s == 0xD) { - *p++ = 0xA; - if (*++s == 0xA) - s++; - } - else - *p++ = *s++; - } while (*s); - *p = XML_T('\0'); -} - -static int -reportProcessingInstruction(XML_Parser parser, const ENCODING *enc, - const char *start, const char *end) -{ - const XML_Char *target; - XML_Char *data; - const char *tem; - if (!processingInstructionHandler) { - if (defaultHandler) - reportDefault(parser, enc, start, end); - return 1; - } - start += enc->minBytesPerChar * 2; - tem = start + XmlNameLength(enc, start); - target = poolStoreString(&tempPool, enc, start, tem); - if (!target) - return 0; - poolFinish(&tempPool); - data = poolStoreString(&tempPool, enc, - XmlSkipS(enc, tem), - end - enc->minBytesPerChar*2); - if (!data) - return 0; - normalizeLines(data); - processingInstructionHandler(handlerArg, target, data); - poolClear(&tempPool); - return 1; -} - -static int -reportComment(XML_Parser parser, const ENCODING *enc, - const char *start, const char *end) -{ - XML_Char *data; - if (!commentHandler) { - if (defaultHandler) - reportDefault(parser, enc, start, end); - return 1; - } - data = poolStoreString(&tempPool, - enc, - start + enc->minBytesPerChar * 4, - end - enc->minBytesPerChar * 3); - if (!data) - return 0; - normalizeLines(data); - commentHandler(handlerArg, data); - poolClear(&tempPool); - return 1; -} - -static void -reportDefault(XML_Parser parser, const ENCODING *enc, - const char *s, const char *end) -{ - if (MUST_CONVERT(enc, s)) { - const char **eventPP; - const char **eventEndPP; - if (enc == encoding) { - eventPP = &eventPtr; - eventEndPP = &eventEndPtr; - } - else { - eventPP = &(openInternalEntities->internalEventPtr); - eventEndPP = &(openInternalEntities->internalEventEndPtr); - } - do { - ICHAR *dataPtr = (ICHAR *)dataBuf; - XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)dataBufEnd); - *eventEndPP = s; - defaultHandler(handlerArg, dataBuf, (int)(dataPtr - (ICHAR *)dataBuf)); - *eventPP = s; - } while (s != end); - } - else - defaultHandler(handlerArg, (XML_Char *)s, (int)((XML_Char *)end - (XML_Char *)s)); -} - - -static int -defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata, - XML_Bool isId, const XML_Char *value, XML_Parser parser) -{ - DEFAULT_ATTRIBUTE *att; - if (value || isId) { - /* The handling of default attributes gets messed up if we have - a default which duplicates a non-default. */ - int i; - for (i = 0; i < type->nDefaultAtts; i++) - if (attId == type->defaultAtts[i].id) - return 1; - if (isId && !type->idAtt && !attId->xmlns) - type->idAtt = attId; - } - if (type->nDefaultAtts == type->allocDefaultAtts) { - if (type->allocDefaultAtts == 0) { - type->allocDefaultAtts = 8; - type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(type->allocDefaultAtts - * sizeof(DEFAULT_ATTRIBUTE)); - if (!type->defaultAtts) - return 0; - } - else { - DEFAULT_ATTRIBUTE *temp; - int count = type->allocDefaultAtts * 2; - temp = (DEFAULT_ATTRIBUTE *) - REALLOC(type->defaultAtts, (count * sizeof(DEFAULT_ATTRIBUTE))); - if (temp == NULL) - return 0; - type->allocDefaultAtts = count; - type->defaultAtts = temp; - } - } - att = type->defaultAtts + type->nDefaultAtts; - att->id = attId; - att->value = value; - att->isCdata = isCdata; - if (!isCdata) - attId->maybeTokenized = XML_TRUE; - type->nDefaultAtts += 1; - return 1; -} - -static int -setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType) -{ - DTD * const dtd = _dtd; /* save one level of indirection */ - const XML_Char *name; - for (name = elementType->name; *name; name++) { - if (*name == XML_T(':')) { - PREFIX *prefix; - const XML_Char *s; - for (s = elementType->name; s != name; s++) { - if (!poolAppendChar(&dtd->pool, *s)) - return 0; - } - if (!poolAppendChar(&dtd->pool, XML_T('\0'))) - return 0; - prefix = (PREFIX *)lookup(&dtd->prefixes, poolStart(&dtd->pool), - sizeof(PREFIX)); - if (!prefix) - return 0; - if (prefix->name == poolStart(&dtd->pool)) - poolFinish(&dtd->pool); - else - poolDiscard(&dtd->pool); - elementType->prefix = prefix; - - } - } - return 1; -} - -static ATTRIBUTE_ID * -getAttributeId(XML_Parser parser, const ENCODING *enc, - const char *start, const char *end) -{ - DTD * const dtd = _dtd; /* save one level of indirection */ - ATTRIBUTE_ID *id; - const XML_Char *name; - if (!poolAppendChar(&dtd->pool, XML_T('\0'))) - return NULL; - name = poolStoreString(&dtd->pool, enc, start, end); - if (!name) - return NULL; - /* skip quotation mark - its storage will be re-used (like in name[-1]) */ - ++name; - id = (ATTRIBUTE_ID *)lookup(&dtd->attributeIds, name, sizeof(ATTRIBUTE_ID)); - if (!id) - return NULL; - if (id->name != name) - poolDiscard(&dtd->pool); - else { - poolFinish(&dtd->pool); - if (!ns) - ; - else if (name[0] == XML_T('x') - && name[1] == XML_T('m') - && name[2] == XML_T('l') - && name[3] == XML_T('n') - && name[4] == XML_T('s') - && (name[5] == XML_T('\0') || name[5] == XML_T(':'))) { - if (name[5] == XML_T('\0')) - id->prefix = &dtd->defaultPrefix; - else - id->prefix = (PREFIX *)lookup(&dtd->prefixes, name + 6, sizeof(PREFIX)); - id->xmlns = XML_TRUE; - } - else { - int i; - for (i = 0; name[i]; i++) { - /* attributes without prefix are *not* in the default namespace */ - if (name[i] == XML_T(':')) { - int j; - for (j = 0; j < i; j++) { - if (!poolAppendChar(&dtd->pool, name[j])) - return NULL; - } - if (!poolAppendChar(&dtd->pool, XML_T('\0'))) - return NULL; - id->prefix = (PREFIX *)lookup(&dtd->prefixes, poolStart(&dtd->pool), - sizeof(PREFIX)); - if (!id->prefix) - return NULL; - if (id->prefix->name == poolStart(&dtd->pool)) - poolFinish(&dtd->pool); - else - poolDiscard(&dtd->pool); - break; - } - } - } - } - return id; -} - -#define CONTEXT_SEP XML_T('\f') - -static const XML_Char * -getContext(XML_Parser parser) -{ - DTD * const dtd = _dtd; /* save one level of indirection */ - HASH_TABLE_ITER iter; - XML_Bool needSep = XML_FALSE; - - if (dtd->defaultPrefix.binding) { - int i; - int len; - if (!poolAppendChar(&tempPool, XML_T('='))) - return NULL; - len = dtd->defaultPrefix.binding->uriLen; - if (namespaceSeparator) - len--; - for (i = 0; i < len; i++) - if (!poolAppendChar(&tempPool, dtd->defaultPrefix.binding->uri[i])) - return NULL; - needSep = XML_TRUE; - } - - hashTableIterInit(&iter, &(dtd->prefixes)); - for (;;) { - int i; - int len; - const XML_Char *s; - PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter); - if (!prefix) - break; - if (!prefix->binding) - continue; - if (needSep && !poolAppendChar(&tempPool, CONTEXT_SEP)) - return NULL; - for (s = prefix->name; *s; s++) - if (!poolAppendChar(&tempPool, *s)) - return NULL; - if (!poolAppendChar(&tempPool, XML_T('='))) - return NULL; - len = prefix->binding->uriLen; - if (namespaceSeparator) - len--; - for (i = 0; i < len; i++) - if (!poolAppendChar(&tempPool, prefix->binding->uri[i])) - return NULL; - needSep = XML_TRUE; - } - - - hashTableIterInit(&iter, &(dtd->generalEntities)); - for (;;) { - const XML_Char *s; - ENTITY *e = (ENTITY *)hashTableIterNext(&iter); - if (!e) - break; - if (!e->open) - continue; - if (needSep && !poolAppendChar(&tempPool, CONTEXT_SEP)) - return NULL; - for (s = e->name; *s; s++) - if (!poolAppendChar(&tempPool, *s)) - return 0; - needSep = XML_TRUE; - } - - if (!poolAppendChar(&tempPool, XML_T('\0'))) - return NULL; - return tempPool.start; -} - -static XML_Bool -setContext(XML_Parser parser, const XML_Char *context) -{ - DTD * const dtd = _dtd; /* save one level of indirection */ - const XML_Char *s = context; - - while (*context != XML_T('\0')) { - if (*s == CONTEXT_SEP || *s == XML_T('\0')) { - ENTITY *e; - if (!poolAppendChar(&tempPool, XML_T('\0'))) - return XML_FALSE; - e = (ENTITY *)lookup(&dtd->generalEntities, poolStart(&tempPool), 0); - if (e) - e->open = XML_TRUE; - if (*s != XML_T('\0')) - s++; - context = s; - poolDiscard(&tempPool); - } - else if (*s == XML_T('=')) { - PREFIX *prefix; - if (poolLength(&tempPool) == 0) - prefix = &dtd->defaultPrefix; - else { - if (!poolAppendChar(&tempPool, XML_T('\0'))) - return XML_FALSE; - prefix = (PREFIX *)lookup(&dtd->prefixes, poolStart(&tempPool), - sizeof(PREFIX)); - if (!prefix) - return XML_FALSE; - if (prefix->name == poolStart(&tempPool)) { - prefix->name = poolCopyString(&dtd->pool, prefix->name); - if (!prefix->name) - return XML_FALSE; - } - poolDiscard(&tempPool); - } - for (context = s + 1; - *context != CONTEXT_SEP && *context != XML_T('\0'); - context++) - if (!poolAppendChar(&tempPool, *context)) - return XML_FALSE; - if (!poolAppendChar(&tempPool, XML_T('\0'))) - return XML_FALSE; - if (addBinding(parser, prefix, NULL, poolStart(&tempPool), - &inheritedBindings) != XML_ERROR_NONE) - return XML_FALSE; - poolDiscard(&tempPool); - if (*context != XML_T('\0')) - ++context; - s = context; - } - else { - if (!poolAppendChar(&tempPool, *s)) - return XML_FALSE; - s++; - } - } - return XML_TRUE; -} - -static void FASTCALL -normalizePublicId(XML_Char *publicId) -{ - XML_Char *p = publicId; - XML_Char *s; - for (s = publicId; *s; s++) { - switch (*s) { - case 0x20: - case 0xD: - case 0xA: - if (p != publicId && p[-1] != 0x20) - *p++ = 0x20; - break; - default: - *p++ = *s; - } - } - if (p != publicId && p[-1] == 0x20) - --p; - *p = XML_T('\0'); -} - -static DTD * -dtdCreate(const XML_Memory_Handling_Suite *ms) -{ - DTD *p = (DTD *)ms->malloc_fcn(sizeof(DTD)); - if (p == NULL) - return p; - poolInit(&(p->pool), ms); - poolInit(&(p->entityValuePool), ms); - hashTableInit(&(p->generalEntities), ms); - hashTableInit(&(p->elementTypes), ms); - hashTableInit(&(p->attributeIds), ms); - hashTableInit(&(p->prefixes), ms); -#ifdef XML_DTD - p->paramEntityRead = XML_FALSE; - hashTableInit(&(p->paramEntities), ms); -#endif /* XML_DTD */ - p->defaultPrefix.name = NULL; - p->defaultPrefix.binding = NULL; - - p->in_eldecl = XML_FALSE; - p->scaffIndex = NULL; - p->scaffold = NULL; - p->scaffLevel = 0; - p->scaffSize = 0; - p->scaffCount = 0; - p->contentStringLen = 0; - - p->keepProcessing = XML_TRUE; - p->hasParamEntityRefs = XML_FALSE; - p->standalone = XML_FALSE; - return p; -} - -static void -dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms) -{ - HASH_TABLE_ITER iter; - hashTableIterInit(&iter, &(p->elementTypes)); - for (;;) { - ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter); - if (!e) - break; - if (e->allocDefaultAtts != 0) - ms->free_fcn(e->defaultAtts); - } - hashTableClear(&(p->generalEntities)); -#ifdef XML_DTD - p->paramEntityRead = XML_FALSE; - hashTableClear(&(p->paramEntities)); -#endif /* XML_DTD */ - hashTableClear(&(p->elementTypes)); - hashTableClear(&(p->attributeIds)); - hashTableClear(&(p->prefixes)); - poolClear(&(p->pool)); - poolClear(&(p->entityValuePool)); - p->defaultPrefix.name = NULL; - p->defaultPrefix.binding = NULL; - - p->in_eldecl = XML_FALSE; - - ms->free_fcn(p->scaffIndex); - p->scaffIndex = NULL; - ms->free_fcn(p->scaffold); - p->scaffold = NULL; - - p->scaffLevel = 0; - p->scaffSize = 0; - p->scaffCount = 0; - p->contentStringLen = 0; - - p->keepProcessing = XML_TRUE; - p->hasParamEntityRefs = XML_FALSE; - p->standalone = XML_FALSE; -} - -static void -dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms) -{ - HASH_TABLE_ITER iter; - hashTableIterInit(&iter, &(p->elementTypes)); - for (;;) { - ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter); - if (!e) - break; - if (e->allocDefaultAtts != 0) - ms->free_fcn(e->defaultAtts); - } - hashTableDestroy(&(p->generalEntities)); -#ifdef XML_DTD - hashTableDestroy(&(p->paramEntities)); -#endif /* XML_DTD */ - hashTableDestroy(&(p->elementTypes)); - hashTableDestroy(&(p->attributeIds)); - hashTableDestroy(&(p->prefixes)); - poolDestroy(&(p->pool)); - poolDestroy(&(p->entityValuePool)); - if (isDocEntity) { - ms->free_fcn(p->scaffIndex); - ms->free_fcn(p->scaffold); - } - ms->free_fcn(p); -} - -/* Do a deep copy of the DTD. Return 0 for out of memory, non-zero otherwise. - The new DTD has already been initialized. -*/ -static int -dtdCopy(DTD *newDtd, const DTD *oldDtd, const XML_Memory_Handling_Suite *ms) -{ - HASH_TABLE_ITER iter; - - /* Copy the prefix table. */ - - hashTableIterInit(&iter, &(oldDtd->prefixes)); - for (;;) { - const XML_Char *name; - const PREFIX *oldP = (PREFIX *)hashTableIterNext(&iter); - if (!oldP) - break; - name = poolCopyString(&(newDtd->pool), oldP->name); - if (!name) - return 0; - if (!lookup(&(newDtd->prefixes), name, sizeof(PREFIX))) - return 0; - } - - hashTableIterInit(&iter, &(oldDtd->attributeIds)); - - /* Copy the attribute id table. */ - - for (;;) { - ATTRIBUTE_ID *newA; - const XML_Char *name; - const ATTRIBUTE_ID *oldA = (ATTRIBUTE_ID *)hashTableIterNext(&iter); - - if (!oldA) - break; - /* Remember to allocate the scratch byte before the name. */ - if (!poolAppendChar(&(newDtd->pool), XML_T('\0'))) - return 0; - name = poolCopyString(&(newDtd->pool), oldA->name); - if (!name) - return 0; - ++name; - newA = (ATTRIBUTE_ID *)lookup(&(newDtd->attributeIds), name, - sizeof(ATTRIBUTE_ID)); - if (!newA) - return 0; - newA->maybeTokenized = oldA->maybeTokenized; - if (oldA->prefix) { - newA->xmlns = oldA->xmlns; - if (oldA->prefix == &oldDtd->defaultPrefix) - newA->prefix = &newDtd->defaultPrefix; - else - newA->prefix = (PREFIX *)lookup(&(newDtd->prefixes), - oldA->prefix->name, 0); - } - } - - /* Copy the element type table. */ - - hashTableIterInit(&iter, &(oldDtd->elementTypes)); - - for (;;) { - int i; - ELEMENT_TYPE *newE; - const XML_Char *name; - const ELEMENT_TYPE *oldE = (ELEMENT_TYPE *)hashTableIterNext(&iter); - if (!oldE) - break; - name = poolCopyString(&(newDtd->pool), oldE->name); - if (!name) - return 0; - newE = (ELEMENT_TYPE *)lookup(&(newDtd->elementTypes), name, - sizeof(ELEMENT_TYPE)); - if (!newE) - return 0; - if (oldE->nDefaultAtts) { - newE->defaultAtts = (DEFAULT_ATTRIBUTE *) - ms->malloc_fcn(oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE)); - if (!newE->defaultAtts) { - ms->free_fcn(newE); - return 0; - } - } - if (oldE->idAtt) - newE->idAtt = (ATTRIBUTE_ID *) - lookup(&(newDtd->attributeIds), oldE->idAtt->name, 0); - newE->allocDefaultAtts = newE->nDefaultAtts = oldE->nDefaultAtts; - if (oldE->prefix) - newE->prefix = (PREFIX *)lookup(&(newDtd->prefixes), - oldE->prefix->name, 0); - for (i = 0; i < newE->nDefaultAtts; i++) { - newE->defaultAtts[i].id = (ATTRIBUTE_ID *) - lookup(&(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0); - newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata; - if (oldE->defaultAtts[i].value) { - newE->defaultAtts[i].value - = poolCopyString(&(newDtd->pool), oldE->defaultAtts[i].value); - if (!newE->defaultAtts[i].value) - return 0; - } - else - newE->defaultAtts[i].value = NULL; - } - } - - /* Copy the entity tables. */ - if (!copyEntityTable(&(newDtd->generalEntities), - &(newDtd->pool), - &(oldDtd->generalEntities))) - return 0; - -#ifdef XML_DTD - if (!copyEntityTable(&(newDtd->paramEntities), - &(newDtd->pool), - &(oldDtd->paramEntities))) - return 0; - newDtd->paramEntityRead = oldDtd->paramEntityRead; -#endif /* XML_DTD */ - - newDtd->keepProcessing = oldDtd->keepProcessing; - newDtd->hasParamEntityRefs = oldDtd->hasParamEntityRefs; - newDtd->standalone = oldDtd->standalone; - - /* Don't want deep copying for scaffolding */ - newDtd->in_eldecl = oldDtd->in_eldecl; - newDtd->scaffold = oldDtd->scaffold; - newDtd->contentStringLen = oldDtd->contentStringLen; - newDtd->scaffSize = oldDtd->scaffSize; - newDtd->scaffLevel = oldDtd->scaffLevel; - newDtd->scaffIndex = oldDtd->scaffIndex; - - return 1; -} /* End dtdCopy */ - -static int -copyEntityTable(HASH_TABLE *newTable, - STRING_POOL *newPool, - const HASH_TABLE *oldTable) -{ - HASH_TABLE_ITER iter; - const XML_Char *cachedOldBase = NULL; - const XML_Char *cachedNewBase = NULL; - - hashTableIterInit(&iter, oldTable); - - for (;;) { - ENTITY *newE; - const XML_Char *name; - const ENTITY *oldE = (ENTITY *)hashTableIterNext(&iter); - if (!oldE) - break; - name = poolCopyString(newPool, oldE->name); - if (!name) - return 0; - newE = (ENTITY *)lookup(newTable, name, sizeof(ENTITY)); - if (!newE) - return 0; - if (oldE->systemId) { - const XML_Char *tem = poolCopyString(newPool, oldE->systemId); - if (!tem) - return 0; - newE->systemId = tem; - if (oldE->base) { - if (oldE->base == cachedOldBase) - newE->base = cachedNewBase; - else { - cachedOldBase = oldE->base; - tem = poolCopyString(newPool, cachedOldBase); - if (!tem) - return 0; - cachedNewBase = newE->base = tem; - } - } - if (oldE->publicId) { - tem = poolCopyString(newPool, oldE->publicId); - if (!tem) - return 0; - newE->publicId = tem; - } - } - else { - const XML_Char *tem = poolCopyStringN(newPool, oldE->textPtr, - oldE->textLen); - if (!tem) - return 0; - newE->textPtr = tem; - newE->textLen = oldE->textLen; - } - if (oldE->notation) { - const XML_Char *tem = poolCopyString(newPool, oldE->notation); - if (!tem) - return 0; - newE->notation = tem; - } - newE->is_param = oldE->is_param; - newE->is_internal = oldE->is_internal; - } - return 1; -} - -#define INIT_POWER 6 - -static XML_Bool FASTCALL -keyeq(KEY s1, KEY s2) -{ - for (; *s1 == *s2; s1++, s2++) - if (*s1 == 0) - return XML_TRUE; - return XML_FALSE; -} - -static unsigned long FASTCALL -hash(KEY s) -{ - unsigned long h = 0; - while (*s) - h = CHAR_HASH(h, *s++); - return h; -} - -static NAMED * -lookup(HASH_TABLE *table, KEY name, size_t createSize) -{ - size_t i; - if (table->size == 0) { - size_t tsize; - if (!createSize) - return NULL; - table->power = INIT_POWER; - /* table->size is a power of 2 */ - table->size = (size_t)1 << INIT_POWER; - tsize = table->size * sizeof(NAMED *); - table->v = (NAMED **)table->mem->malloc_fcn(tsize); - if (!table->v) { - table->size = 0; - return NULL; - } - memset(table->v, 0, tsize); - i = hash(name) & ((unsigned long)table->size - 1); - } - else { - unsigned long h = hash(name); - unsigned long mask = (unsigned long)table->size - 1; - unsigned char step = 0; - i = h & mask; - while (table->v[i]) { - if (keyeq(name, table->v[i]->name)) - return table->v[i]; - if (!step) - step = PROBE_STEP(h, mask, table->power); - i < step ? (i += table->size - step) : (i -= step); - } - if (!createSize) - return NULL; - - /* check for overflow (table is half full) */ - if (table->used >> (table->power - 1)) { - unsigned char newPower = table->power + 1; - size_t newSize = (size_t)1 << newPower; - unsigned long newMask = (unsigned long)newSize - 1; - size_t tsize = newSize * sizeof(NAMED *); - NAMED **newV = (NAMED **)table->mem->malloc_fcn(tsize); - if (!newV) - return NULL; - memset(newV, 0, tsize); - for (i = 0; i < table->size; i++) - if (table->v[i]) { - unsigned long newHash = hash(table->v[i]->name); - size_t j = newHash & newMask; - step = 0; - while (newV[j]) { - if (!step) - step = PROBE_STEP(newHash, newMask, newPower); - j < step ? (j += newSize - step) : (j -= step); - } - newV[j] = table->v[i]; - } - table->mem->free_fcn(table->v); - table->v = newV; - table->power = newPower; - table->size = newSize; - i = h & newMask; - step = 0; - while (table->v[i]) { - if (!step) - step = PROBE_STEP(h, newMask, newPower); - i < step ? (i += newSize - step) : (i -= step); - } - } - } - table->v[i] = (NAMED *)table->mem->malloc_fcn(createSize); - if (!table->v[i]) - return NULL; - memset(table->v[i], 0, createSize); - table->v[i]->name = name; - (table->used)++; - return table->v[i]; -} - -static void FASTCALL -hashTableClear(HASH_TABLE *table) -{ - size_t i; - for (i = 0; i < table->size; i++) { - table->mem->free_fcn(table->v[i]); - table->v[i] = NULL; - } - table->used = 0; -} - -static void FASTCALL -hashTableDestroy(HASH_TABLE *table) -{ - size_t i; - for (i = 0; i < table->size; i++) - table->mem->free_fcn(table->v[i]); - table->mem->free_fcn(table->v); -} - -static void FASTCALL -hashTableInit(HASH_TABLE *p, const XML_Memory_Handling_Suite *ms) -{ - p->power = 0; - p->size = 0; - p->used = 0; - p->v = NULL; - p->mem = ms; -} - -static void FASTCALL -hashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table) -{ - iter->p = table->v; - iter->end = iter->p + table->size; -} - -static NAMED * FASTCALL -hashTableIterNext(HASH_TABLE_ITER *iter) -{ - while (iter->p != iter->end) { - NAMED *tem = *(iter->p)++; - if (tem) - return tem; - } - return NULL; -} - -static void FASTCALL -poolInit(STRING_POOL *pool, const XML_Memory_Handling_Suite *ms) -{ - pool->blocks = NULL; - pool->freeBlocks = NULL; - pool->start = NULL; - pool->ptr = NULL; - pool->end = NULL; - pool->mem = ms; -} - -static void FASTCALL -poolClear(STRING_POOL *pool) -{ - if (!pool->freeBlocks) - pool->freeBlocks = pool->blocks; - else { - BLOCK *p = pool->blocks; - while (p) { - BLOCK *tem = p->next; - p->next = pool->freeBlocks; - pool->freeBlocks = p; - p = tem; - } - } - pool->blocks = NULL; - pool->start = NULL; - pool->ptr = NULL; - pool->end = NULL; -} - -static void FASTCALL -poolDestroy(STRING_POOL *pool) -{ - BLOCK *p = pool->blocks; - while (p) { - BLOCK *tem = p->next; - pool->mem->free_fcn(p); - p = tem; - } - p = pool->freeBlocks; - while (p) { - BLOCK *tem = p->next; - pool->mem->free_fcn(p); - p = tem; - } -} - -static XML_Char * -poolAppend(STRING_POOL *pool, const ENCODING *enc, - const char *ptr, const char *end) -{ - if (!pool->ptr && !poolGrow(pool)) - return NULL; - for (;;) { - XmlConvert(enc, &ptr, end, (ICHAR **)&(pool->ptr), (ICHAR *)pool->end); - if (ptr == end) - break; - if (!poolGrow(pool)) - return NULL; - } - return pool->start; -} - -static const XML_Char * FASTCALL -poolCopyString(STRING_POOL *pool, const XML_Char *s) -{ - do { - if (!poolAppendChar(pool, *s)) - return NULL; - } while (*s++); - s = pool->start; - poolFinish(pool); - return s; -} - -static const XML_Char * -poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n) -{ - if (!pool->ptr && !poolGrow(pool)) - return NULL; - for (; n > 0; --n, s++) { - if (!poolAppendChar(pool, *s)) - return NULL; - } - s = pool->start; - poolFinish(pool); - return s; -} - -static const XML_Char * FASTCALL -poolAppendString(STRING_POOL *pool, const XML_Char *s) -{ - while (*s) { - if (!poolAppendChar(pool, *s)) - return NULL; - s++; - } - return pool->start; -} - -static XML_Char * -poolStoreString(STRING_POOL *pool, const ENCODING *enc, - const char *ptr, const char *end) -{ - if (!poolAppend(pool, enc, ptr, end)) - return NULL; - if (pool->ptr == pool->end && !poolGrow(pool)) - return NULL; - *(pool->ptr)++ = 0; - return pool->start; -} - -static XML_Bool FASTCALL -poolGrow(STRING_POOL *pool) -{ - if (pool->freeBlocks) { - if (pool->start == 0) { - pool->blocks = pool->freeBlocks; - pool->freeBlocks = pool->freeBlocks->next; - pool->blocks->next = NULL; - pool->start = pool->blocks->s; - pool->end = pool->start + pool->blocks->size; - pool->ptr = pool->start; - return XML_TRUE; - } - if (pool->end - pool->start < pool->freeBlocks->size) { - BLOCK *tem = pool->freeBlocks->next; - pool->freeBlocks->next = pool->blocks; - pool->blocks = pool->freeBlocks; - pool->freeBlocks = tem; - memcpy(pool->blocks->s, pool->start, - (pool->end - pool->start) * sizeof(XML_Char)); - pool->ptr = pool->blocks->s + (pool->ptr - pool->start); - pool->start = pool->blocks->s; - pool->end = pool->start + pool->blocks->size; - return XML_TRUE; - } - } - if (pool->blocks && pool->start == pool->blocks->s) { - int blockSize = (int)(pool->end - pool->start)*2; - pool->blocks = (BLOCK *) - pool->mem->realloc_fcn(pool->blocks, - (offsetof(BLOCK, s) - + blockSize * sizeof(XML_Char))); - if (pool->blocks == NULL) - return XML_FALSE; - pool->blocks->size = blockSize; - pool->ptr = pool->blocks->s + (pool->ptr - pool->start); - pool->start = pool->blocks->s; - pool->end = pool->start + blockSize; - } - else { - BLOCK *tem; - int blockSize = (int)(pool->end - pool->start); - if (blockSize < INIT_BLOCK_SIZE) - blockSize = INIT_BLOCK_SIZE; - else - blockSize *= 2; - tem = (BLOCK *)pool->mem->malloc_fcn(offsetof(BLOCK, s) - + blockSize * sizeof(XML_Char)); - if (!tem) - return XML_FALSE; - tem->size = blockSize; - tem->next = pool->blocks; - pool->blocks = tem; - if (pool->ptr != pool->start) - memcpy(tem->s, pool->start, - (pool->ptr - pool->start) * sizeof(XML_Char)); - pool->ptr = tem->s + (pool->ptr - pool->start); - pool->start = tem->s; - pool->end = tem->s + blockSize; - } - return XML_TRUE; -} - -static int FASTCALL -nextScaffoldPart(XML_Parser parser) -{ - DTD * const dtd = _dtd; /* save one level of indirection */ - CONTENT_SCAFFOLD * me; - int next; - - if (!dtd->scaffIndex) { - dtd->scaffIndex = (int *)MALLOC(groupSize * sizeof(int)); - if (!dtd->scaffIndex) - return -1; - dtd->scaffIndex[0] = 0; - } - - if (dtd->scaffCount >= dtd->scaffSize) { - CONTENT_SCAFFOLD *temp; - if (dtd->scaffold) { - temp = (CONTENT_SCAFFOLD *) - REALLOC(dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD)); - if (temp == NULL) - return -1; - dtd->scaffSize *= 2; - } - else { - temp = (CONTENT_SCAFFOLD *)MALLOC(INIT_SCAFFOLD_ELEMENTS - * sizeof(CONTENT_SCAFFOLD)); - if (temp == NULL) - return -1; - dtd->scaffSize = INIT_SCAFFOLD_ELEMENTS; - } - dtd->scaffold = temp; - } - next = dtd->scaffCount++; - me = &dtd->scaffold[next]; - if (dtd->scaffLevel) { - CONTENT_SCAFFOLD *parent = &dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel-1]]; - if (parent->lastchild) { - dtd->scaffold[parent->lastchild].nextsib = next; - } - if (!parent->childcnt) - parent->firstchild = next; - parent->lastchild = next; - parent->childcnt++; - } - me->firstchild = me->lastchild = me->childcnt = me->nextsib = 0; - return next; -} - -static void -build_node(XML_Parser parser, - int src_node, - XML_Content *dest, - XML_Content **contpos, - XML_Char **strpos) -{ - DTD * const dtd = _dtd; /* save one level of indirection */ - dest->type = dtd->scaffold[src_node].type; - dest->quant = dtd->scaffold[src_node].quant; - if (dest->type == XML_CTYPE_NAME) { - const XML_Char *src; - dest->name = *strpos; - src = dtd->scaffold[src_node].name; - for (;;) { - *(*strpos)++ = *src; - if (!*src) - break; - src++; - } - dest->numchildren = 0; - dest->children = NULL; - } - else { - unsigned int i; - int cn; - dest->numchildren = dtd->scaffold[src_node].childcnt; - dest->children = *contpos; - *contpos += dest->numchildren; - for (i = 0, cn = dtd->scaffold[src_node].firstchild; - i < dest->numchildren; - i++, cn = dtd->scaffold[cn].nextsib) { - build_node(parser, cn, &(dest->children[i]), contpos, strpos); - } - dest->name = NULL; - } -} - -static XML_Content * -build_model (XML_Parser parser) -{ - DTD * const dtd = _dtd; /* save one level of indirection */ - XML_Content *ret; - XML_Content *cpos; - XML_Char * str; - int allocsize = (dtd->scaffCount * sizeof(XML_Content) - + (dtd->contentStringLen * sizeof(XML_Char))); - - ret = (XML_Content *)MALLOC(allocsize); - if (!ret) - return NULL; - - str = (XML_Char *) (&ret[dtd->scaffCount]); - cpos = &ret[1]; - - build_node(parser, 0, ret, &cpos, &str); - return ret; -} - -static ELEMENT_TYPE * -getElementType(XML_Parser parser, - const ENCODING *enc, - const char *ptr, - const char *end) -{ - DTD * const dtd = _dtd; /* save one level of indirection */ - const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end); - ELEMENT_TYPE *ret; - - if (!name) - return NULL; - ret = (ELEMENT_TYPE *) lookup(&dtd->elementTypes, name, sizeof(ELEMENT_TYPE)); - if (!ret) - return NULL; - if (ret->name != name) - poolDiscard(&dtd->pool); - else { - poolFinish(&dtd->pool); - if (!setElementTypePrefix(parser, ret)) - return NULL; - } - return ret; -} diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/main.c b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/main.c deleted file mode 100644 index 4b3ce11..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/main.c +++ /dev/null @@ -1,678 +0,0 @@ -/** @file - Python interpreter main program. - - Copyright (c) 2015, Daryl McDaniel. All rights reserved.
-**/ - -#include "Python.h" -#include "osdefs.h" -#include "code.h" /* For CO_FUTURE_DIVISION */ -#include "import.h" - -#ifdef __VMS -#include -#endif - -#if defined(MS_WINDOWS) || defined(__CYGWIN__) -#ifdef HAVE_FCNTL_H -#include -#endif -#endif - -#if (defined(PYOS_OS2) && !defined(PYCC_GCC)) || defined(MS_WINDOWS) -#define PYTHONHOMEHELP "\\lib" -#else -#if defined(PYOS_OS2) && defined(PYCC_GCC) -#define PYTHONHOMEHELP "/Lib" -#else -#define PYTHONHOMEHELP "/pythonX.X" -#endif -#endif - -#include "pygetopt.h" - -#define COPYRIGHT \ - "Type \"help\", \"copyright\", \"credits\" or \"license\" " \ - "for more information." - -#ifdef __cplusplus -extern "C" { -#endif - -/* For Py_GetArgcArgv(); set by main() */ -static char **orig_argv; -static int orig_argc; - -/* command line options */ -#define BASE_OPTS "#3bBc:dEhiJm:OQ:sStuUvVW:xX?" - -#ifndef RISCOS -#define PROGRAM_OPTS BASE_OPTS -#else /*RISCOS*/ -/* extra option saying that we are running under a special task window - frontend; especially my_readline will behave different */ -#define PROGRAM_OPTS BASE_OPTS "w" -/* corresponding flag */ -extern int Py_RISCOSWimpFlag; -#endif /*RISCOS*/ - -/* Short usage message (with %s for argv0) */ -static char *usage_line = -"usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...\n"; - -/* Long usage message, split into parts < 512 bytes */ -static char *usage_1 = "\ -Options and arguments (and corresponding environment variables):\n\ --# : alias stderr to stdout for platforms without STDERR output.\n\ --B : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x\n\ --c cmd : program passed in as string (terminates option list)\n\ --d : debug output from parser; also PYTHONDEBUG=x\n\ --E : ignore PYTHON* environment variables (such as PYTHONPATH)\n\ --h : print this help message and exit (also --help)\n\ --i : inspect interactively after running script; forces a prompt even\n\ -"; -static char *usage_2 = "\ - if stdin does not appear to be a terminal; also PYTHONINSPECT=x\n\ --m mod : run library module as a script (terminates option list)\n\ --O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x\n\ --OO : remove doc-strings in addition to the -O optimizations\n\ --Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew\n\ --s : don't add user site directory to sys.path; also PYTHONNOUSERSITE\n\ --S : don't imply 'import site' on initialization\n\ --t : issue warnings about inconsistent tab usage (-tt: issue errors)\n\ -"; -static char *usage_3 = "\ --u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x\n\ - see man page for details on internal buffering relating to '-u'\n\ --v : verbose (trace import statements); also PYTHONVERBOSE=x\n\ - can be supplied multiple times to increase verbosity\n\ --V : print the Python version number and exit (also --version)\n\ --W arg : warning control; arg is action:message:category:module:lineno\n\ - also PYTHONWARNINGS=arg\n\ --x : skip first line of source, allowing use of non-Unix forms of #!cmd\n\ -"; -static char *usage_4 = "\ --3 : warn about Python 3.x incompatibilities that 2to3 cannot trivially fix\n\ -file : program read from script file\n\ -- : program read from stdin (default; interactive mode if a tty)\n\ -arg ...: arguments passed to program in sys.argv[1:]\n\n\ -Other environment variables:\n\ -PYTHONSTARTUP: file executed on interactive startup (no default)\n\ -PYTHONPATH : '%c'-separated list of directories prefixed to the\n\ - default module search path. The result is sys.path.\n\ -"; -static char *usage_5 = "\ -PYTHONHOME : alternate directory (or %c).\n\ - The default module search path uses %s.\n\ -PYTHONCASEOK : ignore case in 'import' statements (UEFI default).\n\ -PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.\n\ -"; - - -static int -usage(int exitcode, char* program) -{ - FILE *f = exitcode ? stderr : stdout; - - fprintf(f, usage_line, program); - if (exitcode) - fprintf(f, "Try `python -h' for more information.\n"); - else { - fputs(usage_1, f); - fputs(usage_2, f); - fputs(usage_3, f); - fprintf(f, usage_4, DELIM); - fprintf(f, usage_5, DELIM, PYTHONHOMEHELP); - } -#if defined(__VMS) - if (exitcode == 0) { - /* suppress 'error' message */ - return 1; - } - else { - /* STS$M_INHIB_MSG + SS$_ABORT */ - return 0x1000002c; - } -#else - return exitcode; -#endif - /*NOTREACHED*/ -} - -static void RunStartupFile(PyCompilerFlags *cf) -{ - char *startup = Py_GETENV("PYTHONSTARTUP"); - if (startup != NULL && startup[0] != '\0') { - FILE *fp = fopen(startup, "r"); - if (fp != NULL) { - (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf); - PyErr_Clear(); - fclose(fp); - } else { - int save_errno; - save_errno = errno; - PySys_WriteStderr("Could not open PYTHONSTARTUP\n"); - errno = save_errno; - PyErr_SetFromErrnoWithFilename(PyExc_IOError, - startup); - PyErr_Print(); - PyErr_Clear(); - } - } -} - - -static int RunModule(char *module, int set_argv0) -{ - PyObject *runpy, *runmodule, *runargs, *result; - runpy = PyImport_ImportModule("runpy"); - if (runpy == NULL) { - fprintf(stderr, "Could not import runpy module\n"); - return -1; - } - runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main"); - if (runmodule == NULL) { - fprintf(stderr, "Could not access runpy._run_module_as_main\n"); - Py_DECREF(runpy); - return -1; - } - runargs = Py_BuildValue("(si)", module, set_argv0); - if (runargs == NULL) { - fprintf(stderr, - "Could not create arguments for runpy._run_module_as_main\n"); - Py_DECREF(runpy); - Py_DECREF(runmodule); - return -1; - } - result = PyObject_Call(runmodule, runargs, NULL); - if (result == NULL) { - PyErr_Print(); - } - Py_DECREF(runpy); - Py_DECREF(runmodule); - Py_DECREF(runargs); - if (result == NULL) { - return -1; - } - Py_DECREF(result); - return 0; -} - -static int RunMainFromImporter(char *filename) -{ - PyObject *argv0 = NULL, *importer = NULL; - - if ((argv0 = PyString_FromString(filename)) && - (importer = PyImport_GetImporter(argv0)) && - (importer->ob_type != &PyNullImporter_Type)) - { - /* argv0 is usable as an import source, so - put it in sys.path[0] and import __main__ */ - PyObject *sys_path = NULL; - if ((sys_path = PySys_GetObject("path")) && - !PyList_SetItem(sys_path, 0, argv0)) - { - Py_INCREF(argv0); - Py_DECREF(importer); - sys_path = NULL; - return RunModule("__main__", 0) != 0; - } - } - Py_XDECREF(argv0); - Py_XDECREF(importer); - if (PyErr_Occurred()) { - PyErr_Print(); - return 1; - } - return -1; -} - - -/* Main program */ - -int -Py_Main(int argc, char **argv) -{ - int c; - int sts; - char *command = NULL; - char *filename = NULL; - char *module = NULL; - FILE *fp = stdin; - char *p; - int unbuffered = 0; - int skipfirstline = 0; - int stdin_is_interactive = 0; - int help = 0; - int version = 0; - int saw_unbuffered_flag = 0; - int saw_pound_flag = 0; - PyCompilerFlags cf; - - cf.cf_flags = 0; - - orig_argc = argc; /* For Py_GetArgcArgv() */ - orig_argv = argv; - -#ifdef RISCOS - Py_RISCOSWimpFlag = 0; -#endif - - PySys_ResetWarnOptions(); - - while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) { - if (c == 'c') { - /* -c is the last option; following arguments - that look like options are left for the - command to interpret. */ - command = (char *)malloc(strlen(_PyOS_optarg) + 2); - if (command == NULL) - Py_FatalError( - "not enough memory to copy -c argument"); - strcpy(command, _PyOS_optarg); - strcat(command, "\n"); - break; - } - - if (c == 'm') { - /* -m is the last option; following arguments - that look like options are left for the - module to interpret. */ - module = (char *)malloc(strlen(_PyOS_optarg) + 2); - if (module == NULL) - Py_FatalError( - "not enough memory to copy -m argument"); - strcpy(module, _PyOS_optarg); - break; - } - - switch (c) { - case 'b': - Py_BytesWarningFlag++; - break; - - case 'd': - Py_DebugFlag++; - break; - - case '3': - Py_Py3kWarningFlag++; - if (!Py_DivisionWarningFlag) - Py_DivisionWarningFlag = 1; - break; - - case 'Q': - if (strcmp(_PyOS_optarg, "old") == 0) { - Py_DivisionWarningFlag = 0; - break; - } - if (strcmp(_PyOS_optarg, "warn") == 0) { - Py_DivisionWarningFlag = 1; - break; - } - if (strcmp(_PyOS_optarg, "warnall") == 0) { - Py_DivisionWarningFlag = 2; - break; - } - if (strcmp(_PyOS_optarg, "new") == 0) { - /* This only affects __main__ */ - cf.cf_flags |= CO_FUTURE_DIVISION; - /* And this tells the eval loop to treat - BINARY_DIVIDE as BINARY_TRUE_DIVIDE */ - _Py_QnewFlag = 1; - break; - } - fprintf(stderr, - "-Q option should be `-Qold', " - "`-Qwarn', `-Qwarnall', or `-Qnew' only\n"); - return usage(2, argv[0]); - /* NOTREACHED */ - - case 'i': - Py_InspectFlag++; - Py_InteractiveFlag++; - break; - - /* case 'J': reserved for Jython */ - - case 'O': - Py_OptimizeFlag++; - break; - - case 'B': - Py_DontWriteBytecodeFlag++; - break; - - case 's': - Py_NoUserSiteDirectory++; - break; - - case 'S': - Py_NoSiteFlag++; - break; - - case 'E': - Py_IgnoreEnvironmentFlag++; - break; - - case 't': - Py_TabcheckFlag++; - break; - - case 'u': - unbuffered++; - saw_unbuffered_flag = 1; - break; - - case 'v': - Py_VerboseFlag++; - break; - -#ifdef RISCOS - case 'w': - Py_RISCOSWimpFlag = 1; - break; -#endif - - case 'x': - skipfirstline = 1; - break; - - /* case 'X': reserved for implementation-specific arguments */ - - case 'U': - Py_UnicodeFlag++; - break; - case 'h': - case '?': - help++; - break; - case 'V': - version++; - break; - - case 'W': - PySys_AddWarnOption(_PyOS_optarg); - break; - - case '#': - if (saw_pound_flag == 0) { - if(freopen("stdout:", "w", stderr) == NULL) { - puts("ERROR: Unable to reopen stderr as an alias to stdout!"); - } - saw_pound_flag = 0xFF; - } - break; - - /* This space reserved for other options */ - - default: - return usage(2, argv[0]); - /*NOTREACHED*/ - - } - } - - if (help) - return usage(0, argv[0]); - - if (version) { - fprintf(stderr, "Python %s\n", PY_VERSION); - return 0; - } - - if (Py_Py3kWarningFlag && !Py_TabcheckFlag) - /* -3 implies -t (but not -tt) */ - Py_TabcheckFlag = 1; - - if (!Py_InspectFlag && - (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') - Py_InspectFlag = 1; - if (!saw_unbuffered_flag && - (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') - unbuffered = 1; - - if (!Py_NoUserSiteDirectory && - (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0') - Py_NoUserSiteDirectory = 1; - - if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') { - char *buf, *warning; - - buf = (char *)malloc(strlen(p) + 1); - if (buf == NULL) - Py_FatalError( - "not enough memory to copy PYTHONWARNINGS"); - strcpy(buf, p); - for (warning = strtok(buf, ","); - warning != NULL; - warning = strtok(NULL, ",")) - PySys_AddWarnOption(warning); - free(buf); - } - - if (command == NULL && module == NULL && _PyOS_optind < argc && - strcmp(argv[_PyOS_optind], "-") != 0) - { -#ifdef __VMS - filename = decc$translate_vms(argv[_PyOS_optind]); - if (filename == (char *)0 || filename == (char *)-1) - filename = argv[_PyOS_optind]; - -#else - filename = argv[_PyOS_optind]; -#endif - } - - stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0); - - if (unbuffered) { -#if defined(MS_WINDOWS) || defined(__CYGWIN__) - _setmode(fileno(stdin), O_BINARY); - _setmode(fileno(stdout), O_BINARY); -#endif -#ifdef HAVE_SETVBUF - setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ); - setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); - setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ); -#else /* !HAVE_SETVBUF */ - setbuf(stdin, (char *)NULL); - setbuf(stdout, (char *)NULL); - setbuf(stderr, (char *)NULL); -#endif /* !HAVE_SETVBUF */ - } - else if (Py_InteractiveFlag) { -#ifdef MS_WINDOWS - /* Doesn't have to have line-buffered -- use unbuffered */ - /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */ - setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); -#else /* !MS_WINDOWS */ -#ifdef HAVE_SETVBUF - setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ); - setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ); -#endif /* HAVE_SETVBUF */ -#endif /* !MS_WINDOWS */ - /* Leave stderr alone - it should be unbuffered anyway. */ - } -#ifdef __VMS - else { - setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ); - } -#endif /* __VMS */ - -#ifdef __APPLE__ - /* On MacOS X, when the Python interpreter is embedded in an - application bundle, it gets executed by a bootstrapping script - that does os.execve() with an argv[0] that's different from the - actual Python executable. This is needed to keep the Finder happy, - or rather, to work around Apple's overly strict requirements of - the process name. However, we still need a usable sys.executable, - so the actual executable path is passed in an environment variable. - See Lib/plat-mac/bundlebuiler.py for details about the bootstrap - script. */ - if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') - Py_SetProgramName(p); - else - Py_SetProgramName(argv[0]); -#else - Py_SetProgramName(argv[0]); -#endif - Py_Initialize(); - - if (Py_VerboseFlag || - (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) { - fprintf(stderr, "Python %s on %s\n", - Py_GetVersion(), Py_GetPlatform()); - if (!Py_NoSiteFlag) - fprintf(stderr, "%s\n", COPYRIGHT); - } - - if (command != NULL) { - /* Backup _PyOS_optind and force sys.argv[0] = '-c' */ - _PyOS_optind--; - argv[_PyOS_optind] = "-c"; - } - - if (module != NULL) { - /* Backup _PyOS_optind and force sys.argv[0] = '-c' - so that PySys_SetArgv correctly sets sys.path[0] to '' - rather than looking for a file called "-m". See - tracker issue #8202 for details. */ - _PyOS_optind--; - argv[_PyOS_optind] = "-c"; - } - - PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind); - - if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) && - isatty(fileno(stdin))) { - PyObject *v; - v = PyImport_ImportModule("readline"); - if (v == NULL) - PyErr_Clear(); - else - Py_DECREF(v); - } - - if (command) { - sts = PyRun_SimpleStringFlags(command, &cf) != 0; - free(command); - } else if (module) { - sts = (RunModule(module, 1) != 0); - free(module); - } - else { - - if (filename == NULL && stdin_is_interactive) { - Py_InspectFlag = 0; /* do exit on SystemExit */ - RunStartupFile(&cf); - } - /* XXX */ - - sts = -1; /* keep track of whether we've already run __main__ */ - - if (filename != NULL) { - sts = RunMainFromImporter(filename); - } - - if (sts==-1 && filename!=NULL) { - if ((fp = fopen(filename, "r")) == NULL) { - fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n", - argv[0], filename, errno, strerror(errno)); - - return 2; - } - else if (skipfirstline) { - int ch; - /* Push back first newline so line numbers - remain the same */ - while ((ch = getc(fp)) != EOF) { - if (ch == '\n') { - (void)ungetc(ch, fp); - break; - } - } - } - { - /* XXX: does this work on Win/Win64? (see posix_fstat) */ - struct stat sb; - if (fstat(fileno(fp), &sb) == 0 && - S_ISDIR(sb.st_mode)) { - fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename); - fclose(fp); - return 1; - } - } - } - - if (sts==-1) { - /* call pending calls like signal handlers (SIGINT) */ - if (Py_MakePendingCalls() == -1) { - PyErr_Print(); - sts = 1; - } else { - sts = PyRun_AnyFileExFlags( - fp, - filename == NULL ? "" : filename, - filename != NULL, &cf) != 0; - } - } - - } - - /* Check this environment variable at the end, to give programs the - * opportunity to set it from Python. - */ - if (!Py_InspectFlag && - (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') - { - Py_InspectFlag = 1; - } - - if (Py_InspectFlag && stdin_is_interactive && - (filename != NULL || command != NULL || module != NULL)) { - Py_InspectFlag = 0; - /* XXX */ - sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; - } - - Py_Finalize(); -#ifdef RISCOS - if (Py_RISCOSWimpFlag) - fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */ -#endif - -#ifdef __INSURE__ - /* Insure++ is a memory analysis tool that aids in discovering - * memory leaks and other memory problems. On Python exit, the - * interned string dictionary is flagged as being in use at exit - * (which it is). Under normal circumstances, this is fine because - * the memory will be automatically reclaimed by the system. Under - * memory debugging, it's a huge source of useless noise, so we - * trade off slower shutdown for less distraction in the memory - * reports. -baw - */ - _Py_ReleaseInternedStrings(); -#endif /* __INSURE__ */ - - return sts; -} - -/* this is gonna seem *real weird*, but if you put some other code between - Py_Main() and Py_GetArgcArgv() you will need to adjust the test in the - while statement in Misc/gdbinit:ppystack */ - -/* Make the *original* argc/argv available to other modules. - This is rare, but it is needed by the secureware extension. */ - -void -Py_GetArgcArgv(int *argc, char ***argv) -{ - *argc = orig_argc; - *argv = orig_argv; -} - -#ifdef __cplusplus -} -#endif - diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/selectmodule.c b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/selectmodule.c deleted file mode 100644 index 81e5af8..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/selectmodule.c +++ /dev/null @@ -1,1912 +0,0 @@ -/* select - Module containing unix select(2) call. - Under Unix, the file descriptors are small integers. - Under Win32, select only exists for sockets, and sockets may - have any value except INVALID_SOCKET. - Under BeOS, we suffer the same dichotomy as Win32; sockets can be anything - >= 0. -*/ - -#include "Python.h" -#include - -#ifdef __APPLE__ - /* Perform runtime testing for a broken poll on OSX to make it easier - * to use the same binary on multiple releases of the OS. - */ -#undef HAVE_BROKEN_POLL -#endif - -/* Windows #defines FD_SETSIZE to 64 if FD_SETSIZE isn't already defined. - 64 is too small (too many people have bumped into that limit). - Here we boost it. - Users who want even more than the boosted limit should #define - FD_SETSIZE higher before this; e.g., via compiler /D switch. -*/ -#if defined(MS_WINDOWS) && !defined(FD_SETSIZE) -#define FD_SETSIZE 512 -#endif - -#if defined(HAVE_POLL_H) -#include -#elif defined(HAVE_SYS_POLL_H) -#include -#endif - -#ifdef __sgi -/* This is missing from unistd.h */ -extern void bzero(void *, int); -#endif - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - -#if defined(PYOS_OS2) && !defined(PYCC_GCC) -#include -#include -#endif - -#ifdef MS_WINDOWS -# include -#else -# define SOCKET int -# ifdef __BEOS__ -# include -# elif defined(__VMS) -# include -# endif -#endif - -static PyObject *SelectError; - -/* list of Python objects and their file descriptor */ -typedef struct { - PyObject *obj; /* owned reference */ - SOCKET fd; - int sentinel; /* -1 == sentinel */ -} pylist; - -static void -reap_obj(pylist fd2obj[FD_SETSIZE + 1]) -{ - int i; - for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) { - Py_XDECREF(fd2obj[i].obj); - fd2obj[i].obj = NULL; - } - fd2obj[0].sentinel = -1; -} - - -/* returns -1 and sets the Python exception if an error occurred, otherwise - returns a number >= 0 -*/ -static int -seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1]) -{ - int i; - int max = -1; - int index = 0; - int len = -1; - PyObject* fast_seq = NULL; - PyObject* o = NULL; - - fd2obj[0].obj = (PyObject*)0; /* set list to zero size */ - FD_ZERO(set); - - fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences"); - if (!fast_seq) - return -1; - - len = PySequence_Fast_GET_SIZE(fast_seq); - - for (i = 0; i < len; i++) { - SOCKET v; - - /* any intervening fileno() calls could decr this refcnt */ - if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i))) - return -1; - - Py_INCREF(o); - v = PyObject_AsFileDescriptor( o ); - if (v == -1) goto finally; - -#if defined(_MSC_VER) && !defined(UEFI_C_SOURCE) - max = 0; /* not used for Win32 */ -#else /* !_MSC_VER */ - if (v < 0 || v >= FD_SETSIZE) { - PyErr_SetString(PyExc_ValueError, - "filedescriptor out of range in select()"); - goto finally; - } - if (v > max) - max = v; -#endif /* _MSC_VER */ - FD_SET(v, set); - - /* add object and its file descriptor to the list */ - if (index >= FD_SETSIZE) { - PyErr_SetString(PyExc_ValueError, - "too many file descriptors in select()"); - goto finally; - } - fd2obj[index].obj = o; - fd2obj[index].fd = v; - fd2obj[index].sentinel = 0; - fd2obj[++index].sentinel = -1; - } - Py_DECREF(fast_seq); - return max+1; - - finally: - Py_XDECREF(o); - Py_DECREF(fast_seq); - return -1; -} - -/* returns NULL and sets the Python exception if an error occurred */ -static PyObject * -set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1]) -{ - int i, j, count=0; - PyObject *list, *o; - SOCKET fd; - - for (j = 0; fd2obj[j].sentinel >= 0; j++) { - if (FD_ISSET(fd2obj[j].fd, set)) - count++; - } - list = PyList_New(count); - if (!list) - return NULL; - - i = 0; - for (j = 0; fd2obj[j].sentinel >= 0; j++) { - fd = fd2obj[j].fd; - if (FD_ISSET(fd, set)) { -#if !defined(_MSC_VER) || defined(UEFI_C_SOURCE) - if (fd > FD_SETSIZE) { - PyErr_SetString(PyExc_SystemError, - "filedescriptor out of range returned in select()"); - goto finally; - } -#endif - o = fd2obj[j].obj; - fd2obj[j].obj = NULL; - /* transfer ownership */ - if (PyList_SetItem(list, i, o) < 0) - goto finally; - - i++; - } - } - return list; - finally: - Py_DECREF(list); - return NULL; -} - -#undef SELECT_USES_HEAP -#if FD_SETSIZE > 1024 -#define SELECT_USES_HEAP -#endif /* FD_SETSIZE > 1024 */ - -static PyObject * -select_select(PyObject *self, PyObject *args) -{ -#ifdef SELECT_USES_HEAP - pylist *rfd2obj, *wfd2obj, *efd2obj; -#else /* !SELECT_USES_HEAP */ - /* XXX: All this should probably be implemented as follows: - * - find the highest descriptor we're interested in - * - add one - * - that's the size - * See: Stevens, APitUE, $12.5.1 - */ - pylist rfd2obj[FD_SETSIZE + 1]; - pylist wfd2obj[FD_SETSIZE + 1]; - pylist efd2obj[FD_SETSIZE + 1]; -#endif /* SELECT_USES_HEAP */ - PyObject *ifdlist, *ofdlist, *efdlist; - PyObject *ret = NULL; - PyObject *tout = Py_None; - fd_set ifdset, ofdset, efdset; - double timeout; - struct timeval tv, *tvp; - long seconds; - int imax, omax, emax, max; - int n; - - /* convert arguments */ - if (!PyArg_UnpackTuple(args, "select", 3, 4, - &ifdlist, &ofdlist, &efdlist, &tout)) - return NULL; - - if (tout == Py_None) - tvp = (struct timeval *)0; - else if (!PyNumber_Check(tout)) { - PyErr_SetString(PyExc_TypeError, - "timeout must be a float or None"); - return NULL; - } - else { - timeout = PyFloat_AsDouble(tout); - if (timeout == -1 && PyErr_Occurred()) - return NULL; - if (timeout > (double)LONG_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout period too long"); - return NULL; - } - seconds = (long)timeout; - timeout = timeout - (double)seconds; - tv.tv_sec = seconds; - tv.tv_usec = (long)(timeout * 1E6); - tvp = &tv; - } - - -#ifdef SELECT_USES_HEAP - /* Allocate memory for the lists */ - rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); - wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); - efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); - if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) { - if (rfd2obj) PyMem_DEL(rfd2obj); - if (wfd2obj) PyMem_DEL(wfd2obj); - if (efd2obj) PyMem_DEL(efd2obj); - return PyErr_NoMemory(); - } -#endif /* SELECT_USES_HEAP */ - /* Convert sequences to fd_sets, and get maximum fd number - * propagates the Python exception set in seq2set() - */ - rfd2obj[0].sentinel = -1; - wfd2obj[0].sentinel = -1; - efd2obj[0].sentinel = -1; - if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0) - goto finally; - if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0) - goto finally; - if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0) - goto finally; - max = imax; - if (omax > max) max = omax; - if (emax > max) max = emax; - - Py_BEGIN_ALLOW_THREADS - n = select(max, &ifdset, &ofdset, &efdset, tvp); - Py_END_ALLOW_THREADS - -#ifdef MS_WINDOWS - if (n == SOCKET_ERROR) { - PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError()); - } -#else - if (n < 0) { - PyErr_SetFromErrno(SelectError); - } -#endif - else { - /* any of these three calls can raise an exception. it's more - convenient to test for this after all three calls... but - is that acceptable? - */ - ifdlist = set2list(&ifdset, rfd2obj); - ofdlist = set2list(&ofdset, wfd2obj); - efdlist = set2list(&efdset, efd2obj); - if (PyErr_Occurred()) - ret = NULL; - else - ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist); - - Py_DECREF(ifdlist); - Py_DECREF(ofdlist); - Py_DECREF(efdlist); - } - - finally: - reap_obj(rfd2obj); - reap_obj(wfd2obj); - reap_obj(efd2obj); -#ifdef SELECT_USES_HEAP - PyMem_DEL(rfd2obj); - PyMem_DEL(wfd2obj); - PyMem_DEL(efd2obj); -#endif /* SELECT_USES_HEAP */ - return ret; -} - -#if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL) -/* - * poll() support - */ - -typedef struct { - PyObject_HEAD - PyObject *dict; - int ufd_uptodate; - int ufd_len; - struct pollfd *ufds; -} pollObject; - -static PyTypeObject poll_Type; - -/* Update the malloc'ed array of pollfds to match the dictionary - contained within a pollObject. Return 1 on success, 0 on an error. -*/ - -static int -update_ufd_array(pollObject *self) -{ - Py_ssize_t i, pos; - PyObject *key, *value; - struct pollfd *old_ufds = self->ufds; - - self->ufd_len = PyDict_Size(self->dict); - PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len); - if (self->ufds == NULL) { - self->ufds = old_ufds; - PyErr_NoMemory(); - return 0; - } - - i = pos = 0; - while (PyDict_Next(self->dict, &pos, &key, &value)) { - self->ufds[i].fd = PyInt_AsLong(key); - self->ufds[i].events = (short)PyInt_AsLong(value); - i++; - } - self->ufd_uptodate = 1; - return 1; -} - -PyDoc_STRVAR(poll_register_doc, -"register(fd [, eventmask] ) -> None\n\n\ -Register a file descriptor with the polling object.\n\ -fd -- either an integer, or an object with a fileno() method returning an\n\ - int.\n\ -events -- an optional bitmask describing the type of events to check for"); - -static PyObject * -poll_register(pollObject *self, PyObject *args) -{ - PyObject *o, *key, *value; - int fd, events = POLLIN | POLLPRI | POLLOUT; - int err; - - if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) { - return NULL; - } - - fd = PyObject_AsFileDescriptor(o); - if (fd == -1) return NULL; - - /* Add entry to the internal dictionary: the key is the - file descriptor, and the value is the event mask. */ - key = PyInt_FromLong(fd); - if (key == NULL) - return NULL; - value = PyInt_FromLong(events); - if (value == NULL) { - Py_DECREF(key); - return NULL; - } - err = PyDict_SetItem(self->dict, key, value); - Py_DECREF(key); - Py_DECREF(value); - if (err < 0) - return NULL; - - self->ufd_uptodate = 0; - - Py_INCREF(Py_None); - return Py_None; -} - -PyDoc_STRVAR(poll_modify_doc, -"modify(fd, eventmask) -> None\n\n\ -Modify an already registered file descriptor.\n\ -fd -- either an integer, or an object with a fileno() method returning an\n\ - int.\n\ -events -- an optional bitmask describing the type of events to check for"); - -static PyObject * -poll_modify(pollObject *self, PyObject *args) -{ - PyObject *o, *key, *value; - int fd, events; - int err; - - if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) { - return NULL; - } - - fd = PyObject_AsFileDescriptor(o); - if (fd == -1) return NULL; - - /* Modify registered fd */ - key = PyInt_FromLong(fd); - if (key == NULL) - return NULL; - if (PyDict_GetItem(self->dict, key) == NULL) { - errno = ENOENT; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - value = PyInt_FromLong(events); - if (value == NULL) { - Py_DECREF(key); - return NULL; - } - err = PyDict_SetItem(self->dict, key, value); - Py_DECREF(key); - Py_DECREF(value); - if (err < 0) - return NULL; - - self->ufd_uptodate = 0; - - Py_INCREF(Py_None); - return Py_None; -} - - -PyDoc_STRVAR(poll_unregister_doc, -"unregister(fd) -> None\n\n\ -Remove a file descriptor being tracked by the polling object."); - -static PyObject * -poll_unregister(pollObject *self, PyObject *o) -{ - PyObject *key; - int fd; - - fd = PyObject_AsFileDescriptor( o ); - if (fd == -1) - return NULL; - - /* Check whether the fd is already in the array */ - key = PyInt_FromLong(fd); - if (key == NULL) - return NULL; - - if (PyDict_DelItem(self->dict, key) == -1) { - Py_DECREF(key); - /* This will simply raise the KeyError set by PyDict_DelItem - if the file descriptor isn't registered. */ - return NULL; - } - - Py_DECREF(key); - self->ufd_uptodate = 0; - - Py_INCREF(Py_None); - return Py_None; -} - -PyDoc_STRVAR(poll_poll_doc, -"poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\ -Polls the set of registered file descriptors, returning a list containing \n\ -any descriptors that have events or errors to report."); - -static PyObject * -poll_poll(pollObject *self, PyObject *args) -{ - PyObject *result_list = NULL, *tout = NULL; - int timeout = 0, poll_result, i, j; - PyObject *value = NULL, *num = NULL; - - if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) { - return NULL; - } - - /* Check values for timeout */ - if (tout == NULL || tout == Py_None) - timeout = -1; - else if (!PyNumber_Check(tout)) { - PyErr_SetString(PyExc_TypeError, - "timeout must be an integer or None"); - return NULL; - } - else { - tout = PyNumber_Int(tout); - if (!tout) - return NULL; - timeout = PyInt_AsLong(tout); - Py_DECREF(tout); - if (timeout == -1 && PyErr_Occurred()) - return NULL; - } - - /* Ensure the ufd array is up to date */ - if (!self->ufd_uptodate) - if (update_ufd_array(self) == 0) - return NULL; - - /* call poll() */ - Py_BEGIN_ALLOW_THREADS - poll_result = poll(self->ufds, self->ufd_len, timeout); - Py_END_ALLOW_THREADS - - if (poll_result < 0) { - PyErr_SetFromErrno(SelectError); - return NULL; - } - - /* build the result list */ - - result_list = PyList_New(poll_result); - if (!result_list) - return NULL; - else { - for (i = 0, j = 0; j < poll_result; j++) { - /* skip to the next fired descriptor */ - while (!self->ufds[i].revents) { - i++; - } - /* if we hit a NULL return, set value to NULL - and break out of loop; code at end will - clean up result_list */ - value = PyTuple_New(2); - if (value == NULL) - goto error; - num = PyInt_FromLong(self->ufds[i].fd); - if (num == NULL) { - Py_DECREF(value); - goto error; - } - PyTuple_SET_ITEM(value, 0, num); - - /* The &0xffff is a workaround for AIX. 'revents' - is a 16-bit short, and IBM assigned POLLNVAL - to be 0x8000, so the conversion to int results - in a negative number. See SF bug #923315. */ - num = PyInt_FromLong(self->ufds[i].revents & 0xffff); - if (num == NULL) { - Py_DECREF(value); - goto error; - } - PyTuple_SET_ITEM(value, 1, num); - if ((PyList_SetItem(result_list, j, value)) == -1) { - Py_DECREF(value); - goto error; - } - i++; - } - } - return result_list; - - error: - Py_DECREF(result_list); - return NULL; -} - -static PyMethodDef poll_methods[] = { - {"register", (PyCFunction)poll_register, - METH_VARARGS, poll_register_doc}, - {"modify", (PyCFunction)poll_modify, - METH_VARARGS, poll_modify_doc}, - {"unregister", (PyCFunction)poll_unregister, - METH_O, poll_unregister_doc}, - {"poll", (PyCFunction)poll_poll, - METH_VARARGS, poll_poll_doc}, - {NULL, NULL} /* sentinel */ -}; - -static pollObject * -newPollObject(void) -{ - pollObject *self; - self = PyObject_New(pollObject, &poll_Type); - if (self == NULL) - return NULL; - /* ufd_uptodate is a Boolean, denoting whether the - array pointed to by ufds matches the contents of the dictionary. */ - self->ufd_uptodate = 0; - self->ufds = NULL; - self->dict = PyDict_New(); - if (self->dict == NULL) { - Py_DECREF(self); - return NULL; - } - return self; -} - -static void -poll_dealloc(pollObject *self) -{ - if (self->ufds != NULL) - PyMem_DEL(self->ufds); - Py_XDECREF(self->dict); - PyObject_Del(self); -} - -static PyObject * -poll_getattr(pollObject *self, char *name) -{ - return Py_FindMethod(poll_methods, (PyObject *)self, name); -} - -static PyTypeObject poll_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "select.poll", /*tp_name*/ - sizeof(pollObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)poll_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)poll_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ -}; - -PyDoc_STRVAR(poll_doc, -"Returns a polling object, which supports registering and\n\ -unregistering file descriptors, and then polling them for I/O events."); - -static PyObject * -select_poll(PyObject *self, PyObject *unused) -{ - return (PyObject *)newPollObject(); -} - -#ifdef __APPLE__ -/* - * On some systems poll() sets errno on invalid file descriptors. We test - * for this at runtime because this bug may be fixed or introduced between - * OS releases. - */ -static int select_have_broken_poll(void) -{ - int poll_test; - int filedes[2]; - - struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 }; - - /* Create a file descriptor to make invalid */ - if (pipe(filedes) < 0) { - return 1; - } - poll_struct.fd = filedes[0]; - close(filedes[0]); - close(filedes[1]); - poll_test = poll(&poll_struct, 1, 0); - if (poll_test < 0) { - return 1; - } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) { - return 1; - } - return 0; -} -#endif /* __APPLE__ */ - -#endif /* HAVE_POLL */ - -#ifdef HAVE_EPOLL -/* ************************************************************************** - * epoll interface for Linux 2.6 - * - * Written by Christian Heimes - * Inspired by Twisted's _epoll.pyx and select.poll() - */ - -#ifdef HAVE_SYS_EPOLL_H -#include -#endif - -typedef struct { - PyObject_HEAD - SOCKET epfd; /* epoll control file descriptor */ -} pyEpoll_Object; - -static PyTypeObject pyEpoll_Type; -#define pyepoll_CHECK(op) (PyObject_TypeCheck((op), &pyEpoll_Type)) - -static PyObject * -pyepoll_err_closed(void) -{ - PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd"); - return NULL; -} - -static int -pyepoll_internal_close(pyEpoll_Object *self) -{ - int save_errno = 0; - if (self->epfd >= 0) { - int epfd = self->epfd; - self->epfd = -1; - Py_BEGIN_ALLOW_THREADS - if (close(epfd) < 0) - save_errno = errno; - Py_END_ALLOW_THREADS - } - return save_errno; -} - -static PyObject * -newPyEpoll_Object(PyTypeObject *type, int sizehint, SOCKET fd) -{ - pyEpoll_Object *self; - - if (sizehint == -1) { - sizehint = FD_SETSIZE-1; - } - else if (sizehint < 1) { - PyErr_Format(PyExc_ValueError, - "sizehint must be greater zero, got %d", - sizehint); - return NULL; - } - - assert(type != NULL && type->tp_alloc != NULL); - self = (pyEpoll_Object *) type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - if (fd == -1) { - Py_BEGIN_ALLOW_THREADS - self->epfd = epoll_create(sizehint); - Py_END_ALLOW_THREADS - } - else { - self->epfd = fd; - } - if (self->epfd < 0) { - Py_DECREF(self); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return (PyObject *)self; -} - - -static PyObject * -pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds) -{ - int sizehint = -1; - static char *kwlist[] = {"sizehint", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist, - &sizehint)) - return NULL; - - return newPyEpoll_Object(type, sizehint, -1); -} - - -static void -pyepoll_dealloc(pyEpoll_Object *self) -{ - (void)pyepoll_internal_close(self); - Py_TYPE(self)->tp_free(self); -} - -static PyObject* -pyepoll_close(pyEpoll_Object *self) -{ - errno = pyepoll_internal_close(self); - if (errno < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_RETURN_NONE; -} - -PyDoc_STRVAR(pyepoll_close_doc, -"close() -> None\n\ -\n\ -Close the epoll control file descriptor. Further operations on the epoll\n\ -object will raise an exception."); - -static PyObject* -pyepoll_get_closed(pyEpoll_Object *self) -{ - if (self->epfd < 0) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; -} - -static PyObject* -pyepoll_fileno(pyEpoll_Object *self) -{ - if (self->epfd < 0) - return pyepoll_err_closed(); - return PyInt_FromLong(self->epfd); -} - -PyDoc_STRVAR(pyepoll_fileno_doc, -"fileno() -> int\n\ -\n\ -Return the epoll control file descriptor."); - -static PyObject* -pyepoll_fromfd(PyObject *cls, PyObject *args) -{ - SOCKET fd; - - if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) - return NULL; - - return newPyEpoll_Object((PyTypeObject*)cls, -1, fd); -} - -PyDoc_STRVAR(pyepoll_fromfd_doc, -"fromfd(fd) -> epoll\n\ -\n\ -Create an epoll object from a given control fd."); - -static PyObject * -pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events) -{ - struct epoll_event ev; - int result; - int fd; - - if (epfd < 0) - return pyepoll_err_closed(); - - fd = PyObject_AsFileDescriptor(pfd); - if (fd == -1) { - return NULL; - } - - switch(op) { - case EPOLL_CTL_ADD: - case EPOLL_CTL_MOD: - ev.events = events; - ev.data.fd = fd; - Py_BEGIN_ALLOW_THREADS - result = epoll_ctl(epfd, op, fd, &ev); - Py_END_ALLOW_THREADS - break; - case EPOLL_CTL_DEL: - /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL - * operation required a non-NULL pointer in event, even - * though this argument is ignored. */ - Py_BEGIN_ALLOW_THREADS - result = epoll_ctl(epfd, op, fd, &ev); - if (errno == EBADF) { - /* fd already closed */ - result = 0; - errno = 0; - } - Py_END_ALLOW_THREADS - break; - default: - result = -1; - errno = EINVAL; - } - - if (result < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_RETURN_NONE; -} - -static PyObject * -pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds) -{ - PyObject *pfd; - unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI; - static char *kwlist[] = {"fd", "eventmask", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist, - &pfd, &events)) { - return NULL; - } - - return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events); -} - -PyDoc_STRVAR(pyepoll_register_doc, -"register(fd[, eventmask]) -> None\n\ -\n\ -Registers a new fd or modifies an already registered fd.\n\ -fd is the target file descriptor of the operation.\n\ -events is a bit set composed of the various EPOLL constants; the default\n\ -is EPOLL_IN | EPOLL_OUT | EPOLL_PRI.\n\ -\n\ -The epoll interface supports all file descriptors that support poll."); - -static PyObject * -pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds) -{ - PyObject *pfd; - unsigned int events; - static char *kwlist[] = {"fd", "eventmask", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist, - &pfd, &events)) { - return NULL; - } - - return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events); -} - -PyDoc_STRVAR(pyepoll_modify_doc, -"modify(fd, eventmask) -> None\n\ -\n\ -fd is the target file descriptor of the operation\n\ -events is a bit set composed of the various EPOLL constants"); - -static PyObject * -pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds) -{ - PyObject *pfd; - static char *kwlist[] = {"fd", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist, - &pfd)) { - return NULL; - } - - return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0); -} - -PyDoc_STRVAR(pyepoll_unregister_doc, -"unregister(fd) -> None\n\ -\n\ -fd is the target file descriptor of the operation."); - -static PyObject * -pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds) -{ - double dtimeout = -1.; - int timeout; - int maxevents = -1; - int nfds, i; - PyObject *elist = NULL, *etuple = NULL; - struct epoll_event *evs = NULL; - static char *kwlist[] = {"timeout", "maxevents", NULL}; - - if (self->epfd < 0) - return pyepoll_err_closed(); - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist, - &dtimeout, &maxevents)) { - return NULL; - } - - if (dtimeout < 0) { - timeout = -1; - } - else if (dtimeout * 1000.0 > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout is too large"); - return NULL; - } - else { - timeout = (int)(dtimeout * 1000.0); - } - - if (maxevents == -1) { - maxevents = FD_SETSIZE-1; - } - else if (maxevents < 1) { - PyErr_Format(PyExc_ValueError, - "maxevents must be greater than 0, got %d", - maxevents); - return NULL; - } - - evs = PyMem_New(struct epoll_event, maxevents); - if (evs == NULL) { - Py_DECREF(self); - PyErr_NoMemory(); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - nfds = epoll_wait(self->epfd, evs, maxevents, timeout); - Py_END_ALLOW_THREADS - if (nfds < 0) { - PyErr_SetFromErrno(PyExc_IOError); - goto error; - } - - elist = PyList_New(nfds); - if (elist == NULL) { - goto error; - } - - for (i = 0; i < nfds; i++) { - etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events); - if (etuple == NULL) { - Py_CLEAR(elist); - goto error; - } - PyList_SET_ITEM(elist, i, etuple); - } - - error: - PyMem_Free(evs); - return elist; -} - -PyDoc_STRVAR(pyepoll_poll_doc, -"poll([timeout=-1[, maxevents=-1]]) -> [(fd, events), (...)]\n\ -\n\ -Wait for events on the epoll file descriptor for a maximum time of timeout\n\ -in seconds (as float). -1 makes poll wait indefinitely.\n\ -Up to maxevents are returned to the caller."); - -static PyMethodDef pyepoll_methods[] = { - {"fromfd", (PyCFunction)pyepoll_fromfd, - METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc}, - {"close", (PyCFunction)pyepoll_close, METH_NOARGS, - pyepoll_close_doc}, - {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS, - pyepoll_fileno_doc}, - {"modify", (PyCFunction)pyepoll_modify, - METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc}, - {"register", (PyCFunction)pyepoll_register, - METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc}, - {"unregister", (PyCFunction)pyepoll_unregister, - METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc}, - {"poll", (PyCFunction)pyepoll_poll, - METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc}, - {NULL, NULL}, -}; - -static PyGetSetDef pyepoll_getsetlist[] = { - {"closed", (getter)pyepoll_get_closed, NULL, - "True if the epoll handler is closed"}, - {0}, -}; - -PyDoc_STRVAR(pyepoll_doc, -"select.epoll([sizehint=-1])\n\ -\n\ -Returns an epolling object\n\ -\n\ -sizehint must be a positive integer or -1 for the default size. The\n\ -sizehint is used to optimize internal data structures. It doesn't limit\n\ -the maximum number of monitored events."); - -static PyTypeObject pyEpoll_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "select.epoll", /* tp_name */ - sizeof(pyEpoll_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)pyepoll_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - pyepoll_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - pyepoll_methods, /* tp_methods */ - 0, /* tp_members */ - pyepoll_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - pyepoll_new, /* tp_new */ - 0, /* tp_free */ -}; - -#endif /* HAVE_EPOLL */ - -#ifdef HAVE_KQUEUE -/* ************************************************************************** - * kqueue interface for BSD - * - * Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#ifdef HAVE_SYS_EVENT_H -#include -#endif - -PyDoc_STRVAR(kqueue_event_doc, -"kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)\n\ -\n\ -This object is the equivalent of the struct kevent for the C API.\n\ -\n\ -See the kqueue manpage for more detailed information about the meaning\n\ -of the arguments.\n\ -\n\ -One minor note: while you might hope that udata could store a\n\ -reference to a python object, it cannot, because it is impossible to\n\ -keep a proper reference count of the object once it's passed into the\n\ -kernel. Therefore, I have restricted it to only storing an integer. I\n\ -recommend ignoring it and simply using the 'ident' field to key off\n\ -of. You could also set up a dictionary on the python side to store a\n\ -udata->object mapping."); - -typedef struct { - PyObject_HEAD - struct kevent e; -} kqueue_event_Object; - -static PyTypeObject kqueue_event_Type; - -#define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type)) - -typedef struct { - PyObject_HEAD - SOCKET kqfd; /* kqueue control fd */ -} kqueue_queue_Object; - -static PyTypeObject kqueue_queue_Type; - -#define kqueue_queue_Check(op) (PyObject_TypeCheck((op), &kqueue_queue_Type)) - -#if (SIZEOF_UINTPTR_T != SIZEOF_VOID_P) -# error uintptr_t does not match void *! -#elif (SIZEOF_UINTPTR_T == SIZEOF_LONG_LONG) -# define T_UINTPTRT T_ULONGLONG -# define T_INTPTRT T_LONGLONG -# define PyLong_AsUintptr_t PyLong_AsUnsignedLongLong -# define UINTPTRT_FMT_UNIT "K" -# define INTPTRT_FMT_UNIT "L" -#elif (SIZEOF_UINTPTR_T == SIZEOF_LONG) -# define T_UINTPTRT T_ULONG -# define T_INTPTRT T_LONG -# define PyLong_AsUintptr_t PyLong_AsUnsignedLong -# define UINTPTRT_FMT_UNIT "k" -# define INTPTRT_FMT_UNIT "l" -#elif (SIZEOF_UINTPTR_T == SIZEOF_INT) -# define T_UINTPTRT T_UINT -# define T_INTPTRT T_INT -# define PyLong_AsUintptr_t PyLong_AsUnsignedLong -# define UINTPTRT_FMT_UNIT "I" -# define INTPTRT_FMT_UNIT "i" -#else -# error uintptr_t does not match int, long, or long long! -#endif - -/* Unfortunately, we can't store python objects in udata, because - * kevents in the kernel can be removed without warning, which would - * forever lose the refcount on the object stored with it. - */ - -#define KQ_OFF(x) offsetof(kqueue_event_Object, x) -static struct PyMemberDef kqueue_event_members[] = { - {"ident", T_UINTPTRT, KQ_OFF(e.ident)}, - {"filter", T_SHORT, KQ_OFF(e.filter)}, - {"flags", T_USHORT, KQ_OFF(e.flags)}, - {"fflags", T_UINT, KQ_OFF(e.fflags)}, - {"data", T_INTPTRT, KQ_OFF(e.data)}, - {"udata", T_UINTPTRT, KQ_OFF(e.udata)}, - {NULL} /* Sentinel */ -}; -#undef KQ_OFF - -static PyObject * - -kqueue_event_repr(kqueue_event_Object *s) -{ - char buf[1024]; - PyOS_snprintf( - buf, sizeof(buf), - "", - (size_t)(s->e.ident), s->e.filter, s->e.flags, - s->e.fflags, (Py_ssize_t)(s->e.data), s->e.udata); - return PyString_FromString(buf); -} - -static int -kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds) -{ - PyObject *pfd; - static char *kwlist[] = {"ident", "filter", "flags", "fflags", - "data", "udata", NULL}; - static char *fmt = "O|hhi" INTPTRT_FMT_UNIT UINTPTRT_FMT_UNIT ":kevent"; - - EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */ - - if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist, - &pfd, &(self->e.filter), &(self->e.flags), - &(self->e.fflags), &(self->e.data), &(self->e.udata))) { - return -1; - } - - if (PyLong_Check(pfd)) { - self->e.ident = PyLong_AsUintptr_t(pfd); - } - else { - self->e.ident = PyObject_AsFileDescriptor(pfd); - } - if (PyErr_Occurred()) { - return -1; - } - return 0; -} - -static PyObject * -kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o, - int op) -{ - Py_intptr_t result = 0; - - if (!kqueue_event_Check(o)) { - if (op == Py_EQ || op == Py_NE) { - PyObject *res = op == Py_EQ ? Py_False : Py_True; - Py_INCREF(res); - return res; - } - PyErr_Format(PyExc_TypeError, - "can't compare %.200s to %.200s", - Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name); - return NULL; - } - if (((result = s->e.ident - o->e.ident) == 0) && - ((result = s->e.filter - o->e.filter) == 0) && - ((result = s->e.flags - o->e.flags) == 0) && - ((result = s->e.fflags - o->e.fflags) == 0) && - ((result = s->e.data - o->e.data) == 0) && - ((result = s->e.udata - o->e.udata) == 0) - ) { - result = 0; - } - - switch (op) { - case Py_EQ: - result = (result == 0); - break; - case Py_NE: - result = (result != 0); - break; - case Py_LE: - result = (result <= 0); - break; - case Py_GE: - result = (result >= 0); - break; - case Py_LT: - result = (result < 0); - break; - case Py_GT: - result = (result > 0); - break; - } - return PyBool_FromLong((long)result); -} - -static PyTypeObject kqueue_event_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "select.kevent", /* tp_name */ - sizeof(kqueue_event_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - (reprfunc)kqueue_event_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - kqueue_event_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - kqueue_event_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)kqueue_event_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ -}; - -static PyObject * -kqueue_queue_err_closed(void) -{ - PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd"); - return NULL; -} - -static int -kqueue_queue_internal_close(kqueue_queue_Object *self) -{ - int save_errno = 0; - if (self->kqfd >= 0) { - int kqfd = self->kqfd; - self->kqfd = -1; - Py_BEGIN_ALLOW_THREADS - if (close(kqfd) < 0) - save_errno = errno; - Py_END_ALLOW_THREADS - } - return save_errno; -} - -static PyObject * -newKqueue_Object(PyTypeObject *type, SOCKET fd) -{ - kqueue_queue_Object *self; - assert(type != NULL && type->tp_alloc != NULL); - self = (kqueue_queue_Object *) type->tp_alloc(type, 0); - if (self == NULL) { - return NULL; - } - - if (fd == -1) { - Py_BEGIN_ALLOW_THREADS - self->kqfd = kqueue(); - Py_END_ALLOW_THREADS - } - else { - self->kqfd = fd; - } - if (self->kqfd < 0) { - Py_DECREF(self); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return (PyObject *)self; -} - -static PyObject * -kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds) -{ - - if ((args != NULL && PyObject_Size(args)) || - (kwds != NULL && PyObject_Size(kwds))) { - PyErr_SetString(PyExc_ValueError, - "select.kqueue doesn't accept arguments"); - return NULL; - } - - return newKqueue_Object(type, -1); -} - -static void -kqueue_queue_dealloc(kqueue_queue_Object *self) -{ - kqueue_queue_internal_close(self); - Py_TYPE(self)->tp_free(self); -} - -static PyObject* -kqueue_queue_close(kqueue_queue_Object *self) -{ - errno = kqueue_queue_internal_close(self); - if (errno < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_RETURN_NONE; -} - -PyDoc_STRVAR(kqueue_queue_close_doc, -"close() -> None\n\ -\n\ -Close the kqueue control file descriptor. Further operations on the kqueue\n\ -object will raise an exception."); - -static PyObject* -kqueue_queue_get_closed(kqueue_queue_Object *self) -{ - if (self->kqfd < 0) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; -} - -static PyObject* -kqueue_queue_fileno(kqueue_queue_Object *self) -{ - if (self->kqfd < 0) - return kqueue_queue_err_closed(); - return PyInt_FromLong(self->kqfd); -} - -PyDoc_STRVAR(kqueue_queue_fileno_doc, -"fileno() -> int\n\ -\n\ -Return the kqueue control file descriptor."); - -static PyObject* -kqueue_queue_fromfd(PyObject *cls, PyObject *args) -{ - SOCKET fd; - - if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) - return NULL; - - return newKqueue_Object((PyTypeObject*)cls, fd); -} - -PyDoc_STRVAR(kqueue_queue_fromfd_doc, -"fromfd(fd) -> kqueue\n\ -\n\ -Create a kqueue object from a given control fd."); - -static PyObject * -kqueue_queue_control(kqueue_queue_Object *self, PyObject *args) -{ - int nevents = 0; - int gotevents = 0; - int nchanges = 0; - int i = 0; - PyObject *otimeout = NULL; - PyObject *ch = NULL; - PyObject *it = NULL, *ei = NULL; - PyObject *result = NULL; - struct kevent *evl = NULL; - struct kevent *chl = NULL; - struct timespec timeoutspec; - struct timespec *ptimeoutspec; - - if (self->kqfd < 0) - return kqueue_queue_err_closed(); - - if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout)) - return NULL; - - if (nevents < 0) { - PyErr_Format(PyExc_ValueError, - "Length of eventlist must be 0 or positive, got %d", - nevents); - return NULL; - } - - if (otimeout == Py_None || otimeout == NULL) { - ptimeoutspec = NULL; - } - else if (PyNumber_Check(otimeout)) { - double timeout; - long seconds; - - timeout = PyFloat_AsDouble(otimeout); - if (timeout == -1 && PyErr_Occurred()) - return NULL; - if (timeout > (double)LONG_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout period too long"); - return NULL; - } - if (timeout < 0) { - PyErr_SetString(PyExc_ValueError, - "timeout must be positive or None"); - return NULL; - } - - seconds = (long)timeout; - timeout = timeout - (double)seconds; - timeoutspec.tv_sec = seconds; - timeoutspec.tv_nsec = (long)(timeout * 1E9); - ptimeoutspec = &timeoutspec; - } - else { - PyErr_Format(PyExc_TypeError, - "timeout argument must be an number " - "or None, got %.200s", - Py_TYPE(otimeout)->tp_name); - return NULL; - } - - if (ch != NULL && ch != Py_None) { - it = PyObject_GetIter(ch); - if (it == NULL) { - PyErr_SetString(PyExc_TypeError, - "changelist is not iterable"); - return NULL; - } - nchanges = PyObject_Size(ch); - if (nchanges < 0) { - goto error; - } - - chl = PyMem_New(struct kevent, nchanges); - if (chl == NULL) { - PyErr_NoMemory(); - goto error; - } - i = 0; - while ((ei = PyIter_Next(it)) != NULL) { - if (!kqueue_event_Check(ei)) { - Py_DECREF(ei); - PyErr_SetString(PyExc_TypeError, - "changelist must be an iterable of " - "select.kevent objects"); - goto error; - } else { - chl[i++] = ((kqueue_event_Object *)ei)->e; - } - Py_DECREF(ei); - } - } - Py_CLEAR(it); - - /* event list */ - if (nevents) { - evl = PyMem_New(struct kevent, nevents); - if (evl == NULL) { - PyErr_NoMemory(); - goto error; - } - } - - Py_BEGIN_ALLOW_THREADS - gotevents = kevent(self->kqfd, chl, nchanges, - evl, nevents, ptimeoutspec); - Py_END_ALLOW_THREADS - - if (gotevents == -1) { - PyErr_SetFromErrno(PyExc_OSError); - goto error; - } - - result = PyList_New(gotevents); - if (result == NULL) { - goto error; - } - - for (i = 0; i < gotevents; i++) { - kqueue_event_Object *ch; - - ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type); - if (ch == NULL) { - goto error; - } - ch->e = evl[i]; - PyList_SET_ITEM(result, i, (PyObject *)ch); - } - PyMem_Free(chl); - PyMem_Free(evl); - return result; - - error: - PyMem_Free(chl); - PyMem_Free(evl); - Py_XDECREF(result); - Py_XDECREF(it); - return NULL; -} - -PyDoc_STRVAR(kqueue_queue_control_doc, -"control(changelist, max_events[, timeout=None]) -> eventlist\n\ -\n\ -Calls the kernel kevent function.\n\ -- changelist must be a list of kevent objects describing the changes\n\ - to be made to the kernel's watch list or None.\n\ -- max_events lets you specify the maximum number of events that the\n\ - kernel will return.\n\ -- timeout is the maximum time to wait in seconds, or else None,\n\ - to wait forever. timeout accepts floats for smaller timeouts, too."); - - -static PyMethodDef kqueue_queue_methods[] = { - {"fromfd", (PyCFunction)kqueue_queue_fromfd, - METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc}, - {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS, - kqueue_queue_close_doc}, - {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS, - kqueue_queue_fileno_doc}, - {"control", (PyCFunction)kqueue_queue_control, - METH_VARARGS , kqueue_queue_control_doc}, - {NULL, NULL}, -}; - -static PyGetSetDef kqueue_queue_getsetlist[] = { - {"closed", (getter)kqueue_queue_get_closed, NULL, - "True if the kqueue handler is closed"}, - {0}, -}; - -PyDoc_STRVAR(kqueue_queue_doc, -"Kqueue syscall wrapper.\n\ -\n\ -For example, to start watching a socket for input:\n\ ->>> kq = kqueue()\n\ ->>> sock = socket()\n\ ->>> sock.connect((host, port))\n\ ->>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_ADD)], 0)\n\ -\n\ -To wait one second for it to become writeable:\n\ ->>> kq.control(None, 1, 1000)\n\ -\n\ -To stop listening:\n\ ->>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)"); - -static PyTypeObject kqueue_queue_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "select.kqueue", /* tp_name */ - sizeof(kqueue_queue_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)kqueue_queue_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - kqueue_queue_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - kqueue_queue_methods, /* tp_methods */ - 0, /* tp_members */ - kqueue_queue_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - kqueue_queue_new, /* tp_new */ - 0, /* tp_free */ -}; - -#endif /* HAVE_KQUEUE */ -/* ************************************************************************ */ - -PyDoc_STRVAR(select_doc, -"select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)\n\ -\n\ -Wait until one or more file descriptors are ready for some kind of I/O.\n\ -The first three arguments are sequences of file descriptors to be waited for:\n\ -rlist -- wait until ready for reading\n\ -wlist -- wait until ready for writing\n\ -xlist -- wait for an ``exceptional condition''\n\ -If only one kind of condition is required, pass [] for the other lists.\n\ -A file descriptor is either a socket or file object, or a small integer\n\ -gotten from a fileno() method call on one of those.\n\ -\n\ -The optional 4th argument specifies a timeout in seconds; it may be\n\ -a floating point number to specify fractions of seconds. If it is absent\n\ -or None, the call will never time out.\n\ -\n\ -The return value is a tuple of three lists corresponding to the first three\n\ -arguments; each contains the subset of the corresponding file descriptors\n\ -that are ready.\n\ -\n\ -*** IMPORTANT NOTICE ***\n\ -On Windows and OpenVMS, only sockets are supported; on Unix, all file\n\ -descriptors can be used."); - -static PyMethodDef select_methods[] = { - {"select", select_select, METH_VARARGS, select_doc}, -#ifdef HAVE_POLL - {"poll", select_poll, METH_NOARGS, poll_doc}, -#endif /* HAVE_POLL */ - {0, 0}, /* sentinel */ -}; - -PyDoc_STRVAR(module_doc, -"This module supports asynchronous I/O on multiple file descriptors.\n\ -\n\ -*** IMPORTANT NOTICE ***\n\ -On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptors."); - -PyMODINIT_FUNC -initselect(void) -{ - PyObject *m; - m = Py_InitModule3("select", select_methods, module_doc); - if (m == NULL) - return; - - SelectError = PyErr_NewException("select.error", NULL, NULL); - Py_INCREF(SelectError); - PyModule_AddObject(m, "error", SelectError); - -#ifdef PIPE_BUF -#ifdef HAVE_BROKEN_PIPE_BUF -#undef PIPE_BUF -#define PIPE_BUF 512 -#endif - PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF); -#endif - -#if defined(HAVE_POLL) -#ifdef __APPLE__ - if (select_have_broken_poll()) { - if (PyObject_DelAttrString(m, "poll") == -1) { - PyErr_Clear(); - } - } else { -#else - { -#endif - Py_TYPE(&poll_Type) = &PyType_Type; - PyModule_AddIntConstant(m, "POLLIN", POLLIN); - PyModule_AddIntConstant(m, "POLLPRI", POLLPRI); - PyModule_AddIntConstant(m, "POLLOUT", POLLOUT); - PyModule_AddIntConstant(m, "POLLERR", POLLERR); - PyModule_AddIntConstant(m, "POLLHUP", POLLHUP); - PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL); - -#ifdef POLLRDNORM - PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM); -#endif -#ifdef POLLRDBAND - PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND); -#endif -#ifdef POLLWRNORM - PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM); -#endif -#ifdef POLLWRBAND - PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND); -#endif -#ifdef POLLMSG - PyModule_AddIntConstant(m, "POLLMSG", POLLMSG); -#endif - } -#endif /* HAVE_POLL */ - -#ifdef HAVE_EPOLL - Py_TYPE(&pyEpoll_Type) = &PyType_Type; - if (PyType_Ready(&pyEpoll_Type) < 0) - return; - - Py_INCREF(&pyEpoll_Type); - PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type); - - PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN); - PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT); - PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI); - PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR); - PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP); - PyModule_AddIntConstant(m, "EPOLLET", EPOLLET); -#ifdef EPOLLONESHOT - /* Kernel 2.6.2+ */ - PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT); -#endif - /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */ - PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM); - PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND); - PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM); - PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND); - PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG); -#endif /* HAVE_EPOLL */ - -#ifdef HAVE_KQUEUE - kqueue_event_Type.tp_new = PyType_GenericNew; - Py_TYPE(&kqueue_event_Type) = &PyType_Type; - if(PyType_Ready(&kqueue_event_Type) < 0) - return; - - Py_INCREF(&kqueue_event_Type); - PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type); - - Py_TYPE(&kqueue_queue_Type) = &PyType_Type; - if(PyType_Ready(&kqueue_queue_Type) < 0) - return; - Py_INCREF(&kqueue_queue_Type); - PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type); - - /* event filters */ - PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ); - PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE); - PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO); - PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE); - PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC); -#ifdef EVFILT_NETDEV - PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV); -#endif - PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL); - PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER); - - /* event flags */ - PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD); - PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE); - PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE); - PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE); - PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT); - PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR); - - PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS); - PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1); - - PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF); - PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR); - - /* READ WRITE filter flag */ - PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT); - - /* VNODE filter flags */ - PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE); - PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE); - PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND); - PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB); - PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK); - PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME); - PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE); - - /* PROC filter flags */ - PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT); - PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK); - PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC); - PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK); - PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK); - - PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK); - PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD); - PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR); - - /* NETDEV filter flags */ -#ifdef EVFILT_NETDEV - PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP); - PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN); - PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV); -#endif - -#endif /* HAVE_KQUEUE */ -} diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/socketmodule.h b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/socketmodule.h deleted file mode 100644 index 1190bfd..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/socketmodule.h +++ /dev/null @@ -1,250 +0,0 @@ -/* Socket module header file */ - -/* Includes needed for the sockaddr_* symbols below */ -#ifndef MS_WINDOWS -#ifdef __VMS -# include -# else -# include -# endif -# include -# if !(defined(UEFI_C_SOURCE) || defined(__BEOS__) || defined(__CYGWIN__) || (defined(PYOS_OS2) && defined(PYCC_VACPP))) -# include -# endif - -#else /* MS_WINDOWS */ -# include -# include -/* VC6 is shipped with old platform headers, and does not have MSTcpIP.h - * Separate SDKs have all the functions we want, but older ones don't have - * any version information. - * I use SIO_GET_MULTICAST_FILTER to detect a decent SDK. - */ -# ifdef SIO_GET_MULTICAST_FILTER -# include /* for SIO_RCVALL */ -# define HAVE_ADDRINFO -# define HAVE_SOCKADDR_STORAGE -# define HAVE_GETADDRINFO -# define HAVE_GETNAMEINFO -# define ENABLE_IPV6 -# else -typedef int socklen_t; -# endif /* IPPROTO_IPV6 */ -#endif /* MS_WINDOWS */ - -#ifdef HAVE_SYS_UN_H -# include -#else -# undef AF_UNIX -#endif - -#ifdef HAVE_LINUX_NETLINK_H -# ifdef HAVE_ASM_TYPES_H -# include -# endif -# include -#else -# undef AF_NETLINK -#endif - -#ifdef HAVE_BLUETOOTH_BLUETOOTH_H -#include -#include -#include -#include -#include -#endif - -#ifdef HAVE_BLUETOOTH_H -#include -#endif - -#ifdef HAVE_NETPACKET_PACKET_H -# include -# include -# include -#endif - -#ifdef HAVE_LINUX_TIPC_H -# include -#endif - -#ifndef Py__SOCKET_H -#define Py__SOCKET_H -#ifdef __cplusplus -extern "C" { -#endif - -/* Python module and C API name */ -#define PySocket_MODULE_NAME "_socket" -#define PySocket_CAPI_NAME "CAPI" -#define PySocket_CAPSULE_NAME (PySocket_MODULE_NAME "." PySocket_CAPI_NAME) - -/* Abstract the socket file descriptor type */ -#ifdef MS_WINDOWS -typedef SOCKET SOCKET_T; -# ifdef MS_WIN64 -# define SIZEOF_SOCKET_T 8 -# else -# define SIZEOF_SOCKET_T 4 -# endif -#else -typedef int SOCKET_T; -# define SIZEOF_SOCKET_T SIZEOF_INT -#endif - -/* Socket address */ -typedef union sock_addr { - struct sockaddr_in in; -#ifdef AF_UNIX - struct sockaddr_un un; -#endif -#ifdef AF_NETLINK - struct sockaddr_nl nl; -#endif -#ifdef ENABLE_IPV6 - struct sockaddr_in6 in6; - struct sockaddr_storage storage; -#endif -#ifdef HAVE_BLUETOOTH_BLUETOOTH_H - struct sockaddr_l2 bt_l2; - struct sockaddr_rc bt_rc; - struct sockaddr_sco bt_sco; - struct sockaddr_hci bt_hci; -#endif -#ifdef HAVE_NETPACKET_PACKET_H - struct sockaddr_ll ll; -#endif -} sock_addr_t; - -/* The object holding a socket. It holds some extra information, - like the address family, which is used to decode socket address - arguments properly. */ - -typedef struct { - PyObject_HEAD - SOCKET_T sock_fd; /* Socket file descriptor */ - int sock_family; /* Address family, e.g., AF_INET */ - int sock_type; /* Socket type, e.g., SOCK_STREAM */ - int sock_proto; /* Protocol type, usually 0 */ - PyObject *(*errorhandler)(void); /* Error handler; checks - errno, returns NULL and - sets a Python exception */ - double sock_timeout; /* Operation timeout in seconds; - 0.0 means non-blocking */ -} PySocketSockObject; - -/* --- C API ----------------------------------------------------*/ - -/* Short explanation of what this C API export mechanism does - and how it works: - - The _ssl module needs access to the type object defined in - the _socket module. Since cross-DLL linking introduces a lot of - problems on many platforms, the "trick" is to wrap the - C API of a module in a struct which then gets exported to - other modules via a PyCapsule. - - The code in socketmodule.c defines this struct (which currently - only contains the type object reference, but could very - well also include other C APIs needed by other modules) - and exports it as PyCapsule via the module dictionary - under the name "CAPI". - - Other modules can now include the socketmodule.h file - which defines the needed C APIs to import and set up - a static copy of this struct in the importing module. - - After initialization, the importing module can then - access the C APIs from the _socket module by simply - referring to the static struct, e.g. - - Load _socket module and its C API; this sets up the global - PySocketModule: - - if (PySocketModule_ImportModuleAndAPI()) - return; - - - Now use the C API as if it were defined in the using - module: - - if (!PyArg_ParseTuple(args, "O!|zz:ssl", - - PySocketModule.Sock_Type, - - (PyObject*)&Sock, - &key_file, &cert_file)) - return NULL; - - Support could easily be extended to export more C APIs/symbols - this way. Currently, only the type object is exported, - other candidates would be socket constructors and socket - access functions. - -*/ - -/* C API for usage by other Python modules */ -typedef struct { - PyTypeObject *Sock_Type; - PyObject *error; -} PySocketModule_APIObject; - -/* XXX The net effect of the following appears to be to define a function - XXX named PySocketModule_APIObject in _ssl.c. It's unclear why it isn't - XXX defined there directly. - - >>> It's defined here because other modules might also want to use - >>> the C API. - -*/ -#ifndef PySocket_BUILDING_SOCKET - -/* --- C API ----------------------------------------------------*/ - -/* Interfacestructure to C API for other modules. - Call PySocketModule_ImportModuleAndAPI() to initialize this - structure. After that usage is simple: - - if (!PyArg_ParseTuple(args, "O!|zz:ssl", - &PySocketModule.Sock_Type, (PyObject*)&Sock, - &key_file, &cert_file)) - return NULL; - ... -*/ - -static -PySocketModule_APIObject PySocketModule; - -/* You *must* call this before using any of the functions in - PySocketModule and check its outcome; otherwise all accesses will - result in a segfault. Returns 0 on success. */ - -#ifndef DPRINTF -# define DPRINTF if (0) printf -#endif - -static -int PySocketModule_ImportModuleAndAPI(void) -{ - void *api; - - DPRINTF(" Loading capsule %s\n", PySocket_CAPSULE_NAME); - api = PyCapsule_Import(PySocket_CAPSULE_NAME, 1); - if (api == NULL) - goto onError; - memcpy(&PySocketModule, api, sizeof(PySocketModule)); - DPRINTF(" API object loaded and initialized.\n"); - return 0; - - onError: - DPRINTF(" not found.\n"); - return -1; -} - -#endif /* !PySocket_BUILDING_SOCKET */ - -#ifdef __cplusplus -} -#endif -#endif /* !Py__SOCKET_H */ diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/zlib/zutil.h b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/zlib/zutil.h deleted file mode 100644 index 55b6d1a..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/zlib/zutil.h +++ /dev/null @@ -1,277 +0,0 @@ -/* zutil.h -- internal interface and configuration of the compression library - - 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. - - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h -**/ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -#ifndef ZUTIL_H -#define ZUTIL_H - -#define ZLIB_INTERNAL -#include "zlib.h" - -#if defined(UEFI_C_SOURCE) || defined(STDC) -# ifndef _WIN32_WCE -# include -# endif -# include -# include -#endif -#ifdef NO_ERRNO_H -# ifdef _WIN32_WCE - /* The Microsoft C Run-Time Library for Windows CE doesn't have - * errno. We define it as a global variable to simplify porting. - * Its value is always 0 and should not be used. We rename it to - * avoid conflict with other libraries that use the same workaround. - */ -# define errno z_errno -# endif - extern int errno; -#else -# ifndef _WIN32_WCE -# include -# endif -#endif - -#ifndef local -# define local static -#endif -/* compile with -Dlocal if your debugger can't find static symbols */ - -typedef unsigned char uch; -typedef uch FAR uchf; -typedef unsigned short ush; -typedef ush FAR ushf; -typedef unsigned long ulg; - -extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ -/* (size given to avoid silly warnings with Visual C++) */ - -#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] - -#define ERR_RETURN(strm,err) \ - return (strm->msg = (char*)ERR_MSG(err), (err)) -/* To be used only when the state is known to be valid */ - - /* common constants */ - -#ifndef DEF_WBITS -# define DEF_WBITS MAX_WBITS -#endif -/* default windowBits for decompression. MAX_WBITS is for compression only */ - -#if MAX_MEM_LEVEL >= 8 -# define DEF_MEM_LEVEL 8 -#else -# define DEF_MEM_LEVEL MAX_MEM_LEVEL -#endif -/* default memLevel */ - -#define STORED_BLOCK 0 -#define STATIC_TREES 1 -#define DYN_TREES 2 -/* The three kinds of block type */ - -#define MIN_MATCH 3 -#define MAX_MATCH 258 -/* The minimum and maximum match lengths */ - -#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ - - /* target dependencies */ - -#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) -# define OS_CODE 0x00 -# if defined(__TURBOC__) || defined(__BORLANDC__) -# if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) - /* Allow compilation with ANSI keywords only enabled */ - void _Cdecl farfree( void *block ); - void *_Cdecl farmalloc( unsigned long nbytes ); -# else -# include -# endif -# else /* MSC or DJGPP */ -# include -# endif -#endif - -#ifdef AMIGA -# define OS_CODE 0x01 -#endif - -#if defined(VAXC) || defined(VMS) -# define OS_CODE 0x02 -# define F_OPEN(name, mode) \ - fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") -#endif - -#if defined(ATARI) || defined(atarist) -# define OS_CODE 0x05 -#endif - -#ifdef OS2 -# define OS_CODE 0x06 -# ifdef M_I86 - #include -# endif -#endif - -#if defined(MACOS) || defined(TARGET_OS_MAC) -# define OS_CODE 0x07 -# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os -# include /* for fdopen */ -# else -# ifndef fdopen -# define fdopen(fd,mode) NULL /* No fdopen() */ -# endif -# endif -#endif - -#ifdef TOPS20 -# define OS_CODE 0x0a -#endif - -#ifdef WIN32 -# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ -# define OS_CODE 0x0b -# endif -#endif - -#ifdef __50SERIES /* Prime/PRIMOS */ -# define OS_CODE 0x0f -#endif - -#if defined(_BEOS_) || defined(RISCOS) -# define fdopen(fd,mode) NULL /* No fdopen() */ -#endif - -#if !defined(UEFI_C_SOURCE) && (defined(_MSC_VER) && (_MSC_VER > 600)) -# if defined(_WIN32_WCE) -# define fdopen(fd,mode) NULL /* No fdopen() */ -# ifndef _PTRDIFF_T_DEFINED - typedef int ptrdiff_t; -# define _PTRDIFF_T_DEFINED -# endif -# else -# define fdopen(fd,type) _fdopen(fd,type) -# endif -#endif - - /* common defaults */ - -#ifndef OS_CODE -# define OS_CODE 0x03 /* assume Unix */ -#endif - -#ifndef F_OPEN -# define F_OPEN(name, mode) fopen((name), (mode)) -#endif - - /* functions */ - -#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif -#endif -#if defined(__CYGWIN__) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif -#endif -#ifndef HAVE_VSNPRINTF -# ifdef MSDOS - /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), - but for now we just assume it doesn't. */ -# define NO_vsnprintf -# endif -# ifdef __TURBOC__ -# define NO_vsnprintf -# endif -# ifdef WIN32 - /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ -# if !defined(vsnprintf) && !defined(NO_vsnprintf) -# define vsnprintf _vsnprintf -# endif -# endif -# ifdef __SASC -# define NO_vsnprintf -# endif -#endif -#ifdef VMS -# define NO_vsnprintf -#endif - -#if defined(pyr) -# define NO_MEMCPY -#endif -#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) - /* Use our own functions for small and medium model with MSC <= 5.0. - * You may have to use the same strategy for Borland C (untested). - * The __SC__ check is for Symantec. - */ -# define NO_MEMCPY -#endif -#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) -# define HAVE_MEMCPY -#endif -#ifdef HAVE_MEMCPY -# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ -# define zmemcpy _fmemcpy -# define zmemcmp _fmemcmp -# define zmemzero(dest, len) _fmemset(dest, 0, len) -# else -# define zmemcpy memcpy -# define zmemcmp memcmp -# define zmemzero(dest, len) memset(dest, 0, len) -# endif -#else - extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); - extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); - extern void zmemzero OF((Bytef* dest, uInt len)); -#endif - -/* Diagnostic functions */ -#ifdef DEBUG -# include - extern int z_verbose; - extern void z_error OF((char *m)); -# define Assert(cond,msg) {if(!(cond)) z_error(msg);} -# define Trace(x) {if (z_verbose>=0) fprintf x ;} -# define Tracev(x) {if (z_verbose>0) fprintf x ;} -# define Tracevv(x) {if (z_verbose>1) fprintf x ;} -# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} -# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} -#else -# define Assert(cond,msg) -# define Trace(x) -# define Tracev(x) -# define Tracevv(x) -# define Tracec(c,x) -# define Tracecv(c,x) -#endif - - -voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); -void zcfree OF((voidpf opaque, voidpf ptr)); - -#define ZALLOC(strm, items, size) \ - (*((strm)->zalloc))((strm)->opaque, (items), (size)) -#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) -#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} - -#endif /* ZUTIL_H */ diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Objects/longobject.c b/AppPkg/Applications/Python/PyMod-2.7.2/Objects/longobject.c deleted file mode 100644 index 2552e99..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Objects/longobject.c +++ /dev/null @@ -1,4381 +0,0 @@ -/** @file - Long (arbitrary precision) integer object implementation. - - 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. -**/ - -/* XXX The functional organization of this file is terrible */ - -#include "Python.h" -#include "longintrepr.h" -#include "structseq.h" - -#include -#include -#include - -/* For long multiplication, use the O(N**2) school algorithm unless - * both operands contain more than KARATSUBA_CUTOFF digits (this - * being an internal Python long digit, in base PyLong_BASE). - */ -#define KARATSUBA_CUTOFF 70 -#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF) - -/* For exponentiation, use the binary left-to-right algorithm - * unless the exponent contains more than FIVEARY_CUTOFF digits. - * In that case, do 5 bits at a time. The potential drawback is that - * a table of 2**5 intermediate results is computed. - */ -#define FIVEARY_CUTOFF 8 - -#ifndef ABS - #define ABS(x) ((x) < 0 ? -(x) : (x)) -#endif - -#ifndef MAX - #define MAX(x, y) ((x) < (y) ? (y) : (x)) -#endif - -#ifndef MIN - #define MIN(x, y) ((x) > (y) ? (y) : (x)) -#endif - -#define SIGCHECK(PyTryBlock) \ - do { \ - if (--_Py_Ticker < 0) { \ - _Py_Ticker = _Py_CheckInterval; \ - if (PyErr_CheckSignals()) PyTryBlock \ - } \ - } while(0) - -/* Normalize (remove leading zeros from) a long int object. - Doesn't attempt to free the storage--in most cases, due to the nature - of the algorithms used, this could save at most be one word anyway. */ - -static PyLongObject * -long_normalize(register PyLongObject *v) -{ - Py_ssize_t j = ABS(Py_SIZE(v)); - Py_ssize_t i = j; - - while (i > 0 && v->ob_digit[i-1] == 0) - --i; - if (i != j) - Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i; - return v; -} - -/* Allocate a new long int object with size digits. - Return NULL and set exception if we run out of memory. */ - -#define MAX_LONG_DIGITS \ - ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit)) - -PyLongObject * -_PyLong_New(Py_ssize_t size) -{ - if (size > (Py_ssize_t)MAX_LONG_DIGITS) { - PyErr_SetString(PyExc_OverflowError, - "too many digits in integer"); - return NULL; - } - /* coverity[ampersand_in_size] */ - /* XXX(nnorwitz): PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect - overflow */ - return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size); -} - -PyObject * -_PyLong_Copy(PyLongObject *src) -{ - PyLongObject *result; - Py_ssize_t i; - - assert(src != NULL); - i = src->ob_size; - if (i < 0) - i = -(i); - result = _PyLong_New(i); - if (result != NULL) { - result->ob_size = src->ob_size; - while (--i >= 0) - result->ob_digit[i] = src->ob_digit[i]; - } - return (PyObject *)result; -} - -/* Create a new long int object from a C long int */ - -PyObject * -PyLong_FromLong(long ival) -{ - PyLongObject *v; - unsigned long abs_ival; - unsigned long t; /* unsigned so >> doesn't propagate sign bit */ - int ndigits = 0; - int negative = 0; - - if (ival < 0) { - /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then - ANSI C says that the result of -ival is undefined when ival - == LONG_MIN. Hence the following workaround. */ - abs_ival = (unsigned long)(-1-ival) + 1; - negative = 1; - } - else { - abs_ival = (unsigned long)ival; - } - - /* Count the number of Python digits. - We used to pick 5 ("big enough for anything"), but that's a - waste of time and space given that 5*15 = 75 bits are rarely - needed. */ - t = abs_ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - v->ob_size = negative ? -ndigits : ndigits; - t = abs_ival; - while (t) { - *p++ = (digit)(t & PyLong_MASK); - t >>= PyLong_SHIFT; - } - } - return (PyObject *)v; -} - -/* Create a new long int object from a C unsigned long int */ - -PyObject * -PyLong_FromUnsignedLong(unsigned long ival) -{ - PyLongObject *v; - unsigned long t; - int ndigits = 0; - - /* Count the number of Python digits. */ - t = (unsigned long)ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = ndigits; - while (ival) { - *p++ = (digit)(ival & PyLong_MASK); - ival >>= PyLong_SHIFT; - } - } - return (PyObject *)v; -} - -/* Create a new long int object from a C double */ - -PyObject * -PyLong_FromDouble(double dval) -{ - PyLongObject *v; - double frac; - int i, ndig, expo, neg; - neg = 0; - if (Py_IS_INFINITY(dval)) { - PyErr_SetString(PyExc_OverflowError, - "cannot convert float infinity to integer"); - return NULL; - } - if (Py_IS_NAN(dval)) { - PyErr_SetString(PyExc_ValueError, - "cannot convert float NaN to integer"); - return NULL; - } - if (dval < 0.0) { - neg = 1; - dval = -dval; - } - frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */ - if (expo <= 0) - return PyLong_FromLong(0L); - ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */ - v = _PyLong_New(ndig); - if (v == NULL) - return NULL; - frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1); - for (i = ndig; --i >= 0; ) { - digit bits = (digit)frac; - v->ob_digit[i] = bits; - frac = frac - (double)bits; - frac = ldexp(frac, PyLong_SHIFT); - } - if (neg) - Py_SIZE(v) = -(Py_SIZE(v)); - return (PyObject *)v; -} - -/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define - * anything about what happens when a signed integer operation overflows, - * and some compilers think they're doing you a favor by being "clever" - * then. The bit pattern for the largest postive signed long is - * (unsigned long)LONG_MAX, and for the smallest negative signed long - * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN. - * However, some other compilers warn about applying unary minus to an - * unsigned operand. Hence the weird "0-". - */ -#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) -#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN) - -/* Get a C long int from a Python long or Python int object. - On overflow, returns -1 and sets *overflow to 1 or -1 depending - on the sign of the result. Otherwise *overflow is 0. - - For other errors (e.g., type error), returns -1 and sets an error - condition. -*/ - -long -PyLong_AsLongAndOverflow(PyObject *vv, int *overflow) -{ - /* This version by Tim Peters */ - register PyLongObject *v; - unsigned long x, prev; - long res; - Py_ssize_t i; - int sign; - int do_decref = 0; /* if nb_int was called */ - - *overflow = 0; - if (vv == NULL) { - PyErr_BadInternalCall(); - return -1; - } - - if(PyInt_Check(vv)) - return PyInt_AsLong(vv); - - if (!PyLong_Check(vv)) { - PyNumberMethods *nb; - nb = vv->ob_type->tp_as_number; - if (nb == NULL || nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - return -1; - } - vv = (*nb->nb_int) (vv); - if (vv == NULL) - return -1; - do_decref = 1; - if(PyInt_Check(vv)) { - res = PyInt_AsLong(vv); - goto exit; - } - if (!PyLong_Check(vv)) { - Py_DECREF(vv); - PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); - return -1; - } - } - - res = -1; - v = (PyLongObject *)vv; - i = Py_SIZE(v); - - switch (i) { - case -1: - res = -(sdigit)v->ob_digit[0]; - break; - case 0: - res = 0; - break; - case 1: - res = v->ob_digit[0]; - break; - default: - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) + v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) { - *overflow = sign; - goto exit; - } - } - /* Haven't lost any bits, but casting to long requires extra - * care (see comment above). - */ - if (x <= (unsigned long)LONG_MAX) { - res = (long)x * sign; - } - else if (sign < 0 && x == PY_ABS_LONG_MIN) { - res = LONG_MIN; - } - else { - *overflow = sign; - /* res is already set to -1 */ - } - } - exit: - if (do_decref) { - Py_DECREF(vv); - } - return res; -} - -/* Get a C long int from a long int object. - Returns -1 and sets an error condition if overflow occurs. */ - -long -PyLong_AsLong(PyObject *obj) -{ - int overflow; - long result = PyLong_AsLongAndOverflow(obj, &overflow); - if (overflow) { - /* XXX: could be cute and give a different - message for overflow == -1 */ - PyErr_SetString(PyExc_OverflowError, - "Python int too large to convert to C long"); - } - return result; -} - -/* Get a Py_ssize_t from a long int object. - Returns -1 and sets an error condition if overflow occurs. */ - -Py_ssize_t -PyLong_AsSsize_t(PyObject *vv) { - register PyLongObject *v; - size_t x, prev; - Py_ssize_t i; - int sign; - - if (vv == NULL || !PyLong_Check(vv)) { - PyErr_BadInternalCall(); - return -1; - } - v = (PyLongObject *)vv; - i = v->ob_size; - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) - goto overflow; - } - /* Haven't lost any bits, but casting to a signed type requires - * extra care (see comment above). - */ - if (x <= (size_t)PY_SSIZE_T_MAX) { - return (Py_ssize_t)x * sign; - } - else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) { - return PY_SSIZE_T_MIN; - } - /* else overflow */ - - overflow: - PyErr_SetString(PyExc_OverflowError, - "long int too large to convert to int"); - return -1; -} - -/* Get a C unsigned long int from a long int object. - Returns -1 and sets an error condition if overflow occurs. */ - -unsigned long -PyLong_AsUnsignedLong(PyObject *vv) -{ - register PyLongObject *v; - unsigned long x, prev; - Py_ssize_t i; - - if (vv == NULL || !PyLong_Check(vv)) { - if (vv != NULL && PyInt_Check(vv)) { - long val = PyInt_AsLong(vv); - if (val < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value " - "to unsigned long"); - return (unsigned long) -1; - } - return val; - } - PyErr_BadInternalCall(); - return (unsigned long) -1; - } - v = (PyLongObject *)vv; - i = Py_SIZE(v); - x = 0; - if (i < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long) -1; - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) { - PyErr_SetString(PyExc_OverflowError, - "long int too large to convert"); - return (unsigned long) -1; - } - } - return x; -} - -/* Get a C unsigned long int from a long int object, ignoring the high bits. - Returns -1 and sets an error condition if an error occurs. */ - -unsigned long -PyLong_AsUnsignedLongMask(PyObject *vv) -{ - register PyLongObject *v; - unsigned long x; - Py_ssize_t i; - int sign; - - if (vv == NULL || !PyLong_Check(vv)) { - if (vv != NULL && PyInt_Check(vv)) - return PyInt_AsUnsignedLongMask(vv); - PyErr_BadInternalCall(); - return (unsigned long) -1; - } - v = (PyLongObject *)vv; - i = v->ob_size; - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -i; - } - while (--i >= 0) { - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - } - return x * sign; -} - -int -_PyLong_Sign(PyObject *vv) -{ - PyLongObject *v = (PyLongObject *)vv; - - assert(v != NULL); - assert(PyLong_Check(v)); - - return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1); -} - -size_t -_PyLong_NumBits(PyObject *vv) -{ - PyLongObject *v = (PyLongObject *)vv; - size_t result = 0; - Py_ssize_t ndigits; - - assert(v != NULL); - assert(PyLong_Check(v)); - ndigits = ABS(Py_SIZE(v)); - assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); - if (ndigits > 0) { - digit msd = v->ob_digit[ndigits - 1]; - - result = (ndigits - 1) * PyLong_SHIFT; - if (result / PyLong_SHIFT != (size_t)(ndigits - 1)) - goto Overflow; - do { - ++result; - if (result == 0) - goto Overflow; - msd >>= 1; - } while (msd); - } - return result; - - Overflow: - PyErr_SetString(PyExc_OverflowError, "long has too many bits " - "to express in a platform size_t"); - return (size_t)-1; -} - -PyObject * -_PyLong_FromByteArray(const unsigned char* bytes, size_t n, - int little_endian, int is_signed) -{ - const unsigned char* pstartbyte; /* LSB of bytes */ - int incr; /* direction to move pstartbyte */ - const unsigned char* pendbyte; /* MSB of bytes */ - size_t numsignificantbytes; /* number of bytes that matter */ - Py_ssize_t ndigits; /* number of Python long digits */ - PyLongObject* v; /* result */ - Py_ssize_t idigit = 0; /* next free index in v->ob_digit */ - - if (n == 0) - return PyLong_FromLong(0L); - - if (little_endian) { - pstartbyte = bytes; - pendbyte = bytes + n - 1; - incr = 1; - } - else { - pstartbyte = bytes + n - 1; - pendbyte = bytes; - incr = -1; - } - - if (is_signed) - is_signed = *pendbyte >= 0x80; - - /* Compute numsignificantbytes. This consists of finding the most - significant byte. Leading 0 bytes are insignificant if the number - is positive, and leading 0xff bytes if negative. */ - { - size_t i; - const unsigned char* p = pendbyte; - const int pincr = -incr; /* search MSB to LSB */ - const unsigned char insignficant = is_signed ? 0xff : 0x00; - - for (i = 0; i < n; ++i, p += pincr) { - if (*p != insignficant) - break; - } - numsignificantbytes = n - i; - /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so - actually has 2 significant bytes. OTOH, 0xff0001 == - -0x00ffff, so we wouldn't *need* to bump it there; but we - do for 0xffff = -0x0001. To be safe without bothering to - check every case, bump it regardless. */ - if (is_signed && numsignificantbytes < n) - ++numsignificantbytes; - } - - /* How many Python long digits do we need? We have - 8*numsignificantbytes bits, and each Python long digit has - PyLong_SHIFT bits, so it's the ceiling of the quotient. */ - /* catch overflow before it happens */ - if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) { - PyErr_SetString(PyExc_OverflowError, - "byte array too long to convert to int"); - return NULL; - } - ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT; - v = _PyLong_New(ndigits); - if (v == NULL) - return NULL; - - /* Copy the bits over. The tricky parts are computing 2's-comp on - the fly for signed numbers, and dealing with the mismatch between - 8-bit bytes and (probably) 15-bit Python digits.*/ - { - size_t i; - twodigits carry = 1; /* for 2's-comp calculation */ - twodigits accum = 0; /* sliding register */ - unsigned int accumbits = 0; /* number of bits in accum */ - const unsigned char* p = pstartbyte; - - for (i = 0; i < numsignificantbytes; ++i, p += incr) { - twodigits thisbyte = *p; - /* Compute correction for 2's comp, if needed. */ - if (is_signed) { - thisbyte = (0xff ^ thisbyte) + carry; - carry = thisbyte >> 8; - thisbyte &= 0xff; - } - /* Because we're going LSB to MSB, thisbyte is - more significant than what's already in accum, - so needs to be prepended to accum. */ - accum |= (twodigits)thisbyte << accumbits; - accumbits += 8; - if (accumbits >= PyLong_SHIFT) { - /* There's enough to fill a Python digit. */ - assert(idigit < ndigits); - v->ob_digit[idigit] = (digit)(accum & PyLong_MASK); - ++idigit; - accum >>= PyLong_SHIFT; - accumbits -= PyLong_SHIFT; - assert(accumbits < PyLong_SHIFT); - } - } - assert(accumbits < PyLong_SHIFT); - if (accumbits) { - assert(idigit < ndigits); - v->ob_digit[idigit] = (digit)accum; - ++idigit; - } - } - - Py_SIZE(v) = is_signed ? -idigit : idigit; - return (PyObject *)long_normalize(v); -} - -int -_PyLong_AsByteArray(PyLongObject* v, - unsigned char* bytes, size_t n, - int little_endian, int is_signed) -{ - Py_ssize_t i; /* index into v->ob_digit */ - Py_ssize_t ndigits; /* |v->ob_size| */ - twodigits accum; /* sliding register */ - unsigned int accumbits; /* # bits in accum */ - int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */ - digit carry; /* for computing 2's-comp */ - size_t j; /* # bytes filled */ - unsigned char* p; /* pointer to next byte in bytes */ - int pincr; /* direction to move p */ - - assert(v != NULL && PyLong_Check(v)); - - if (Py_SIZE(v) < 0) { - ndigits = -(Py_SIZE(v)); - if (!is_signed) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative long to unsigned"); - return -1; - } - do_twos_comp = 1; - } - else { - ndigits = Py_SIZE(v); - do_twos_comp = 0; - } - - if (little_endian) { - p = bytes; - pincr = 1; - } - else { - p = bytes + n - 1; - pincr = -1; - } - - /* Copy over all the Python digits. - It's crucial that every Python digit except for the MSD contribute - exactly PyLong_SHIFT bits to the total, so first assert that the long is - normalized. */ - assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); - j = 0; - accum = 0; - accumbits = 0; - carry = do_twos_comp ? 1 : 0; - for (i = 0; i < ndigits; ++i) { - digit thisdigit = v->ob_digit[i]; - if (do_twos_comp) { - thisdigit = (thisdigit ^ PyLong_MASK) + carry; - carry = thisdigit >> PyLong_SHIFT; - thisdigit &= PyLong_MASK; - } - /* Because we're going LSB to MSB, thisdigit is more - significant than what's already in accum, so needs to be - prepended to accum. */ - accum |= (twodigits)thisdigit << accumbits; - - /* The most-significant digit may be (probably is) at least - partly empty. */ - if (i == ndigits - 1) { - /* Count # of sign bits -- they needn't be stored, - * although for signed conversion we need later to - * make sure at least one sign bit gets stored. */ - digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit; - while (s != 0) { - s >>= 1; - accumbits++; - } - } - else - accumbits += PyLong_SHIFT; - - /* Store as many bytes as possible. */ - while (accumbits >= 8) { - if (j >= n) - goto Overflow; - ++j; - *p = (unsigned char)(accum & 0xff); - p += pincr; - accumbits -= 8; - accum >>= 8; - } - } - - /* Store the straggler (if any). */ - assert(accumbits < 8); - assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */ - if (accumbits > 0) { - if (j >= n) - goto Overflow; - ++j; - if (do_twos_comp) { - /* Fill leading bits of the byte with sign bits - (appropriately pretending that the long had an - infinite supply of sign bits). */ - accum |= (~(twodigits)0) << accumbits; - } - *p = (unsigned char)(accum & 0xff); - p += pincr; - } - else if (j == n && n > 0 && is_signed) { - /* The main loop filled the byte array exactly, so the code - just above didn't get to ensure there's a sign bit, and the - loop below wouldn't add one either. Make sure a sign bit - exists. */ - unsigned char msb = *(p - pincr); - int sign_bit_set = msb >= 0x80; - assert(accumbits == 0); - if (sign_bit_set == do_twos_comp) - return 0; - else - goto Overflow; - } - - /* Fill remaining bytes with copies of the sign bit. */ - { - unsigned char signbyte = do_twos_comp ? 0xffU : 0U; - for ( ; j < n; ++j, p += pincr) - *p = signbyte; - } - - return 0; - - Overflow: - PyErr_SetString(PyExc_OverflowError, "long too big to convert"); - return -1; - -} - -/* Create a new long (or int) object from a C pointer */ - -PyObject * -PyLong_FromVoidPtr(void *p) -{ -#if SIZEOF_VOID_P <= SIZEOF_LONG - if ((long)p < 0) - return PyLong_FromUnsignedLong((unsigned long)p); - return PyInt_FromLong((long)p); -#else - -#ifndef HAVE_LONG_LONG -# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long" -#endif -#if SIZEOF_LONG_LONG < SIZEOF_VOID_P -# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)" -#endif - /* optimize null pointers */ - if (p == NULL) - return PyInt_FromLong(0); - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p); - -#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */ -} - -/* Get a C pointer from a long object (or an int object in some cases) */ - -void * -PyLong_AsVoidPtr(PyObject *vv) -{ - /* This function will allow int or long objects. If vv is neither, - then the PyLong_AsLong*() functions will raise the exception: - PyExc_SystemError, "bad argument to internal function" - */ -#if SIZEOF_VOID_P <= SIZEOF_LONG - long x; - - if (PyInt_Check(vv)) - x = PyInt_AS_LONG(vv); - else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) - x = PyLong_AsLong(vv); - else - x = PyLong_AsUnsignedLong(vv); -#else - -#ifndef HAVE_LONG_LONG -# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long" -#endif -#if SIZEOF_LONG_LONG < SIZEOF_VOID_P -# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)" -#endif - PY_LONG_LONG x; - - if (PyInt_Check(vv)) - x = PyInt_AS_LONG(vv); - else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) - x = PyLong_AsLongLong(vv); - else - x = PyLong_AsUnsignedLongLong(vv); - -#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */ - - if (x == -1 && PyErr_Occurred()) - return NULL; - return (void *)x; -} - -#ifdef HAVE_LONG_LONG - -/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later - * rewritten to use the newer PyLong_{As,From}ByteArray API. - */ - -#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one -#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN) - -/* Create a new long int object from a C PY_LONG_LONG int. */ - -PyObject * -PyLong_FromLongLong(PY_LONG_LONG ival) -{ - PyLongObject *v; - unsigned PY_LONG_LONG abs_ival; - unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */ - int ndigits = 0; - int negative = 0; - - if (ival < 0) { - /* avoid signed overflow on negation; see comments - in PyLong_FromLong above. */ - abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1; - negative = 1; - } - else { - abs_ival = (unsigned PY_LONG_LONG)ival; - } - - /* Count the number of Python digits. - We used to pick 5 ("big enough for anything"), but that's a - waste of time and space given that 5*15 = 75 bits are rarely - needed. */ - t = abs_ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = negative ? -ndigits : ndigits; - t = abs_ival; - while (t) { - *p++ = (digit)(t & PyLong_MASK); - t >>= PyLong_SHIFT; - } - } - return (PyObject *)v; -} - -/* Create a new long int object from a C unsigned PY_LONG_LONG int. */ - -PyObject * -PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival) -{ - PyLongObject *v; - unsigned PY_LONG_LONG t; - int ndigits = 0; - - /* Count the number of Python digits. */ - t = (unsigned PY_LONG_LONG)ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = ndigits; - while (ival) { - *p++ = (digit)(ival & PyLong_MASK); - ival >>= PyLong_SHIFT; - } - } - return (PyObject *)v; -} - -/* Create a new long int object from a C Py_ssize_t. */ - -PyObject * -PyLong_FromSsize_t(Py_ssize_t ival) -{ - Py_ssize_t bytes = ival; - int one = 1; - return _PyLong_FromByteArray((unsigned char *)&bytes, - SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1); -} - -/* Create a new long int object from a C size_t. */ - -PyObject * -PyLong_FromSize_t(size_t ival) -{ - size_t bytes = ival; - int one = 1; - return _PyLong_FromByteArray((unsigned char *)&bytes, - SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0); -} - -/* Get a C PY_LONG_LONG int from a long int object. - Return -1 and set an error if overflow occurs. */ - -PY_LONG_LONG -PyLong_AsLongLong(PyObject *vv) -{ - PY_LONG_LONG bytes; - int one = 1; - int res; - - if (vv == NULL) { - PyErr_BadInternalCall(); - return -1; - } - if (!PyLong_Check(vv)) { - PyNumberMethods *nb; - PyObject *io; - if (PyInt_Check(vv)) - return (PY_LONG_LONG)PyInt_AsLong(vv); - if ((nb = vv->ob_type->tp_as_number) == NULL || - nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return -1; - } - io = (*nb->nb_int) (vv); - if (io == NULL) - return -1; - if (PyInt_Check(io)) { - bytes = PyInt_AsLong(io); - Py_DECREF(io); - return bytes; - } - if (PyLong_Check(io)) { - bytes = PyLong_AsLongLong(io); - Py_DECREF(io); - return bytes; - } - Py_DECREF(io); - PyErr_SetString(PyExc_TypeError, "integer conversion failed"); - return -1; - } - - res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes, - SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1); - - /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ - if (res < 0) - return (PY_LONG_LONG)-1; - else - return bytes; -} - -/* Get a C unsigned PY_LONG_LONG int from a long int object. - Return -1 and set an error if overflow occurs. */ - -unsigned PY_LONG_LONG -PyLong_AsUnsignedLongLong(PyObject *vv) -{ - unsigned PY_LONG_LONG bytes; - int one = 1; - int res; - - if (vv == NULL || !PyLong_Check(vv)) { - PyErr_BadInternalCall(); - return (unsigned PY_LONG_LONG)-1; - } - - res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes, - SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0); - - /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ - if (res < 0) - return (unsigned PY_LONG_LONG)res; - else - return bytes; -} - -/* Get a C unsigned long int from a long int object, ignoring the high bits. - Returns -1 and sets an error condition if an error occurs. */ - -unsigned PY_LONG_LONG -PyLong_AsUnsignedLongLongMask(PyObject *vv) -{ - register PyLongObject *v; - unsigned PY_LONG_LONG x; - Py_ssize_t i; - int sign; - - if (vv == NULL || !PyLong_Check(vv)) { - PyErr_BadInternalCall(); - return (unsigned long) -1; - } - v = (PyLongObject *)vv; - i = v->ob_size; - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -i; - } - while (--i >= 0) { - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - } - return x * sign; -} - -/* Get a C long long int from a Python long or Python int object. - On overflow, returns -1 and sets *overflow to 1 or -1 depending - on the sign of the result. Otherwise *overflow is 0. - - For other errors (e.g., type error), returns -1 and sets an error - condition. -*/ - -PY_LONG_LONG -PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow) -{ - /* This version by Tim Peters */ - register PyLongObject *v; - unsigned PY_LONG_LONG x, prev; - PY_LONG_LONG res; - Py_ssize_t i; - int sign; - int do_decref = 0; /* if nb_int was called */ - - *overflow = 0; - if (vv == NULL) { - PyErr_BadInternalCall(); - return -1; - } - - if (PyInt_Check(vv)) - return PyInt_AsLong(vv); - - if (!PyLong_Check(vv)) { - PyNumberMethods *nb; - nb = vv->ob_type->tp_as_number; - if (nb == NULL || nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - return -1; - } - vv = (*nb->nb_int) (vv); - if (vv == NULL) - return -1; - do_decref = 1; - if(PyInt_Check(vv)) { - res = PyInt_AsLong(vv); - goto exit; - } - if (!PyLong_Check(vv)) { - Py_DECREF(vv); - PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); - return -1; - } - } - - res = -1; - v = (PyLongObject *)vv; - i = Py_SIZE(v); - - switch (i) { - case -1: - res = -(sdigit)v->ob_digit[0]; - break; - case 0: - res = 0; - break; - case 1: - res = v->ob_digit[0]; - break; - default: - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) + v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) { - *overflow = sign; - goto exit; - } - } - /* Haven't lost any bits, but casting to long requires extra - * care (see comment above). - */ - if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) { - res = (PY_LONG_LONG)x * sign; - } - else if (sign < 0 && x == PY_ABS_LLONG_MIN) { - res = PY_LLONG_MIN; - } - else { - *overflow = sign; - /* res is already set to -1 */ - } - } - exit: - if (do_decref) { - Py_DECREF(vv); - } - return res; -} - -#undef IS_LITTLE_ENDIAN - -#endif /* HAVE_LONG_LONG */ - - -static int -convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) { - if (PyLong_Check(v)) { - *a = (PyLongObject *) v; - Py_INCREF(v); - } - else if (PyInt_Check(v)) { - *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v)); - } - else { - return 0; - } - if (PyLong_Check(w)) { - *b = (PyLongObject *) w; - Py_INCREF(w); - } - else if (PyInt_Check(w)) { - *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w)); - } - else { - Py_DECREF(*a); - return 0; - } - return 1; -} - -#define CONVERT_BINOP(v, w, a, b) \ - do { \ - if (!convert_binop(v, w, a, b)) { \ - Py_INCREF(Py_NotImplemented); \ - return Py_NotImplemented; \ - } \ - } while(0) \ - -/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d < - 2**k if d is nonzero, else 0. */ - -static const unsigned char BitLengthTable[32] = { - 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 -}; - -static int -bits_in_digit(digit d) -{ - int d_bits = 0; - while (d >= 32) { - d_bits += 6; - d >>= 6; - } - d_bits += (int)BitLengthTable[d]; - return d_bits; -} - -/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n] - * is modified in place, by adding y to it. Carries are propagated as far as - * x[m-1], and the remaining carry (0 or 1) is returned. - */ -static digit -v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n) -{ - Py_ssize_t i; - digit carry = 0; - - assert(m >= n); - for (i = 0; i < n; ++i) { - carry += x[i] + y[i]; - x[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - assert((carry & 1) == carry); - } - for (; carry && i < m; ++i) { - carry += x[i]; - x[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - assert((carry & 1) == carry); - } - return carry; -} - -/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n] - * is modified in place, by subtracting y from it. Borrows are propagated as - * far as x[m-1], and the remaining borrow (0 or 1) is returned. - */ -static digit -v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n) -{ - Py_ssize_t i; - digit borrow = 0; - - assert(m >= n); - for (i = 0; i < n; ++i) { - borrow = x[i] - y[i] - borrow; - x[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; /* keep only 1 sign bit */ - } - for (; borrow && i < m; ++i) { - borrow = x[i] - borrow; - x[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; - } - return borrow; -} - -/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put - * result in z[0:m], and return the d bits shifted out of the top. - */ -static digit -v_lshift(digit *z, digit *a, Py_ssize_t m, int d) -{ - Py_ssize_t i; - digit carry = 0; - - assert(0 <= d && d < PyLong_SHIFT); - for (i=0; i < m; i++) { - twodigits acc = (twodigits)a[i] << d | carry; - z[i] = (digit)acc & PyLong_MASK; - carry = (digit)(acc >> PyLong_SHIFT); - } - return carry; -} - -/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put - * result in z[0:m], and return the d bits shifted out of the bottom. - */ -static digit -v_rshift(digit *z, digit *a, Py_ssize_t m, int d) -{ - Py_ssize_t i; - digit carry = 0; - digit mask = ((digit)1 << d) - 1U; - - assert(0 <= d && d < PyLong_SHIFT); - for (i=m; i-- > 0;) { - twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i]; - carry = (digit)acc & mask; - z[i] = (digit)(acc >> d); - } - return carry; -} - -/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient - in pout, and returning the remainder. pin and pout point at the LSD. - It's OK for pin == pout on entry, which saves oodles of mallocs/frees in - _PyLong_Format, but that should be done with great care since longs are - immutable. */ - -static digit -inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n) -{ - twodigits rem = 0; - - assert(n > 0 && n <= PyLong_MASK); - pin += size; - pout += size; - while (--size >= 0) { - digit hi; - rem = (rem << PyLong_SHIFT) | *--pin; - *--pout = hi = (digit)(rem / n); - rem -= (twodigits)hi * n; - } - return (digit)rem; -} - -/* Divide a long integer by a digit, returning both the quotient - (as function result) and the remainder (through *prem). - The sign of a is ignored; n should not be zero. */ - -static PyLongObject * -divrem1(PyLongObject *a, digit n, digit *prem) -{ - const Py_ssize_t size = ABS(Py_SIZE(a)); - PyLongObject *z; - - assert(n > 0 && n <= PyLong_MASK); - z = _PyLong_New(size); - if (z == NULL) - return NULL; - *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n); - return long_normalize(z); -} - -/* Convert a long integer to a base 10 string. Returns a new non-shared - string. (Return value is non-shared so that callers can modify the - returned value if necessary.) */ - -static PyObject * -long_to_decimal_string(PyObject *aa, int addL) -{ - PyLongObject *scratch, *a; - PyObject *str; - Py_ssize_t size, strlen, size_a, i, j; - digit *pout, *pin, rem, tenpow; - char *p; - int negative; - - a = (PyLongObject *)aa; - if (a == NULL || !PyLong_Check(a)) { - PyErr_BadInternalCall(); - return NULL; - } - size_a = ABS(Py_SIZE(a)); - negative = Py_SIZE(a) < 0; - - /* quick and dirty upper bound for the number of digits - required to express a in base _PyLong_DECIMAL_BASE: - - #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE)) - - But log2(a) < size_a * PyLong_SHIFT, and - log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT - > 3 * _PyLong_DECIMAL_SHIFT - */ - if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) { - PyErr_SetString(PyExc_OverflowError, - "long is too large to format"); - return NULL; - } - /* the expression size_a * PyLong_SHIFT is now safe from overflow */ - size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT); - scratch = _PyLong_New(size); - if (scratch == NULL) - return NULL; - - /* convert array of base _PyLong_BASE digits in pin to an array of - base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP, - Volume 2 (3rd edn), section 4.4, Method 1b). */ - pin = a->ob_digit; - pout = scratch->ob_digit; - size = 0; - for (i = size_a; --i >= 0; ) { - digit hi = pin[i]; - for (j = 0; j < size; j++) { - twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi; - hi = (digit)(z / _PyLong_DECIMAL_BASE); - pout[j] = (digit)(z - (twodigits)hi * - _PyLong_DECIMAL_BASE); - } - while (hi) { - pout[size++] = hi % _PyLong_DECIMAL_BASE; - hi /= _PyLong_DECIMAL_BASE; - } - /* check for keyboard interrupt */ - SIGCHECK({ - Py_DECREF(scratch); - return NULL; - }); - } - /* pout should have at least one digit, so that the case when a = 0 - works correctly */ - if (size == 0) - pout[size++] = 0; - - /* calculate exact length of output string, and allocate */ - strlen = (addL != 0) + negative + - 1 + (size - 1) * _PyLong_DECIMAL_SHIFT; - tenpow = 10; - rem = pout[size-1]; - while (rem >= tenpow) { - tenpow *= 10; - strlen++; - } - str = PyString_FromStringAndSize(NULL, strlen); - if (str == NULL) { - Py_DECREF(scratch); - return NULL; - } - - /* fill the string right-to-left */ - p = PyString_AS_STRING(str) + strlen; - *p = '\0'; - if (addL) - *--p = 'L'; - /* pout[0] through pout[size-2] contribute exactly - _PyLong_DECIMAL_SHIFT digits each */ - for (i=0; i < size - 1; i++) { - rem = pout[i]; - for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { - *--p = '0' + rem % 10; - rem /= 10; - } - } - /* pout[size-1]: always produce at least one decimal digit */ - rem = pout[i]; - do { - *--p = '0' + rem % 10; - rem /= 10; - } while (rem != 0); - - /* and sign */ - if (negative) - *--p = '-'; - - /* check we've counted correctly */ - assert(p == PyString_AS_STRING(str)); - Py_DECREF(scratch); - return (PyObject *)str; -} - -/* 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) -{ - register PyLongObject *a = (PyLongObject *)aa; - PyStringObject *str; - Py_ssize_t i, sz; - Py_ssize_t size_a; - char *p; - int bits; - char sign = '\0'; - - if (base == 10) - return long_to_decimal_string((PyObject *)a, addL); - - if (a == NULL || !PyLong_Check(a)) { - PyErr_BadInternalCall(); - return NULL; - } - assert(base >= 2 && base <= 36); - size_a = ABS(Py_SIZE(a)); - - /* Compute a rough upper bound for the length of the string */ - i = base; - bits = 0; - while (i > 1) { - ++bits; - i >>= 1; - } - i = 5 + (addL ? 1 : 0); - /* ensure we don't get signed overflow in sz calculation */ - if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) { - PyErr_SetString(PyExc_OverflowError, - "long is too large to format"); - return NULL; - } - sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits; - assert(sz >= 0); - str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz); - if (str == NULL) - return NULL; - p = PyString_AS_STRING(str) + sz; - *p = '\0'; - if (addL) - *--p = 'L'; - if (a->ob_size < 0) - sign = '-'; - - if (a->ob_size == 0) { - *--p = '0'; - } - else if ((base & (base - 1)) == 0) { - /* JRH: special case for power-of-2 bases */ - twodigits accum = 0; - int accumbits = 0; /* # of bits in accum */ - int basebits = 1; /* # of bits in base-1 */ - i = base; - while ((i >>= 1) > 1) - ++basebits; - - for (i = 0; i < size_a; ++i) { - accum |= (twodigits)a->ob_digit[i] << accumbits; - accumbits += PyLong_SHIFT; - assert(accumbits >= basebits); - do { - char cdigit = (char)(accum & (base - 1)); - cdigit += (cdigit < 10) ? '0' : 'a'-10; - assert(p > PyString_AS_STRING(str)); - *--p = cdigit; - accumbits -= basebits; - accum >>= basebits; - } while (i < size_a-1 ? accumbits >= basebits : accum > 0); - } - } - else { - /* Not 0, and base not a power of 2. Divide repeatedly by - base, but for speed use the highest power of base that - fits in a digit. */ - Py_ssize_t size = size_a; - digit *pin = a->ob_digit; - PyLongObject *scratch; - /* powbasw <- largest power of base that fits in a digit. */ - digit powbase = base; /* powbase == base ** power */ - int power = 1; - for (;;) { - twodigits newpow = powbase * (twodigits)base; - if (newpow >> PyLong_SHIFT) - /* doesn't fit in a digit */ - break; - powbase = (digit)newpow; - ++power; - } - - /* Get a scratch area for repeated division. */ - scratch = _PyLong_New(size); - if (scratch == NULL) { - Py_DECREF(str); - return NULL; - } - - /* Repeatedly divide by powbase. */ - do { - int ntostore = power; - digit rem = inplace_divrem1(scratch->ob_digit, - pin, size, powbase); - pin = scratch->ob_digit; /* no need to use a again */ - if (pin[size - 1] == 0) - --size; - SIGCHECK({ - Py_DECREF(scratch); - Py_DECREF(str); - return NULL; - }); - - /* Break rem into digits. */ - assert(ntostore > 0); - do { - digit nextrem = (digit)(rem / base); - char c = (char)(rem - nextrem * base); - assert(p > PyString_AS_STRING(str)); - c += (c < 10) ? '0' : 'a'-10; - *--p = c; - rem = nextrem; - --ntostore; - /* Termination is a bit delicate: must not - store leading zeroes, so must get out if - remaining quotient and rem are both 0. */ - } while (ntostore && (size || rem)); - } while (size != 0); - Py_DECREF(scratch); - } - - if (base == 2) { - *--p = 'b'; - *--p = '0'; - } - else if (base == 8) { - if (newstyle) { - *--p = 'o'; - *--p = '0'; - } - else - if (size_a != 0) - *--p = '0'; - } - else if (base == 16) { - *--p = 'x'; - *--p = '0'; - } - else if (base != 10) { - *--p = '#'; - *--p = '0' + base%10; - if (base > 10) - *--p = '0' + base/10; - } - if (sign) - *--p = sign; - if (p != PyString_AS_STRING(str)) { - char *q = PyString_AS_STRING(str); - assert(p > q); - do { - } while ((*q++ = *p++) != '\0'); - q--; - _PyString_Resize((PyObject **)&str, - (Py_ssize_t) (q - PyString_AS_STRING(str))); - } - return (PyObject *)str; -} - -/* Table of digit values for 8-bit string -> integer conversion. - * '0' maps to 0, ..., '9' maps to 9. - * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35. - * All other indices map to 37. - * Note that when converting a base B string, a char c is a legitimate - * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B. - */ -int _PyLong_DigitValue[256] = { - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37, - 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, - 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, -}; - -/* *str points to the first digit in a string of base `base` digits. base - * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first - * non-digit (which may be *str!). A normalized long is returned. - * The point to this routine is that it takes time linear in the number of - * string characters. - */ -static PyLongObject * -long_from_binary_base(char **str, int base) -{ - char *p = *str; - char *start = p; - int bits_per_char; - Py_ssize_t n; - PyLongObject *z; - twodigits accum; - int bits_in_accum; - digit *pdigit; - - assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0); - n = base; - for (bits_per_char = -1; n; ++bits_per_char) - n >>= 1; - /* n <- total # of bits needed, while setting p to end-of-string */ - while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base) - ++p; - *str = p; - /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */ - n = (p - start) * bits_per_char + PyLong_SHIFT - 1; - if (n / bits_per_char < p - start) { - PyErr_SetString(PyExc_ValueError, - "long string too large to convert"); - return NULL; - } - n = n / PyLong_SHIFT; - z = _PyLong_New(n); - if (z == NULL) - return NULL; - /* Read string from right, and fill in long from left; i.e., - * from least to most significant in both. - */ - accum = 0; - bits_in_accum = 0; - pdigit = z->ob_digit; - while (--p >= start) { - int k = _PyLong_DigitValue[Py_CHARMASK(*p)]; - assert(k >= 0 && k < base); - accum |= (twodigits)k << bits_in_accum; - bits_in_accum += bits_per_char; - if (bits_in_accum >= PyLong_SHIFT) { - *pdigit++ = (digit)(accum & PyLong_MASK); - assert(pdigit - z->ob_digit <= n); - accum >>= PyLong_SHIFT; - bits_in_accum -= PyLong_SHIFT; - assert(bits_in_accum < PyLong_SHIFT); - } - } - if (bits_in_accum) { - assert(bits_in_accum <= PyLong_SHIFT); - *pdigit++ = (digit)accum; - assert(pdigit - z->ob_digit <= n); - } - while (pdigit - z->ob_digit < n) - *pdigit++ = 0; - return long_normalize(z); -} - -PyObject * -PyLong_FromString(char *str, char **pend, int base) -{ - int sign = 1; - char *start, *orig_str = str; - PyLongObject *z; - PyObject *strobj, *strrepr; - Py_ssize_t slen; - - if ((base != 0 && base < 2) || base > 36) { - PyErr_SetString(PyExc_ValueError, - "long() arg 2 must be >= 2 and <= 36"); - return NULL; - } - while (*str != '\0' && isspace(Py_CHARMASK(*str))) - str++; - if (*str == '+') - ++str; - else if (*str == '-') { - ++str; - sign = -1; - } - while (*str != '\0' && isspace(Py_CHARMASK(*str))) - str++; - if (base == 0) { - /* No base given. Deduce the base from the contents - of the string */ - if (str[0] != '0') - base = 10; - else if (str[1] == 'x' || str[1] == 'X') - base = 16; - else if (str[1] == 'o' || str[1] == 'O') - base = 8; - else if (str[1] == 'b' || str[1] == 'B') - base = 2; - else - /* "old" (C-style) octal literal, still valid in - 2.x, although illegal in 3.x */ - base = 8; - } - /* Whether or not we were deducing the base, skip leading chars - as needed */ - if (str[0] == '0' && - ((base == 16 && (str[1] == 'x' || str[1] == 'X')) || - (base == 8 && (str[1] == 'o' || str[1] == 'O')) || - (base == 2 && (str[1] == 'b' || str[1] == 'B')))) - str += 2; - - start = str; - if ((base & (base - 1)) == 0) - z = long_from_binary_base(&str, base); - else { -/*** -Binary bases can be converted in time linear in the number of digits, because -Python's representation base is binary. Other bases (including decimal!) use -the simple quadratic-time algorithm below, complicated by some speed tricks. - -First some math: the largest integer that can be expressed in N base-B digits -is B**N-1. Consequently, if we have an N-digit input in base B, the worst- -case number of Python digits needed to hold it is the smallest integer n s.t. - - PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides] - PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE] - n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE) - -The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so -we can compute this quickly. A Python long with that much space is reserved -near the start, and the result is computed into it. - -The input string is actually treated as being in base base**i (i.e., i digits -are processed at a time), where two more static arrays hold: - - convwidth_base[base] = the largest integer i such that - base**i <= PyLong_BASE - convmultmax_base[base] = base ** convwidth_base[base] - -The first of these is the largest i such that i consecutive input digits -must fit in a single Python digit. The second is effectively the input -base we're really using. - -Viewing the input as a sequence of digits in base -convmultmax_base[base], the result is "simply" - - (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1 - -where B = convmultmax_base[base]. - -Error analysis: as above, the number of Python digits `n` needed is worst- -case - - n >= N * log(B)/log(PyLong_BASE) - -where `N` is the number of input digits in base `B`. This is computed via - - size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1; - -below. Two numeric concerns are how much space this can waste, and whether -the computed result can be too small. To be concrete, assume PyLong_BASE = -2**15, which is the default (and it's unlikely anyone changes that). - -Waste isn't a problem: provided the first input digit isn't 0, the difference -between the worst-case input with N digits and the smallest input with N -digits is about a factor of B, but B is small compared to PyLong_BASE so at -most one allocated Python digit can remain unused on that count. If -N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating -that and adding 1 returns a result 1 larger than necessary. However, that -can't happen: whenever B is a power of 2, long_from_binary_base() is called -instead, and it's impossible for B**i to be an integer power of 2**15 when B -is not a power of 2 (i.e., it's impossible for N*log(B)/log(PyLong_BASE) to be -an exact integer when B is not a power of 2, since B**i has a prime factor -other than 2 in that case, but (2**15)**j's only prime factor is 2). - -The computed result can be too small if the true value of -N*log(B)/log(PyLong_BASE) is a little bit larger than an exact integer, but -due to roundoff errors (in computing log(B), log(PyLong_BASE), their quotient, -and/or multiplying that by N) yields a numeric result a little less than that -integer. Unfortunately, "how close can a transcendental function get to an -integer over some range?" questions are generally theoretically intractable. -Computer analysis via continued fractions is practical: expand -log(B)/log(PyLong_BASE) via continued fractions, giving a sequence i/j of "the -best" rational approximations. Then j*log(B)/log(PyLong_BASE) is -approximately equal to (the integer) i. This shows that we can get very close -to being in trouble, but very rarely. For example, 76573 is a denominator in -one of the continued-fraction approximations to log(10)/log(2**15), and -indeed: - - >>> log(10)/log(2**15)*76573 - 16958.000000654003 - -is very close to an integer. If we were working with IEEE single-precision, -rounding errors could kill us. Finding worst cases in IEEE double-precision -requires better-than-double-precision log() functions, and Tim didn't bother. -Instead the code checks to see whether the allocated space is enough as each -new Python digit is added, and copies the whole thing to a larger long if not. -This should happen extremely rarely, and in fact I don't have a test case -that triggers it(!). Instead the code was tested by artificially allocating -just 1 digit at the start, so that the copying code was exercised for every -digit beyond the first. -***/ - register twodigits c; /* current input character */ - Py_ssize_t size_z; - int i; - int convwidth; - twodigits convmultmax, convmult; - digit *pz, *pzstop; - char* scan; - - static double log_base_PyLong_BASE[37] = {0.0e0,}; - static int convwidth_base[37] = {0,}; - static twodigits convmultmax_base[37] = {0,}; - - if (log_base_PyLong_BASE[base] == 0.0) { - twodigits convmax = base; - int i = 1; - - log_base_PyLong_BASE[base] = (log((double)base) / - log((double)PyLong_BASE)); - for (;;) { - twodigits next = convmax * base; - if (next > PyLong_BASE) - break; - convmax = next; - ++i; - } - convmultmax_base[base] = convmax; - assert(i > 0); - convwidth_base[base] = i; - } - - /* Find length of the string of numeric characters. */ - scan = str; - while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base) - ++scan; - - /* Create a long object that can contain the largest possible - * integer with this base and length. Note that there's no - * need to initialize z->ob_digit -- no slot is read up before - * being stored into. - */ - size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1; - /* Uncomment next line to test exceedingly rare copy code */ - /* size_z = 1; */ - assert(size_z > 0); - z = _PyLong_New(size_z); - if (z == NULL) - return NULL; - Py_SIZE(z) = 0; - - /* `convwidth` consecutive input digits are treated as a single - * digit in base `convmultmax`. - */ - convwidth = convwidth_base[base]; - convmultmax = convmultmax_base[base]; - - /* Work ;-) */ - while (str < scan) { - /* grab up to convwidth digits from the input string */ - c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)]; - for (i = 1; i < convwidth && str != scan; ++i, ++str) { - c = (twodigits)(c * base + - _PyLong_DigitValue[Py_CHARMASK(*str)]); - assert(c < PyLong_BASE); - } - - convmult = convmultmax; - /* Calculate the shift only if we couldn't get - * convwidth digits. - */ - if (i != convwidth) { - convmult = base; - for ( ; i > 1; --i) - convmult *= base; - } - - /* Multiply z by convmult, and add c. */ - pz = z->ob_digit; - pzstop = pz + Py_SIZE(z); - for (; pz < pzstop; ++pz) { - c += (twodigits)*pz * convmult; - *pz = (digit)(c & PyLong_MASK); - c >>= PyLong_SHIFT; - } - /* carry off the current end? */ - if (c) { - assert(c < PyLong_BASE); - if (Py_SIZE(z) < size_z) { - *pz = (digit)c; - ++Py_SIZE(z); - } - else { - PyLongObject *tmp; - /* Extremely rare. Get more space. */ - assert(Py_SIZE(z) == size_z); - tmp = _PyLong_New(size_z + 1); - if (tmp == NULL) { - Py_DECREF(z); - return NULL; - } - memcpy(tmp->ob_digit, - z->ob_digit, - sizeof(digit) * size_z); - Py_DECREF(z); - z = tmp; - z->ob_digit[size_z] = (digit)c; - ++size_z; - } - } - } - } - if (z == NULL) - return NULL; - if (str == start) - goto onError; - if (sign < 0) - Py_SIZE(z) = -(Py_SIZE(z)); - if (*str == 'L' || *str == 'l') - str++; - while (*str && isspace(Py_CHARMASK(*str))) - str++; - if (*str != '\0') - goto onError; - if (pend) - *pend = str; - return (PyObject *) z; - - onError: - Py_XDECREF(z); - slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200; - strobj = PyString_FromStringAndSize(orig_str, slen); - if (strobj == NULL) - return NULL; - strrepr = PyObject_Repr(strobj); - Py_DECREF(strobj); - if (strrepr == NULL) - return NULL; - PyErr_Format(PyExc_ValueError, - "invalid literal for long() with base %d: %s", - base, PyString_AS_STRING(strrepr)); - Py_DECREF(strrepr); - return NULL; -} - -#ifdef Py_USING_UNICODE -PyObject * -PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base) -{ - PyObject *result; - char *buffer = (char *)PyMem_MALLOC(length+1); - - if (buffer == NULL) - return NULL; - - if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) { - PyMem_FREE(buffer); - return NULL; - } - result = PyLong_FromString(buffer, NULL, base); - PyMem_FREE(buffer); - return result; -} -#endif - -/* forward */ -static PyLongObject *x_divrem - (PyLongObject *, PyLongObject *, PyLongObject **); -static PyObject *long_long(PyObject *v); - -/* Long division with remainder, top-level routine */ - -static int -long_divrem(PyLongObject *a, PyLongObject *b, - PyLongObject **pdiv, PyLongObject **prem) -{ - Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); - PyLongObject *z; - - if (size_b == 0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "long division or modulo by zero"); - return -1; - } - if (size_a < size_b || - (size_a == size_b && - a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) { - /* |a| < |b|. */ - *pdiv = _PyLong_New(0); - if (*pdiv == NULL) - return -1; - Py_INCREF(a); - *prem = (PyLongObject *) a; - return 0; - } - if (size_b == 1) { - digit rem = 0; - z = divrem1(a, b->ob_digit[0], &rem); - if (z == NULL) - return -1; - *prem = (PyLongObject *) PyLong_FromLong((long)rem); - if (*prem == NULL) { - Py_DECREF(z); - return -1; - } - } - else { - z = x_divrem(a, b, prem); - if (z == NULL) - return -1; - } - /* Set the signs. - The quotient z has the sign of a*b; - the remainder r has the sign of a, - so a = b*z + r. */ - if ((a->ob_size < 0) != (b->ob_size < 0)) - z->ob_size = -(z->ob_size); - if (a->ob_size < 0 && (*prem)->ob_size != 0) - (*prem)->ob_size = -((*prem)->ob_size); - *pdiv = z; - return 0; -} - -/* Unsigned long division with remainder -- the algorithm. The arguments v1 - and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */ - -static PyLongObject * -x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem) -{ - PyLongObject *v, *w, *a; - Py_ssize_t i, k, size_v, size_w; - int d; - digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak; - twodigits vv; - sdigit zhi; - stwodigits z; - - /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd - edn.), section 4.3.1, Algorithm D], except that we don't explicitly - handle the special case when the initial estimate q for a quotient - digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and - that won't overflow a digit. */ - - /* allocate space; w will also be used to hold the final remainder */ - size_v = ABS(Py_SIZE(v1)); - size_w = ABS(Py_SIZE(w1)); - assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */ - v = _PyLong_New(size_v+1); - if (v == NULL) { - *prem = NULL; - return NULL; - } - w = _PyLong_New(size_w); - if (w == NULL) { - Py_DECREF(v); - *prem = NULL; - return NULL; - } - - /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2. - shift v1 left by the same amount. Results go into w and v. */ - d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]); - carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d); - assert(carry == 0); - carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d); - if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) { - v->ob_digit[size_v] = carry; - size_v++; - } - - /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has - at most (and usually exactly) k = size_v - size_w digits. */ - k = size_v - size_w; - assert(k >= 0); - a = _PyLong_New(k); - if (a == NULL) { - Py_DECREF(w); - Py_DECREF(v); - *prem = NULL; - return NULL; - } - v0 = v->ob_digit; - w0 = w->ob_digit; - wm1 = w0[size_w-1]; - wm2 = w0[size_w-2]; - for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) { - /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving - single-digit quotient q, remainder in vk[0:size_w]. */ - - SIGCHECK({ - Py_DECREF(a); - Py_DECREF(w); - Py_DECREF(v); - *prem = NULL; - return NULL; - }); - - /* estimate quotient digit q; may overestimate by 1 (rare) */ - vtop = vk[size_w]; - assert(vtop <= wm1); - vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1]; - q = (digit)(vv / wm1); - r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */ - while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT) - | vk[size_w-2])) { - --q; - r += wm1; - if (r >= PyLong_BASE) - break; - } - assert(q <= PyLong_BASE); - - /* subtract q*w0[0:size_w] from vk[0:size_w+1] */ - zhi = 0; - for (i = 0; i < size_w; ++i) { - /* invariants: -PyLong_BASE <= -q <= zhi <= 0; - -PyLong_BASE * q <= z < PyLong_BASE */ - z = (sdigit)vk[i] + zhi - - (stwodigits)q * (stwodigits)w0[i]; - vk[i] = (digit)z & PyLong_MASK; - zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits, - z, PyLong_SHIFT); - } - - /* add w back if q was too large (this branch taken rarely) */ - assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0); - if ((sdigit)vtop + zhi < 0) { - carry = 0; - for (i = 0; i < size_w; ++i) { - carry += vk[i] + w0[i]; - vk[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - --q; - } - - /* store quotient digit */ - assert(q < PyLong_BASE); - *--ak = q; - } - - /* unshift remainder; we reuse w to store the result */ - carry = v_rshift(w0, v0, size_w, d); - assert(carry==0); - Py_DECREF(v); - - *prem = long_normalize(w); - return long_normalize(a); -} - -/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <= - abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is - rounded to DBL_MANT_DIG significant bits using round-half-to-even. - If a == 0, return 0.0 and set *e = 0. If the resulting exponent - e is larger than PY_SSIZE_T_MAX, raise OverflowError and return - -1.0. */ - -/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */ -#if DBL_MANT_DIG == 53 -#define EXP2_DBL_MANT_DIG 9007199254740992.0 -#else -#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG)) -#endif - -double -_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e) -{ - Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size; - /* See below for why x_digits is always large enough. */ - digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT]; - double dx; - /* Correction term for round-half-to-even rounding. For a digit x, - "x + half_even_correction[x & 7]" gives x rounded to the nearest - multiple of 4, rounding ties to a multiple of 8. */ - static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1}; - - a_size = ABS(Py_SIZE(a)); - if (a_size == 0) { - /* Special case for 0: significand 0.0, exponent 0. */ - *e = 0; - return 0.0; - } - a_bits = bits_in_digit(a->ob_digit[a_size-1]); - /* The following is an overflow-free version of the check - "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */ - if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 && - (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 || - a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1)) - goto overflow; - a_bits = (a_size - 1) * PyLong_SHIFT + a_bits; - - /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size] - (shifting left if a_bits <= DBL_MANT_DIG + 2). - - Number of digits needed for result: write // for floor division. - Then if shifting left, we end up using - - 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT - - digits. If shifting right, we use - - a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT - - digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with - the inequalities - - m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT - m // PyLong_SHIFT - n // PyLong_SHIFT <= - 1 + (m - n - 1) // PyLong_SHIFT, - - valid for any integers m and n, we find that x_size satisfies - - x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT - - in both cases. - */ - if (a_bits <= DBL_MANT_DIG + 2) { - shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT; - shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT; - x_size = 0; - while (x_size < shift_digits) - x_digits[x_size++] = 0; - rem = v_lshift(x_digits + x_size, a->ob_digit, a_size, - (int)shift_bits); - x_size += a_size; - x_digits[x_size++] = rem; - } - else { - shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT; - shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT; - rem = v_rshift(x_digits, a->ob_digit + shift_digits, - a_size - shift_digits, (int)shift_bits); - x_size = a_size - shift_digits; - /* For correct rounding below, we need the least significant - bit of x to be 'sticky' for this shift: if any of the bits - shifted out was nonzero, we set the least significant bit - of x. */ - if (rem) - x_digits[0] |= 1; - else - while (shift_digits > 0) - if (a->ob_digit[--shift_digits]) { - x_digits[0] |= 1; - break; - } - } - assert(1 <= x_size && - x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit))); - - /* Round, and convert to double. */ - x_digits[0] += half_even_correction[x_digits[0] & 7]; - dx = x_digits[--x_size]; - while (x_size > 0) - dx = dx * PyLong_BASE + x_digits[--x_size]; - - /* Rescale; make correction if result is 1.0. */ - dx /= 4.0 * EXP2_DBL_MANT_DIG; - if (dx == 1.0) { - if (a_bits == PY_SSIZE_T_MAX) - goto overflow; - dx = 0.5; - a_bits += 1; - } - - *e = a_bits; - return Py_SIZE(a) < 0 ? -dx : dx; - - overflow: - /* exponent > PY_SSIZE_T_MAX */ - PyErr_SetString(PyExc_OverflowError, - "huge integer: number of bits overflows a Py_ssize_t"); - *e = 0; - return -1.0; -} - -/* Get a C double from a long int object. Rounds to the nearest double, - using the round-half-to-even rule in the case of a tie. */ - -double -PyLong_AsDouble(PyObject *v) -{ - Py_ssize_t exponent; - double x; - - if (v == NULL || !PyLong_Check(v)) { - PyErr_BadInternalCall(); - return -1.0; - } - x = _PyLong_Frexp((PyLongObject *)v, &exponent); - if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) { - PyErr_SetString(PyExc_OverflowError, - "long int too large to convert to float"); - return -1.0; - } - return ldexp(x, (int)exponent); -} - -/* Methods */ - -static void -long_dealloc(PyObject *v) -{ - Py_TYPE(v)->tp_free(v); -} - -static PyObject * -long_repr(PyObject *v) -{ - return _PyLong_Format(v, 10, 1, 0); -} - -static PyObject * -long_str(PyObject *v) -{ - return _PyLong_Format(v, 10, 0, 0); -} - -static int -long_compare(PyLongObject *a, PyLongObject *b) -{ - Py_ssize_t sign; - - if (Py_SIZE(a) != Py_SIZE(b)) { - sign = Py_SIZE(a) - Py_SIZE(b); - } - else { - Py_ssize_t i = ABS(Py_SIZE(a)); - while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) - ; - if (i < 0) - sign = 0; - else { - sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i]; - if (Py_SIZE(a) < 0) - sign = -sign; - } - } - return sign < 0 ? -1 : sign > 0 ? 1 : 0; -} - -static long -long_hash(PyLongObject *v) -{ - unsigned long x; - Py_ssize_t i; - int sign; - - /* This is designed so that Python ints and longs with the - same value hash to the same value, otherwise comparisons - of mapping keys will turn out weird */ - i = v->ob_size; - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - /* The following loop produces a C unsigned long x such that x is - congruent to the absolute value of v modulo ULONG_MAX. The - resulting x is nonzero if and only if v is. */ - while (--i >= 0) { - /* Force a native long #-bits (32 or 64) circular shift */ - x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT); - x += v->ob_digit[i]; - /* If the addition above overflowed we compensate by - incrementing. This preserves the value modulo - ULONG_MAX. */ - if (x < v->ob_digit[i]) - x++; - } - x = x * sign; - if (x == (unsigned long)-1) - x = (unsigned long)-2; - return (long)x; -} - - -/* Add the absolute values of two long integers. */ - -static PyLongObject * -x_add(PyLongObject *a, PyLongObject *b) -{ - Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); - PyLongObject *z; - Py_ssize_t i; - digit carry = 0; - - /* Ensure a is the larger of the two: */ - if (size_a < size_b) { - { PyLongObject *temp = a; a = b; b = temp; } - { Py_ssize_t size_temp = size_a; - size_a = size_b; - size_b = size_temp; } - } - z = _PyLong_New(size_a+1); - if (z == NULL) - return NULL; - for (i = 0; i < size_b; ++i) { - carry += a->ob_digit[i] + b->ob_digit[i]; - z->ob_digit[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - for (; i < size_a; ++i) { - carry += a->ob_digit[i]; - z->ob_digit[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - z->ob_digit[i] = carry; - return long_normalize(z); -} - -/* Subtract the absolute values of two integers. */ - -static PyLongObject * -x_sub(PyLongObject *a, PyLongObject *b) -{ - Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); - PyLongObject *z; - Py_ssize_t i; - int sign = 1; - digit borrow = 0; - - /* Ensure a is the larger of the two: */ - if (size_a < size_b) { - sign = -1; - { PyLongObject *temp = a; a = b; b = temp; } - { Py_ssize_t size_temp = size_a; - size_a = size_b; - size_b = size_temp; } - } - else if (size_a == size_b) { - /* Find highest digit where a and b differ: */ - i = size_a; - while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) - ; - if (i < 0) - return _PyLong_New(0); - if (a->ob_digit[i] < b->ob_digit[i]) { - sign = -1; - { PyLongObject *temp = a; a = b; b = temp; } - } - size_a = size_b = i+1; - } - z = _PyLong_New(size_a); - if (z == NULL) - return NULL; - for (i = 0; i < size_b; ++i) { - /* The following assumes unsigned arithmetic - works module 2**N for some N>PyLong_SHIFT. */ - borrow = a->ob_digit[i] - b->ob_digit[i] - borrow; - z->ob_digit[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; /* Keep only one sign bit */ - } - for (; i < size_a; ++i) { - borrow = a->ob_digit[i] - borrow; - z->ob_digit[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; /* Keep only one sign bit */ - } - assert(borrow == 0); - if (sign < 0) - z->ob_size = -(z->ob_size); - return long_normalize(z); -} - -static PyObject * -long_add(PyLongObject *v, PyLongObject *w) -{ - PyLongObject *a, *b, *z; - - CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b); - - if (a->ob_size < 0) { - if (b->ob_size < 0) { - z = x_add(a, b); - if (z != NULL && z->ob_size != 0) - z->ob_size = -(z->ob_size); - } - else - z = x_sub(b, a); - } - else { - if (b->ob_size < 0) - z = x_sub(a, b); - else - z = x_add(a, b); - } - Py_DECREF(a); - Py_DECREF(b); - return (PyObject *)z; -} - -static PyObject * -long_sub(PyLongObject *v, PyLongObject *w) -{ - PyLongObject *a, *b, *z; - - CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b); - - if (a->ob_size < 0) { - if (b->ob_size < 0) - z = x_sub(a, b); - else - z = x_add(a, b); - if (z != NULL && z->ob_size != 0) - z->ob_size = -(z->ob_size); - } - else { - if (b->ob_size < 0) - z = x_add(a, b); - else - z = x_sub(a, b); - } - Py_DECREF(a); - Py_DECREF(b); - return (PyObject *)z; -} - -/* Grade school multiplication, ignoring the signs. - * Returns the absolute value of the product, or NULL if error. - */ -static PyLongObject * -x_mul(PyLongObject *a, PyLongObject *b) -{ - PyLongObject *z; - Py_ssize_t size_a = ABS(Py_SIZE(a)); - Py_ssize_t size_b = ABS(Py_SIZE(b)); - Py_ssize_t i; - - z = _PyLong_New(size_a + size_b); - if (z == NULL) - return NULL; - - memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit)); - if (a == b) { - /* Efficient squaring per HAC, Algorithm 14.16: - * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf - * Gives slightly less than a 2x speedup when a == b, - * via exploiting that each entry in the multiplication - * pyramid appears twice (except for the size_a squares). - */ - for (i = 0; i < size_a; ++i) { - twodigits carry; - twodigits f = a->ob_digit[i]; - digit *pz = z->ob_digit + (i << 1); - digit *pa = a->ob_digit + i + 1; - digit *paend = a->ob_digit + size_a; - - SIGCHECK({ - Py_DECREF(z); - return NULL; - }); - - carry = *pz + f * f; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - assert(carry <= PyLong_MASK); - - /* Now f is added in twice in each column of the - * pyramid it appears. Same as adding f<<1 once. - */ - f <<= 1; - while (pa < paend) { - carry += *pz + *pa++ * f; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - assert(carry <= (PyLong_MASK << 1)); - } - if (carry) { - carry += *pz; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - } - if (carry) - *pz += (digit)(carry & PyLong_MASK); - assert((carry >> PyLong_SHIFT) == 0); - } - } - else { /* a is not the same as b -- gradeschool long mult */ - for (i = 0; i < size_a; ++i) { - twodigits carry = 0; - twodigits f = a->ob_digit[i]; - digit *pz = z->ob_digit + i; - digit *pb = b->ob_digit; - digit *pbend = b->ob_digit + size_b; - - SIGCHECK({ - Py_DECREF(z); - return NULL; - }); - - while (pb < pbend) { - carry += *pz + *pb++ * f; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - assert(carry <= PyLong_MASK); - } - if (carry) - *pz += (digit)(carry & PyLong_MASK); - assert((carry >> PyLong_SHIFT) == 0); - } - } - return long_normalize(z); -} - -/* A helper for Karatsuba multiplication (k_mul). - Takes a long "n" and an integer "size" representing the place to - split, and sets low and high such that abs(n) == (high << size) + low, - viewing the shift as being by digits. The sign bit is ignored, and - the return values are >= 0. - Returns 0 on success, -1 on failure. -*/ -static int -kmul_split(PyLongObject *n, - Py_ssize_t size, - PyLongObject **high, - PyLongObject **low) -{ - PyLongObject *hi, *lo; - Py_ssize_t size_lo, size_hi; - const Py_ssize_t size_n = ABS(Py_SIZE(n)); - - size_lo = MIN(size_n, size); - size_hi = size_n - size_lo; - - if ((hi = _PyLong_New(size_hi)) == NULL) - return -1; - if ((lo = _PyLong_New(size_lo)) == NULL) { - Py_DECREF(hi); - return -1; - } - - memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit)); - memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit)); - - *high = long_normalize(hi); - *low = long_normalize(lo); - return 0; -} - -static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b); - -/* Karatsuba multiplication. Ignores the input signs, and returns the - * absolute value of the product (or NULL if error). - * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295). - */ -static PyLongObject * -k_mul(PyLongObject *a, PyLongObject *b) -{ - Py_ssize_t asize = ABS(Py_SIZE(a)); - Py_ssize_t bsize = ABS(Py_SIZE(b)); - PyLongObject *ah = NULL; - PyLongObject *al = NULL; - PyLongObject *bh = NULL; - PyLongObject *bl = NULL; - PyLongObject *ret = NULL; - PyLongObject *t1, *t2, *t3; - Py_ssize_t shift; /* the number of digits we split off */ - Py_ssize_t i; - - /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl - * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl - * Then the original product is - * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl - * By picking X to be a power of 2, "*X" is just shifting, and it's - * been reduced to 3 multiplies on numbers half the size. - */ - - /* We want to split based on the larger number; fiddle so that b - * is largest. - */ - if (asize > bsize) { - t1 = a; - a = b; - b = t1; - - i = asize; - asize = bsize; - bsize = i; - } - - /* Use gradeschool math when either number is too small. */ - i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF; - if (asize <= i) { - if (asize == 0) - return _PyLong_New(0); - else - return x_mul(a, b); - } - - /* If a is small compared to b, splitting on b gives a degenerate - * case with ah==0, and Karatsuba may be (even much) less efficient - * than "grade school" then. However, we can still win, by viewing - * b as a string of "big digits", each of width a->ob_size. That - * leads to a sequence of balanced calls to k_mul. - */ - if (2 * asize <= bsize) - return k_lopsided_mul(a, b); - - /* Split a & b into hi & lo pieces. */ - shift = bsize >> 1; - if (kmul_split(a, shift, &ah, &al) < 0) goto fail; - assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */ - - if (a == b) { - bh = ah; - bl = al; - Py_INCREF(bh); - Py_INCREF(bl); - } - else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail; - - /* The plan: - * 1. Allocate result space (asize + bsize digits: that's always - * enough). - * 2. Compute ah*bh, and copy into result at 2*shift. - * 3. Compute al*bl, and copy into result at 0. Note that this - * can't overlap with #2. - * 4. Subtract al*bl from the result, starting at shift. This may - * underflow (borrow out of the high digit), but we don't care: - * we're effectively doing unsigned arithmetic mod - * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits, - * borrows and carries out of the high digit can be ignored. - * 5. Subtract ah*bh from the result, starting at shift. - * 6. Compute (ah+al)*(bh+bl), and add it into the result starting - * at shift. - */ - - /* 1. Allocate result space. */ - ret = _PyLong_New(asize + bsize); - if (ret == NULL) goto fail; -#ifdef Py_DEBUG - /* Fill with trash, to catch reference to uninitialized digits. */ - memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit)); -#endif - - /* 2. t1 <- ah*bh, and copy into high digits of result. */ - if ((t1 = k_mul(ah, bh)) == NULL) goto fail; - assert(Py_SIZE(t1) >= 0); - assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret)); - memcpy(ret->ob_digit + 2*shift, t1->ob_digit, - Py_SIZE(t1) * sizeof(digit)); - - /* Zero-out the digits higher than the ah*bh copy. */ - i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1); - if (i) - memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0, - i * sizeof(digit)); - - /* 3. t2 <- al*bl, and copy into the low digits. */ - if ((t2 = k_mul(al, bl)) == NULL) { - Py_DECREF(t1); - goto fail; - } - assert(Py_SIZE(t2) >= 0); - assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */ - memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit)); - - /* Zero out remaining digits. */ - i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */ - if (i) - memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit)); - - /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first - * because it's fresher in cache. - */ - i = Py_SIZE(ret) - shift; /* # digits after shift */ - (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2)); - Py_DECREF(t2); - - (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1)); - Py_DECREF(t1); - - /* 6. t3 <- (ah+al)(bh+bl), and add into result. */ - if ((t1 = x_add(ah, al)) == NULL) goto fail; - Py_DECREF(ah); - Py_DECREF(al); - ah = al = NULL; - - if (a == b) { - t2 = t1; - Py_INCREF(t2); - } - else if ((t2 = x_add(bh, bl)) == NULL) { - Py_DECREF(t1); - goto fail; - } - Py_DECREF(bh); - Py_DECREF(bl); - bh = bl = NULL; - - t3 = k_mul(t1, t2); - Py_DECREF(t1); - Py_DECREF(t2); - if (t3 == NULL) goto fail; - assert(Py_SIZE(t3) >= 0); - - /* Add t3. It's not obvious why we can't run out of room here. - * See the (*) comment after this function. - */ - (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3)); - Py_DECREF(t3); - - return long_normalize(ret); - - fail: - Py_XDECREF(ret); - Py_XDECREF(ah); - Py_XDECREF(al); - Py_XDECREF(bh); - Py_XDECREF(bl); - return NULL; -} - -/* (*) Why adding t3 can't "run out of room" above. - -Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts -to start with: - -1. For any integer i, i = c(i/2) + f(i/2). In particular, - bsize = c(bsize/2) + f(bsize/2). -2. shift = f(bsize/2) -3. asize <= bsize -4. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this - routine, so asize > bsize/2 >= f(bsize/2) in this routine. - -We allocated asize + bsize result digits, and add t3 into them at an offset -of shift. This leaves asize+bsize-shift allocated digit positions for t3 -to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) = -asize + c(bsize/2) available digit positions. - -bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has -at most c(bsize/2) digits + 1 bit. - -If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2) -digits, and al has at most f(bsize/2) digits in any case. So ah+al has at -most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit. - -The product (ah+al)*(bh+bl) therefore has at most - - c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits - -and we have asize + c(bsize/2) available digit positions. We need to show -this is always enough. An instance of c(bsize/2) cancels out in both, so -the question reduces to whether asize digits is enough to hold -(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize, -then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4, -asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1 -digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If -asize == bsize, then we're asking whether bsize digits is enough to hold -c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits -is enough to hold 2 bits. This is so if bsize >= 2, which holds because -bsize >= KARATSUBA_CUTOFF >= 2. - -Note that since there's always enough room for (ah+al)*(bh+bl), and that's -clearly >= each of ah*bh and al*bl, there's always enough room to subtract -ah*bh and al*bl too. -*/ - -/* b has at least twice the digits of a, and a is big enough that Karatsuba - * would pay off *if* the inputs had balanced sizes. View b as a sequence - * of slices, each with a->ob_size digits, and multiply the slices by a, - * one at a time. This gives k_mul balanced inputs to work with, and is - * also cache-friendly (we compute one double-width slice of the result - * at a time, then move on, never backtracking except for the helpful - * single-width slice overlap between successive partial sums). - */ -static PyLongObject * -k_lopsided_mul(PyLongObject *a, PyLongObject *b) -{ - const Py_ssize_t asize = ABS(Py_SIZE(a)); - Py_ssize_t bsize = ABS(Py_SIZE(b)); - Py_ssize_t nbdone; /* # of b digits already multiplied */ - PyLongObject *ret; - PyLongObject *bslice = NULL; - - assert(asize > KARATSUBA_CUTOFF); - assert(2 * asize <= bsize); - - /* Allocate result space, and zero it out. */ - ret = _PyLong_New(asize + bsize); - if (ret == NULL) - return NULL; - memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit)); - - /* Successive slices of b are copied into bslice. */ - bslice = _PyLong_New(asize); - if (bslice == NULL) - goto fail; - - nbdone = 0; - while (bsize > 0) { - PyLongObject *product; - const Py_ssize_t nbtouse = MIN(bsize, asize); - - /* Multiply the next slice of b by a. */ - memcpy(bslice->ob_digit, b->ob_digit + nbdone, - nbtouse * sizeof(digit)); - Py_SIZE(bslice) = nbtouse; - product = k_mul(a, bslice); - if (product == NULL) - goto fail; - - /* Add into result. */ - (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone, - product->ob_digit, Py_SIZE(product)); - Py_DECREF(product); - - bsize -= nbtouse; - nbdone += nbtouse; - } - - Py_DECREF(bslice); - return long_normalize(ret); - - fail: - Py_DECREF(ret); - Py_XDECREF(bslice); - return NULL; -} - -static PyObject * -long_mul(PyLongObject *v, PyLongObject *w) -{ - PyLongObject *a, *b, *z; - - if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - z = k_mul(a, b); - /* Negate if exactly one of the inputs is negative. */ - if (((a->ob_size ^ b->ob_size) < 0) && z) - z->ob_size = -(z->ob_size); - Py_DECREF(a); - Py_DECREF(b); - return (PyObject *)z; -} - -/* The / and % operators are now defined in terms of divmod(). - The expression a mod b has the value a - b*floor(a/b). - The long_divrem function gives the remainder after division of - |a| by |b|, with the sign of a. This is also expressed - as a - b*trunc(a/b), if trunc truncates towards zero. - Some examples: - a b a rem b a mod b - 13 10 3 3 - -13 10 -3 7 - 13 -10 3 -7 - -13 -10 -3 -3 - So, to get from rem to mod, we have to add b if a and b - have different signs. We then subtract one from the 'div' - part of the outcome to keep the invariant intact. */ - -/* Compute - * *pdiv, *pmod = divmod(v, w) - * NULL can be passed for pdiv or pmod, in which case that part of - * the result is simply thrown away. The caller owns a reference to - * each of these it requests (does not pass NULL for). - */ -static int -l_divmod(PyLongObject *v, PyLongObject *w, - PyLongObject **pdiv, PyLongObject **pmod) -{ - PyLongObject *div, *mod; - - if (long_divrem(v, w, &div, &mod) < 0) - return -1; - if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) || - (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) { - PyLongObject *temp; - PyLongObject *one; - temp = (PyLongObject *) long_add(mod, w); - Py_DECREF(mod); - mod = temp; - if (mod == NULL) { - Py_DECREF(div); - return -1; - } - one = (PyLongObject *) PyLong_FromLong(1L); - if (one == NULL || - (temp = (PyLongObject *) long_sub(div, one)) == NULL) { - Py_DECREF(mod); - Py_DECREF(div); - Py_XDECREF(one); - return -1; - } - Py_DECREF(one); - Py_DECREF(div); - div = temp; - } - if (pdiv != NULL) - *pdiv = div; - else - Py_DECREF(div); - - if (pmod != NULL) - *pmod = mod; - else - Py_DECREF(mod); - - return 0; -} - -static PyObject * -long_div(PyObject *v, PyObject *w) -{ - PyLongObject *a, *b, *div; - - CONVERT_BINOP(v, w, &a, &b); - if (l_divmod(a, b, &div, NULL) < 0) - div = NULL; - Py_DECREF(a); - Py_DECREF(b); - return (PyObject *)div; -} - -static PyObject * -long_classic_div(PyObject *v, PyObject *w) -{ - PyLongObject *a, *b, *div; - - CONVERT_BINOP(v, w, &a, &b); - if (Py_DivisionWarningFlag && - PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0) - div = NULL; - else if (l_divmod(a, b, &div, NULL) < 0) - div = NULL; - Py_DECREF(a); - Py_DECREF(b); - return (PyObject *)div; -} - -/* PyLong/PyLong -> float, with correctly rounded result. */ - -#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT) -#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT) - -static PyObject * -long_true_divide(PyObject *v, PyObject *w) -{ - PyLongObject *a, *b, *x; - Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits; - digit mask, low; - int inexact, negate, a_is_small, b_is_small; - double dx, result; - - CONVERT_BINOP(v, w, &a, &b); - - /* - Method in a nutshell: - - 0. reduce to case a, b > 0; filter out obvious underflow/overflow - 1. choose a suitable integer 'shift' - 2. use integer arithmetic to compute x = floor(2**-shift*a/b) - 3. adjust x for correct rounding - 4. convert x to a double dx with the same value - 5. return ldexp(dx, shift). - - In more detail: - - 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b - returns either 0.0 or -0.0, depending on the sign of b. For a and - b both nonzero, ignore signs of a and b, and add the sign back in - at the end. Now write a_bits and b_bits for the bit lengths of a - and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise - for b). Then - - 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1). - - So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and - so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP - - DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of - the way, we can assume that - - DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP. - - 1. The integer 'shift' is chosen so that x has the right number of - bits for a double, plus two or three extra bits that will be used - in the rounding decisions. Writing a_bits and b_bits for the - number of significant bits in a and b respectively, a - straightforward formula for shift is: - - shift = a_bits - b_bits - DBL_MANT_DIG - 2 - - This is fine in the usual case, but if a/b is smaller than the - smallest normal float then it can lead to double rounding on an - IEEE 754 platform, giving incorrectly rounded results. So we - adjust the formula slightly. The actual formula used is: - - shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2 - - 2. The quantity x is computed by first shifting a (left -shift bits - if shift <= 0, right shift bits if shift > 0) and then dividing by - b. For both the shift and the division, we keep track of whether - the result is inexact, in a flag 'inexact'; this information is - needed at the rounding stage. - - With the choice of shift above, together with our assumption that - a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows - that x >= 1. - - 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace - this with an exactly representable float of the form - - round(x/2**extra_bits) * 2**(extra_bits+shift). - - For float representability, we need x/2**extra_bits < - 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP - - DBL_MANT_DIG. This translates to the condition: - - extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG - - To round, we just modify the bottom digit of x in-place; this can - end up giving a digit with value > PyLONG_MASK, but that's not a - problem since digits can hold values up to 2*PyLONG_MASK+1. - - With the original choices for shift above, extra_bits will always - be 2 or 3. Then rounding under the round-half-to-even rule, we - round up iff the most significant of the extra bits is 1, and - either: (a) the computation of x in step 2 had an inexact result, - or (b) at least one other of the extra bits is 1, or (c) the least - significant bit of x (above those to be rounded) is 1. - - 4. Conversion to a double is straightforward; all floating-point - operations involved in the conversion are exact, so there's no - danger of rounding errors. - - 5. Use ldexp(x, shift) to compute x*2**shift, the final result. - The result will always be exactly representable as a double, except - in the case that it overflows. To avoid dependence on the exact - behaviour of ldexp on overflow, we check for overflow before - applying ldexp. The result of ldexp is adjusted for sign before - returning. - */ - - /* Reduce to case where a and b are both positive. */ - a_size = ABS(Py_SIZE(a)); - b_size = ABS(Py_SIZE(b)); - negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0); - if (b_size == 0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "division by zero"); - goto error; - } - if (a_size == 0) - goto underflow_or_zero; - - /* Fast path for a and b small (exactly representable in a double). - Relies on floating-point division being correctly rounded; results - may be subject to double rounding on x86 machines that operate with - the x87 FPU set to 64-bit precision. */ - a_is_small = a_size <= MANT_DIG_DIGITS || - (a_size == MANT_DIG_DIGITS+1 && - a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0); - b_is_small = b_size <= MANT_DIG_DIGITS || - (b_size == MANT_DIG_DIGITS+1 && - b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0); - if (a_is_small && b_is_small) { - double da, db; - da = a->ob_digit[--a_size]; - while (a_size > 0) - da = da * PyLong_BASE + a->ob_digit[--a_size]; - db = b->ob_digit[--b_size]; - while (b_size > 0) - db = db * PyLong_BASE + b->ob_digit[--b_size]; - result = da / db; - goto success; - } - - /* Catch obvious cases of underflow and overflow */ - diff = a_size - b_size; - if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1) - /* Extreme overflow */ - goto overflow; - else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT) - /* Extreme underflow */ - goto underflow_or_zero; - /* Next line is now safe from overflowing a Py_ssize_t */ - diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) - - bits_in_digit(b->ob_digit[b_size - 1]); - /* Now diff = a_bits - b_bits. */ - if (diff > DBL_MAX_EXP) - goto overflow; - else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1) - goto underflow_or_zero; - - /* Choose value for shift; see comments for step 1 above. */ - shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2; - - inexact = 0; - - /* x = abs(a * 2**-shift) */ - if (shift <= 0) { - Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT; - digit rem; - /* x = a << -shift */ - if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) { - /* In practice, it's probably impossible to end up - here. Both a and b would have to be enormous, - using close to SIZE_T_MAX bytes of memory each. */ - PyErr_SetString(PyExc_OverflowError, - "intermediate overflow during division"); - goto error; - } - x = _PyLong_New(a_size + shift_digits + 1); - if (x == NULL) - goto error; - for (i = 0; i < shift_digits; i++) - x->ob_digit[i] = 0; - rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit, - a_size, -shift % PyLong_SHIFT); - x->ob_digit[a_size + shift_digits] = rem; - } - else { - Py_ssize_t shift_digits = shift / PyLong_SHIFT; - digit rem; - /* x = a >> shift */ - assert(a_size >= shift_digits); - x = _PyLong_New(a_size - shift_digits); - if (x == NULL) - goto error; - rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits, - a_size - shift_digits, shift % PyLong_SHIFT); - /* set inexact if any of the bits shifted out is nonzero */ - if (rem) - inexact = 1; - while (!inexact && shift_digits > 0) - if (a->ob_digit[--shift_digits]) - inexact = 1; - } - long_normalize(x); - x_size = Py_SIZE(x); - - /* x //= b. If the remainder is nonzero, set inexact. We own the only - reference to x, so it's safe to modify it in-place. */ - if (b_size == 1) { - digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size, - b->ob_digit[0]); - long_normalize(x); - if (rem) - inexact = 1; - } - else { - PyLongObject *div, *rem; - div = x_divrem(x, b, &rem); - Py_DECREF(x); - x = div; - if (x == NULL) - goto error; - if (Py_SIZE(rem)) - inexact = 1; - Py_DECREF(rem); - } - x_size = ABS(Py_SIZE(x)); - assert(x_size > 0); /* result of division is never zero */ - x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]); - - /* The number of extra bits that have to be rounded away. */ - extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG; - assert(extra_bits == 2 || extra_bits == 3); - - /* Round by directly modifying the low digit of x. */ - mask = (digit)1 << (extra_bits - 1); - low = x->ob_digit[0] | inexact; - if (low & mask && low & (3*mask-1)) - low += mask; - x->ob_digit[0] = low & ~(mask-1U); - - /* Convert x to a double dx; the conversion is exact. */ - dx = x->ob_digit[--x_size]; - while (x_size > 0) - dx = dx * PyLong_BASE + x->ob_digit[--x_size]; - Py_DECREF(x); - - /* Check whether ldexp result will overflow a double. */ - if (shift + x_bits >= DBL_MAX_EXP && - (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits))) - goto overflow; - result = ldexp(dx, (int)shift); - - success: - Py_DECREF(a); - Py_DECREF(b); - return PyFloat_FromDouble(negate ? -result : result); - - underflow_or_zero: - Py_DECREF(a); - Py_DECREF(b); - return PyFloat_FromDouble(negate ? -0.0 : 0.0); - - overflow: - PyErr_SetString(PyExc_OverflowError, - "integer division result too large for a float"); - error: - Py_DECREF(a); - Py_DECREF(b); - return NULL; -} - -static PyObject * -long_mod(PyObject *v, PyObject *w) -{ - PyLongObject *a, *b, *mod; - - CONVERT_BINOP(v, w, &a, &b); - - if (l_divmod(a, b, NULL, &mod) < 0) - mod = NULL; - Py_DECREF(a); - Py_DECREF(b); - return (PyObject *)mod; -} - -static PyObject * -long_divmod(PyObject *v, PyObject *w) -{ - PyLongObject *a, *b, *div, *mod; - PyObject *z; - - CONVERT_BINOP(v, w, &a, &b); - - if (l_divmod(a, b, &div, &mod) < 0) { - Py_DECREF(a); - Py_DECREF(b); - return NULL; - } - z = PyTuple_New(2); - if (z != NULL) { - PyTuple_SetItem(z, 0, (PyObject *) div); - PyTuple_SetItem(z, 1, (PyObject *) mod); - } - else { - Py_DECREF(div); - Py_DECREF(mod); - } - Py_DECREF(a); - Py_DECREF(b); - return z; -} - -/* pow(v, w, x) */ -static PyObject * -long_pow(PyObject *v, PyObject *w, PyObject *x) -{ - PyLongObject *a, *b, *c; /* a,b,c = v,w,x */ - int negativeOutput = 0; /* if x<0 return negative output */ - - PyLongObject *z = NULL; /* accumulated result */ - Py_ssize_t i, j, k; /* counters */ - PyLongObject *temp = NULL; - - /* 5-ary values. If the exponent is large enough, table is - * precomputed so that table[i] == a**i % c for i in range(32). - */ - PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; - - /* a, b, c = v, w, x */ - CONVERT_BINOP(v, w, &a, &b); - if (PyLong_Check(x)) { - c = (PyLongObject *)x; - Py_INCREF(x); - } - else if (PyInt_Check(x)) { - c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x)); - if (c == NULL) - goto Error; - } - else if (x == Py_None) - c = NULL; - else { - Py_DECREF(a); - Py_DECREF(b); - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - if (Py_SIZE(b) < 0) { /* if exponent is negative */ - if (c) { - PyErr_SetString(PyExc_TypeError, "pow() 2nd argument " - "cannot be negative when 3rd argument specified"); - goto Error; - } - else { - /* else return a float. This works because we know - that this calls float_pow() which converts its - arguments to double. */ - Py_DECREF(a); - Py_DECREF(b); - return PyFloat_Type.tp_as_number->nb_power(v, w, x); - } - } - - if (c) { - /* if modulus == 0: - raise ValueError() */ - if (Py_SIZE(c) == 0) { - PyErr_SetString(PyExc_ValueError, - "pow() 3rd argument cannot be 0"); - goto Error; - } - - /* if modulus < 0: - negativeOutput = True - modulus = -modulus */ - if (Py_SIZE(c) < 0) { - negativeOutput = 1; - temp = (PyLongObject *)_PyLong_Copy(c); - if (temp == NULL) - goto Error; - Py_DECREF(c); - c = temp; - temp = NULL; - c->ob_size = - c->ob_size; - } - - /* if modulus == 1: - return 0 */ - if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) { - z = (PyLongObject *)PyLong_FromLong(0L); - goto Done; - } - - /* if base < 0: - base = base % modulus - Having the base positive just makes things easier. */ - if (Py_SIZE(a) < 0) { - if (l_divmod(a, c, NULL, &temp) < 0) - goto Error; - Py_DECREF(a); - a = temp; - temp = NULL; - } - } - - /* At this point a, b, and c are guaranteed non-negative UNLESS - c is NULL, in which case a may be negative. */ - - z = (PyLongObject *)PyLong_FromLong(1L); - if (z == NULL) - goto Error; - - /* Perform a modular reduction, X = X % c, but leave X alone if c - * is NULL. - */ -#define REDUCE(X) \ - do { \ - if (c != NULL) { \ - if (l_divmod(X, c, NULL, &temp) < 0) \ - goto Error; \ - Py_XDECREF(X); \ - X = temp; \ - temp = NULL; \ - } \ - } while(0) - - /* Multiply two values, then reduce the result: - result = X*Y % c. If c is NULL, skip the mod. */ -#define MULT(X, Y, result) \ - do { \ - temp = (PyLongObject *)long_mul(X, Y); \ - if (temp == NULL) \ - goto Error; \ - Py_XDECREF(result); \ - result = temp; \ - temp = NULL; \ - REDUCE(result); \ - } while(0) - - if (Py_SIZE(b) <= FIVEARY_CUTOFF) { - /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */ - /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */ - for (i = Py_SIZE(b) - 1; i >= 0; --i) { - digit bi = b->ob_digit[i]; - - for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) { - MULT(z, z, z); - if (bi & j) - MULT(z, a, z); - } - } - } - else { - /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */ - Py_INCREF(z); /* still holds 1L */ - table[0] = z; - for (i = 1; i < 32; ++i) - MULT(table[i-1], a, table[i]); - - for (i = Py_SIZE(b) - 1; i >= 0; --i) { - const digit bi = b->ob_digit[i]; - - for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) { - const int index = (bi >> j) & 0x1f; - for (k = 0; k < 5; ++k) - MULT(z, z, z); - if (index) - MULT(z, table[index], z); - } - } - } - - if (negativeOutput && (Py_SIZE(z) != 0)) { - temp = (PyLongObject *)long_sub(z, c); - if (temp == NULL) - goto Error; - Py_DECREF(z); - z = temp; - temp = NULL; - } - goto Done; - - Error: - if (z != NULL) { - Py_DECREF(z); - z = NULL; - } - /* fall through */ - Done: - if (Py_SIZE(b) > FIVEARY_CUTOFF) { - for (i = 0; i < 32; ++i) - Py_XDECREF(table[i]); - } - Py_DECREF(a); - Py_DECREF(b); - Py_XDECREF(c); - Py_XDECREF(temp); - return (PyObject *)z; -} - -static PyObject * -long_invert(PyLongObject *v) -{ - /* Implement ~x as -(x+1) */ - PyLongObject *x; - PyLongObject *w; - w = (PyLongObject *)PyLong_FromLong(1L); - if (w == NULL) - return NULL; - x = (PyLongObject *) long_add(v, w); - Py_DECREF(w); - if (x == NULL) - return NULL; - Py_SIZE(x) = -(Py_SIZE(x)); - return (PyObject *)x; -} - -static PyObject * -long_neg(PyLongObject *v) -{ - PyLongObject *z; - if (v->ob_size == 0 && PyLong_CheckExact(v)) { - /* -0 == 0 */ - Py_INCREF(v); - return (PyObject *) v; - } - z = (PyLongObject *)_PyLong_Copy(v); - if (z != NULL) - z->ob_size = -(v->ob_size); - return (PyObject *)z; -} - -static PyObject * -long_abs(PyLongObject *v) -{ - if (v->ob_size < 0) - return long_neg(v); - else - return long_long((PyObject *)v); -} - -static int -long_nonzero(PyLongObject *v) -{ - return Py_SIZE(v) != 0; -} - -static PyObject * -long_rshift(PyLongObject *v, PyLongObject *w) -{ - PyLongObject *a, *b; - PyLongObject *z = NULL; - Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j; - digit lomask, himask; - - CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b); - - if (Py_SIZE(a) < 0) { - /* Right shifting negative numbers is harder */ - PyLongObject *a1, *a2; - a1 = (PyLongObject *) long_invert(a); - if (a1 == NULL) - goto rshift_error; - a2 = (PyLongObject *) long_rshift(a1, b); - Py_DECREF(a1); - if (a2 == NULL) - goto rshift_error; - z = (PyLongObject *) long_invert(a2); - Py_DECREF(a2); - } - else { - shiftby = PyLong_AsSsize_t((PyObject *)b); - if (shiftby == -1L && PyErr_Occurred()) - goto rshift_error; - if (shiftby < 0) { - PyErr_SetString(PyExc_ValueError, - "negative shift count"); - goto rshift_error; - } - wordshift = shiftby / PyLong_SHIFT; - newsize = ABS(Py_SIZE(a)) - wordshift; - if (newsize <= 0) { - z = _PyLong_New(0); - Py_DECREF(a); - Py_DECREF(b); - return (PyObject *)z; - } - loshift = shiftby % PyLong_SHIFT; - hishift = PyLong_SHIFT - loshift; - lomask = ((digit)1 << hishift) - 1; - himask = PyLong_MASK ^ lomask; - z = _PyLong_New(newsize); - if (z == NULL) - goto rshift_error; - if (Py_SIZE(a) < 0) - Py_SIZE(z) = -(Py_SIZE(z)); - for (i = 0, j = wordshift; i < newsize; i++, j++) { - z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask; - if (i+1 < newsize) - z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask; - } - z = long_normalize(z); - } - rshift_error: - Py_DECREF(a); - Py_DECREF(b); - return (PyObject *) z; - -} - -static PyObject * -long_lshift(PyObject *v, PyObject *w) -{ - /* This version due to Tim Peters */ - PyLongObject *a, *b; - PyLongObject *z = NULL; - Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j; - twodigits accum; - - CONVERT_BINOP(v, w, &a, &b); - - shiftby = PyLong_AsSsize_t((PyObject *)b); - if (shiftby == -1L && PyErr_Occurred()) - goto lshift_error; - if (shiftby < 0) { - PyErr_SetString(PyExc_ValueError, "negative shift count"); - goto lshift_error; - } - /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */ - wordshift = shiftby / PyLong_SHIFT; - remshift = shiftby - wordshift * PyLong_SHIFT; - - oldsize = ABS(a->ob_size); - newsize = oldsize + wordshift; - if (remshift) - ++newsize; - z = _PyLong_New(newsize); - if (z == NULL) - goto lshift_error; - if (a->ob_size < 0) - z->ob_size = -(z->ob_size); - for (i = 0; i < wordshift; i++) - z->ob_digit[i] = 0; - accum = 0; - for (i = wordshift, j = 0; j < oldsize; i++, j++) { - accum |= (twodigits)a->ob_digit[j] << remshift; - z->ob_digit[i] = (digit)(accum & PyLong_MASK); - accum >>= PyLong_SHIFT; - } - if (remshift) - z->ob_digit[newsize-1] = (digit)accum; - else - assert(!accum); - z = long_normalize(z); - lshift_error: - Py_DECREF(a); - Py_DECREF(b); - return (PyObject *) z; -} - -/* Compute two's complement of digit vector a[0:m], writing result to - z[0:m]. The digit vector a need not be normalized, but should not - be entirely zero. a and z may point to the same digit vector. */ - -static void -v_complement(digit *z, digit *a, Py_ssize_t m) -{ - Py_ssize_t i; - digit carry = 1; - for (i = 0; i < m; ++i) { - carry += a[i] ^ PyLong_MASK; - z[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - assert(carry == 0); -} - -/* Bitwise and/xor/or operations */ - -static PyObject * -long_bitwise(PyLongObject *a, - int op, /* '&', '|', '^' */ - PyLongObject *b) -{ - int nega, negb, negz; - Py_ssize_t size_a, size_b, size_z, i; - PyLongObject *z; - - /* Bitwise operations for negative numbers operate as though - on a two's complement representation. So convert arguments - from sign-magnitude to two's complement, and convert the - result back to sign-magnitude at the end. */ - - /* If a is negative, replace it by its two's complement. */ - size_a = ABS(Py_SIZE(a)); - nega = Py_SIZE(a) < 0; - if (nega) { - z = _PyLong_New(size_a); - if (z == NULL) - return NULL; - v_complement(z->ob_digit, a->ob_digit, size_a); - a = z; - } - else - /* Keep reference count consistent. */ - Py_INCREF(a); - - /* Same for b. */ - size_b = ABS(Py_SIZE(b)); - negb = Py_SIZE(b) < 0; - if (negb) { - z = _PyLong_New(size_b); - if (z == NULL) { - Py_DECREF(a); - return NULL; - } - v_complement(z->ob_digit, b->ob_digit, size_b); - b = z; - } - else - Py_INCREF(b); - - /* Swap a and b if necessary to ensure size_a >= size_b. */ - if (size_a < size_b) { - z = a; a = b; b = z; - size_z = size_a; size_a = size_b; size_b = size_z; - negz = nega; nega = negb; negb = negz; - } - - /* JRH: The original logic here was to allocate the result value (z) - as the longer of the two operands. However, there are some cases - where the result is guaranteed to be shorter than that: AND of two - positives, OR of two negatives: use the shorter number. AND with - mixed signs: use the positive number. OR with mixed signs: use the - negative number. - */ - switch (op) { - case '^': - negz = nega ^ negb; - size_z = size_a; - break; - case '&': - negz = nega & negb; - size_z = negb ? size_a : size_b; - break; - case '|': - negz = nega | negb; - size_z = negb ? size_b : size_a; - break; - default: - PyErr_BadArgument(); - return NULL; - } - - /* We allow an extra digit if z is negative, to make sure that - the final two's complement of z doesn't overflow. */ - z = _PyLong_New(size_z + negz); - if (z == NULL) { - Py_DECREF(a); - Py_DECREF(b); - return NULL; - } - - /* Compute digits for overlap of a and b. */ - switch(op) { - case '&': - for (i = 0; i < size_b; ++i) - z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i]; - break; - case '|': - for (i = 0; i < size_b; ++i) - z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i]; - break; - case '^': - for (i = 0; i < size_b; ++i) - z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i]; - break; - default: - PyErr_BadArgument(); - return NULL; - } - - /* Copy any remaining digits of a, inverting if necessary. */ - if (op == '^' && negb) - for (; i < size_z; ++i) - z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK; - else if (i < size_z) - memcpy(&z->ob_digit[i], &a->ob_digit[i], - (size_z-i)*sizeof(digit)); - - /* Complement result if negative. */ - if (negz) { - Py_SIZE(z) = -(Py_SIZE(z)); - z->ob_digit[size_z] = PyLong_MASK; - v_complement(z->ob_digit, z->ob_digit, size_z+1); - } - - Py_DECREF(a); - Py_DECREF(b); - return (PyObject *)long_normalize(z); -} - -static PyObject * -long_and(PyObject *v, PyObject *w) -{ - PyLongObject *a, *b; - PyObject *c; - CONVERT_BINOP(v, w, &a, &b); - c = long_bitwise(a, '&', b); - Py_DECREF(a); - Py_DECREF(b); - return c; -} - -static PyObject * -long_xor(PyObject *v, PyObject *w) -{ - PyLongObject *a, *b; - PyObject *c; - CONVERT_BINOP(v, w, &a, &b); - c = long_bitwise(a, '^', b); - Py_DECREF(a); - Py_DECREF(b); - return c; -} - -static PyObject * -long_or(PyObject *v, PyObject *w) -{ - PyLongObject *a, *b; - PyObject *c; - CONVERT_BINOP(v, w, &a, &b); - c = long_bitwise(a, '|', b); - Py_DECREF(a); - Py_DECREF(b); - return c; -} - -static int -long_coerce(PyObject **pv, PyObject **pw) -{ - if (PyInt_Check(*pw)) { - *pw = PyLong_FromLong(PyInt_AS_LONG(*pw)); - if (*pw == NULL) - return -1; - Py_INCREF(*pv); - return 0; - } - else if (PyLong_Check(*pw)) { - Py_INCREF(*pv); - Py_INCREF(*pw); - return 0; - } - return 1; /* Can't do it */ -} - -static PyObject * -long_long(PyObject *v) -{ - if (PyLong_CheckExact(v)) - Py_INCREF(v); - else - v = _PyLong_Copy((PyLongObject *)v); - return v; -} - -static PyObject * -long_int(PyObject *v) -{ - long x; - x = PyLong_AsLong(v); - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) { - PyErr_Clear(); - if (PyLong_CheckExact(v)) { - Py_INCREF(v); - return v; - } - else - return _PyLong_Copy((PyLongObject *)v); - } - else - return NULL; - } - return PyInt_FromLong(x); -} - -static PyObject * -long_float(PyObject *v) -{ - double result; - result = PyLong_AsDouble(v); - if (result == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(result); -} - -static PyObject * -long_oct(PyObject *v) -{ - return _PyLong_Format(v, 8, 1, 0); -} - -static PyObject * -long_hex(PyObject *v) -{ - return _PyLong_Format(v, 16, 1, 0); -} - -static PyObject * -long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds); - -static PyObject * -long_new(PyTypeObject *type, PyObject *args, PyObject *kwds) -{ - PyObject *x = NULL; - int base = -909; /* unlikely! */ - static char *kwlist[] = {"x", "base", 0}; - - if (type != &PyLong_Type) - return long_subtype_new(type, args, kwds); /* Wimp out */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist, - &x, &base)) - return NULL; - if (x == NULL) - return PyLong_FromLong(0L); - if (base == -909) - return PyNumber_Long(x); - else if (PyString_Check(x)) { - /* Since PyLong_FromString doesn't have a length parameter, - * check here for possible NULs in the string. */ - char *string = PyString_AS_STRING(x); - if (strlen(string) != (size_t)PyString_Size(x)) { - /* create a repr() of the input string, - * just like PyLong_FromString does. */ - PyObject *srepr; - srepr = PyObject_Repr(x); - if (srepr == NULL) - return NULL; - PyErr_Format(PyExc_ValueError, - "invalid literal for long() with base %d: %s", - base, PyString_AS_STRING(srepr)); - Py_DECREF(srepr); - return NULL; - } - return PyLong_FromString(PyString_AS_STRING(x), NULL, base); - } -#ifdef Py_USING_UNICODE - else if (PyUnicode_Check(x)) - return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x), - PyUnicode_GET_SIZE(x), - base); -#endif - else { - PyErr_SetString(PyExc_TypeError, - "long() can't convert non-string with explicit base"); - return NULL; - } -} - -/* Wimpy, slow approach to tp_new calls for subtypes of long: - first create a regular long from whatever arguments we got, - then allocate a subtype instance and initialize it from - the regular long. The regular long is then thrown away. -*/ -static PyObject * -long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) -{ - PyLongObject *tmp, *newobj; - Py_ssize_t i, n; - - assert(PyType_IsSubtype(type, &PyLong_Type)); - tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds); - if (tmp == NULL) - return NULL; - assert(PyLong_CheckExact(tmp)); - n = Py_SIZE(tmp); - if (n < 0) - n = -n; - newobj = (PyLongObject *)type->tp_alloc(type, n); - if (newobj == NULL) { - Py_DECREF(tmp); - return NULL; - } - assert(PyLong_Check(newobj)); - Py_SIZE(newobj) = Py_SIZE(tmp); - for (i = 0; i < n; i++) - newobj->ob_digit[i] = tmp->ob_digit[i]; - Py_DECREF(tmp); - return (PyObject *)newobj; -} - -static PyObject * -long_getnewargs(PyLongObject *v) -{ - return Py_BuildValue("(N)", _PyLong_Copy(v)); -} - -static PyObject * -long_get0(PyLongObject *v, void *context) { - return PyLong_FromLong(0L); -} - -static PyObject * -long_get1(PyLongObject *v, void *context) { - return PyLong_FromLong(1L); -} - -static PyObject * -long__format__(PyObject *self, PyObject *args) -{ - PyObject *format_spec; - - if (!PyArg_ParseTuple(args, "O:__format__", &format_spec)) - return NULL; - if (PyBytes_Check(format_spec)) - return _PyLong_FormatAdvanced(self, - PyBytes_AS_STRING(format_spec), - PyBytes_GET_SIZE(format_spec)); - if (PyUnicode_Check(format_spec)) { - /* Convert format_spec to a str */ - PyObject *result; - PyObject *str_spec = PyObject_Str(format_spec); - - if (str_spec == NULL) - return NULL; - - result = _PyLong_FormatAdvanced(self, - PyBytes_AS_STRING(str_spec), - PyBytes_GET_SIZE(str_spec)); - - Py_DECREF(str_spec); - return result; - } - PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode"); - return NULL; -} - -static PyObject * -long_sizeof(PyLongObject *v) -{ - Py_ssize_t res; - - res = v->ob_type->tp_basicsize + ABS(Py_SIZE(v))*sizeof(digit); - return PyInt_FromSsize_t(res); -} - -static PyObject * -long_bit_length(PyLongObject *v) -{ - PyLongObject *result, *x, *y; - Py_ssize_t ndigits, msd_bits = 0; - digit msd; - - assert(v != NULL); - assert(PyLong_Check(v)); - - ndigits = ABS(Py_SIZE(v)); - if (ndigits == 0) - return PyInt_FromLong(0); - - msd = v->ob_digit[ndigits-1]; - while (msd >= 32) { - msd_bits += 6; - msd >>= 6; - } - msd_bits += (long)(BitLengthTable[msd]); - - if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT) - return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits); - - /* expression above may overflow; use Python integers instead */ - result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1); - if (result == NULL) - return NULL; - x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT); - if (x == NULL) - goto error; - y = (PyLongObject *)long_mul(result, x); - Py_DECREF(x); - if (y == NULL) - goto error; - Py_DECREF(result); - result = y; - - x = (PyLongObject *)PyLong_FromLong((long)msd_bits); - if (x == NULL) - goto error; - y = (PyLongObject *)long_add(result, x); - Py_DECREF(x); - if (y == NULL) - goto error; - Py_DECREF(result); - result = y; - - return (PyObject *)result; - - error: - Py_DECREF(result); - return NULL; -} - -PyDoc_STRVAR(long_bit_length_doc, -"long.bit_length() -> int or long\n\ -\n\ -Number of bits necessary to represent self in binary.\n\ ->>> bin(37L)\n\ -'0b100101'\n\ ->>> (37L).bit_length()\n\ -6"); - -#if 0 -static PyObject * -long_is_finite(PyObject *v) -{ - Py_RETURN_TRUE; -} -#endif - -static PyMethodDef long_methods[] = { - {"conjugate", (PyCFunction)long_long, METH_NOARGS, - "Returns self, the complex conjugate of any long."}, - {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS, - long_bit_length_doc}, -#if 0 - {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS, - "Returns always True."}, -#endif - {"__trunc__", (PyCFunction)long_long, METH_NOARGS, - "Truncating an Integral returns itself."}, - {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS}, - {"__format__", (PyCFunction)long__format__, METH_VARARGS}, - {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS, - "Returns size in memory, in bytes"}, - {NULL, NULL} /* sentinel */ -}; - -static PyGetSetDef long_getset[] = { - {"real", - (getter)long_long, (setter)NULL, - "the real part of a complex number", - NULL}, - {"imag", - (getter)long_get0, (setter)NULL, - "the imaginary part of a complex number", - NULL}, - {"numerator", - (getter)long_long, (setter)NULL, - "the numerator of a rational number in lowest terms", - NULL}, - {"denominator", - (getter)long_get1, (setter)NULL, - "the denominator of a rational number in lowest terms", - NULL}, - {NULL} /* Sentinel */ -}; - -PyDoc_STRVAR(long_doc, -"long(x[, base]) -> integer\n\ -\n\ -Convert a string or number to a long integer, if possible. A floating\n\ -point argument will be truncated towards zero (this does not include a\n\ -string representation of a floating point number!) When converting a\n\ -string, use the optional base. It is an error to supply a base when\n\ -converting a non-string."); - -static PyNumberMethods long_as_number = { - (binaryfunc)long_add, /*nb_add*/ - (binaryfunc)long_sub, /*nb_subtract*/ - (binaryfunc)long_mul, /*nb_multiply*/ - long_classic_div, /*nb_divide*/ - long_mod, /*nb_remainder*/ - long_divmod, /*nb_divmod*/ - long_pow, /*nb_power*/ - (unaryfunc)long_neg, /*nb_negative*/ - (unaryfunc)long_long, /*tp_positive*/ - (unaryfunc)long_abs, /*tp_absolute*/ - (inquiry)long_nonzero, /*tp_nonzero*/ - (unaryfunc)long_invert, /*nb_invert*/ - long_lshift, /*nb_lshift*/ - (binaryfunc)long_rshift, /*nb_rshift*/ - long_and, /*nb_and*/ - long_xor, /*nb_xor*/ - long_or, /*nb_or*/ - long_coerce, /*nb_coerce*/ - long_int, /*nb_int*/ - long_long, /*nb_long*/ - long_float, /*nb_float*/ - long_oct, /*nb_oct*/ - long_hex, /*nb_hex*/ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply */ - 0, /* nb_inplace_divide */ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - long_div, /* nb_floor_divide */ - long_true_divide, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ - long_long, /* nb_index */ -}; - -PyTypeObject PyLong_Type = { - PyObject_HEAD_INIT(&PyType_Type) - 0, /* ob_size */ - "long", /* tp_name */ - offsetof(PyLongObject, ob_digit), /* tp_basicsize */ - sizeof(digit), /* tp_itemsize */ - long_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - (cmpfunc)long_compare, /* tp_compare */ - long_repr, /* tp_repr */ - &long_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)long_hash, /* tp_hash */ - 0, /* tp_call */ - long_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | - Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */ - long_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - long_methods, /* tp_methods */ - 0, /* tp_members */ - long_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - long_new, /* tp_new */ - PyObject_Del, /* tp_free */ -}; - -static PyTypeObject Long_InfoType; - -PyDoc_STRVAR(long_info__doc__, -"sys.long_info\n\ -\n\ -A struct sequence that holds information about Python's\n\ -internal representation of integers. The attributes are read only."); - -static PyStructSequence_Field long_info_fields[] = { - {"bits_per_digit", "size of a digit in bits"}, - {"sizeof_digit", "size in bytes of the C type used to represent a digit"}, - {NULL, NULL} -}; - -static PyStructSequence_Desc long_info_desc = { - "sys.long_info", /* name */ - long_info__doc__, /* doc */ - long_info_fields, /* fields */ - 2 /* number of fields */ -}; - -PyObject * -PyLong_GetInfo(void) -{ - PyObject* long_info; - int field = 0; - long_info = PyStructSequence_New(&Long_InfoType); - if (long_info == NULL) - return NULL; - PyStructSequence_SET_ITEM(long_info, field++, - PyInt_FromLong(PyLong_SHIFT)); - PyStructSequence_SET_ITEM(long_info, field++, - PyInt_FromLong(sizeof(digit))); - if (PyErr_Occurred()) { - Py_CLEAR(long_info); - return NULL; - } - return long_info; -} - -int -_PyLong_Init(void) -{ - /* initialize long_info */ - if (Long_InfoType.tp_name == 0) - PyStructSequence_InitType(&Long_InfoType, &long_info_desc); - return 1; -} diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Objects/stringlib/localeutil.h b/AppPkg/Applications/Python/PyMod-2.7.2/Objects/stringlib/localeutil.h deleted file mode 100644 index 45c980c..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Objects/stringlib/localeutil.h +++ /dev/null @@ -1,227 +0,0 @@ -/** @file - stringlib: locale related helpers implementation. - - 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 STRINGLIB_LOCALEUTIL_H -#define STRINGLIB_LOCALEUTIL_H - -#include - -// Prevent conflicts with EFI -#undef MAX -#undef MIN - -#define MAX(x, y) ((x) < (y) ? (y) : (x)) -#define MIN(x, y) ((x) < (y) ? (x) : (y)) - -typedef struct { - const char *grouping; - char previous; - Py_ssize_t i; /* Where we're currently pointing in grouping. */ -} GroupGenerator; - -static void -_GroupGenerator_init(GroupGenerator *self, const char *grouping) -{ - self->grouping = grouping; - self->i = 0; - self->previous = 0; -} - -/* Returns the next grouping, or 0 to signify end. */ -static Py_ssize_t -_GroupGenerator_next(GroupGenerator *self) -{ - /* Note that we don't really do much error checking here. If a - grouping string contains just CHAR_MAX, for example, then just - terminate the generator. That shouldn't happen, but at least we - fail gracefully. */ - switch (self->grouping[self->i]) { - case 0: - return self->previous; - case CHAR_MAX: - /* Stop the generator. */ - return 0; - default: { - char ch = self->grouping[self->i]; - self->previous = ch; - self->i++; - return (Py_ssize_t)ch; - } - } -} - -/* Fill in some digits, leading zeros, and thousands separator. All - are optional, depending on when we're called. */ -static void -fill(STRINGLIB_CHAR **digits_end, STRINGLIB_CHAR **buffer_end, - Py_ssize_t n_chars, Py_ssize_t n_zeros, const char* thousands_sep, - Py_ssize_t thousands_sep_len) -{ -#if STRINGLIB_IS_UNICODE - Py_ssize_t i; -#endif - - if (thousands_sep) { - *buffer_end -= thousands_sep_len; - - /* Copy the thousands_sep chars into the buffer. */ -#if STRINGLIB_IS_UNICODE - /* Convert from the char's of the thousands_sep from - the locale into unicode. */ - for (i = 0; i < thousands_sep_len; ++i) - (*buffer_end)[i] = thousands_sep[i]; -#else - /* No conversion, just memcpy the thousands_sep. */ - memcpy(*buffer_end, thousands_sep, thousands_sep_len); -#endif - } - - *buffer_end -= n_chars; - *digits_end -= n_chars; - memcpy(*buffer_end, *digits_end, n_chars * sizeof(STRINGLIB_CHAR)); - - *buffer_end -= n_zeros; - STRINGLIB_FILL(*buffer_end, '0', n_zeros); -} - -/** - * _Py_InsertThousandsGrouping: - * @buffer: A pointer to the start of a string. - * @n_buffer: Number of characters in @buffer. - * @digits: A pointer to the digits we're reading from. If count - * is non-NULL, this is unused. - * @n_digits: The number of digits in the string, in which we want - * to put the grouping chars. - * @min_width: The minimum width of the digits in the output string. - * Output will be zero-padded on the left to fill. - * @grouping: see definition in localeconv(). - * @thousands_sep: see definition in localeconv(). - * - * There are 2 modes: counting and filling. If @buffer is NULL, - * we are in counting mode, else filling mode. - * If counting, the required buffer size is returned. - * If filling, we know the buffer will be large enough, so we don't - * need to pass in the buffer size. - * Inserts thousand grouping characters (as defined by grouping and - * thousands_sep) into the string between buffer and buffer+n_digits. - * - * Return value: 0 on error, else 1. Note that no error can occur if - * count is non-NULL. - * - * This name won't be used, the includer of this file should define - * it to be the actual function name, based on unicode or string. - * - * As closely as possible, this code mimics the logic in decimal.py's - _insert_thousands_sep(). - **/ -Py_ssize_t -_Py_InsertThousandsGrouping(STRINGLIB_CHAR *buffer, - Py_ssize_t n_buffer, - STRINGLIB_CHAR *digits, - Py_ssize_t n_digits, - Py_ssize_t min_width, - const char *grouping, - const char *thousands_sep) -{ - Py_ssize_t count = 0; - Py_ssize_t n_zeros; - int loop_broken = 0; - int use_separator = 0; /* First time through, don't append the - separator. They only go between - groups. */ - STRINGLIB_CHAR *buffer_end = NULL; - STRINGLIB_CHAR *digits_end = NULL; - Py_ssize_t l; - Py_ssize_t n_chars; - Py_ssize_t thousands_sep_len = strlen(thousands_sep); - Py_ssize_t remaining = n_digits; /* Number of chars remaining to - be looked at */ - /* A generator that returns all of the grouping widths, until it - returns 0. */ - GroupGenerator groupgen; - _GroupGenerator_init(&groupgen, grouping); - - if (buffer) { - buffer_end = buffer + n_buffer; - digits_end = digits + n_digits; - } - - while ((l = _GroupGenerator_next(&groupgen)) > 0) { - l = MIN(l, MAX(MAX(remaining, min_width), 1)); - n_zeros = MAX(0, l - remaining); - n_chars = MAX(0, MIN(remaining, l)); - - /* Use n_zero zero's and n_chars chars */ - - /* Count only, don't do anything. */ - count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars; - - if (buffer) { - /* Copy into the output buffer. */ - fill(&digits_end, &buffer_end, n_chars, n_zeros, - use_separator ? thousands_sep : NULL, thousands_sep_len); - } - - /* Use a separator next time. */ - use_separator = 1; - - remaining -= n_chars; - min_width -= l; - - if (remaining <= 0 && min_width <= 0) { - loop_broken = 1; - break; - } - min_width -= thousands_sep_len; - } - if (!loop_broken) { - /* We left the loop without using a break statement. */ - - l = MAX(MAX(remaining, min_width), 1); - n_zeros = MAX(0, l - remaining); - n_chars = MAX(0, MIN(remaining, l)); - - /* Use n_zero zero's and n_chars chars */ - count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars; - if (buffer) { - /* Copy into the output buffer. */ - fill(&digits_end, &buffer_end, n_chars, n_zeros, - use_separator ? thousands_sep : NULL, thousands_sep_len); - } - } - return count; -} - -/** - * _Py_InsertThousandsGroupingLocale: - * @buffer: A pointer to the start of a string. - * @n_digits: The number of digits in the string, in which we want - * to put the grouping chars. - * - * Reads thee current locale and calls _Py_InsertThousandsGrouping(). - **/ -Py_ssize_t -_Py_InsertThousandsGroupingLocale(STRINGLIB_CHAR *buffer, - Py_ssize_t n_buffer, - STRINGLIB_CHAR *digits, - Py_ssize_t n_digits, - Py_ssize_t min_width) -{ - struct lconv *locale_data = localeconv(); - const char *grouping = locale_data->grouping; - const char *thousands_sep = locale_data->thousands_sep; - - return _Py_InsertThousandsGrouping(buffer, n_buffer, digits, n_digits, - min_width, grouping, thousands_sep); -} -#endif /* STRINGLIB_LOCALEUTIL_H */ diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Python/getcopyright.c b/AppPkg/Applications/Python/PyMod-2.7.2/Python/getcopyright.c deleted file mode 100644 index 66ebc75..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Python/getcopyright.c +++ /dev/null @@ -1,36 +0,0 @@ -/* Return the copyright string. This is updated manually. - - 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. -*/ - -#include "Python.h" - -static char cprt[] = -"\ -Copyright (c) 2010-2011 Intel Corporation.\n\ -All Rights Reserved.\n\ -\n\ -Copyright (c) 2001-2011 Python Software Foundation.\n\ -All Rights Reserved.\n\ -\n\ -Copyright (c) 2000 BeOpen.com.\n\ -All Rights Reserved.\n\ -\n\ -Copyright (c) 1995-2001 Corporation for National Research Initiatives.\n\ -All Rights Reserved.\n\ -\n\ -Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\n\ -All Rights Reserved."; - -const char * -Py_GetCopyright(void) -{ - return cprt; -} diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Python/import.c b/AppPkg/Applications/Python/PyMod-2.7.2/Python/import.c deleted file mode 100644 index 31ccd31..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Python/import.c +++ /dev/null @@ -1,3398 +0,0 @@ - -/* Module definition and import implementation */ - -#include "Python.h" - -#include "Python-ast.h" -#undef Yield /* undefine macro conflicting with winbase.h */ -#include "pyarena.h" -#include "pythonrun.h" -#include "errcode.h" -#include "marshal.h" -#include "code.h" -#include "compile.h" -#include "eval.h" -#include "osdefs.h" -#include "importdl.h" - -#ifdef HAVE_FCNTL_H -#include -#endif -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef MS_WINDOWS -/* for stat.st_mode */ -typedef unsigned short mode_t; -#endif - - -/* Magic word to reject .pyc files generated by other Python versions. - It should change for each incompatible change to the bytecode. - - The value of CR and LF is incorporated so if you ever read or write - a .pyc file in text mode the magic number will be wrong; also, the - Apple MPW compiler swaps their values, botching string constants. - - The magic numbers must be spaced apart atleast 2 values, as the - -U interpeter flag will cause MAGIC+1 being used. They have been - odd numbers for some time now. - - There were a variety of old schemes for setting the magic number. - The current working scheme is to increment the previous value by - 10. - - Known values: - Python 1.5: 20121 - Python 1.5.1: 20121 - Python 1.5.2: 20121 - Python 1.6: 50428 - Python 2.0: 50823 - Python 2.0.1: 50823 - Python 2.1: 60202 - Python 2.1.1: 60202 - Python 2.1.2: 60202 - Python 2.2: 60717 - Python 2.3a0: 62011 - Python 2.3a0: 62021 - Python 2.3a0: 62011 (!) - Python 2.4a0: 62041 - Python 2.4a3: 62051 - Python 2.4b1: 62061 - Python 2.5a0: 62071 - Python 2.5a0: 62081 (ast-branch) - Python 2.5a0: 62091 (with) - Python 2.5a0: 62092 (changed WITH_CLEANUP opcode) - Python 2.5b3: 62101 (fix wrong code: for x, in ...) - Python 2.5b3: 62111 (fix wrong code: x += yield) - Python 2.5c1: 62121 (fix wrong lnotab with for loops and - storing constants that should have been removed) - Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp) - Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode) - Python 2.6a1: 62161 (WITH_CLEANUP optimization) - Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND) - Python 2.7a0: 62181 (optimize conditional branches: - introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE) - Python 2.7a0 62191 (introduce SETUP_WITH) - Python 2.7a0 62201 (introduce BUILD_SET) - Python 2.7a0 62211 (introduce MAP_ADD and SET_ADD) -. -*/ -#define MAGIC (62211 | ((long)'\r'<<16) | ((long)'\n'<<24)) - -/* Magic word as global; note that _PyImport_Init() can change the - value of this global to accommodate for alterations of how the - compiler works which are enabled by command line switches. */ -static long pyc_magic = MAGIC; - -/* See _PyImport_FixupExtension() below */ -static PyObject *extensions = NULL; - -/* This table is defined in config.c: */ -extern struct _inittab _PyImport_Inittab[]; - -struct _inittab *PyImport_Inittab = _PyImport_Inittab; - -/* these tables define the module suffixes that Python recognizes */ -struct filedescr * _PyImport_Filetab = NULL; - -#ifdef RISCOS -static const struct filedescr _PyImport_StandardFiletab[] = { - {"/py", "U", PY_SOURCE}, - {"/pyc", "rb", PY_COMPILED}, - {0, 0} -}; -#else -static const struct filedescr _PyImport_StandardFiletab[] = { - {".py", "U", PY_SOURCE}, -#ifdef MS_WINDOWS - {".pyw", "U", PY_SOURCE}, -#endif - {".pyc", "rb", PY_COMPILED}, - {0, 0} -}; -#endif - - -/* Initialize things */ - -void -_PyImport_Init(void) -{ - const struct filedescr *scan; - struct filedescr *filetab; - int countD = 0; - int countS = 0; - - /* prepare _PyImport_Filetab: copy entries from - _PyImport_DynLoadFiletab and _PyImport_StandardFiletab. - */ -#ifdef HAVE_DYNAMIC_LOADING - for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan) - ++countD; -#endif - for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan) - ++countS; - filetab = PyMem_NEW(struct filedescr, countD + countS + 1); - if (filetab == NULL) - Py_FatalError("Can't initialize import file table."); -#ifdef HAVE_DYNAMIC_LOADING - memcpy(filetab, _PyImport_DynLoadFiletab, - countD * sizeof(struct filedescr)); -#endif - memcpy(filetab + countD, _PyImport_StandardFiletab, - countS * sizeof(struct filedescr)); - filetab[countD + countS].suffix = NULL; - - _PyImport_Filetab = filetab; - - if (Py_OptimizeFlag) { - /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */ - for (; filetab->suffix != NULL; filetab++) { -#ifndef RISCOS - if (strcmp(filetab->suffix, ".pyc") == 0) - filetab->suffix = ".pyo"; -#else - if (strcmp(filetab->suffix, "/pyc") == 0) - filetab->suffix = "/pyo"; -#endif - } - } - - if (Py_UnicodeFlag) { - /* Fix the pyc_magic so that byte compiled code created - using the all-Unicode method doesn't interfere with - code created in normal operation mode. */ - pyc_magic = MAGIC + 1; - } -} - -void -_PyImportHooks_Init(void) -{ - PyObject *v, *path_hooks = NULL, *zimpimport; - int err = 0; - - /* adding sys.path_hooks and sys.path_importer_cache, setting up - zipimport */ - if (PyType_Ready(&PyNullImporter_Type) < 0) - goto error; - - if (Py_VerboseFlag) - PySys_WriteStderr("# installing zipimport hook\n"); - - v = PyList_New(0); - if (v == NULL) - goto error; - err = PySys_SetObject("meta_path", v); - Py_DECREF(v); - if (err) - goto error; - v = PyDict_New(); - if (v == NULL) - goto error; - err = PySys_SetObject("path_importer_cache", v); - Py_DECREF(v); - if (err) - goto error; - path_hooks = PyList_New(0); - if (path_hooks == NULL) - goto error; - err = PySys_SetObject("path_hooks", path_hooks); - if (err) { - error: - PyErr_Print(); - Py_FatalError("initializing sys.meta_path, sys.path_hooks, " - "path_importer_cache, or NullImporter failed" - ); - } - - zimpimport = PyImport_ImportModule("zipimport"); - if (zimpimport == NULL) { - PyErr_Clear(); /* No zip import module -- okay */ - if (Py_VerboseFlag) - PySys_WriteStderr("# can't import zipimport\n"); - } - else { - PyObject *zipimporter = PyObject_GetAttrString(zimpimport, - "zipimporter"); - Py_DECREF(zimpimport); - if (zipimporter == NULL) { - PyErr_Clear(); /* No zipimporter object -- okay */ - if (Py_VerboseFlag) - PySys_WriteStderr( - "# can't import zipimport.zipimporter\n"); - } - else { - /* sys.path_hooks.append(zipimporter) */ - err = PyList_Append(path_hooks, zipimporter); - Py_DECREF(zipimporter); - if (err) - goto error; - if (Py_VerboseFlag) - PySys_WriteStderr( - "# installed zipimport hook\n"); - } - } - Py_DECREF(path_hooks); -} - -void -_PyImport_Fini(void) -{ - Py_XDECREF(extensions); - extensions = NULL; - PyMem_DEL(_PyImport_Filetab); - _PyImport_Filetab = NULL; -} - - -/* Locking primitives to prevent parallel imports of the same module - in different threads to return with a partially loaded module. - These calls are serialized by the global interpreter lock. */ - -#ifdef WITH_THREAD - -#include "pythread.h" - -static PyThread_type_lock import_lock = 0; -static long import_lock_thread = -1; -static int import_lock_level = 0; - -void -_PyImport_AcquireLock(void) -{ - long me = PyThread_get_thread_ident(); - if (me == -1) - return; /* Too bad */ - if (import_lock == NULL) { - import_lock = PyThread_allocate_lock(); - if (import_lock == NULL) - return; /* Nothing much we can do. */ - } - if (import_lock_thread == me) { - import_lock_level++; - return; - } - if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) - { - PyThreadState *tstate = PyEval_SaveThread(); - PyThread_acquire_lock(import_lock, 1); - PyEval_RestoreThread(tstate); - } - import_lock_thread = me; - import_lock_level = 1; -} - -int -_PyImport_ReleaseLock(void) -{ - long me = PyThread_get_thread_ident(); - if (me == -1 || import_lock == NULL) - return 0; /* Too bad */ - if (import_lock_thread != me) - return -1; - import_lock_level--; - if (import_lock_level == 0) { - import_lock_thread = -1; - PyThread_release_lock(import_lock); - } - return 1; -} - -/* This function is called from PyOS_AfterFork to ensure that newly - created child processes do not share locks with the parent. - We now acquire the import lock around fork() calls but on some platforms - (Solaris 9 and earlier? see isue7242) that still left us with problems. */ - -void -_PyImport_ReInitLock(void) -{ - if (import_lock != NULL) - import_lock = PyThread_allocate_lock(); - import_lock_thread = -1; - import_lock_level = 0; -} - -#endif - -static PyObject * -imp_lock_held(PyObject *self, PyObject *noargs) -{ -#ifdef WITH_THREAD - return PyBool_FromLong(import_lock_thread != -1); -#else - return PyBool_FromLong(0); -#endif -} - -static PyObject * -imp_acquire_lock(PyObject *self, PyObject *noargs) -{ -#ifdef WITH_THREAD - _PyImport_AcquireLock(); -#endif - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -imp_release_lock(PyObject *self, PyObject *noargs) -{ -#ifdef WITH_THREAD - if (_PyImport_ReleaseLock() < 0) { - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } -#endif - Py_INCREF(Py_None); - return Py_None; -} - -static void -imp_modules_reloading_clear(void) -{ - PyInterpreterState *interp = PyThreadState_Get()->interp; - if (interp->modules_reloading != NULL) - PyDict_Clear(interp->modules_reloading); -} - -/* Helper for sys */ - -PyObject * -PyImport_GetModuleDict(void) -{ - PyInterpreterState *interp = PyThreadState_GET()->interp; - if (interp->modules == NULL) - Py_FatalError("PyImport_GetModuleDict: no module dictionary!"); - return interp->modules; -} - - -/* List of names to clear in sys */ -static char* sys_deletes[] = { - "path", "argv", "ps1", "ps2", "exitfunc", - "exc_type", "exc_value", "exc_traceback", - "last_type", "last_value", "last_traceback", - "path_hooks", "path_importer_cache", "meta_path", - /* misc stuff */ - "flags", "float_info", - NULL -}; - -static char* sys_files[] = { - "stdin", "__stdin__", - "stdout", "__stdout__", - "stderr", "__stderr__", - NULL -}; - - -/* Un-initialize things, as good as we can */ - -void -PyImport_Cleanup(void) -{ - Py_ssize_t pos, ndone; - char *name; - PyObject *key, *value, *dict; - PyInterpreterState *interp = PyThreadState_GET()->interp; - PyObject *modules = interp->modules; - - if (modules == NULL) - return; /* Already done */ - - /* Delete some special variables first. These are common - places where user values hide and people complain when their - destructors fail. Since the modules containing them are - deleted *last* of all, they would come too late in the normal - destruction order. Sigh. */ - - value = PyDict_GetItemString(modules, "__builtin__"); - if (value != NULL && PyModule_Check(value)) { - dict = PyModule_GetDict(value); - if (Py_VerboseFlag) - PySys_WriteStderr("# clear __builtin__._\n"); - PyDict_SetItemString(dict, "_", Py_None); - } - value = PyDict_GetItemString(modules, "sys"); - if (value != NULL && PyModule_Check(value)) { - char **p; - PyObject *v; - dict = PyModule_GetDict(value); - for (p = sys_deletes; *p != NULL; p++) { - if (Py_VerboseFlag) - PySys_WriteStderr("# clear sys.%s\n", *p); - PyDict_SetItemString(dict, *p, Py_None); - } - for (p = sys_files; *p != NULL; p+=2) { - if (Py_VerboseFlag) - PySys_WriteStderr("# restore sys.%s\n", *p); - v = PyDict_GetItemString(dict, *(p+1)); - if (v == NULL) - v = Py_None; - PyDict_SetItemString(dict, *p, v); - } - } - - /* First, delete __main__ */ - value = PyDict_GetItemString(modules, "__main__"); - if (value != NULL && PyModule_Check(value)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup __main__\n"); - _PyModule_Clear(value); - PyDict_SetItemString(modules, "__main__", Py_None); - } - - /* The special treatment of __builtin__ here is because even - when it's not referenced as a module, its dictionary is - referenced by almost every module's __builtins__. Since - deleting a module clears its dictionary (even if there are - references left to it), we need to delete the __builtin__ - module last. Likewise, we don't delete sys until the very - end because it is implicitly referenced (e.g. by print). - - Also note that we 'delete' modules by replacing their entry - in the modules dict with None, rather than really deleting - them; this avoids a rehash of the modules dictionary and - also marks them as "non existent" so they won't be - re-imported. */ - - /* Next, repeatedly delete modules with a reference count of - one (skipping __builtin__ and sys) and delete them */ - do { - ndone = 0; - pos = 0; - while (PyDict_Next(modules, &pos, &key, &value)) { - if (value->ob_refcnt != 1) - continue; - if (PyString_Check(key) && PyModule_Check(value)) { - name = PyString_AS_STRING(key); - if (strcmp(name, "__builtin__") == 0) - continue; - if (strcmp(name, "sys") == 0) - continue; - if (Py_VerboseFlag) - PySys_WriteStderr( - "# cleanup[1] %s\n", name); - _PyModule_Clear(value); - PyDict_SetItem(modules, key, Py_None); - ndone++; - } - } - } while (ndone > 0); - - /* Next, delete all modules (still skipping __builtin__ and sys) */ - pos = 0; - while (PyDict_Next(modules, &pos, &key, &value)) { - if (PyString_Check(key) && PyModule_Check(value)) { - name = PyString_AS_STRING(key); - if (strcmp(name, "__builtin__") == 0) - continue; - if (strcmp(name, "sys") == 0) - continue; - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup[2] %s\n", name); - _PyModule_Clear(value); - PyDict_SetItem(modules, key, Py_None); - } - } - - /* Next, delete sys and __builtin__ (in that order) */ - value = PyDict_GetItemString(modules, "sys"); - if (value != NULL && PyModule_Check(value)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup sys\n"); - _PyModule_Clear(value); - PyDict_SetItemString(modules, "sys", Py_None); - } - value = PyDict_GetItemString(modules, "__builtin__"); - if (value != NULL && PyModule_Check(value)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup __builtin__\n"); - _PyModule_Clear(value); - PyDict_SetItemString(modules, "__builtin__", Py_None); - } - - /* Finally, clear and delete the modules directory */ - PyDict_Clear(modules); - interp->modules = NULL; - Py_DECREF(modules); - Py_CLEAR(interp->modules_reloading); -} - - -/* Helper for pythonrun.c -- return magic number */ - -long -PyImport_GetMagicNumber(void) -{ - return pyc_magic; -} - - -/* Magic for extension modules (built-in as well as dynamically - loaded). To prevent initializing an extension module more than - once, we keep a static dictionary 'extensions' keyed by module name - (for built-in modules) or by filename (for dynamically loaded - modules), containing these modules. A copy of the module's - dictionary is stored by calling _PyImport_FixupExtension() - immediately after the module initialization function succeeds. A - copy can be retrieved from there by calling - _PyImport_FindExtension(). */ - -PyObject * -_PyImport_FixupExtension(char *name, char *filename) -{ - PyObject *modules, *mod, *dict, *copy; - if (extensions == NULL) { - extensions = PyDict_New(); - if (extensions == NULL) - return NULL; - } - modules = PyImport_GetModuleDict(); - mod = PyDict_GetItemString(modules, name); - if (mod == NULL || !PyModule_Check(mod)) { - PyErr_Format(PyExc_SystemError, - "_PyImport_FixupExtension: module %.200s not loaded", name); - return NULL; - } - dict = PyModule_GetDict(mod); - if (dict == NULL) - return NULL; - copy = PyDict_Copy(dict); - if (copy == NULL) - return NULL; - PyDict_SetItemString(extensions, filename, copy); - Py_DECREF(copy); - return copy; -} - -PyObject * -_PyImport_FindExtension(char *name, char *filename) -{ - PyObject *dict, *mod, *mdict; - if (extensions == NULL) - return NULL; - dict = PyDict_GetItemString(extensions, filename); - if (dict == NULL) - return NULL; - mod = PyImport_AddModule(name); - if (mod == NULL) - return NULL; - mdict = PyModule_GetDict(mod); - if (mdict == NULL) - return NULL; - if (PyDict_Update(mdict, dict)) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # previously loaded (%s)\n", - name, filename); - return mod; -} - - -/* Get the module object corresponding to a module name. - First check the modules dictionary if there's one there, - if not, create a new one and insert it in the modules dictionary. - Because the former action is most common, THIS DOES NOT RETURN A - 'NEW' REFERENCE! */ - -PyObject * -PyImport_AddModule(const char *name) -{ - PyObject *modules = PyImport_GetModuleDict(); - PyObject *m; - - if ((m = PyDict_GetItemString(modules, name)) != NULL && - PyModule_Check(m)) - return m; - m = PyModule_New(name); - if (m == NULL) - return NULL; - if (PyDict_SetItemString(modules, name, m) != 0) { - Py_DECREF(m); - return NULL; - } - Py_DECREF(m); /* Yes, it still exists, in modules! */ - - return m; -} - -/* Remove name from sys.modules, if it's there. */ -static void -remove_module(const char *name) -{ - PyObject *modules = PyImport_GetModuleDict(); - if (PyDict_GetItemString(modules, name) == NULL) - return; - if (PyDict_DelItemString(modules, name) < 0) - Py_FatalError("import: deleting existing key in" - "sys.modules failed"); -} - -/* Execute a code object in a module and return the module object - * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is - * removed from sys.modules, to avoid leaving damaged module objects - * in sys.modules. The caller may wish to restore the original - * module object (if any) in this case; PyImport_ReloadModule is an - * example. - */ -PyObject * -PyImport_ExecCodeModule(char *name, PyObject *co) -{ - return PyImport_ExecCodeModuleEx(name, co, (char *)NULL); -} - -PyObject * -PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname) -{ - PyObject *modules = PyImport_GetModuleDict(); - PyObject *m, *d, *v; - - m = PyImport_AddModule(name); - if (m == NULL) - return NULL; - /* If the module is being reloaded, we get the old module back - and re-use its dict to exec the new code. */ - d = PyModule_GetDict(m); - if (PyDict_GetItemString(d, "__builtins__") == NULL) { - if (PyDict_SetItemString(d, "__builtins__", - PyEval_GetBuiltins()) != 0) - goto error; - } - /* Remember the filename as the __file__ attribute */ - v = NULL; - if (pathname != NULL) { - v = PyString_FromString(pathname); - if (v == NULL) - PyErr_Clear(); - } - if (v == NULL) { - v = ((PyCodeObject *)co)->co_filename; - Py_INCREF(v); - } - if (PyDict_SetItemString(d, "__file__", v) != 0) - PyErr_Clear(); /* Not important enough to report */ - Py_DECREF(v); - - v = PyEval_EvalCode((PyCodeObject *)co, d, d); - if (v == NULL) - goto error; - Py_DECREF(v); - - if ((m = PyDict_GetItemString(modules, name)) == NULL) { - PyErr_Format(PyExc_ImportError, - "Loaded module %.200s not found in sys.modules", - name); - return NULL; - } - - Py_INCREF(m); - - return m; - - error: - remove_module(name); - return NULL; -} - - -/* Given a pathname for a Python source file, fill a buffer with the - pathname for the corresponding compiled file. Return the pathname - for the compiled file, or NULL if there's no space in the buffer. - Doesn't set an exception. */ - -static char * -make_compiled_pathname(char *pathname, char *buf, size_t buflen) -{ - size_t len = strlen(pathname); - if (len+2 > buflen) - return NULL; - -#ifdef MS_WINDOWS - /* Treat .pyw as if it were .py. The case of ".pyw" must match - that used in _PyImport_StandardFiletab. */ - if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0) - --len; /* pretend 'w' isn't there */ -#endif - memcpy(buf, pathname, len); - buf[len] = Py_OptimizeFlag ? 'o' : 'c'; - buf[len+1] = '\0'; - - return buf; -} - - -/* Given a pathname for a Python source file, its time of last - modification, and a pathname for a compiled file, check whether the - compiled file represents the same version of the source. If so, - return a FILE pointer for the compiled file, positioned just after - the header; if not, return NULL. - Doesn't set an exception. */ - -static FILE * -check_compiled_module(char *pathname, time_t mtime, char *cpathname) -{ - FILE *fp; - long magic; - long pyc_mtime; - - fp = fopen(cpathname, "rb"); - if (fp == NULL) - return NULL; - magic = PyMarshal_ReadLongFromFile(fp); - if (magic != pyc_magic) { - if (Py_VerboseFlag) - PySys_WriteStderr("# %s has bad magic\n", cpathname); - fclose(fp); - return NULL; - } - pyc_mtime = PyMarshal_ReadLongFromFile(fp); - if (pyc_mtime != mtime) { - if (Py_VerboseFlag) - PySys_WriteStderr("# %s has bad mtime\n", cpathname); - fclose(fp); - return NULL; - } - if (Py_VerboseFlag) - PySys_WriteStderr("# %s matches %s\n", cpathname, pathname); - return fp; -} - - -/* Read a code object from a file and check it for validity */ - -static PyCodeObject * -read_compiled_module(char *cpathname, FILE *fp) -{ - PyObject *co; - - co = PyMarshal_ReadLastObjectFromFile(fp); - if (co == NULL) - return NULL; - if (!PyCode_Check(co)) { - PyErr_Format(PyExc_ImportError, - "Non-code object in %.200s", cpathname); - Py_DECREF(co); - return NULL; - } - return (PyCodeObject *)co; -} - - -/* Load a module from a compiled file, execute it, and return its - module object WITH INCREMENTED REFERENCE COUNT */ - -static PyObject * -load_compiled_module(char *name, char *cpathname, FILE *fp) -{ - long magic; - PyCodeObject *co; - PyObject *m; - - magic = PyMarshal_ReadLongFromFile(fp); - if (magic != pyc_magic) { - PyErr_Format(PyExc_ImportError, - "Bad magic number in %.200s", cpathname); - return NULL; - } - (void) PyMarshal_ReadLongFromFile(fp); - co = read_compiled_module(cpathname, fp); - if (co == NULL) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # precompiled from %s\n", - name, cpathname); - m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname); - Py_DECREF(co); - - return m; -} - -/* Parse a source file and return the corresponding code object */ - -static PyCodeObject * -parse_source_module(const char *pathname, FILE *fp) -{ - PyCodeObject *co = NULL; - mod_ty mod; - PyCompilerFlags flags; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - flags.cf_flags = 0; - - mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, &flags, - NULL, arena); - if (mod) { - co = PyAST_Compile(mod, pathname, NULL, arena); - } - PyArena_Free(arena); - return co; -} - - -/* Helper to open a bytecode file for writing in exclusive mode */ - -static FILE * -open_exclusive(char *filename, mode_t mode) -{ -#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC) - /* Use O_EXCL to avoid a race condition when another process tries to - write the same file. When that happens, our open() call fails, - which is just fine (since it's only a cache). - XXX If the file exists and is writable but the directory is not - writable, the file will never be written. Oh well. - */ - int fd; - (void) unlink(filename); - fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC -#ifdef O_BINARY - |O_BINARY /* necessary for Windows */ -#endif -#ifdef __VMS - , mode, "ctxt=bin", "shr=nil" -#else - , mode -#endif - ); - if (fd < 0) - return NULL; - return fdopen(fd, "wb"); -#else - /* Best we can do -- on Windows this can't happen anyway */ - return fopen(filename, "wb"); -#endif -} - - -/* Write a compiled module to a file, placing the time of last - modification of its source into the header. - Errors are ignored, if a write error occurs an attempt is made to - remove the file. */ - -static void -write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat) -{ - FILE *fp; - time_t mtime = srcstat->st_mtime; -#ifdef MS_WINDOWS /* since Windows uses different permissions */ - mode_t mode = srcstat->st_mode & ~S_IEXEC; -#else - mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH; -#endif - - fp = open_exclusive(cpathname, mode); - if (fp == NULL) { - if (Py_VerboseFlag) - PySys_WriteStderr( - "# can't create %s\n", cpathname); - return; - } - PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION); - /* First write a 0 for mtime */ - PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION); - PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION); - if (fflush(fp) != 0 || ferror(fp)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# can't write %s\n", cpathname); - /* Don't keep partial file */ - fclose(fp); - (void) unlink(cpathname); - return; - } - /* Now write the true mtime */ - fseek(fp, 4L, 0); - assert(mtime < LONG_MAX); - PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION); - fflush(fp); - fclose(fp); - if (Py_VerboseFlag) - PySys_WriteStderr("# wrote %s\n", cpathname); -} - -static void -update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname) -{ - PyObject *constants, *tmp; - Py_ssize_t i, n; - - if (!_PyString_Eq(co->co_filename, oldname)) - return; - - tmp = co->co_filename; - co->co_filename = newname; - Py_INCREF(co->co_filename); - Py_DECREF(tmp); - - constants = co->co_consts; - n = PyTuple_GET_SIZE(constants); - for (i = 0; i < n; i++) { - tmp = PyTuple_GET_ITEM(constants, i); - if (PyCode_Check(tmp)) - update_code_filenames((PyCodeObject *)tmp, - oldname, newname); - } -} - -static int -update_compiled_module(PyCodeObject *co, char *pathname) -{ - PyObject *oldname, *newname; - - if (strcmp(PyString_AsString(co->co_filename), pathname) == 0) - return 0; - - newname = PyString_FromString(pathname); - if (newname == NULL) - return -1; - - oldname = co->co_filename; - Py_INCREF(oldname); - update_code_filenames(co, oldname, newname); - Py_DECREF(oldname); - Py_DECREF(newname); - return 1; -} - -/* Load a source module from a given file and return its module - object WITH INCREMENTED REFERENCE COUNT. If there's a matching - byte-compiled file, use that instead. */ - -static PyObject * -load_source_module(char *name, char *pathname, FILE *fp) -{ - struct stat st; - FILE *fpc; - char buf[MAXPATHLEN+1]; - char *cpathname; - PyCodeObject *co; - PyObject *m; - - if (fstat(fileno(fp), &st) != 0) { - PyErr_Format(PyExc_RuntimeError, - "unable to get file status from '%s'", - pathname); - return NULL; - } -#if SIZEOF_TIME_T > 4 - /* Python's .pyc timestamp handling presumes that the timestamp fits - in 4 bytes. This will be fine until sometime in the year 2038, - when a 4-byte signed time_t will overflow. - */ - if (st.st_mtime >> 32) { - PyErr_SetString(PyExc_OverflowError, - "modification time overflows a 4 byte field"); - return NULL; - } -#endif - cpathname = make_compiled_pathname(pathname, buf, - (size_t)MAXPATHLEN + 1); - if (cpathname != NULL && - (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) { - co = read_compiled_module(cpathname, fpc); - fclose(fpc); - if (co == NULL) - return NULL; - if (update_compiled_module(co, pathname) < 0) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # precompiled from %s\n", - name, cpathname); - pathname = cpathname; - } - else { - co = parse_source_module(pathname, fp); - if (co == NULL) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # from %s\n", - name, pathname); - if (cpathname) { - PyObject *ro = PySys_GetObject("dont_write_bytecode"); - if (ro == NULL || !PyObject_IsTrue(ro)) - write_compiled_module(co, cpathname, &st); - } - } - m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname); - Py_DECREF(co); - - return m; -} - - -/* Forward */ -static PyObject *load_module(char *, FILE *, char *, int, PyObject *); -static struct filedescr *find_module(char *, char *, PyObject *, - char *, size_t, FILE **, PyObject **); -static struct _frozen *find_frozen(char *name); - -/* Load a package and return its module object WITH INCREMENTED - REFERENCE COUNT */ - -static PyObject * -load_package(char *name, char *pathname) -{ - PyObject *m, *d; - PyObject *file = NULL; - PyObject *path = NULL; - int err; - char buf[MAXPATHLEN+1]; - FILE *fp = NULL; - struct filedescr *fdp; - - m = PyImport_AddModule(name); - if (m == NULL) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # directory %s\n", - name, pathname); - d = PyModule_GetDict(m); - file = PyString_FromString(pathname); - if (file == NULL) - goto error; - path = Py_BuildValue("[O]", file); - if (path == NULL) - goto error; - err = PyDict_SetItemString(d, "__file__", file); - if (err == 0) - err = PyDict_SetItemString(d, "__path__", path); - if (err != 0) - goto error; - buf[0] = '\0'; - fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL); - if (fdp == NULL) { - if (PyErr_ExceptionMatches(PyExc_ImportError)) { - PyErr_Clear(); - Py_INCREF(m); - } - else - m = NULL; - goto cleanup; - } - m = load_module(name, fp, buf, fdp->type, NULL); - if (fp != NULL) - fclose(fp); - goto cleanup; - - error: - m = NULL; - cleanup: - Py_XDECREF(path); - Py_XDECREF(file); - return m; -} - - -/* Helper to test for built-in module */ - -static int -is_builtin(char *name) -{ - int i; - for (i = 0; PyImport_Inittab[i].name != NULL; i++) { - if (strcmp(name, PyImport_Inittab[i].name) == 0) { - if (PyImport_Inittab[i].initfunc == NULL) - return -1; - else - return 1; - } - } - return 0; -} - - -/* Return an importer object for a sys.path/pkg.__path__ item 'p', - possibly by fetching it from the path_importer_cache dict. If it - wasn't yet cached, traverse path_hooks until a hook is found - that can handle the path item. Return None if no hook could; - this tells our caller it should fall back to the builtin - import mechanism. Cache the result in path_importer_cache. - Returns a borrowed reference. */ - -static PyObject * -get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks, - PyObject *p) -{ - PyObject *importer; - Py_ssize_t j, nhooks; - - /* These conditions are the caller's responsibility: */ - assert(PyList_Check(path_hooks)); - assert(PyDict_Check(path_importer_cache)); - - nhooks = PyList_Size(path_hooks); - if (nhooks < 0) - return NULL; /* Shouldn't happen */ - - importer = PyDict_GetItem(path_importer_cache, p); - if (importer != NULL) - return importer; - - /* set path_importer_cache[p] to None to avoid recursion */ - if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0) - return NULL; - - for (j = 0; j < nhooks; j++) { - PyObject *hook = PyList_GetItem(path_hooks, j); - if (hook == NULL) - return NULL; - importer = PyObject_CallFunctionObjArgs(hook, p, NULL); - if (importer != NULL) - break; - - if (!PyErr_ExceptionMatches(PyExc_ImportError)) { - return NULL; - } - PyErr_Clear(); - } - if (importer == NULL) { - importer = PyObject_CallFunctionObjArgs( - (PyObject *)&PyNullImporter_Type, p, NULL - ); - if (importer == NULL) { - if (PyErr_ExceptionMatches(PyExc_ImportError)) { - PyErr_Clear(); - return Py_None; - } - } - } - if (importer != NULL) { - int err = PyDict_SetItem(path_importer_cache, p, importer); - Py_DECREF(importer); - if (err != 0) - return NULL; - } - return importer; -} - -PyAPI_FUNC(PyObject *) -PyImport_GetImporter(PyObject *path) { - PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL; - - if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) { - if ((path_hooks = PySys_GetObject("path_hooks"))) { - importer = get_path_importer(path_importer_cache, - path_hooks, path); - } - } - Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */ - return importer; -} - -/* Search the path (default sys.path) for a module. Return the - corresponding filedescr struct, and (via return arguments) the - pathname and an open file. Return NULL if the module is not found. */ - -#ifdef MS_COREDLL -extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **, - char *, Py_ssize_t); -#endif - -static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *); -static int find_init_module(char *); /* Forward */ -static struct filedescr importhookdescr = {"", "", IMP_HOOK}; - -static struct filedescr * -find_module(char *fullname, char *subname, PyObject *path, char *buf, - size_t buflen, FILE **p_fp, PyObject **p_loader) -{ - Py_ssize_t i, npath; - size_t len, namelen; - struct filedescr *fdp = NULL; - char *filemode; - FILE *fp = NULL; - PyObject *path_hooks, *path_importer_cache; -#ifndef RISCOS - struct stat statbuf; -#endif - static struct filedescr fd_frozen = {"", "", PY_FROZEN}; - static struct filedescr fd_builtin = {"", "", C_BUILTIN}; - static struct filedescr fd_package = {"", "", PKG_DIRECTORY}; - char name[MAXPATHLEN+1]; -#if defined(PYOS_OS2) - size_t saved_len; - size_t saved_namelen; - char *saved_buf = NULL; -#endif - if (p_loader != NULL) - *p_loader = NULL; - - if (strlen(subname) > MAXPATHLEN) { - PyErr_SetString(PyExc_OverflowError, - "module name is too long"); - return NULL; - } - strcpy(name, subname); - - /* sys.meta_path import hook */ - if (p_loader != NULL) { - PyObject *meta_path; - - meta_path = PySys_GetObject("meta_path"); - if (meta_path == NULL || !PyList_Check(meta_path)) { - PyErr_SetString(PyExc_ImportError, - "sys.meta_path must be a list of " - "import hooks"); - return NULL; - } - Py_INCREF(meta_path); /* zap guard */ - npath = PyList_Size(meta_path); - for (i = 0; i < npath; i++) { - PyObject *loader; - PyObject *hook = PyList_GetItem(meta_path, i); - loader = PyObject_CallMethod(hook, "find_module", - "sO", fullname, - path != NULL ? - path : Py_None); - if (loader == NULL) { - Py_DECREF(meta_path); - return NULL; /* true error */ - } - if (loader != Py_None) { - /* a loader was found */ - *p_loader = loader; - Py_DECREF(meta_path); - return &importhookdescr; - } - Py_DECREF(loader); - } - Py_DECREF(meta_path); - } - - if (path != NULL && PyString_Check(path)) { - /* The only type of submodule allowed inside a "frozen" - package are other frozen modules or packages. */ - if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) { - PyErr_SetString(PyExc_ImportError, - "full frozen module name too long"); - return NULL; - } - strcpy(buf, PyString_AsString(path)); - strcat(buf, "."); - strcat(buf, name); - strcpy(name, buf); - if (find_frozen(name) != NULL) { - strcpy(buf, name); - return &fd_frozen; - } - PyErr_Format(PyExc_ImportError, - "No frozen submodule named %.200s", name); - return NULL; - } - if (path == NULL) { - if (is_builtin(name)) { - strcpy(buf, name); - return &fd_builtin; - } - if ((find_frozen(name)) != NULL) { - strcpy(buf, name); - return &fd_frozen; - } - -#ifdef MS_COREDLL - fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen); - if (fp != NULL) { - *p_fp = fp; - return fdp; - } -#endif - path = PySys_GetObject("path"); - } - if (path == NULL || !PyList_Check(path)) { - PyErr_SetString(PyExc_ImportError, - "sys.path must be a list of directory names"); - return NULL; - } - - path_hooks = PySys_GetObject("path_hooks"); - if (path_hooks == NULL || !PyList_Check(path_hooks)) { - PyErr_SetString(PyExc_ImportError, - "sys.path_hooks must be a list of " - "import hooks"); - return NULL; - } - path_importer_cache = PySys_GetObject("path_importer_cache"); - if (path_importer_cache == NULL || - !PyDict_Check(path_importer_cache)) { - PyErr_SetString(PyExc_ImportError, - "sys.path_importer_cache must be a dict"); - return NULL; - } - - npath = PyList_Size(path); - namelen = strlen(name); - for (i = 0; i < npath; i++) { - PyObject *copy = NULL; - PyObject *v = PyList_GetItem(path, i); - if (!v) - return NULL; -#ifdef Py_USING_UNICODE - if (PyUnicode_Check(v)) { - copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v), - PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL); - if (copy == NULL) - return NULL; - v = copy; - } - else -#endif - if (!PyString_Check(v)) - continue; - len = PyString_GET_SIZE(v); - if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) { - Py_XDECREF(copy); - continue; /* Too long */ - } - strcpy(buf, PyString_AS_STRING(v)); - if (strlen(buf) != len) { - Py_XDECREF(copy); - continue; /* v contains '\0' */ - } - - /* sys.path_hooks import hook */ - if (p_loader != NULL) { - PyObject *importer; - - importer = get_path_importer(path_importer_cache, - path_hooks, v); - if (importer == NULL) { - Py_XDECREF(copy); - return NULL; - } - /* Note: importer is a borrowed reference */ - if (importer != Py_None) { - PyObject *loader; - loader = PyObject_CallMethod(importer, - "find_module", - "s", fullname); - Py_XDECREF(copy); - if (loader == NULL) - return NULL; /* error */ - if (loader != Py_None) { - /* a loader was found */ - *p_loader = loader; - return &importhookdescr; - } - Py_DECREF(loader); - continue; - } - } - /* no hook was found, use builtin import */ - - if (len > 0 && buf[len-1] != SEP -#ifdef ALTSEP - && buf[len-1] != ALTSEP -#endif - ) - buf[len++] = SEP; - strcpy(buf+len, name); - len += namelen; - - /* Check for package import (buf holds a directory name, - and there's an __init__ module in that directory */ -#ifdef HAVE_STAT - if (stat(buf, &statbuf) == 0 && /* it exists */ - S_ISDIR(statbuf.st_mode) && /* it's a directory */ - case_ok(buf, len, namelen, name)) { /* case matches */ - if (find_init_module(buf)) { /* and has __init__.py */ - Py_XDECREF(copy); - return &fd_package; - } - else { - char warnstr[MAXPATHLEN+80]; - sprintf(warnstr, "Not importing directory " - "'%.*s': missing __init__.py", - MAXPATHLEN, buf); - if (PyErr_Warn(PyExc_ImportWarning, - warnstr)) { - Py_XDECREF(copy); - return NULL; - } - } - } -#else - /* XXX How are you going to test for directories? */ -#ifdef RISCOS - if (isdir(buf) && - case_ok(buf, len, namelen, name)) { - if (find_init_module(buf)) { - Py_XDECREF(copy); - return &fd_package; - } - else { - char warnstr[MAXPATHLEN+80]; - sprintf(warnstr, "Not importing directory " - "'%.*s': missing __init__.py", - MAXPATHLEN, buf); - if (PyErr_Warn(PyExc_ImportWarning, - warnstr)) { - Py_XDECREF(copy); - return NULL; - } - } -#endif -#endif -#if defined(PYOS_OS2) - /* take a snapshot of the module spec for restoration - * after the 8 character DLL hackery - */ - saved_buf = strdup(buf); - saved_len = len; - saved_namelen = namelen; -#endif /* PYOS_OS2 */ - for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { -#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING) - /* OS/2 limits DLLs to 8 character names (w/o - extension) - * so if the name is longer than that and its a - * dynamically loaded module we're going to try, - * truncate the name before trying - */ - if (strlen(subname) > 8) { - /* is this an attempt to load a C extension? */ - const struct filedescr *scan; - scan = _PyImport_DynLoadFiletab; - while (scan->suffix != NULL) { - if (!strcmp(scan->suffix, fdp->suffix)) - break; - else - scan++; - } - if (scan->suffix != NULL) { - /* yes, so truncate the name */ - namelen = 8; - len -= strlen(subname) - namelen; - buf[len] = '\0'; - } - } -#endif /* PYOS_OS2 */ - strcpy(buf+len, fdp->suffix); - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# trying %s\n", buf); - filemode = fdp->mode; - if (filemode[0] == 'U') - filemode = "r" PY_STDIOTEXTMODE; - fp = fopen(buf, filemode); - if (fp != NULL) { - if (case_ok(buf, len, namelen, name)) - break; - else { /* continue search */ - fclose(fp); - fp = NULL; - } - } -#if defined(PYOS_OS2) - /* restore the saved snapshot */ - strcpy(buf, saved_buf); - len = saved_len; - namelen = saved_namelen; -#endif - } -#if defined(PYOS_OS2) - /* don't need/want the module name snapshot anymore */ - if (saved_buf) - { - free(saved_buf); - saved_buf = NULL; - } -#endif - Py_XDECREF(copy); - if (fp != NULL) - break; - } - if (fp == NULL) { - PyErr_Format(PyExc_ImportError, - "No module named %.200s", name); - return NULL; - } - *p_fp = fp; - return fdp; -} - -/* Helpers for main.c - * Find the source file corresponding to a named module - */ -struct filedescr * -_PyImport_FindModule(const char *name, PyObject *path, char *buf, - size_t buflen, FILE **p_fp, PyObject **p_loader) -{ - return find_module((char *) name, (char *) name, path, - buf, buflen, p_fp, p_loader); -} - -PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd) -{ - return fd->type == PY_SOURCE || fd->type == PY_COMPILED; -} - -/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name) - * The arguments here are tricky, best shown by example: - * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0 - * ^ ^ ^ ^ - * |--------------------- buf ---------------------| - * |------------------- len ------------------| - * |------ name -------| - * |----- namelen -----| - * buf is the full path, but len only counts up to (& exclusive of) the - * extension. name is the module name, also exclusive of extension. - * - * We've already done a successful stat() or fopen() on buf, so know that - * there's some match, possibly case-insensitive. - * - * case_ok() is to return 1 if there's a case-sensitive match for - * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK - * exists. - * - * case_ok() is used to implement case-sensitive import semantics even - * on platforms with case-insensitive filesystems. It's trivial to implement - * for case-sensitive filesystems. It's pretty much a cross-platform - * nightmare for systems with case-insensitive filesystems. - */ - -/* First we may need a pile of platform-specific header files; the sequence - * of #if's here should match the sequence in the body of case_ok(). - */ -#if defined(MS_WINDOWS) -#include - -#elif defined(DJGPP) -#include - -#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H) -#include -#include - -#elif defined(PYOS_OS2) -#define INCL_DOS -#define INCL_DOSERRORS -#define INCL_NOPMAPI -#include - -#elif defined(RISCOS) -#include "oslib/osfscontrol.h" -#endif - -static int -case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name) -{ -/* Pick a platform-specific implementation; the sequence of #if's here should - * match the sequence just above. - */ - -/* MS_WINDOWS */ -#if defined(MS_WINDOWS) - WIN32_FIND_DATA data; - HANDLE h; - - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; - - h = FindFirstFile(buf, &data); - if (h == INVALID_HANDLE_VALUE) { - PyErr_Format(PyExc_NameError, - "Can't find file for module %.100s\n(filename %.300s)", - name, buf); - return 0; - } - FindClose(h); - return strncmp(data.cFileName, name, namelen) == 0; - -/* DJGPP */ -#elif defined(DJGPP) - struct ffblk ffblk; - int done; - - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; - - done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC); - if (done) { - PyErr_Format(PyExc_NameError, - "Can't find file for module %.100s\n(filename %.300s)", - name, buf); - return 0; - } - return strncmp(ffblk.ff_name, name, namelen) == 0; - -/* new-fangled macintosh (macosx) or Cygwin */ -#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H) - DIR *dirp; - struct dirent *dp; - char dirname[MAXPATHLEN + 1]; - const int dirlen = len - namelen - 1; /* don't want trailing SEP */ - - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; - - /* Copy the dir component into dirname; substitute "." if empty */ - if (dirlen <= 0) { - dirname[0] = '.'; - dirname[1] = '\0'; - } - else { - assert(dirlen <= MAXPATHLEN); - memcpy(dirname, buf, dirlen); - dirname[dirlen] = '\0'; - } - /* Open the directory and search the entries for an exact match. */ - dirp = opendir(dirname); - if (dirp) { - char *nameWithExt = buf + len - namelen; - while ((dp = readdir(dirp)) != NULL) { - const int thislen = -#ifdef _DIRENT_HAVE_D_NAMELEN - dp->d_namlen; -#else - strlen(dp->d_name); -#endif - if (thislen >= namelen && - strcmp(dp->d_name, nameWithExt) == 0) { - (void)closedir(dirp); - return 1; /* Found */ - } - } - (void)closedir(dirp); - } - return 0 ; /* Not found */ - -/* RISC OS */ -#elif defined(RISCOS) - char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */ - char buf2[MAXPATHLEN+2]; - char *nameWithExt = buf+len-namelen; - int canonlen; - os_error *e; - - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; - - /* workaround: - append wildcard, otherwise case of filename wouldn't be touched */ - strcpy(buf2, buf); - strcat(buf2, "*"); - - e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen); - canonlen = MAXPATHLEN+1-canonlen; - if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) ) - return 0; - if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0) - return 1; /* match */ - - return 0; - -/* OS/2 */ -#elif defined(PYOS_OS2) - HDIR hdir = 1; - ULONG srchcnt = 1; - FILEFINDBUF3 ffbuf; - APIRET rc; - - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; - - rc = DosFindFirst(buf, - &hdir, - FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY, - &ffbuf, sizeof(ffbuf), - &srchcnt, - FIL_STANDARD); - if (rc != NO_ERROR) - return 0; - return strncmp(ffbuf.achName, name, namelen) == 0; - -/* assuming it's a case-sensitive filesystem, so there's nothing to do! */ -#else - return 1; - -#endif -} - - -#ifdef HAVE_STAT -/* Helper to look for __init__.py or __init__.py[co] in potential package */ -static int -find_init_module(char *buf) -{ - const size_t save_len = strlen(buf); - size_t i = save_len; - char *pname; /* pointer to start of __init__ */ - struct stat statbuf; - -/* For calling case_ok(buf, len, namelen, name): - * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0 - * ^ ^ ^ ^ - * |--------------------- buf ---------------------| - * |------------------- len ------------------| - * |------ name -------| - * |----- namelen -----| - */ - if (save_len + 13 >= MAXPATHLEN) - return 0; - buf[i++] = SEP; - pname = buf + i; - strcpy(pname, "__init__.py"); - if (stat(buf, &statbuf) == 0) { - if (case_ok(buf, - save_len + 9, /* len("/__init__") */ - 8, /* len("__init__") */ - pname)) { - buf[save_len] = '\0'; - return 1; - } - } - i += strlen(pname); - strcpy(buf+i, Py_OptimizeFlag ? "o" : "c"); - if (stat(buf, &statbuf) == 0) { - if (case_ok(buf, - save_len + 9, /* len("/__init__") */ - 8, /* len("__init__") */ - pname)) { - buf[save_len] = '\0'; - return 1; - } - } - buf[save_len] = '\0'; - return 0; -} - -#else - -#ifdef RISCOS -static int -find_init_module(buf) - char *buf; -{ - int save_len = strlen(buf); - int i = save_len; - - if (save_len + 13 >= MAXPATHLEN) - return 0; - buf[i++] = SEP; - strcpy(buf+i, "__init__/py"); - if (isfile(buf)) { - buf[save_len] = '\0'; - return 1; - } - - if (Py_OptimizeFlag) - strcpy(buf+i, "o"); - else - strcpy(buf+i, "c"); - if (isfile(buf)) { - buf[save_len] = '\0'; - return 1; - } - buf[save_len] = '\0'; - return 0; -} -#endif /*RISCOS*/ - -#endif /* HAVE_STAT */ - - -static int init_builtin(char *); /* Forward */ - -/* Load an external module using the default search path and return - its module object WITH INCREMENTED REFERENCE COUNT */ - -static PyObject * -load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader) -{ - PyObject *modules; - PyObject *m; - int err; - - /* First check that there's an open file (if we need one) */ - switch (type) { - case PY_SOURCE: - case PY_COMPILED: - if (fp == NULL) { - PyErr_Format(PyExc_ValueError, - "file object required for import (type code %d)", - type); - return NULL; - } - } - - switch (type) { - - case PY_SOURCE: - m = load_source_module(name, pathname, fp); - break; - - case PY_COMPILED: - m = load_compiled_module(name, pathname, fp); - break; - -#ifdef HAVE_DYNAMIC_LOADING - case C_EXTENSION: - m = _PyImport_LoadDynamicModule(name, pathname, fp); - break; -#endif - - case PKG_DIRECTORY: - m = load_package(name, pathname); - break; - - case C_BUILTIN: - case PY_FROZEN: - if (pathname != NULL && pathname[0] != '\0') - name = pathname; - if (type == C_BUILTIN) - err = init_builtin(name); - else - err = PyImport_ImportFrozenModule(name); - if (err < 0) - return NULL; - if (err == 0) { - PyErr_Format(PyExc_ImportError, - "Purported %s module %.200s not found", - type == C_BUILTIN ? - "builtin" : "frozen", - name); - return NULL; - } - modules = PyImport_GetModuleDict(); - m = PyDict_GetItemString(modules, name); - if (m == NULL) { - PyErr_Format( - PyExc_ImportError, - "%s module %.200s not properly initialized", - type == C_BUILTIN ? - "builtin" : "frozen", - name); - return NULL; - } - Py_INCREF(m); - break; - - case IMP_HOOK: { - if (loader == NULL) { - PyErr_SetString(PyExc_ImportError, - "import hook without loader"); - return NULL; - } - m = PyObject_CallMethod(loader, "load_module", "s", name); - break; - } - - default: - PyErr_Format(PyExc_ImportError, - "Don't know how to import %.200s (type code %d)", - name, type); - m = NULL; - - } - - return m; -} - - -/* Initialize a built-in module. - Return 1 for success, 0 if the module is not found, and -1 with - an exception set if the initialization failed. */ - -static int -init_builtin(char *name) -{ - struct _inittab *p; - - if (_PyImport_FindExtension(name, name) != NULL) - return 1; - - for (p = PyImport_Inittab; p->name != NULL; p++) { - if (strcmp(name, p->name) == 0) { - if (p->initfunc == NULL) { - PyErr_Format(PyExc_ImportError, - "Cannot re-init internal module %.200s", - name); - return -1; - } - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # builtin\n", name); - (*p->initfunc)(); - if (PyErr_Occurred()) - return -1; - if (_PyImport_FixupExtension(name, name) == NULL) - return -1; - return 1; - } - } - return 0; -} - - -/* Frozen modules */ - -static struct _frozen * -find_frozen(char *name) -{ - struct _frozen *p; - - for (p = PyImport_FrozenModules; ; p++) { - if (p->name == NULL) - return NULL; - if (strcmp(p->name, name) == 0) - break; - } - return p; -} - -static PyObject * -get_frozen_object(char *name) -{ - struct _frozen *p = find_frozen(name); - int size; - - if (p == NULL) { - PyErr_Format(PyExc_ImportError, - "No such frozen object named %.200s", - name); - return NULL; - } - if (p->code == NULL) { - PyErr_Format(PyExc_ImportError, - "Excluded frozen object named %.200s", - name); - return NULL; - } - size = p->size; - if (size < 0) - size = -size; - return PyMarshal_ReadObjectFromString((char *)p->code, size); -} - -/* Initialize a frozen module. - Return 1 for succes, 0 if the module is not found, and -1 with - an exception set if the initialization failed. - This function is also used from frozenmain.c */ - -int -PyImport_ImportFrozenModule(char *name) -{ - struct _frozen *p = find_frozen(name); - PyObject *co; - PyObject *m; - int ispackage; - int size; - - if (p == NULL) - return 0; - if (p->code == NULL) { - PyErr_Format(PyExc_ImportError, - "Excluded frozen object named %.200s", - name); - return -1; - } - size = p->size; - ispackage = (size < 0); - if (ispackage) - size = -size; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # frozen%s\n", - name, ispackage ? " package" : ""); - co = PyMarshal_ReadObjectFromString((char *)p->code, size); - if (co == NULL) - return -1; - if (!PyCode_Check(co)) { - PyErr_Format(PyExc_TypeError, - "frozen object %.200s is not a code object", - name); - goto err_return; - } - if (ispackage) { - /* Set __path__ to the package name */ - PyObject *d, *s; - int err; - m = PyImport_AddModule(name); - if (m == NULL) - goto err_return; - d = PyModule_GetDict(m); - s = PyString_InternFromString(name); - if (s == NULL) - goto err_return; - err = PyDict_SetItemString(d, "__path__", s); - Py_DECREF(s); - if (err != 0) - goto err_return; - } - m = PyImport_ExecCodeModuleEx(name, co, ""); - if (m == NULL) - goto err_return; - Py_DECREF(co); - Py_DECREF(m); - return 1; -err_return: - Py_DECREF(co); - return -1; -} - - -/* Import a module, either built-in, frozen, or external, and return - its module object WITH INCREMENTED REFERENCE COUNT */ - -PyObject * -PyImport_ImportModule(const char *name) -{ - PyObject *pname; - PyObject *result; - - pname = PyString_FromString(name); - if (pname == NULL) - return NULL; - result = PyImport_Import(pname); - Py_DECREF(pname); - return result; -} - -/* Import a module without blocking - * - * At first it tries to fetch the module from sys.modules. If the module was - * never loaded before it loads it with PyImport_ImportModule() unless another - * thread holds the import lock. In the latter case the function raises an - * ImportError instead of blocking. - * - * Returns the module object with incremented ref count. - */ -PyObject * -PyImport_ImportModuleNoBlock(const char *name) -{ - PyObject *result; - PyObject *modules; -#ifdef WITH_THREAD - long me; -#endif - - /* Try to get the module from sys.modules[name] */ - modules = PyImport_GetModuleDict(); - if (modules == NULL) - return NULL; - - result = PyDict_GetItemString(modules, name); - if (result != NULL) { - Py_INCREF(result); - return result; - } - else { - PyErr_Clear(); - } -#ifdef WITH_THREAD - /* check the import lock - * me might be -1 but I ignore the error here, the lock function - * takes care of the problem */ - me = PyThread_get_thread_ident(); - if (import_lock_thread == -1 || import_lock_thread == me) { - /* no thread or me is holding the lock */ - return PyImport_ImportModule(name); - } - else { - PyErr_Format(PyExc_ImportError, - "Failed to import %.200s because the import lock" - "is held by another thread.", - name); - return NULL; - } -#else - return PyImport_ImportModule(name); -#endif -} - -/* Forward declarations for helper routines */ -static PyObject *get_parent(PyObject *globals, char *buf, - Py_ssize_t *p_buflen, int level); -static PyObject *load_next(PyObject *mod, PyObject *altmod, - char **p_name, char *buf, Py_ssize_t *p_buflen); -static int mark_miss(char *name); -static int ensure_fromlist(PyObject *mod, PyObject *fromlist, - char *buf, Py_ssize_t buflen, int recursive); -static PyObject * import_submodule(PyObject *mod, char *name, char *fullname); - -/* The Magnum Opus of dotted-name import :-) */ - -static PyObject * -import_module_level(char *name, PyObject *globals, PyObject *locals, - PyObject *fromlist, int level) -{ - char buf[MAXPATHLEN+1]; - Py_ssize_t buflen = 0; - PyObject *parent, *head, *next, *tail; - - if (strchr(name, '/') != NULL -#ifdef MS_WINDOWS - || strchr(name, '\\') != NULL -#endif - ) { - PyErr_SetString(PyExc_ImportError, - "Import by filename is not supported."); - return NULL; - } - - parent = get_parent(globals, buf, &buflen, level); - if (parent == NULL) - return NULL; - - head = load_next(parent, level < 0 ? Py_None : parent, &name, buf, - &buflen); - if (head == NULL) - return NULL; - - tail = head; - Py_INCREF(tail); - while (name) { - next = load_next(tail, tail, &name, buf, &buflen); - Py_DECREF(tail); - if (next == NULL) { - Py_DECREF(head); - return NULL; - } - tail = next; - } - if (tail == Py_None) { - /* If tail is Py_None, both get_parent and load_next found - an empty module name: someone called __import__("") or - doctored faulty bytecode */ - Py_DECREF(tail); - Py_DECREF(head); - PyErr_SetString(PyExc_ValueError, - "Empty module name"); - return NULL; - } - - if (fromlist != NULL) { - if (fromlist == Py_None || !PyObject_IsTrue(fromlist)) - fromlist = NULL; - } - - if (fromlist == NULL) { - Py_DECREF(tail); - return head; - } - - Py_DECREF(head); - if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) { - Py_DECREF(tail); - return NULL; - } - - return tail; -} - -PyObject * -PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals, - PyObject *fromlist, int level) -{ - PyObject *result; - _PyImport_AcquireLock(); - result = import_module_level(name, globals, locals, fromlist, level); - if (_PyImport_ReleaseLock() < 0) { - Py_XDECREF(result); - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return result; -} - -/* Return the package that an import is being performed in. If globals comes - from the module foo.bar.bat (not itself a package), this returns the - sys.modules entry for foo.bar. If globals is from a package's __init__.py, - the package's entry in sys.modules is returned, as a borrowed reference. - - The *name* of the returned package is returned in buf, with the length of - the name in *p_buflen. - - If globals doesn't come from a package or a module in a package, or a - corresponding entry is not found in sys.modules, Py_None is returned. -*/ -static PyObject * -get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level) -{ - static PyObject *namestr = NULL; - static PyObject *pathstr = NULL; - static PyObject *pkgstr = NULL; - PyObject *pkgname, *modname, *modpath, *modules, *parent; - int orig_level = level; - - if (globals == NULL || !PyDict_Check(globals) || !level) - return Py_None; - - if (namestr == NULL) { - namestr = PyString_InternFromString("__name__"); - if (namestr == NULL) - return NULL; - } - if (pathstr == NULL) { - pathstr = PyString_InternFromString("__path__"); - if (pathstr == NULL) - return NULL; - } - if (pkgstr == NULL) { - pkgstr = PyString_InternFromString("__package__"); - if (pkgstr == NULL) - return NULL; - } - - *buf = '\0'; - *p_buflen = 0; - pkgname = PyDict_GetItem(globals, pkgstr); - - if ((pkgname != NULL) && (pkgname != Py_None)) { - /* __package__ is set, so use it */ - Py_ssize_t len; - if (!PyString_Check(pkgname)) { - PyErr_SetString(PyExc_ValueError, - "__package__ set to non-string"); - return NULL; - } - len = PyString_GET_SIZE(pkgname); - if (len == 0) { - if (level > 0) { - PyErr_SetString(PyExc_ValueError, - "Attempted relative import in non-package"); - return NULL; - } - return Py_None; - } - if (len > MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Package name too long"); - return NULL; - } - strcpy(buf, PyString_AS_STRING(pkgname)); - } else { - /* __package__ not set, so figure it out and set it */ - modname = PyDict_GetItem(globals, namestr); - if (modname == NULL || !PyString_Check(modname)) - return Py_None; - - modpath = PyDict_GetItem(globals, pathstr); - if (modpath != NULL) { - /* __path__ is set, so modname is already the package name */ - Py_ssize_t len = PyString_GET_SIZE(modname); - int error; - if (len > MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - return NULL; - } - strcpy(buf, PyString_AS_STRING(modname)); - error = PyDict_SetItem(globals, pkgstr, modname); - if (error) { - PyErr_SetString(PyExc_ValueError, - "Could not set __package__"); - return NULL; - } - } else { - /* Normal module, so work out the package name if any */ - char *start = PyString_AS_STRING(modname); - char *lastdot = strrchr(start, '.'); - size_t len; - int error; - if (lastdot == NULL && level > 0) { - PyErr_SetString(PyExc_ValueError, - "Attempted relative import in non-package"); - return NULL; - } - if (lastdot == NULL) { - error = PyDict_SetItem(globals, pkgstr, Py_None); - if (error) { - PyErr_SetString(PyExc_ValueError, - "Could not set __package__"); - return NULL; - } - return Py_None; - } - len = lastdot - start; - if (len >= MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - return NULL; - } - strncpy(buf, start, len); - buf[len] = '\0'; - pkgname = PyString_FromString(buf); - if (pkgname == NULL) { - return NULL; - } - error = PyDict_SetItem(globals, pkgstr, pkgname); - Py_DECREF(pkgname); - if (error) { - PyErr_SetString(PyExc_ValueError, - "Could not set __package__"); - return NULL; - } - } - } - while (--level > 0) { - char *dot = strrchr(buf, '.'); - if (dot == NULL) { - PyErr_SetString(PyExc_ValueError, - "Attempted relative import beyond " - "toplevel package"); - return NULL; - } - *dot = '\0'; - } - *p_buflen = strlen(buf); - - modules = PyImport_GetModuleDict(); - parent = PyDict_GetItemString(modules, buf); - if (parent == NULL) { - if (orig_level < 1) { - PyObject *err_msg = PyString_FromFormat( - "Parent module '%.200s' not found " - "while handling absolute import", buf); - if (err_msg == NULL) { - return NULL; - } - if (!PyErr_WarnEx(PyExc_RuntimeWarning, - PyString_AsString(err_msg), 1)) { - *buf = '\0'; - *p_buflen = 0; - parent = Py_None; - } - Py_DECREF(err_msg); - } else { - PyErr_Format(PyExc_SystemError, - "Parent module '%.200s' not loaded, " - "cannot perform relative import", buf); - } - } - return parent; - /* We expect, but can't guarantee, if parent != None, that: - - parent.__name__ == buf - - parent.__dict__ is globals - If this is violated... Who cares? */ -} - -/* altmod is either None or same as mod */ -static PyObject * -load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf, - Py_ssize_t *p_buflen) -{ - char *name = *p_name; - char *dot = strchr(name, '.'); - size_t len; - char *p; - PyObject *result; - - if (strlen(name) == 0) { - /* completely empty module name should only happen in - 'from . import' (or '__import__("")')*/ - Py_INCREF(mod); - *p_name = NULL; - return mod; - } - - if (dot == NULL) { - *p_name = NULL; - len = strlen(name); - } - else { - *p_name = dot+1; - len = dot-name; - } - if (len == 0) { - PyErr_SetString(PyExc_ValueError, - "Empty module name"); - return NULL; - } - - p = buf + *p_buflen; - if (p != buf) - *p++ = '.'; - if (p+len-buf >= MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - return NULL; - } - strncpy(p, name, len); - p[len] = '\0'; - *p_buflen = p+len-buf; - - result = import_submodule(mod, p, buf); - if (result == Py_None && altmod != mod) { - Py_DECREF(result); - /* Here, altmod must be None and mod must not be None */ - result = import_submodule(altmod, p, p); - if (result != NULL && result != Py_None) { - if (mark_miss(buf) != 0) { - Py_DECREF(result); - return NULL; - } - strncpy(buf, name, len); - buf[len] = '\0'; - *p_buflen = len; - } - } - if (result == NULL) - return NULL; - - if (result == Py_None) { - Py_DECREF(result); - PyErr_Format(PyExc_ImportError, - "No module named %.200s", name); - return NULL; - } - - return result; -} - -static int -mark_miss(char *name) -{ - PyObject *modules = PyImport_GetModuleDict(); - return PyDict_SetItemString(modules, name, Py_None); -} - -static int -ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen, - int recursive) -{ - int i; - - if (!PyObject_HasAttrString(mod, "__path__")) - return 1; - - for (i = 0; ; i++) { - PyObject *item = PySequence_GetItem(fromlist, i); - int hasit; - if (item == NULL) { - if (PyErr_ExceptionMatches(PyExc_IndexError)) { - PyErr_Clear(); - return 1; - } - return 0; - } - if (!PyString_Check(item)) { - PyErr_SetString(PyExc_TypeError, - "Item in ``from list'' not a string"); - Py_DECREF(item); - return 0; - } - if (PyString_AS_STRING(item)[0] == '*') { - PyObject *all; - Py_DECREF(item); - /* See if the package defines __all__ */ - if (recursive) - continue; /* Avoid endless recursion */ - all = PyObject_GetAttrString(mod, "__all__"); - if (all == NULL) - PyErr_Clear(); - else { - int ret = ensure_fromlist(mod, all, buf, buflen, 1); - Py_DECREF(all); - if (!ret) - return 0; - } - continue; - } - hasit = PyObject_HasAttr(mod, item); - if (!hasit) { - char *subname = PyString_AS_STRING(item); - PyObject *submod; - char *p; - if (buflen + strlen(subname) >= MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - Py_DECREF(item); - return 0; - } - p = buf + buflen; - *p++ = '.'; - strcpy(p, subname); - submod = import_submodule(mod, subname, buf); - Py_XDECREF(submod); - if (submod == NULL) { - Py_DECREF(item); - return 0; - } - } - Py_DECREF(item); - } - - /* NOTREACHED */ -} - -static int -add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname, - PyObject *modules) -{ - if (mod == Py_None) - return 1; - /* Irrespective of the success of this load, make a - reference to it in the parent package module. A copy gets - saved in the modules dictionary under the full name, so get a - reference from there, if need be. (The exception is when the - load failed with a SyntaxError -- then there's no trace in - sys.modules. In that case, of course, do nothing extra.) */ - if (submod == NULL) { - submod = PyDict_GetItemString(modules, fullname); - if (submod == NULL) - return 1; - } - if (PyModule_Check(mod)) { - /* We can't use setattr here since it can give a - * spurious warning if the submodule name shadows a - * builtin name */ - PyObject *dict = PyModule_GetDict(mod); - if (!dict) - return 0; - if (PyDict_SetItemString(dict, subname, submod) < 0) - return 0; - } - else { - if (PyObject_SetAttrString(mod, subname, submod) < 0) - return 0; - } - return 1; -} - -static PyObject * -import_submodule(PyObject *mod, char *subname, char *fullname) -{ - PyObject *modules = PyImport_GetModuleDict(); - PyObject *m = NULL; - - /* Require: - if mod == None: subname == fullname - else: mod.__name__ + "." + subname == fullname - */ - - if ((m = PyDict_GetItemString(modules, fullname)) != NULL) { - Py_INCREF(m); - } - else { - PyObject *path, *loader = NULL; - char buf[MAXPATHLEN+1]; - struct filedescr *fdp; - FILE *fp = NULL; - - if (mod == Py_None) - path = NULL; - else { - path = PyObject_GetAttrString(mod, "__path__"); - if (path == NULL) { - PyErr_Clear(); - Py_INCREF(Py_None); - return Py_None; - } - } - - buf[0] = '\0'; - fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1, - &fp, &loader); - Py_XDECREF(path); - if (fdp == NULL) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - return NULL; - PyErr_Clear(); - Py_INCREF(Py_None); - return Py_None; - } - m = load_module(fullname, fp, buf, fdp->type, loader); - Py_XDECREF(loader); - if (fp) - fclose(fp); - if (!add_submodule(mod, m, fullname, subname, modules)) { - Py_XDECREF(m); - m = NULL; - } - } - - return m; -} - - -/* Re-import a module of any kind and return its module object, WITH - INCREMENTED REFERENCE COUNT */ - -PyObject * -PyImport_ReloadModule(PyObject *m) -{ - PyInterpreterState *interp = PyThreadState_Get()->interp; - PyObject *modules_reloading = interp->modules_reloading; - PyObject *modules = PyImport_GetModuleDict(); - PyObject *path = NULL, *loader = NULL, *existing_m = NULL; - char *name, *subname; - char buf[MAXPATHLEN+1]; - struct filedescr *fdp; - FILE *fp = NULL; - PyObject *newm; - - if (modules_reloading == NULL) { - Py_FatalError("PyImport_ReloadModule: " - "no modules_reloading dictionary!"); - return NULL; - } - - if (m == NULL || !PyModule_Check(m)) { - PyErr_SetString(PyExc_TypeError, - "reload() argument must be module"); - return NULL; - } - name = PyModule_GetName(m); - if (name == NULL) - return NULL; - if (m != PyDict_GetItemString(modules, name)) { - PyErr_Format(PyExc_ImportError, - "reload(): module %.200s not in sys.modules", - name); - return NULL; - } - existing_m = PyDict_GetItemString(modules_reloading, name); - if (existing_m != NULL) { - /* Due to a recursive reload, this module is already - being reloaded. */ - Py_INCREF(existing_m); - return existing_m; - } - if (PyDict_SetItemString(modules_reloading, name, m) < 0) - return NULL; - - subname = strrchr(name, '.'); - if (subname == NULL) - subname = name; - else { - PyObject *parentname, *parent; - parentname = PyString_FromStringAndSize(name, (subname-name)); - if (parentname == NULL) { - imp_modules_reloading_clear(); - return NULL; - } - parent = PyDict_GetItem(modules, parentname); - if (parent == NULL) { - PyErr_Format(PyExc_ImportError, - "reload(): parent %.200s not in sys.modules", - PyString_AS_STRING(parentname)); - Py_DECREF(parentname); - imp_modules_reloading_clear(); - return NULL; - } - Py_DECREF(parentname); - subname++; - path = PyObject_GetAttrString(parent, "__path__"); - if (path == NULL) - PyErr_Clear(); - } - buf[0] = '\0'; - fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader); - Py_XDECREF(path); - - if (fdp == NULL) { - Py_XDECREF(loader); - imp_modules_reloading_clear(); - return NULL; - } - - newm = load_module(name, fp, buf, fdp->type, loader); - Py_XDECREF(loader); - - if (fp) - fclose(fp); - if (newm == NULL) { - /* load_module probably removed name from modules because of - * the error. Put back the original module object. We're - * going to return NULL in this case regardless of whether - * replacing name succeeds, so the return value is ignored. - */ - PyDict_SetItemString(modules, name, m); - } - imp_modules_reloading_clear(); - return newm; -} - - -/* Higher-level import emulator which emulates the "import" statement - more accurately -- it invokes the __import__() function from the - builtins of the current globals. This means that the import is - done using whatever import hooks are installed in the current - environment, e.g. by "rexec". - A dummy list ["__doc__"] is passed as the 4th argument so that - e.g. PyImport_Import(PyString_FromString("win32com.client.gencache")) - will return instead of . */ - -PyObject * -PyImport_Import(PyObject *module_name) -{ - static PyObject *silly_list = NULL; - static PyObject *builtins_str = NULL; - static PyObject *import_str = NULL; - PyObject *globals = NULL; - PyObject *import = NULL; - PyObject *builtins = NULL; - PyObject *r = NULL; - - /* Initialize constant string objects */ - if (silly_list == NULL) { - import_str = PyString_InternFromString("__import__"); - if (import_str == NULL) - return NULL; - builtins_str = PyString_InternFromString("__builtins__"); - if (builtins_str == NULL) - return NULL; - silly_list = Py_BuildValue("[s]", "__doc__"); - if (silly_list == NULL) - return NULL; - } - - /* Get the builtins from current globals */ - globals = PyEval_GetGlobals(); - if (globals != NULL) { - Py_INCREF(globals); - builtins = PyObject_GetItem(globals, builtins_str); - if (builtins == NULL) - goto err; - } - else { - /* No globals -- use standard builtins, and fake globals */ - builtins = PyImport_ImportModuleLevel("__builtin__", - NULL, NULL, NULL, 0); - if (builtins == NULL) - return NULL; - globals = Py_BuildValue("{OO}", builtins_str, builtins); - if (globals == NULL) - goto err; - } - - /* Get the __import__ function from the builtins */ - if (PyDict_Check(builtins)) { - import = PyObject_GetItem(builtins, import_str); - if (import == NULL) - PyErr_SetObject(PyExc_KeyError, import_str); - } - else - import = PyObject_GetAttr(builtins, import_str); - if (import == NULL) - goto err; - - /* Call the __import__ function with the proper argument list - * Always use absolute import here. */ - r = PyObject_CallFunction(import, "OOOOi", module_name, globals, - globals, silly_list, 0, NULL); - - err: - Py_XDECREF(globals); - Py_XDECREF(builtins); - Py_XDECREF(import); - - return r; -} - - -/* Module 'imp' provides Python access to the primitives used for - importing modules. -*/ - -static PyObject * -imp_get_magic(PyObject *self, PyObject *noargs) -{ - char buf[4]; - - buf[0] = (char) ((pyc_magic >> 0) & 0xff); - buf[1] = (char) ((pyc_magic >> 8) & 0xff); - buf[2] = (char) ((pyc_magic >> 16) & 0xff); - buf[3] = (char) ((pyc_magic >> 24) & 0xff); - - return PyString_FromStringAndSize(buf, 4); -} - -static PyObject * -imp_get_suffixes(PyObject *self, PyObject *noargs) -{ - PyObject *list; - struct filedescr *fdp; - - list = PyList_New(0); - if (list == NULL) - return NULL; - for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { - PyObject *item = Py_BuildValue("ssi", - fdp->suffix, fdp->mode, fdp->type); - if (item == NULL) { - Py_DECREF(list); - return NULL; - } - if (PyList_Append(list, item) < 0) { - Py_DECREF(list); - Py_DECREF(item); - return NULL; - } - Py_DECREF(item); - } - return list; -} - -static PyObject * -call_find_module(char *name, PyObject *path) -{ - extern int fclose(FILE *); - PyObject *fob, *ret; - struct filedescr *fdp; - char pathname[MAXPATHLEN+1]; - FILE *fp = NULL; - - pathname[0] = '\0'; - if (path == Py_None) - path = NULL; - fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL); - if (fdp == NULL) - return NULL; - if (fp != NULL) { - fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose); - if (fob == NULL) { - fclose(fp); - return NULL; - } - } - else { - fob = Py_None; - Py_INCREF(fob); - } - ret = Py_BuildValue("Os(ssi)", - fob, pathname, fdp->suffix, fdp->mode, fdp->type); - Py_DECREF(fob); - return ret; -} - -static PyObject * -imp_find_module(PyObject *self, PyObject *args) -{ - char *name; - PyObject *path = NULL; - if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path)) - return NULL; - return call_find_module(name, path); -} - -static PyObject * -imp_init_builtin(PyObject *self, PyObject *args) -{ - char *name; - int ret; - PyObject *m; - if (!PyArg_ParseTuple(args, "s:init_builtin", &name)) - return NULL; - ret = init_builtin(name); - if (ret < 0) - return NULL; - if (ret == 0) { - Py_INCREF(Py_None); - return Py_None; - } - m = PyImport_AddModule(name); - Py_XINCREF(m); - return m; -} - -static PyObject * -imp_init_frozen(PyObject *self, PyObject *args) -{ - char *name; - int ret; - PyObject *m; - if (!PyArg_ParseTuple(args, "s:init_frozen", &name)) - return NULL; - ret = PyImport_ImportFrozenModule(name); - if (ret < 0) - return NULL; - if (ret == 0) { - Py_INCREF(Py_None); - return Py_None; - } - m = PyImport_AddModule(name); - Py_XINCREF(m); - return m; -} - -static PyObject * -imp_get_frozen_object(PyObject *self, PyObject *args) -{ - char *name; - - if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name)) - return NULL; - return get_frozen_object(name); -} - -static PyObject * -imp_is_builtin(PyObject *self, PyObject *args) -{ - char *name; - if (!PyArg_ParseTuple(args, "s:is_builtin", &name)) - return NULL; - return PyInt_FromLong(is_builtin(name)); -} - -static PyObject * -imp_is_frozen(PyObject *self, PyObject *args) -{ - char *name; - struct _frozen *p; - if (!PyArg_ParseTuple(args, "s:is_frozen", &name)) - return NULL; - p = find_frozen(name); - return PyBool_FromLong((long) (p == NULL ? 0 : p->size)); -} - -static FILE * -get_file(char *pathname, PyObject *fob, char *mode) -{ - FILE *fp; - if (fob == NULL) { - if (mode[0] == 'U') - mode = "r" PY_STDIOTEXTMODE; - fp = fopen(pathname, mode); - if (fp == NULL) - PyErr_SetFromErrno(PyExc_IOError); - } - else { - fp = PyFile_AsFile(fob); - if (fp == NULL) - PyErr_SetString(PyExc_ValueError, - "bad/closed file object"); - } - return fp; -} - -static PyObject * -imp_load_compiled(PyObject *self, PyObject *args) -{ - char *name; - char *pathname; - PyObject *fob = NULL; - PyObject *m; - FILE *fp; - if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname, - &PyFile_Type, &fob)) - return NULL; - fp = get_file(pathname, fob, "rb"); - if (fp == NULL) - return NULL; - m = load_compiled_module(name, pathname, fp); - if (fob == NULL) - fclose(fp); - return m; -} - -#ifdef HAVE_DYNAMIC_LOADING - -static PyObject * -imp_load_dynamic(PyObject *self, PyObject *args) -{ - char *name; - char *pathname; - PyObject *fob = NULL; - PyObject *m; - FILE *fp = NULL; - if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname, - &PyFile_Type, &fob)) - return NULL; - if (fob) { - fp = get_file(pathname, fob, "r"); - if (fp == NULL) - return NULL; - } - m = _PyImport_LoadDynamicModule(name, pathname, fp); - return m; -} - -#endif /* HAVE_DYNAMIC_LOADING */ - -static PyObject * -imp_load_source(PyObject *self, PyObject *args) -{ - char *name; - char *pathname; - PyObject *fob = NULL; - PyObject *m; - FILE *fp; - if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname, - &PyFile_Type, &fob)) - return NULL; - fp = get_file(pathname, fob, "r"); - if (fp == NULL) - return NULL; - m = load_source_module(name, pathname, fp); - if (fob == NULL) - fclose(fp); - return m; -} - -static PyObject * -imp_load_module(PyObject *self, PyObject *args) -{ - char *name; - PyObject *fob; - char *pathname; - char *suffix; /* Unused */ - char *mode; - int type; - FILE *fp; - - if (!PyArg_ParseTuple(args, "sOs(ssi):load_module", - &name, &fob, &pathname, - &suffix, &mode, &type)) - return NULL; - if (*mode) { - /* Mode must start with 'r' or 'U' and must not contain '+'. - Implicit in this test is the assumption that the mode - may contain other modifiers like 'b' or 't'. */ - - if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) { - PyErr_Format(PyExc_ValueError, - "invalid file open mode %.200s", mode); - return NULL; - } - } - if (fob == Py_None) - fp = NULL; - else { - if (!PyFile_Check(fob)) { - PyErr_SetString(PyExc_ValueError, - "load_module arg#2 should be a file or None"); - return NULL; - } - fp = get_file(pathname, fob, mode); - if (fp == NULL) - return NULL; - } - return load_module(name, fp, pathname, type, NULL); -} - -static PyObject * -imp_load_package(PyObject *self, PyObject *args) -{ - char *name; - char *pathname; - if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname)) - return NULL; - return load_package(name, pathname); -} - -static PyObject * -imp_new_module(PyObject *self, PyObject *args) -{ - char *name; - if (!PyArg_ParseTuple(args, "s:new_module", &name)) - return NULL; - return PyModule_New(name); -} - -static PyObject * -imp_reload(PyObject *self, PyObject *v) -{ - return PyImport_ReloadModule(v); -} - - -/* Doc strings */ - -PyDoc_STRVAR(doc_imp, -"This module provides the components needed to build your own\n\ -__import__ function. Undocumented functions are obsolete."); - -PyDoc_STRVAR(doc_reload, -"reload(module) -> module\n\ -\n\ -Reload the module. The module must have been successfully imported before."); - -PyDoc_STRVAR(doc_find_module, -"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\ -Search for a module. If path is omitted or None, search for a\n\ -built-in, frozen or special module and continue search in sys.path.\n\ -The module name cannot contain '.'; to search for a submodule of a\n\ -package, pass the submodule name and the package's __path__."); - -PyDoc_STRVAR(doc_load_module, -"load_module(name, file, filename, (suffix, mode, type)) -> module\n\ -Load a module, given information returned by find_module().\n\ -The module name must include the full package name, if any."); - -PyDoc_STRVAR(doc_get_magic, -"get_magic() -> string\n\ -Return the magic number for .pyc or .pyo files."); - -PyDoc_STRVAR(doc_get_suffixes, -"get_suffixes() -> [(suffix, mode, type), ...]\n\ -Return a list of (suffix, mode, type) tuples describing the files\n\ -that find_module() looks for."); - -PyDoc_STRVAR(doc_new_module, -"new_module(name) -> module\n\ -Create a new module. Do not enter it in sys.modules.\n\ -The module name must include the full package name, if any."); - -PyDoc_STRVAR(doc_lock_held, -"lock_held() -> boolean\n\ -Return True if the import lock is currently held, else False.\n\ -On platforms without threads, return False."); - -PyDoc_STRVAR(doc_acquire_lock, -"acquire_lock() -> None\n\ -Acquires the interpreter's import lock for the current thread.\n\ -This lock should be used by import hooks to ensure thread-safety\n\ -when importing modules.\n\ -On platforms without threads, this function does nothing."); - -PyDoc_STRVAR(doc_release_lock, -"release_lock() -> None\n\ -Release the interpreter's import lock.\n\ -On platforms without threads, this function does nothing."); - -static PyMethodDef imp_methods[] = { - {"reload", imp_reload, METH_O, doc_reload}, - {"find_module", imp_find_module, METH_VARARGS, doc_find_module}, - {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic}, - {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes}, - {"load_module", imp_load_module, METH_VARARGS, doc_load_module}, - {"new_module", imp_new_module, METH_VARARGS, doc_new_module}, - {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held}, - {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock}, - {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock}, - /* The rest are obsolete */ - {"get_frozen_object", imp_get_frozen_object, METH_VARARGS}, - {"init_builtin", imp_init_builtin, METH_VARARGS}, - {"init_frozen", imp_init_frozen, METH_VARARGS}, - {"is_builtin", imp_is_builtin, METH_VARARGS}, - {"is_frozen", imp_is_frozen, METH_VARARGS}, - {"load_compiled", imp_load_compiled, METH_VARARGS}, -#ifdef HAVE_DYNAMIC_LOADING - {"load_dynamic", imp_load_dynamic, METH_VARARGS}, -#endif - {"load_package", imp_load_package, METH_VARARGS}, - {"load_source", imp_load_source, METH_VARARGS}, - {NULL, NULL} /* sentinel */ -}; - -static int -setint(PyObject *d, char *name, int value) -{ - PyObject *v; - int err; - - v = PyInt_FromLong((long)value); - err = PyDict_SetItemString(d, name, v); - Py_XDECREF(v); - return err; -} - -typedef struct { - PyObject_HEAD -} NullImporter; - -static int -NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds) -{ - char *path; - Py_ssize_t pathlen; - - if (!_PyArg_NoKeywords("NullImporter()", kwds)) - return -1; - - if (!PyArg_ParseTuple(args, "s:NullImporter", - &path)) - return -1; - - pathlen = strlen(path); - if (pathlen == 0) { - PyErr_SetString(PyExc_ImportError, "empty pathname"); - return -1; - } else { -#ifndef RISCOS -#ifndef MS_WINDOWS - struct stat statbuf; - int rv; - - rv = stat(path, &statbuf); - if (rv == 0) { - /* it exists */ - if (S_ISDIR(statbuf.st_mode)) { - /* it's a directory */ - PyErr_SetString(PyExc_ImportError, - "existing directory"); - return -1; - } - } -#else /* MS_WINDOWS */ - DWORD rv; - /* see issue1293 and issue3677: - * stat() on Windows doesn't recognise paths like - * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs. - */ - rv = GetFileAttributesA(path); - if (rv != INVALID_FILE_ATTRIBUTES) { - /* it exists */ - if (rv & FILE_ATTRIBUTE_DIRECTORY) { - /* it's a directory */ - PyErr_SetString(PyExc_ImportError, - "existing directory"); - return -1; - } - } -#endif -#else /* RISCOS */ - if (object_exists(path)) { - /* it exists */ - if (isdir(path)) { - /* it's a directory */ - PyErr_SetString(PyExc_ImportError, - "existing directory"); - return -1; - } - } -#endif - } - return 0; -} - -static PyObject * -NullImporter_find_module(NullImporter *self, PyObject *args) -{ - Py_RETURN_NONE; -} - -static PyMethodDef NullImporter_methods[] = { - {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS, - "Always return None" - }, - {NULL} /* Sentinel */ -}; - - -PyTypeObject PyNullImporter_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "imp.NullImporter", /*tp_name*/ - sizeof(NullImporter), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - "Null importer object", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - NullImporter_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)NullImporter_init, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew /* tp_new */ -}; - - -PyMODINIT_FUNC -initimp(void) -{ - PyObject *m, *d; - - if (PyType_Ready(&PyNullImporter_Type) < 0) - goto failure; - - m = Py_InitModule4("imp", imp_methods, doc_imp, - NULL, PYTHON_API_VERSION); - if (m == NULL) - goto failure; - d = PyModule_GetDict(m); - if (d == NULL) - goto failure; - - if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure; - if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure; - if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure; - if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure; - if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure; - if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure; - if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure; - if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure; - if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure; - if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure; - - Py_INCREF(&PyNullImporter_Type); - PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type); - failure: - ; -} - - -/* API for embedding applications that want to add their own entries - to the table of built-in modules. This should normally be called - *before* Py_Initialize(). When the table resize fails, -1 is - returned and the existing table is unchanged. - - After a similar function by Just van Rossum. */ - -int -PyImport_ExtendInittab(struct _inittab *newtab) -{ - static struct _inittab *our_copy = NULL; - struct _inittab *p; - int i, n; - - /* Count the number of entries in both tables */ - for (n = 0; newtab[n].name != NULL; n++) - ; - if (n == 0) - return 0; /* Nothing to do */ - for (i = 0; PyImport_Inittab[i].name != NULL; i++) - ; - - /* Allocate new memory for the combined table */ - p = our_copy; - PyMem_RESIZE(p, struct _inittab, i+n+1); - if (p == NULL) - return -1; - - /* Copy the tables into the new memory */ - if (our_copy != PyImport_Inittab) - memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab)); - PyImport_Inittab = our_copy = p; - memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab)); - - return 0; -} - -/* Shorthand to add a single entry given a name and a function */ - -int -PyImport_AppendInittab(const char *name, void (*initfunc)(void)) -{ - struct _inittab newtab[2]; - - memset(newtab, '\0', sizeof newtab); - - newtab[0].name = (char *)name; - newtab[0].initfunc = initfunc; - - return PyImport_ExtendInittab(newtab); -} - -#ifdef __cplusplus -} -#endif diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Python/marshal.c b/AppPkg/Applications/Python/PyMod-2.7.2/Python/marshal.c deleted file mode 100644 index 698ffb5..0000000 --- a/AppPkg/Applications/Python/PyMod-2.7.2/Python/marshal.c +++ /dev/null @@ -1,1422 +0,0 @@ -/** @file - Write Python objects to files and read them back. - This is intended for writing and reading compiled Python code only; - a true persistent storage facility would be much harder, since - it would have to take circular links and sharing into account. - - 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. -**/ - -#define PY_SSIZE_T_CLEAN - -#include "Python.h" -#include "longintrepr.h" -#include "code.h" -#include "marshal.h" - -#ifndef ABS - #define ABS(x) ((x) < 0 ? -(x) : (x)) -#endif - -/* High water mark to determine when the marshalled object is dangerously deep - * and risks coring the interpreter. When the object stack gets this deep, - * raise an exception instead of continuing. - */ -#define MAX_MARSHAL_STACK_DEPTH 2000 - -#define TYPE_NULL '0' -#define TYPE_NONE 'N' -#define TYPE_FALSE 'F' -#define TYPE_TRUE 'T' -#define TYPE_STOPITER 'S' -#define TYPE_ELLIPSIS '.' -#define TYPE_INT 'i' -#define TYPE_INT64 'I' -#define TYPE_FLOAT 'f' -#define TYPE_BINARY_FLOAT 'g' -#define TYPE_COMPLEX 'x' -#define TYPE_BINARY_COMPLEX 'y' -#define TYPE_LONG 'l' -#define TYPE_STRING 's' -#define TYPE_INTERNED 't' -#define TYPE_STRINGREF 'R' -#define TYPE_TUPLE '(' -#define TYPE_LIST '[' -#define TYPE_DICT '{' -#define TYPE_CODE 'c' -#define TYPE_UNICODE 'u' -#define TYPE_UNKNOWN '?' -#define TYPE_SET '<' -#define TYPE_FROZENSET '>' - -#define WFERR_OK 0 -#define WFERR_UNMARSHALLABLE 1 -#define WFERR_NESTEDTOODEEP 2 -#define WFERR_NOMEMORY 3 - -typedef struct { - FILE *fp; - int error; /* see WFERR_* values */ - int depth; - /* If fp == NULL, the following are valid: */ - PyObject *str; - char *ptr; - char *end; - PyObject *strings; /* dict on marshal, list on unmarshal */ - int version; -} WFILE; - -#define w_byte(c, p) if (((p)->fp)) putc((c), (p)->fp); \ - else if ((p)->ptr != (p)->end) *(p)->ptr++ = (c); \ - else w_more(c, p) - -static void -w_more(int c, WFILE *p) -{ - Py_ssize_t size, newsize; - if (p->str == NULL) - return; /* An error already occurred */ - size = PyString_Size(p->str); - newsize = size + size + 1024; - if (newsize > 32*1024*1024) { - newsize = size + (size >> 3); /* 12.5% overallocation */ - } - if (_PyString_Resize(&p->str, newsize) != 0) { - p->ptr = p->end = NULL; - } - else { - p->ptr = PyString_AS_STRING((PyStringObject *)p->str) + size; - p->end = - PyString_AS_STRING((PyStringObject *)p->str) + newsize; - *p->ptr++ = Py_SAFE_DOWNCAST(c, int, char); - } -} - -static void -w_string(char *s, int n, WFILE *p) -{ - if (p->fp != NULL) { - fwrite(s, 1, n, p->fp); - } - else { - while (--n >= 0) { - w_byte(*s, p); - s++; - } - } -} - -static void -w_short(int x, WFILE *p) -{ - w_byte((char)( x & 0xff), p); - w_byte((char)((x>> 8) & 0xff), p); -} - -static void -w_long(long x, WFILE *p) -{ - w_byte((char)( x & 0xff), p); - w_byte((char)((x>> 8) & 0xff), p); - w_byte((char)((x>>16) & 0xff), p); - w_byte((char)((x>>24) & 0xff), p); -} - -#if SIZEOF_LONG > 4 -static void -w_long64(long x, WFILE *p) -{ - w_long(x, p); - w_long(x>>32, p); -} -#endif - -/* We assume that Python longs are stored internally in base some power of - 2**15; for the sake of portability we'll always read and write them in base - exactly 2**15. */ - -#define PyLong_MARSHAL_SHIFT 15 -#define PyLong_MARSHAL_BASE ((short)1 << PyLong_MARSHAL_SHIFT) -#define PyLong_MARSHAL_MASK (PyLong_MARSHAL_BASE - 1) -#if PyLong_SHIFT % PyLong_MARSHAL_SHIFT != 0 -#error "PyLong_SHIFT must be a multiple of PyLong_MARSHAL_SHIFT" -#endif -#define PyLong_MARSHAL_RATIO (PyLong_SHIFT / PyLong_MARSHAL_SHIFT) - -static void -w_PyLong(const PyLongObject *ob, WFILE *p) -{ - Py_ssize_t i, j, n, l; - digit d; - - w_byte(TYPE_LONG, p); - if (Py_SIZE(ob) == 0) { - w_long((long)0, p); - return; - } - - /* set l to number of base PyLong_MARSHAL_BASE digits */ - n = ABS(Py_SIZE(ob)); - l = (n-1) * PyLong_MARSHAL_RATIO; - d = ob->ob_digit[n-1]; - assert(d != 0); /* a PyLong is always normalized */ - do { - d >>= PyLong_MARSHAL_SHIFT; - l++; - } while (d != 0); - w_long((long)(Py_SIZE(ob) > 0 ? l : -l), p); - - for (i=0; i < n-1; i++) { - d = ob->ob_digit[i]; - for (j=0; j < PyLong_MARSHAL_RATIO; j++) { - w_short(d & PyLong_MARSHAL_MASK, p); - d >>= PyLong_MARSHAL_SHIFT; - } - assert (d == 0); - } - d = ob->ob_digit[n-1]; - do { - w_short(d & PyLong_MARSHAL_MASK, p); - d >>= PyLong_MARSHAL_SHIFT; - } while (d != 0); -} - -static void -w_object(PyObject *v, WFILE *p) -{ - Py_ssize_t i, n; - - p->depth++; - - if (p->depth > MAX_MARSHAL_STACK_DEPTH) { - p->error = WFERR_NESTEDTOODEEP; - } - else if (v == NULL) { - w_byte(TYPE_NULL, p); - } - else if (v == Py_None) { - w_byte(TYPE_NONE, p); - } - else if (v == PyExc_StopIteration) { - w_byte(TYPE_STOPITER, p); - } - else if (v == Py_Ellipsis) { - w_byte(TYPE_ELLIPSIS, p); - } - else if (v == Py_False) { - w_byte(TYPE_FALSE, p); - } - else if (v == Py_True) { - w_byte(TYPE_TRUE, p); - } - else if (PyInt_CheckExact(v)) { - long x = PyInt_AS_LONG((PyIntObject *)v); -#if SIZEOF_LONG > 4 - long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31); - if (y && y != -1) { - w_byte(TYPE_INT64, p); - w_long64(x, p); - } - else -#endif - { - w_byte(TYPE_INT, p); - w_long(x, p); - } - } - else if (PyLong_CheckExact(v)) { - PyLongObject *ob = (PyLongObject *)v; - w_PyLong(ob, p); - } - else if (PyFloat_CheckExact(v)) { - if (p->version > 1) { - unsigned char buf[8]; - if (_PyFloat_Pack8(PyFloat_AsDouble(v), - buf, 1) < 0) { - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_byte(TYPE_BINARY_FLOAT, p); - w_string((char*)buf, 8, p); - } - else { - char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v), - 'g', 17, 0, NULL); - if (!buf) { - p->error = WFERR_NOMEMORY; - return; - } - n = strlen(buf); - w_byte(TYPE_FLOAT, p); - w_byte((int)n, p); - w_string(buf, (int)n, p); - PyMem_Free(buf); - } - } -#ifndef WITHOUT_COMPLEX - else if (PyComplex_CheckExact(v)) { - if (p->version > 1) { - unsigned char buf[8]; - if (_PyFloat_Pack8(PyComplex_RealAsDouble(v), - buf, 1) < 0) { - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_byte(TYPE_BINARY_COMPLEX, p); - w_string((char*)buf, 8, p); - if (_PyFloat_Pack8(PyComplex_ImagAsDouble(v), - buf, 1) < 0) { - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_string((char*)buf, 8, p); - } - else { - char *buf; - w_byte(TYPE_COMPLEX, p); - buf = PyOS_double_to_string(PyComplex_RealAsDouble(v), - 'g', 17, 0, NULL); - if (!buf) { - p->error = WFERR_NOMEMORY; - return; - } - n = strlen(buf); - w_byte((int)n, p); - w_string(buf, (int)n, p); - PyMem_Free(buf); - buf = PyOS_double_to_string(PyComplex_ImagAsDouble(v), - 'g', 17, 0, NULL); - if (!buf) { - p->error = WFERR_NOMEMORY; - return; - } - n = strlen(buf); - w_byte((int)n, p); - w_string(buf, (int)n, p); - PyMem_Free(buf); - } - } -#endif - else if (PyString_CheckExact(v)) { - if (p->strings && PyString_CHECK_INTERNED(v)) { - PyObject *o = PyDict_GetItem(p->strings, v); - if (o) { - long w = PyInt_AsLong(o); - w_byte(TYPE_STRINGREF, p); - w_long(w, p); - goto exit; - } - else { - int ok; - o = PyInt_FromSsize_t(PyDict_Size(p->strings)); - ok = o && - PyDict_SetItem(p->strings, v, o) >= 0; - Py_XDECREF(o); - if (!ok) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_byte(TYPE_INTERNED, p); - } - } - else { - w_byte(TYPE_STRING, p); - } - n = PyString_GET_SIZE(v); - if (n > INT_MAX) { - /* huge strings are not supported */ - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - w_string(PyString_AS_STRING(v), (int)n, p); - } -#ifdef Py_USING_UNICODE - else if (PyUnicode_CheckExact(v)) { - PyObject *utf8; - utf8 = PyUnicode_AsUTF8String(v); - if (utf8 == NULL) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_byte(TYPE_UNICODE, p); - n = PyString_GET_SIZE(utf8); - if (n > INT_MAX) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - w_string(PyString_AS_STRING(utf8), (int)n, p); - Py_DECREF(utf8); - } -#endif - else if (PyTuple_CheckExact(v)) { - w_byte(TYPE_TUPLE, p); - n = PyTuple_Size(v); - w_long((long)n, p); - for (i = 0; i < n; i++) { - w_object(PyTuple_GET_ITEM(v, i), p); - } - } - else if (PyList_CheckExact(v)) { - w_byte(TYPE_LIST, p); - n = PyList_GET_SIZE(v); - w_long((long)n, p); - for (i = 0; i < n; i++) { - w_object(PyList_GET_ITEM(v, i), p); - } - } - else if (PyDict_CheckExact(v)) { - Py_ssize_t pos; - PyObject *key, *value; - w_byte(TYPE_DICT, p); - /* This one is NULL object terminated! */ - pos = 0; - while (PyDict_Next(v, &pos, &key, &value)) { - w_object(key, p); - w_object(value, p); - } - w_object((PyObject *)NULL, p); - } - else if (PyAnySet_CheckExact(v)) { - PyObject *value, *it; - - if (PyObject_TypeCheck(v, &PySet_Type)) - w_byte(TYPE_SET, p); - else - w_byte(TYPE_FROZENSET, p); - n = PyObject_Size(v); - if (n == -1) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - it = PyObject_GetIter(v); - if (it == NULL) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - while ((value = PyIter_Next(it)) != NULL) { - w_object(value, p); - Py_DECREF(value); - } - Py_DECREF(it); - if (PyErr_Occurred()) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - } - else if (PyCode_Check(v)) { - PyCodeObject *co = (PyCodeObject *)v; - w_byte(TYPE_CODE, p); - w_long(co->co_argcount, p); - w_long(co->co_nlocals, p); - w_long(co->co_stacksize, p); - w_long(co->co_flags, p); - w_object(co->co_code, p); - w_object(co->co_consts, p); - w_object(co->co_names, p); - w_object(co->co_varnames, p); - w_object(co->co_freevars, p); - w_object(co->co_cellvars, p); - w_object(co->co_filename, p); - w_object(co->co_name, p); - w_long(co->co_firstlineno, p); - w_object(co->co_lnotab, p); - } - else if (PyObject_CheckReadBuffer(v)) { - /* Write unknown buffer-style objects as a string */ - char *s; - PyBufferProcs *pb = v->ob_type->tp_as_buffer; - w_byte(TYPE_STRING, p); - n = (*pb->bf_getreadbuffer)(v, 0, (void **)&s); - if (n > INT_MAX) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - w_string(s, (int)n, p); - } - else { - w_byte(TYPE_UNKNOWN, p); - p->error = WFERR_UNMARSHALLABLE; - } - exit: - p->depth--; -} - -/* version currently has no effect for writing longs. */ -void -PyMarshal_WriteLongToFile(long x, FILE *fp, int version) -{ - WFILE wf; - wf.fp = fp; - wf.error = WFERR_OK; - wf.depth = 0; - wf.strings = NULL; - wf.version = version; - w_long(x, &wf); -} - -void -PyMarshal_WriteObjectToFile(PyObject *x, FILE *fp, int version) -{ - WFILE wf; - wf.fp = fp; - wf.error = WFERR_OK; - wf.depth = 0; - wf.strings = (version > 0) ? PyDict_New() : NULL; - wf.version = version; - w_object(x, &wf); - Py_XDECREF(wf.strings); -} - -typedef WFILE RFILE; /* Same struct with different invariants */ - -#define rs_byte(p) (((p)->ptr < (p)->end) ? (unsigned char)*(p)->ptr++ : EOF) - -#define r_byte(p) ((p)->fp ? getc((p)->fp) : rs_byte(p)) - -static int -r_string(char *s, int n, RFILE *p) -{ - if (p->fp != NULL) - /* The result fits into int because it must be <=n. */ - return (int)fread(s, 1, n, p->fp); - if (p->end - p->ptr < n) - n = (int)(p->end - p->ptr); - memcpy(s, p->ptr, n); - p->ptr += n; - return n; -} - -static int -r_short(RFILE *p) -{ - register short x; - x = r_byte(p); - x |= r_byte(p) << 8; - /* Sign-extension, in case short greater than 16 bits */ - x |= -(x & 0x8000); - return x; -} - -static long -r_long(RFILE *p) -{ - register long x; - register FILE *fp = p->fp; - if (fp) { - x = getc(fp); - x |= (long)getc(fp) << 8; - x |= (long)getc(fp) << 16; - x |= (long)getc(fp) << 24; - } - else { - x = rs_byte(p); - x |= (long)rs_byte(p) << 8; - x |= (long)rs_byte(p) << 16; - x |= (long)rs_byte(p) << 24; - } -#if SIZEOF_LONG > 4 - /* Sign extension for 64-bit machines */ - x |= -(x & 0x80000000L); -#endif - return x; -} - -/* r_long64 deals with the TYPE_INT64 code. On a machine with - sizeof(long) > 4, it returns a Python int object, else a Python long - object. Note that w_long64 writes out TYPE_INT if 32 bits is enough, - so there's no inefficiency here in returning a PyLong on 32-bit boxes - for everything written via TYPE_INT64 (i.e., if an int is written via - TYPE_INT64, it *needs* more than 32 bits). -*/ -static PyObject * -r_long64(RFILE *p) -{ - long lo4 = r_long(p); - long hi4 = r_long(p); -#if SIZEOF_LONG > 4 - long x = (hi4 << 32) | (lo4 & 0xFFFFFFFFL); - return PyInt_FromLong(x); -#else - unsigned char buf[8]; - int one = 1; - int is_little_endian = (int)*(char*)&one; - if (is_little_endian) { - memcpy(buf, &lo4, 4); - memcpy(buf+4, &hi4, 4); - } - else { - memcpy(buf, &hi4, 4); - memcpy(buf+4, &lo4, 4); - } - return _PyLong_FromByteArray(buf, 8, is_little_endian, 1); -#endif -} - -static PyObject * -r_PyLong(RFILE *p) -{ - PyLongObject *ob; - int size, i, j, md, shorts_in_top_digit; - long n; - digit d; - - n = r_long(p); - if (n == 0) - return (PyObject *)_PyLong_New(0); - if (n < -INT_MAX || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, - "bad marshal data (long size out of range)"); - return NULL; - } - - size = 1 + (ABS(n) - 1) / PyLong_MARSHAL_RATIO; - shorts_in_top_digit = 1 + (ABS(n) - 1) % PyLong_MARSHAL_RATIO; - ob = _PyLong_New(size); - if (ob == NULL) - return NULL; - Py_SIZE(ob) = n > 0 ? size : -size; - - for (i = 0; i < size-1; i++) { - d = 0; - for (j=0; j < PyLong_MARSHAL_RATIO; j++) { - md = r_short(p); - if (md < 0 || md > PyLong_MARSHAL_BASE) - goto bad_digit; - d += (digit)md << j*PyLong_MARSHAL_SHIFT; - } - ob->ob_digit[i] = d; - } - d = 0; - for (j=0; j < shorts_in_top_digit; j++) { - md = r_short(p); - if (md < 0 || md > PyLong_MARSHAL_BASE) - goto bad_digit; - /* topmost marshal digit should be nonzero */ - if (md == 0 && j == shorts_in_top_digit - 1) { - Py_DECREF(ob); - PyErr_SetString(PyExc_ValueError, - "bad marshal data (unnormalized long data)"); - return NULL; - } - d += (digit)md << j*PyLong_MARSHAL_SHIFT; - } - /* top digit should be nonzero, else the resulting PyLong won't be - normalized */ - ob->ob_digit[size-1] = d; - return (PyObject *)ob; - bad_digit: - Py_DECREF(ob); - PyErr_SetString(PyExc_ValueError, - "bad marshal data (digit out of range in long)"); - return NULL; -} - - -static PyObject * -r_object(RFILE *p) -{ - /* NULL is a valid return value, it does not necessarily means that - an exception is set. */ - PyObject *v, *v2; - long i, n; - int type = r_byte(p); - PyObject *retval; - - p->depth++; - - if (p->depth > MAX_MARSHAL_STACK_DEPTH) { - p->depth--; - PyErr_SetString(PyExc_ValueError, "recursion limit exceeded"); - return NULL; - } - - switch (type) { - - case EOF: - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - - case TYPE_NULL: - retval = NULL; - break; - - case TYPE_NONE: - Py_INCREF(Py_None); - retval = Py_None; - break; - - case TYPE_STOPITER: - Py_INCREF(PyExc_StopIteration); - retval = PyExc_StopIteration; - break; - - case TYPE_ELLIPSIS: - Py_INCREF(Py_Ellipsis); - retval = Py_Ellipsis; - break; - - case TYPE_FALSE: - Py_INCREF(Py_False); - retval = Py_False; - break; - - case TYPE_TRUE: - Py_INCREF(Py_True); - retval = Py_True; - break; - - case TYPE_INT: - retval = PyInt_FromLong(r_long(p)); - break; - - case TYPE_INT64: - retval = r_long64(p); - break; - - case TYPE_LONG: - retval = r_PyLong(p); - break; - - case TYPE_FLOAT: - { - char buf[256]; - double dx; - n = r_byte(p); - if (n == EOF || r_string(buf, (int)n, p) != n) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - buf[n] = '\0'; - dx = PyOS_string_to_double(buf, NULL, NULL); - if (dx == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - retval = PyFloat_FromDouble(dx); - break; - } - - case TYPE_BINARY_FLOAT: - { - unsigned char buf[8]; - double x; - if (r_string((char*)buf, 8, p) != 8) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - x = _PyFloat_Unpack8(buf, 1); - if (x == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - retval = PyFloat_FromDouble(x); - break; - } - -#ifndef WITHOUT_COMPLEX - case TYPE_COMPLEX: - { - char buf[256]; - Py_complex c; - n = r_byte(p); - if (n == EOF || r_string(buf, (int)n, p) != n) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - buf[n] = '\0'; - c.real = PyOS_string_to_double(buf, NULL, NULL); - if (c.real == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - n = r_byte(p); - if (n == EOF || r_string(buf, (int)n, p) != n) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - buf[n] = '\0'; - c.imag = PyOS_string_to_double(buf, NULL, NULL); - if (c.imag == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - retval = PyComplex_FromCComplex(c); - break; - } - - case TYPE_BINARY_COMPLEX: - { - unsigned char buf[8]; - Py_complex c; - if (r_string((char*)buf, 8, p) != 8) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - c.real = _PyFloat_Unpack8(buf, 1); - if (c.real == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - if (r_string((char*)buf, 8, p) != 8) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - c.imag = _PyFloat_Unpack8(buf, 1); - if (c.imag == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - retval = PyComplex_FromCComplex(c); - break; - } -#endif - - case TYPE_INTERNED: - case TYPE_STRING: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)"); - retval = NULL; - break; - } - v = PyString_FromStringAndSize((char *)NULL, n); - if (v == NULL) { - retval = NULL; - break; - } - if (r_string(PyString_AS_STRING(v), (int)n, p) != n) { - Py_DECREF(v); - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - if (type == TYPE_INTERNED) { - PyString_InternInPlace(&v); - if (PyList_Append(p->strings, v) < 0) { - retval = NULL; - break; - } - } - retval = v; - break; - - case TYPE_STRINGREF: - n = r_long(p); - if (n < 0 || n >= PyList_GET_SIZE(p->strings)) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (string ref out of range)"); - retval = NULL; - break; - } - v = PyList_GET_ITEM(p->strings, n); - Py_INCREF(v); - retval = v; - break; - -#ifdef Py_USING_UNICODE - case TYPE_UNICODE: - { - char *buffer; - - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)"); - retval = NULL; - break; - } - buffer = PyMem_NEW(char, n); - if (buffer == NULL) { - retval = PyErr_NoMemory(); - break; - } - if (r_string(buffer, (int)n, p) != n) { - PyMem_DEL(buffer); - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - v = PyUnicode_DecodeUTF8(buffer, n, NULL); - PyMem_DEL(buffer); - retval = v; - break; - } -#endif - - case TYPE_TUPLE: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (tuple size out of range)"); - retval = NULL; - break; - } - v = PyTuple_New((int)n); - if (v == NULL) { - retval = NULL; - break; - } - for (i = 0; i < n; i++) { - v2 = r_object(p); - if ( v2 == NULL ) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "NULL object in marshal data for tuple"); - Py_DECREF(v); - v = NULL; - break; - } - PyTuple_SET_ITEM(v, (int)i, v2); - } - retval = v; - break; - - case TYPE_LIST: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (list size out of range)"); - retval = NULL; - break; - } - v = PyList_New((int)n); - if (v == NULL) { - retval = NULL; - break; - } - for (i = 0; i < n; i++) { - v2 = r_object(p); - if ( v2 == NULL ) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "NULL object in marshal data for list"); - Py_DECREF(v); - v = NULL; - break; - } - PyList_SET_ITEM(v, (int)i, v2); - } - retval = v; - break; - - case TYPE_DICT: - v = PyDict_New(); - if (v == NULL) { - retval = NULL; - break; - } - for (;;) { - PyObject *key, *val; - key = r_object(p); - if (key == NULL) - break; - val = r_object(p); - if (val != NULL) - PyDict_SetItem(v, key, val); - Py_DECREF(key); - Py_XDECREF(val); - } - if (PyErr_Occurred()) { - Py_DECREF(v); - v = NULL; - } - retval = v; - break; - - case TYPE_SET: - case TYPE_FROZENSET: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (set size out of range)"); - retval = NULL; - break; - } - v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL); - if (v == NULL) { - retval = NULL; - break; - } - for (i = 0; i < n; i++) { - v2 = r_object(p); - if ( v2 == NULL ) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "NULL object in marshal data for set"); - Py_DECREF(v); - v = NULL; - break; - } - if (PySet_Add(v, v2) == -1) { - Py_DECREF(v); - Py_DECREF(v2); - v = NULL; - break; - } - Py_DECREF(v2); - } - retval = v; - break; - - case TYPE_CODE: - if (PyEval_GetRestricted()) { - PyErr_SetString(PyExc_RuntimeError, - "cannot unmarshal code objects in " - "restricted execution mode"); - retval = NULL; - break; - } - else { - int argcount; - int nlocals; - int stacksize; - int flags; - PyObject *code = NULL; - PyObject *consts = NULL; - PyObject *names = NULL; - PyObject *varnames = NULL; - PyObject *freevars = NULL; - PyObject *cellvars = NULL; - PyObject *filename = NULL; - PyObject *name = NULL; - int firstlineno; - PyObject *lnotab = NULL; - - v = NULL; - - /* XXX ignore long->int overflows for now */ - argcount = (int)r_long(p); - nlocals = (int)r_long(p); - stacksize = (int)r_long(p); - flags = (int)r_long(p); - code = r_object(p); - if (code == NULL) - goto code_error; - consts = r_object(p); - if (consts == NULL) - goto code_error; - names = r_object(p); - if (names == NULL) - goto code_error; - varnames = r_object(p); - if (varnames == NULL) - goto code_error; - freevars = r_object(p); - if (freevars == NULL) - goto code_error; - cellvars = r_object(p); - if (cellvars == NULL) - goto code_error; - filename = r_object(p); - if (filename == NULL) - goto code_error; - name = r_object(p); - if (name == NULL) - goto code_error; - firstlineno = (int)r_long(p); - lnotab = r_object(p); - if (lnotab == NULL) - goto code_error; - - v = (PyObject *) PyCode_New( - argcount, nlocals, stacksize, flags, - code, consts, names, varnames, - freevars, cellvars, filename, name, - firstlineno, lnotab); - - code_error: - Py_XDECREF(code); - Py_XDECREF(consts); - Py_XDECREF(names); - Py_XDECREF(varnames); - Py_XDECREF(freevars); - Py_XDECREF(cellvars); - Py_XDECREF(filename); - Py_XDECREF(name); - Py_XDECREF(lnotab); - - } - retval = v; - break; - - default: - /* Bogus data got written, which isn't ideal. - This will let you keep working and recover. */ - PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)"); - retval = NULL; - break; - - } - p->depth--; - return retval; -} - -static PyObject * -read_object(RFILE *p) -{ - PyObject *v; - if (PyErr_Occurred()) { - fprintf(stderr, "XXX readobject called with exception set\n"); - return NULL; - } - v = r_object(p); - if (v == NULL && !PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object"); - return v; -} - -int -PyMarshal_ReadShortFromFile(FILE *fp) -{ - RFILE rf; - assert(fp); - rf.fp = fp; - rf.strings = NULL; - rf.end = rf.ptr = NULL; - return r_short(&rf); -} - -long -PyMarshal_ReadLongFromFile(FILE *fp) -{ - RFILE rf; - rf.fp = fp; - rf.strings = NULL; - rf.ptr = rf.end = NULL; - return r_long(&rf); -} - -#ifdef HAVE_FSTAT -/* Return size of file in bytes; < 0 if unknown. */ -static off_t -getfilesize(FILE *fp) -{ - struct stat st; - if (fstat(fileno(fp), &st) != 0) - return -1; - else - return st.st_size; -} -#endif - -/* If we can get the size of the file up-front, and it's reasonably small, - * read it in one gulp and delegate to ...FromString() instead. Much quicker - * than reading a byte at a time from file; speeds .pyc imports. - * CAUTION: since this may read the entire remainder of the file, don't - * call it unless you know you're done with the file. - */ -PyObject * -PyMarshal_ReadLastObjectFromFile(FILE *fp) -{ -/* REASONABLE_FILE_LIMIT is by defn something big enough for Tkinter.pyc. */ -#define REASONABLE_FILE_LIMIT (1L << 18) -#ifdef HAVE_FSTAT - off_t filesize; - filesize = getfilesize(fp); - if (filesize > 0 && filesize <= REASONABLE_FILE_LIMIT) { - char* pBuf = (char *)PyMem_MALLOC(filesize); - if (pBuf != NULL) { - PyObject* v; - size_t n; - /* filesize must fit into an int, because it - is smaller than REASONABLE_FILE_LIMIT */ - n = fread(pBuf, 1, (int)filesize, fp); - v = PyMarshal_ReadObjectFromString(pBuf, n); - PyMem_FREE(pBuf); - return v; - } - - } -#endif - /* We don't have fstat, or we do but the file is larger than - * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time. - */ - return PyMarshal_ReadObjectFromFile(fp); - -#undef REASONABLE_FILE_LIMIT -} - -PyObject * -PyMarshal_ReadObjectFromFile(FILE *fp) -{ - RFILE rf; - PyObject *result; - rf.fp = fp; - rf.strings = PyList_New(0); - rf.depth = 0; - rf.ptr = rf.end = NULL; - result = r_object(&rf); - Py_DECREF(rf.strings); - return result; -} - -PyObject * -PyMarshal_ReadObjectFromString(char *str, Py_ssize_t len) -{ - RFILE rf; - PyObject *result; - rf.fp = NULL; - rf.ptr = str; - rf.end = str + len; - rf.strings = PyList_New(0); - rf.depth = 0; - result = r_object(&rf); - Py_DECREF(rf.strings); - return result; -} - -static void -set_error(int error) -{ - switch (error) { - case WFERR_NOMEMORY: - PyErr_NoMemory(); - break; - case WFERR_UNMARSHALLABLE: - PyErr_SetString(PyExc_ValueError, "unmarshallable object"); - break; - case WFERR_NESTEDTOODEEP: - default: - PyErr_SetString(PyExc_ValueError, - "object too deeply nested to marshal"); - break; - } -} - -PyObject * -PyMarshal_WriteObjectToString(PyObject *x, int version) -{ - WFILE wf; - wf.fp = NULL; - wf.str = PyString_FromStringAndSize((char *)NULL, 50); - if (wf.str == NULL) - return NULL; - wf.ptr = PyString_AS_STRING((PyStringObject *)wf.str); - wf.end = wf.ptr + PyString_Size(wf.str); - wf.error = WFERR_OK; - wf.depth = 0; - wf.version = version; - wf.strings = (version > 0) ? PyDict_New() : NULL; - w_object(x, &wf); - Py_XDECREF(wf.strings); - if (wf.str != NULL) { - char *base = PyString_AS_STRING((PyStringObject *)wf.str); - if (wf.ptr - base > PY_SSIZE_T_MAX) { - Py_DECREF(wf.str); - PyErr_SetString(PyExc_OverflowError, - "too much marshall data for a string"); - return NULL; - } - if (_PyString_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base))) - return NULL; - } - if (wf.error != WFERR_OK) { - Py_XDECREF(wf.str); - set_error(wf.error); - return NULL; - } - return wf.str; -} - -/* And an interface for Python programs... */ - -static PyObject * -marshal_dump(PyObject *self, PyObject *args) -{ - WFILE wf; - PyObject *x; - PyObject *f; - int version = Py_MARSHAL_VERSION; - if (!PyArg_ParseTuple(args, "OO|i:dump", &x, &f, &version)) - return NULL; - if (!PyFile_Check(f)) { - PyErr_SetString(PyExc_TypeError, - "marshal.dump() 2nd arg must be file"); - return NULL; - } - wf.fp = PyFile_AsFile(f); - wf.str = NULL; - wf.ptr = wf.end = NULL; - wf.error = WFERR_OK; - wf.depth = 0; - wf.strings = (version > 0) ? PyDict_New() : 0; - wf.version = version; - w_object(x, &wf); - Py_XDECREF(wf.strings); - if (wf.error != WFERR_OK) { - set_error(wf.error); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; -} - -PyDoc_STRVAR(dump_doc, -"dump(value, file[, version])\n\ -\n\ -Write the value on the open file. The value must be a supported type.\n\ -The file must be an open file object such as sys.stdout or returned by\n\ -open() or os.popen(). It must be opened in binary mode ('wb' or 'w+b').\n\ -\n\ -If the value has (or contains an object that has) an unsupported type, a\n\ -ValueError exception is raised - but garbage data will also be written\n\ -to the file. The object will not be properly read back by load()\n\ -\n\ -New in version 2.4: The version argument indicates the data format that\n\ -dump should use."); - -static PyObject * -marshal_load(PyObject *self, PyObject *f) -{ - RFILE rf; - PyObject *result; - if (!PyFile_Check(f)) { - PyErr_SetString(PyExc_TypeError, - "marshal.load() arg must be file"); - return NULL; - } - rf.fp = PyFile_AsFile(f); - rf.strings = PyList_New(0); - rf.depth = 0; - result = read_object(&rf); - Py_DECREF(rf.strings); - return result; -} - -PyDoc_STRVAR(load_doc, -"load(file)\n\ -\n\ -Read one value from the open file and return it. If no valid value is\n\ -read (e.g. because the data has a different Python version's\n\ -incompatible marshal format), raise EOFError, ValueError or TypeError.\n\ -The file must be an open file object opened in binary mode ('rb' or\n\ -'r+b').\n\ -\n\ -Note: If an object containing an unsupported type was marshalled with\n\ -dump(), load() will substitute None for the unmarshallable type."); - - -static PyObject * -marshal_dumps(PyObject *self, PyObject *args) -{ - PyObject *x; - int version = Py_MARSHAL_VERSION; - if (!PyArg_ParseTuple(args, "O|i:dumps", &x, &version)) - return NULL; - return PyMarshal_WriteObjectToString(x, version); -} - -PyDoc_STRVAR(dumps_doc, -"dumps(value[, version])\n\ -\n\ -Return the string that would be written to a file by dump(value, file).\n\ -The value must be a supported type. Raise a ValueError exception if\n\ -value has (or contains an object that has) an unsupported type.\n\ -\n\ -New in version 2.4: The version argument indicates the data format that\n\ -dumps should use."); - - -static PyObject * -marshal_loads(PyObject *self, PyObject *args) -{ - RFILE rf; - char *s; - Py_ssize_t n; - PyObject* result; - if (!PyArg_ParseTuple(args, "s#:loads", &s, &n)) - return NULL; - rf.fp = NULL; - rf.ptr = s; - rf.end = s + n; - rf.strings = PyList_New(0); - rf.depth = 0; - result = read_object(&rf); - Py_DECREF(rf.strings); - return result; -} - -PyDoc_STRVAR(loads_doc, -"loads(string)\n\ -\n\ -Convert the string to a value. If no valid value is found, raise\n\ -EOFError, ValueError or TypeError. Extra characters in the string are\n\ -ignored."); - -static PyMethodDef marshal_methods[] = { - {"dump", marshal_dump, METH_VARARGS, dump_doc}, - {"load", marshal_load, METH_O, load_doc}, - {"dumps", marshal_dumps, METH_VARARGS, dumps_doc}, - {"loads", marshal_loads, METH_VARARGS, loads_doc}, - {NULL, NULL} /* sentinel */ -}; - -PyDoc_STRVAR(marshal_doc, -"This module contains functions that can read and write Python values in\n\ -a binary format. The format is specific to Python, but independent of\n\ -machine architecture issues.\n\ -\n\ -Not all Python object types are supported; in general, only objects\n\ -whose value is independent from a particular invocation of Python can be\n\ -written and read by this module. The following types are supported:\n\ -None, integers, long integers, floating point numbers, strings, Unicode\n\ -objects, tuples, lists, sets, dictionaries, and code objects, where it\n\ -should be understood that tuples, lists and dictionaries are only\n\ -supported as long as the values contained therein are themselves\n\ -supported; and recursive lists and dictionaries should not be written\n\ -(they will cause infinite loops).\n\ -\n\ -Variables:\n\ -\n\ -version -- indicates the format that the module uses. Version 0 is the\n\ - historical format, version 1 (added in Python 2.4) shares interned\n\ - strings and version 2 (added in Python 2.5) uses a binary format for\n\ - floating point numbers. (New in version 2.4)\n\ -\n\ -Functions:\n\ -\n\ -dump() -- write value to a file\n\ -load() -- read value from a file\n\ -dumps() -- write value to a string\n\ -loads() -- read value from a string"); - - -PyMODINIT_FUNC -PyMarshal_Init(void) -{ - PyObject *mod = Py_InitModule3("marshal", marshal_methods, - marshal_doc); - if (mod == NULL) - return; - PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION); -} diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/README b/AppPkg/Applications/Python/Python-2.7.2/Demo/README deleted file mode 100644 index ce362ee..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/README +++ /dev/null @@ -1,40 +0,0 @@ -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 deleted file mode 100644 index 90d6c9b..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/README +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index ee35375..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi0.sh +++ /dev/null @@ -1,8 +0,0 @@ -#! /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 deleted file mode 100644 index 3a0c604..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi1.py +++ /dev/null @@ -1,14 +0,0 @@ -#!/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 deleted file mode 100644 index 1ed9f55..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi2.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/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 deleted file mode 100644 index 224fc83..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/cgi3.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/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 deleted file mode 100644 index 990c2e6..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/cgi/wiki.py +++ /dev/null @@ -1,123 +0,0 @@ -"""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 "

", label, self.name, "

" - print '
' % self.scripturl - s = '' - print s % self.data - print '' - print '' % self.name - print '
' - print '' % label - print "
" - - def cmd_create(self, form): - self.data = form.getvalue("text", "").strip() - error = self.store() - if error: - print "

I'm sorry. That didn't work

" - 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 deleted file mode 100644 index 9d631b8..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Complex.py +++ /dev/null @@ -1,320 +0,0 @@ -# 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 deleted file mode 100644 index 9c13f4c..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Dates.py +++ /dev/null @@ -1,227 +0,0 @@ -# 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 deleted file mode 100644 index 7bcb257..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Dbm.py +++ /dev/null @@ -1,66 +0,0 @@ -# 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 deleted file mode 100644 index 8fc839a..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/README +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index b0ce5cb..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Range.py +++ /dev/null @@ -1,93 +0,0 @@ -"""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 deleted file mode 100644 index a509e70..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Rev.py +++ /dev/null @@ -1,95 +0,0 @@ -''' -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 deleted file mode 100644 index a5834e9..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/Vec.py +++ /dev/null @@ -1,68 +0,0 @@ -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 deleted file mode 100644 index 86805e1..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/classes/bitvec.py +++ /dev/null @@ -1,333 +0,0 @@ -# -# 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 deleted file mode 100644 index af86feb..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/README +++ /dev/null @@ -1,60 +0,0 @@ -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 deleted file mode 100644 index 11ec3fa..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/patterns +++ /dev/null @@ -1,4 +0,0 @@ -^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 deleted file mode 100644 index 19617a3..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/regextest.py +++ /dev/null @@ -1,47 +0,0 @@ -#! /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 deleted file mode 100644 index e19f63e..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/sortingtest.py +++ /dev/null @@ -1,45 +0,0 @@ -#! /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 deleted file mode 100644 index a715fe0..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/comparisons/systemtest.py +++ /dev/null @@ -1,74 +0,0 @@ -#! /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 deleted file mode 100644 index 69f6264..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/README +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index f2ba8f8..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/foo +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index ec4323c..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/md5test/md5driver.py +++ /dev/null @@ -1,123 +0,0 @@ -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 deleted file mode 100644 index 732c7be..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Eiffel.py +++ /dev/null @@ -1,113 +0,0 @@ -"""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 deleted file mode 100644 index 204f308..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Enum.py +++ /dev/null @@ -1,169 +0,0 @@ -"""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 deleted file mode 100644 index b262a80..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Meta.py +++ /dev/null @@ -1,118 +0,0 @@ -"""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 deleted file mode 100644 index 5334860..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Simple.py +++ /dev/null @@ -1,45 +0,0 @@ -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 deleted file mode 100644 index d3b3f38..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Synch.py +++ /dev/null @@ -1,256 +0,0 @@ -"""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 deleted file mode 100644 index b02d05a..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Trace.py +++ /dev/null @@ -1,144 +0,0 @@ -"""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 deleted file mode 100644 index 88e05a3..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/index.html +++ /dev/null @@ -1,605 +0,0 @@ - - - -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: - -
-class MySpecialClass(BaseClass1):
-    i = 1
-    def f(s): pass
-
- -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: - -

-x = MySpecialClass()
-y = MySpecialClass()
-print x.__class__, y.__class__
-
- -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: - -

- -
Enum.py - -
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. - -

- -

Trace.py - -
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. - -

- -

Meta.py - -
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.) - -

- -

Eiffel.py - -
Uses the above generic metaclass to implement Eiffel style -pre-conditions and post-conditions. - -

- -

Synch.py - -
Uses the above generic metaclass to implement synchronized -methods. - -

- -

Simple.py - -
The example module used above. - -

- -

- -

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 deleted file mode 100644 index 81298a7..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/meta-vladimir.txt +++ /dev/null @@ -1,256 +0,0 @@ -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 deleted file mode 100644 index f3a412b..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/newmetaclasses/Eiffel.py +++ /dev/null @@ -1,141 +0,0 @@ -"""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 deleted file mode 100644 index a080e8d..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/newmetaclasses/Enum.py +++ /dev/null @@ -1,177 +0,0 @@ -"""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 deleted file mode 100644 index 1df6c3d..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/FILES +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index fa5bd31..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/README +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 81efa02..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/docstring.py +++ /dev/null @@ -1,2 +0,0 @@ -"""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 deleted file mode 100644 index 346f973..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/example.py +++ /dev/null @@ -1,190 +0,0 @@ -"""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 deleted file mode 100644 index 75ab0e7..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/simple.py +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index e5b6bec..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/source.py +++ /dev/null @@ -1,27 +0,0 @@ -"""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 deleted file mode 100644 index f3f48b8..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/test_parser.py +++ /dev/null @@ -1,48 +0,0 @@ -#! /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 deleted file mode 100644 index eee1c7a..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/test_unparse.py +++ /dev/null @@ -1,213 +0,0 @@ -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 deleted file mode 100644 index b42d979..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/parser/unparse.py +++ /dev/null @@ -1,606 +0,0 @@ -"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 deleted file mode 100644 index 58354e1..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/FSProxy.py +++ /dev/null @@ -1,301 +0,0 @@ -"""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 deleted file mode 100644 index b4b0d92..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/RCSProxy.py +++ /dev/null @@ -1,198 +0,0 @@ -#! /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 deleted file mode 100644 index c8137e9..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/README +++ /dev/null @@ -1,121 +0,0 @@ -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 deleted file mode 100644 index 41a5bcc..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/client.py +++ /dev/null @@ -1,157 +0,0 @@ -"""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 deleted file mode 100644 index 96cc257..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cmdfw.py +++ /dev/null @@ -1,144 +0,0 @@ -"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 deleted file mode 100644 index 2f8a8a8..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cmptree.py +++ /dev/null @@ -1,208 +0,0 @@ -"""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 deleted file mode 100644 index 41c5979..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cvslib.py +++ /dev/null @@ -1,364 +0,0 @@ -"""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 deleted file mode 100644 index 95f5c58..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/cvslock.py +++ /dev/null @@ -1,280 +0,0 @@ -"""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 deleted file mode 100644 index 43a904e..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/mac.py +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 2f5519f..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/makechangelog.py +++ /dev/null @@ -1,109 +0,0 @@ -#! /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 deleted file mode 100644 index 775de71..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcsbump +++ /dev/null @@ -1,33 +0,0 @@ -#!/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 deleted file mode 100644 index dfa9436..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcsclient.py +++ /dev/null @@ -1,71 +0,0 @@ -"""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 deleted file mode 100644 index 7d6ce9f..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/rcslib.py +++ /dev/null @@ -1,334 +0,0 @@ -"""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 deleted file mode 100644 index 051ace8..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/security.py +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index c7a4491..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/server.py +++ /dev/null @@ -1,145 +0,0 @@ -"""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 deleted file mode 100644 index 3c82282..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/pdist/sumtree.py +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 6550e67..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/README +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index f1ff58b..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/beer.py +++ /dev/null @@ -1,20 +0,0 @@ -#! /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 deleted file mode 100644 index fc903c5..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/eqfix.py +++ /dev/null @@ -1,198 +0,0 @@ -#! /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 deleted file mode 100644 index 2068c85..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/fact.py +++ /dev/null @@ -1,49 +0,0 @@ -#! /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 deleted file mode 100644 index 1213643..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/find-uname.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/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 deleted file mode 100644 index c7fcb9f..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/from.py +++ /dev/null @@ -1,35 +0,0 @@ -#! /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 deleted file mode 100644 index 61e937f..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/lpwatch.py +++ /dev/null @@ -1,102 +0,0 @@ -#! /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 deleted file mode 100644 index 294502f..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/makedir.py +++ /dev/null @@ -1,21 +0,0 @@ -#! /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 deleted file mode 100644 index 993c3f6..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/markov.py +++ /dev/null @@ -1,121 +0,0 @@ -#! /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 deleted file mode 100644 index 41d59d6..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/mboxconvert.py +++ /dev/null @@ -1,124 +0,0 @@ -#! /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 deleted file mode 100644 index 138a186..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/morse.py +++ /dev/null @@ -1,138 +0,0 @@ -#! /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 deleted file mode 100644 index d02e96f..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/newslist.doc +++ /dev/null @@ -1,59 +0,0 @@ - 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 deleted file mode 100644 index 5462520..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/newslist.py +++ /dev/null @@ -1,362 +0,0 @@ -#! /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('

Newsgroups available%s

\n' % detail) - f.write('Back to top level

\n' % - (httppref, rootpage)) - printtree(f, tree, 0, p) - f.write('\n

') - 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('

  • ' % (httppref, p[1:])) - f.write(p[1:] + '.*') - f.write('%s\n' % pagelinkicon) - createpage(p[1:], tree, p) - return - - kl = tree.keys() - - if l > 1: - kl.sort() - if indent > 0: - # Create a sub-list - f.write('
  • %s\n
      ' % p[1:]) - else: - # Create a main list - f.write('
        ') - indent = indent + 1 - - for i in kl: - if i == '.': - # Output a newsgroup - f.write('
      • %s ' % (p[1:], p[1:])) - if p[1:] in desc: - f.write(' %s\n' % desc[p[1:]]) - else: - f.write('\n') - else: - # Output a hierarchy - printtree(f, tree[i], indent, p+'.'+i) - - if l > 1: - f.write('\n
      ') - -# Reading descriptions file --------------------------------------- - -# This returns a dict mapping group name to its description - -def readdesc(descfile): - global desc - desc = {} - - if descfile == '': - return - - try: - with open(descfile, 'r') as d: - print 'Reading descriptions...' - for l in d: - bits = l.split() - try: - grp = bits[0] - dsc = ' '.join(bits[1:]) - if len(dsc) > 1: - desc[grp] = dsc - except IndexError: - pass - except IOError: - print 'Failed to open description file ' + descfile - return - -# Check that ouput directory exists, ------------------------------ -# and offer to create it if not - -def checkopdir(pagedir): - if not os.path.isdir(pagedir): - print 'Directory %s does not exist.' % pagedir - print 'Shall I create it for you? (y/n)' - if sys.stdin.readline()[0] == 'y': - try: - os.mkdir(pagedir, 0777) - except: - print 'Sorry - failed!' - sys.exit(1) - else: - print 'OK. Exiting.' - sys.exit(1) - -# Read and write current local tree ---------------------------------- - -def readlocallist(treefile): - print 'Reading current local group list...' - tree = {} - try: - treetime = time.localtime(os.stat(treefile)[ST_MTIME]) - except: - print '\n*** Failed to open local group cache '+treefile - print 'If this is the first time you have run newslist, then' - print 'use the -a option to create it.' - sys.exit(1) - treedate = '%02d%02d%02d' % (treetime[0] % 100, treetime[1], treetime[2]) - try: - with open(treefile, 'rb') as dump: - tree = marshal.load(dump) - except IOError: - print 'Cannot open local group list ' + treefile - return (tree, treedate) - -def writelocallist(treefile, tree): - try: - with open(treefile, 'wb') as dump: - groups = marshal.dump(tree, dump) - print 'Saved list to %s\n' % treefile - except: - print 'Sorry - failed to write to local group cache', treefile - print 'Does it (or its directory) have the correct permissions?' - sys.exit(1) - -# Return list of all groups on server ----------------------------- - -def getallgroups(server): - print 'Getting list of all groups...' - treedate = '010101' - info = server.list()[1] - groups = [] - print 'Processing...' - if skipempty: - print '\nIgnoring following empty groups:' - for i in info: - grpname = i[0].split()[0] - if skipempty and int(i[1]) < int(i[2]): - print grpname + ' ', - else: - groups.append(grpname) - print '\n' - if skipempty: - print '(End of empty groups)' - return groups - -# Return list of new groups on server ----------------------------- - -def getnewgroups(server, treedate): - print 'Getting list of new groups since start of %s...' % treedate, - info = server.newgroups(treedate, '000001')[1] - print 'got %d.' % len(info) - print 'Processing...', - groups = [] - for i in info: - grpname = i.split()[0] - groups.append(grpname) - print 'Done' - return groups - -# Now the main program -------------------------------------------- - -def main(): - tree = {} - - # Check that the output directory exists - checkopdir(pagedir) - - try: - print 'Connecting to %s...' % newshost - if sys.version[0] == '0': - s = NNTP.init(newshost) - else: - s = NNTP(newshost) - connected = True - except (nntplib.error_temp, nntplib.error_perm), x: - print 'Error connecting to host:', x - print 'I\'ll try to use just the local list.' - connected = False - - # If -a is specified, read the full list of groups from server - if connected and len(sys.argv) > 1 and sys.argv[1] == '-a': - groups = getallgroups(s) - - # Otherwise just read the local file and then add - # groups created since local file last modified. - else: - - (tree, treedate) = readlocallist(treefile) - if connected: - groups = getnewgroups(s, treedate) - - if connected: - addtotree(tree, groups) - writelocallist(treefile,tree) - - # Read group descriptions - readdesc(descfile) - - print 'Creating pages...' - createpage(rootpage, tree, '') - print 'Done' - -if __name__ == "__main__": - main() - -# That's all folks -###################################################################### diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/pi.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/pi.py deleted file mode 100644 index f46fcff..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/pi.py +++ /dev/null @@ -1,33 +0,0 @@ -#! /usr/bin/env python - -# Print digits of pi forever. -# -# The algorithm, using Python's 'long' integers ("bignums"), works -# with continued fractions, and was conceived by Lambert Meertens. -# -# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton, -# published by Prentice-Hall (UK) Ltd., 1990. - -import sys - -def main(): - k, a, b, a1, b1 = 2, 4, 1, 12, 4 - while True: - # Next approximation - p, q, k = k*k, 2*k+1, k+1 - a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 - # Print common digits - d, d1 = a//b, a1//b1 - while d == d1: - output(d) - a, a1 = 10*(a%b), 10*(a1%b1) - d, d1 = a//b, a1//b1 - -def output(d): - # Use write() to avoid spaces between the digits - sys.stdout.write(str(d)) - # Flush so the output is seen immediately - sys.stdout.flush() - -if __name__ == "__main__": - main() diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/pp.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/pp.py deleted file mode 100644 index ccc7bc0..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/pp.py +++ /dev/null @@ -1,129 +0,0 @@ -#! /usr/bin/env python - -# Emulate some Perl command line options. -# Usage: pp [-a] [-c] [-d] [-e scriptline] [-F fieldsep] [-n] [-p] [file] ... -# Where the options mean the following: -# -a : together with -n or -p, splits each line into list F -# -c : check syntax only, do not execute any code -# -d : run the script under the debugger, pdb -# -e scriptline : gives one line of the Python script; may be repeated -# -F fieldsep : sets the field separator for the -a option [not in Perl] -# -n : runs the script for each line of input -# -p : prints the line after the script has run -# When no script lines have been passed, the first file argument -# contains the script. With -n or -p, the remaining arguments are -# read as input to the script, line by line. If a file is '-' -# or missing, standard input is read. - -# XXX To do: -# - add -i extension option (change files in place) -# - make a single loop over the files and lines (changes effect of 'break')? -# - add an option to specify the record separator -# - except for -n/-p, run directly from the file if at all possible - -import sys -import getopt - -FS = '' -SCRIPT = [] -AFLAG = 0 -CFLAG = 0 -DFLAG = 0 -NFLAG = 0 -PFLAG = 0 - -try: - optlist, ARGS = getopt.getopt(sys.argv[1:], 'acde:F:np') -except getopt.error, msg: - sys.stderr.write('%s: %s\n' % (sys.argv[0], msg)) - sys.exit(2) - -for option, optarg in optlist: - if option == '-a': - AFLAG = 1 - elif option == '-c': - CFLAG = 1 - elif option == '-d': - DFLAG = 1 - elif option == '-e': - for line in optarg.split('\n'): - SCRIPT.append(line) - elif option == '-F': - FS = optarg - elif option == '-n': - NFLAG = 1 - PFLAG = 0 - elif option == '-p': - NFLAG = 1 - PFLAG = 1 - else: - print option, 'not recognized???' - -if not ARGS: ARGS.append('-') - -if not SCRIPT: - if ARGS[0] == '-': - fp = sys.stdin - else: - fp = open(ARGS[0], 'r') - while 1: - line = fp.readline() - if not line: break - SCRIPT.append(line[:-1]) - del fp - del ARGS[0] - if not ARGS: ARGS.append('-') - -if CFLAG: - prologue = ['if 0:'] - epilogue = [] -elif NFLAG: - # Note that it is on purpose that AFLAG and PFLAG are - # tested dynamically each time through the loop - prologue = [ - 'LINECOUNT = 0', - 'for FILE in ARGS:', - ' \tif FILE == \'-\':', - ' \t \tFP = sys.stdin', - ' \telse:', - ' \t \tFP = open(FILE, \'r\')', - ' \tLINENO = 0', - ' \twhile 1:', - ' \t \tLINE = FP.readline()', - ' \t \tif not LINE: break', - ' \t \tLINENO = LINENO + 1', - ' \t \tLINECOUNT = LINECOUNT + 1', - ' \t \tL = LINE[:-1]', - ' \t \taflag = AFLAG', - ' \t \tif aflag:', - ' \t \t \tif FS: F = L.split(FS)', - ' \t \t \telse: F = L.split()' - ] - epilogue = [ - ' \t \tif not PFLAG: continue', - ' \t \tif aflag:', - ' \t \t \tif FS: print FS.join(F)', - ' \t \t \telse: print \' \'.join(F)', - ' \t \telse: print L', - ] -else: - prologue = ['if 1:'] - epilogue = [] - -# Note that we indent using tabs only, so that any indentation style -# used in 'command' will come out right after re-indentation. - -program = '\n'.join(prologue) + '\n' -for line in SCRIPT: - program += ' \t \t' + line + '\n' -program += '\n'.join(epilogue) + '\n' - -import tempfile -fp = tempfile.NamedTemporaryFile() -fp.write(program) -fp.flush() -if DFLAG: - import pdb - pdb.run('execfile(%r)' % (fp.name,)) -else: - execfile(fp.name) diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/primes.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/primes.py deleted file mode 100644 index 6c6a152..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/primes.py +++ /dev/null @@ -1,30 +0,0 @@ -#! /usr/bin/env python - -# Print prime numbers in a given range - -def primes(min, max): - if max >= 2 >= min: - print 2 - primes = [2] - i = 3 - while i <= max: - for p in primes: - if i % p == 0 or p*p > i: - break - if i % p != 0: - primes.append(i) - if i >= min: - print i - i += 2 - -def main(): - import sys - min, max = 2, 0x7fffffff - if sys.argv[1:]: - min = int(sys.argv[1]) - if sys.argv[2:]: - max = int(sys.argv[2]) - primes(min, max) - -if __name__ == "__main__": - main() diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/queens.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/queens.py deleted file mode 100644 index 5d212ed..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/queens.py +++ /dev/null @@ -1,85 +0,0 @@ -#! /usr/bin/env python - -"""N queens problem. - -The (well-known) problem is due to Niklaus Wirth. - -This solution is inspired by Dijkstra (Structured Programming). It is -a classic recursive backtracking approach. - -""" - -N = 8 # Default; command line overrides - -class Queens: - - def __init__(self, n=N): - self.n = n - self.reset() - - def reset(self): - n = self.n - self.y = [None] * n # Where is the queen in column x - self.row = [0] * n # Is row[y] safe? - self.up = [0] * (2*n-1) # Is upward diagonal[x-y] safe? - self.down = [0] * (2*n-1) # Is downward diagonal[x+y] safe? - self.nfound = 0 # Instrumentation - - def solve(self, x=0): # Recursive solver - for y in range(self.n): - if self.safe(x, y): - self.place(x, y) - if x+1 == self.n: - self.display() - else: - self.solve(x+1) - self.remove(x, y) - - def safe(self, x, y): - return not self.row[y] and not self.up[x-y] and not self.down[x+y] - - def place(self, x, y): - self.y[x] = y - self.row[y] = 1 - self.up[x-y] = 1 - self.down[x+y] = 1 - - def remove(self, x, y): - self.y[x] = None - self.row[y] = 0 - self.up[x-y] = 0 - self.down[x+y] = 0 - - silent = 0 # If true, count solutions only - - def display(self): - self.nfound = self.nfound + 1 - if self.silent: - return - print '+-' + '--'*self.n + '+' - for y in range(self.n-1, -1, -1): - print '|', - for x in range(self.n): - if self.y[x] == y: - print "Q", - else: - print ".", - print '|' - print '+-' + '--'*self.n + '+' - -def main(): - import sys - silent = 0 - n = N - if sys.argv[1:2] == ['-n']: - silent = 1 - del sys.argv[1] - if sys.argv[1:]: - n = int(sys.argv[1]) - q = Queens(n) - q.silent = silent - q.solve() - print "Found", q.nfound, "solutions." - -if __name__ == "__main__": - main() diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/script.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/script.py deleted file mode 100644 index 8098dfc..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/script.py +++ /dev/null @@ -1,42 +0,0 @@ -#! /usr/bin/env python - -# script.py -- Make typescript of terminal session. -# Usage: -# -a Append to typescript. -# -p Use Python as shell. -# Author: Steen Lumholt. - - -import os, time, sys, getopt -import pty - -def read(fd): - data = os.read(fd, 1024) - script.write(data) - return data - -shell = 'sh' -filename = 'typescript' -mode = 'w' -if os.environ.has_key('SHELL'): - shell = os.environ['SHELL'] - -try: - opts, args = getopt.getopt(sys.argv[1:], 'ap') -except getopt.error, msg: - print '%s: %s' % (sys.argv[0], msg) - sys.exit(2) - -for o, a in opts: - if o == '-a': - mode = 'a' - elif o == '-p': - shell = 'python' - -script = open(filename, mode) - -sys.stdout.write('Script started, file is %s\n' % filename) -script.write('Script started on %s\n' % time.ctime(time.time())) -pty.spawn(shell, read) -script.write('Script done on %s\n' % time.ctime(time.time())) -sys.stdout.write('Script done, file is %s\n' % filename) diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/unbirthday.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/unbirthday.py deleted file mode 100644 index e4dbb1a..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/unbirthday.py +++ /dev/null @@ -1,104 +0,0 @@ -#! /usr/bin/env python - -# Calculate your unbirthday count (see Alice in Wonderland). -# This is defined as the number of days from your birth until today -# that weren't your birthday. (The day you were born is not counted). -# Leap years make it interesting. - -import sys -import time -import calendar - -def main(): - if sys.argv[1:]: - year = int(sys.argv[1]) - else: - year = int(raw_input('In which year were you born? ')) - if 0 <= year < 100: - print "I'll assume that by", year, - year = year + 1900 - print 'you mean', year, 'and not the early Christian era' - elif not (1850 <= year <= time.localtime()[0]): - print "It's hard to believe you were born in", year - return - - if sys.argv[2:]: - month = int(sys.argv[2]) - else: - month = int(raw_input('And in which month? (1-12) ')) - if not (1 <= month <= 12): - print 'There is no month numbered', month - return - - if sys.argv[3:]: - day = int(sys.argv[3]) - else: - day = int(raw_input('And on what day of that month? (1-31) ')) - if month == 2 and calendar.isleap(year): - maxday = 29 - else: - maxday = calendar.mdays[month] - if not (1 <= day <= maxday): - print 'There are no', day, 'days in that month!' - return - - bdaytuple = (year, month, day) - bdaydate = mkdate(bdaytuple) - print 'You were born on', format(bdaytuple) - - todaytuple = time.localtime()[:3] - todaydate = mkdate(todaytuple) - print 'Today is', format(todaytuple) - - if bdaytuple > todaytuple: - print 'You are a time traveler. Go back to the future!' - return - - if bdaytuple == todaytuple: - print 'You were born today. Have a nice life!' - return - - days = todaydate - bdaydate - print 'You have lived', days, 'days' - - age = 0 - for y in range(year, todaytuple[0] + 1): - if bdaytuple < (y, month, day) <= todaytuple: - age = age + 1 - - print 'You are', age, 'years old' - - if todaytuple[1:] == bdaytuple[1:]: - print 'Congratulations! Today is your', nth(age), 'birthday' - print 'Yesterday was your', - else: - print 'Today is your', - print nth(days - age), 'unbirthday' - -def format((year, month, day)): - return '%d %s %d' % (day, calendar.month_name[month], year) - -def nth(n): - if n == 1: return '1st' - if n == 2: return '2nd' - if n == 3: return '3rd' - return '%dth' % n - -def mkdate((year, month, day)): - # January 1st, in 0 A.D. is arbitrarily defined to be day 1, - # even though that day never actually existed and the calendar - # was different then... - days = year*365 # years, roughly - days = days + (year+3)//4 # plus leap years, roughly - days = days - (year+99)//100 # minus non-leap years every century - days = days + (year+399)//400 # plus leap years every 4 centirues - for i in range(1, month): - if i == 2 and calendar.isleap(year): - days = days + 29 - else: - days = days + calendar.mdays[i] - days = days + day - return days - -if __name__ == "__main__": - main() diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/update.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/update.py deleted file mode 100644 index 17f101c..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/update.py +++ /dev/null @@ -1,92 +0,0 @@ -#! /usr/bin/env python - -# Update a bunch of files according to a script. -# The input file contains lines of the form ::, -# meaning that the given line of the given file is to be replaced -# by the given text. This is useful for performing global substitutions -# on grep output: - -import os -import sys -import re - -pat = '^([^: \t\n]+):([1-9][0-9]*):' -prog = re.compile(pat) - -class FileObj: - def __init__(self, filename): - self.filename = filename - self.changed = 0 - try: - self.lines = open(filename, 'r').readlines() - except IOError, msg: - print '*** Can\'t open "%s":' % filename, msg - self.lines = None - return - print 'diffing', self.filename - - def finish(self): - if not self.changed: - print 'no changes to', self.filename - return - try: - os.rename(self.filename, self.filename + '~') - fp = open(self.filename, 'w') - except (os.error, IOError), msg: - print '*** Can\'t rewrite "%s":' % self.filename, msg - return - print 'writing', self.filename - for line in self.lines: - fp.write(line) - fp.close() - self.changed = 0 - - def process(self, lineno, rest): - if self.lines is None: - print '(not processed): %s:%s:%s' % ( - self.filename, lineno, rest), - return - i = eval(lineno) - 1 - if not 0 <= i < len(self.lines): - print '*** Line number out of range: %s:%s:%s' % ( - self.filename, lineno, rest), - return - if self.lines[i] == rest: - print '(no change): %s:%s:%s' % ( - self.filename, lineno, rest), - return - if not self.changed: - self.changed = 1 - print '%sc%s' % (lineno, lineno) - print '<', self.lines[i], - print '---' - self.lines[i] = rest - print '>', self.lines[i], - -def main(): - if sys.argv[1:]: - try: - fp = open(sys.argv[1], 'r') - except IOError, msg: - print 'Can\'t open "%s":' % sys.argv[1], msg - sys.exit(1) - else: - fp = sys.stdin - curfile = None - while 1: - line = fp.readline() - if not line: - if curfile: curfile.finish() - break - n = prog.match(line) - if n < 0: - print 'Funny line:', line, - continue - filename, lineno = prog.group(1, 2) - if not curfile or filename <> curfile.filename: - if curfile: curfile.finish() - curfile = FileObj(filename) - curfile.process(lineno, line[n:]) - -if __name__ == "__main__": - main() diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/README b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/README deleted file mode 100644 index 69618fc..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/README +++ /dev/null @@ -1,14 +0,0 @@ -This directory contains some demonstrations of the socket module: - -broadcast.py Broadcast the time to radio.py. -echosvr.py About the simplest TCP server possible. -finger.py Client for the 'finger' protocol. -ftp.py A very simple ftp client. -gopher.py A simple gopher client. -mcast.py IPv4/v6 multicast example -radio.py Receive time broadcasts from broadcast.py. -telnet.py Client for the 'telnet' protocol. -throughput.py Client and server to measure TCP throughput. -unixclient.py Unix socket example, client side -unixserver.py Unix socket example, server side -udpecho.py Client and server for the UDP echo protocol. diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/broadcast.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/broadcast.py deleted file mode 100644 index f022240..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/broadcast.py +++ /dev/null @@ -1,15 +0,0 @@ -# Send UDP broadcast packets - -MYPORT = 50000 - -import sys, time -from socket import * - -s = socket(AF_INET, SOCK_DGRAM) -s.bind(('', 0)) -s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) - -while 1: - data = repr(time.time()) + '\n' - s.sendto(data, ('', MYPORT)) - time.sleep(2) diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/echosvr.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/echosvr.py deleted file mode 100644 index 893a486..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/echosvr.py +++ /dev/null @@ -1,31 +0,0 @@ -#! /usr/bin/env python - -# Python implementation of an 'echo' tcp server: echo all data it receives. -# -# This is the simplest possible server, servicing a single request only. - -import sys -from socket import * - -# The standard echo port isn't very useful, it requires root permissions! -# ECHO_PORT = 7 -ECHO_PORT = 50000 + 7 -BUFSIZE = 1024 - -def main(): - if len(sys.argv) > 1: - port = int(eval(sys.argv[1])) - else: - port = ECHO_PORT - s = socket(AF_INET, SOCK_STREAM) - s.bind(('', port)) - s.listen(1) - conn, (remotehost, remoteport) = s.accept() - print 'connected by', remotehost, remoteport - while 1: - data = conn.recv(BUFSIZE) - if not data: - break - conn.send(data) - -main() diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/finger.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/finger.py deleted file mode 100644 index 9cd854c..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/finger.py +++ /dev/null @@ -1,58 +0,0 @@ -#! /usr/bin/env python - -# Python interface to the Internet finger daemon. -# -# Usage: finger [options] [user][@host] ... -# -# If no host is given, the finger daemon on the local host is contacted. -# Options are passed uninterpreted to the finger daemon! - - -import sys, string -from socket import * - - -# Hardcode the number of the finger port here. -# It's not likely to change soon... -# -FINGER_PORT = 79 - - -# Function to do one remote finger invocation. -# Output goes directly to stdout (although this can be changed). -# -def finger(host, args): - s = socket(AF_INET, SOCK_STREAM) - s.connect((host, FINGER_PORT)) - s.send(args + '\n') - while 1: - buf = s.recv(1024) - if not buf: break - sys.stdout.write(buf) - sys.stdout.flush() - - -# Main function: argument parsing. -# -def main(): - options = '' - i = 1 - while i < len(sys.argv) and sys.argv[i][:1] == '-': - options = options + sys.argv[i] + ' ' - i = i+1 - args = sys.argv[i:] - if not args: - args = [''] - for arg in args: - if '@' in arg: - at = string.index(arg, '@') - host = arg[at+1:] - arg = arg[:at] - else: - host = '' - finger(host, options + arg) - - -# Call the main function. -# -main() diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/ftp.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/ftp.py deleted file mode 100644 index 3acdabf..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/ftp.py +++ /dev/null @@ -1,146 +0,0 @@ -# A simple FTP client. -# -# The information to write this program was gathered from RFC 959, -# but this is not a complete implementation! Yet it shows how a simple -# FTP client can be built, and you are welcome to extend it to suit -# it to your needs... -# -# How it works (assuming you've read the RFC): -# -# User commands are passed uninterpreted to the server. However, the -# user never needs to send a PORT command. Rather, the client opens a -# port right away and sends the appropriate PORT command to the server. -# When a response code 150 is received, this port is used to receive -# the data (which is written to stdout in this version), and when the -# data is exhausted, a new port is opened and a corresponding PORT -# command sent. In order to avoid errors when reusing ports quickly -# (and because there is no s.getsockname() method in Python yet) we -# cycle through a number of ports in the 50000 range. - - -import sys, posix, string -from socket import * - - -BUFSIZE = 1024 - -# Default port numbers used by the FTP protocol. -# -FTP_PORT = 21 -FTP_DATA_PORT = FTP_PORT - 1 - -# Change the data port to something not needing root permissions. -# -FTP_DATA_PORT = FTP_DATA_PORT + 50000 - - -# Main program (called at the end of this file). -# -def main(): - hostname = sys.argv[1] - control(hostname) - - -# Control process (user interface and user protocol interpreter). -# -def control(hostname): - # - # Create control connection - # - s = socket(AF_INET, SOCK_STREAM) - s.connect((hostname, FTP_PORT)) - f = s.makefile('r') # Reading the replies is easier from a file... - # - # Control loop - # - r = None - while 1: - code = getreply(f) - if code in ('221', 'EOF'): break - if code == '150': - getdata(r) - code = getreply(f) - r = None - if not r: - r = newdataport(s, f) - cmd = getcommand() - if not cmd: break - s.send(cmd + '\r\n') - - -# Create a new data port and send a PORT command to the server for it. -# (Cycle through a number of ports to avoid problems with reusing -# a port within a short time.) -# -nextport = 0 -# -def newdataport(s, f): - global nextport - port = nextport + FTP_DATA_PORT - nextport = (nextport+1) % 16 - r = socket(AF_INET, SOCK_STREAM) - r.bind((gethostbyname(gethostname()), port)) - r.listen(1) - sendportcmd(s, f, port) - return r - - -# Send an appropriate port command. -# -def sendportcmd(s, f, port): - hostname = gethostname() - hostaddr = gethostbyname(hostname) - hbytes = string.splitfields(hostaddr, '.') - pbytes = [repr(port//256), repr(port%256)] - bytes = hbytes + pbytes - cmd = 'PORT ' + string.joinfields(bytes, ',') - s.send(cmd + '\r\n') - code = getreply(f) - - -# Process an ftp reply and return the 3-digit reply code (as a string). -# The reply should be a line of text starting with a 3-digit number. -# If the 4th char is '-', it is a multi-line reply and is -# terminate by a line starting with the same 3-digit number. -# Any text while receiving the reply is echoed to the file. -# -def getreply(f): - line = f.readline() - if not line: return 'EOF' - print line, - code = line[:3] - if line[3:4] == '-': - while 1: - line = f.readline() - if not line: break # Really an error - print line, - if line[:3] == code and line[3:4] != '-': break - return code - - -# Get the data from the data connection. -# -def getdata(r): - print '(accepting data connection)' - conn, host = r.accept() - print '(data connection accepted)' - while 1: - data = conn.recv(BUFSIZE) - if not data: break - sys.stdout.write(data) - print '(end of data connection)' - -# Get a command from the user. -# -def getcommand(): - try: - while 1: - line = raw_input('ftp.py> ') - if line: return line - except EOFError: - return '' - - -# Call the main program. -# -main() diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/gopher.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/gopher.py deleted file mode 100644 index e47eca5..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/gopher.py +++ /dev/null @@ -1,347 +0,0 @@ -#! /usr/bin/env python - -# A simple gopher client. -# -# Usage: gopher [ [selector] host [port] ] - -import string -import sys -import os -import socket - -# Default selector, host and port -DEF_SELECTOR = '' -DEF_HOST = 'gopher.micro.umn.edu' -DEF_PORT = 70 - -# Recognized file types -T_TEXTFILE = '0' -T_MENU = '1' -T_CSO = '2' -T_ERROR = '3' -T_BINHEX = '4' -T_DOS = '5' -T_UUENCODE = '6' -T_SEARCH = '7' -T_TELNET = '8' -T_BINARY = '9' -T_REDUNDANT = '+' -T_SOUND = 's' - -# Dictionary mapping types to strings -typename = {'0': '', '1': '', '2': '', '3': '', \ - '4': '', '5': '', '6': '', '7': '', \ - '8': '', '9': '', '+': '', 's': ''} - -# Oft-used characters and strings -CRLF = '\r\n' -TAB = '\t' - -# Open a TCP connection to a given host and port -def open_socket(host, port): - if not port: - port = DEF_PORT - elif type(port) == type(''): - port = string.atoi(port) - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.connect((host, port)) - return s - -# Send a selector to a given host and port, return a file with the reply -def send_request(selector, host, port): - s = open_socket(host, port) - s.send(selector + CRLF) - s.shutdown(1) - return s.makefile('r') - -# Get a menu in the form of a list of entries -def get_menu(selector, host, port): - f = send_request(selector, host, port) - list = [] - while 1: - line = f.readline() - if not line: - print '(Unexpected EOF from server)' - break - if line[-2:] == CRLF: - line = line[:-2] - elif line[-1:] in CRLF: - line = line[:-1] - if line == '.': - break - if not line: - print '(Empty line from server)' - continue - typechar = line[0] - parts = string.splitfields(line[1:], TAB) - if len(parts) < 4: - print '(Bad line from server: %r)' % (line,) - continue - if len(parts) > 4: - print '(Extra info from server: %r)' % (parts[4:],) - parts.insert(0, typechar) - list.append(parts) - f.close() - return list - -# Get a text file as a list of lines, with trailing CRLF stripped -def get_textfile(selector, host, port): - list = [] - get_alt_textfile(selector, host, port, list.append) - return list - -# Get a text file and pass each line to a function, with trailing CRLF stripped -def get_alt_textfile(selector, host, port, func): - f = send_request(selector, host, port) - while 1: - line = f.readline() - if not line: - print '(Unexpected EOF from server)' - break - if line[-2:] == CRLF: - line = line[:-2] - elif line[-1:] in CRLF: - line = line[:-1] - if line == '.': - break - if line[:2] == '..': - line = line[1:] - func(line) - f.close() - -# Get a binary file as one solid data block -def get_binary(selector, host, port): - f = send_request(selector, host, port) - data = f.read() - f.close() - return data - -# Get a binary file and pass each block to a function -def get_alt_binary(selector, host, port, func, blocksize): - f = send_request(selector, host, port) - while 1: - data = f.read(blocksize) - if not data: - break - func(data) - -# A *very* simple interactive browser - -# Browser main command, has default arguments -def browser(*args): - selector = DEF_SELECTOR - host = DEF_HOST - port = DEF_PORT - n = len(args) - if n > 0 and args[0]: - selector = args[0] - if n > 1 and args[1]: - host = args[1] - if n > 2 and args[2]: - port = args[2] - if n > 3: - raise RuntimeError, 'too many args' - try: - browse_menu(selector, host, port) - except socket.error, msg: - print 'Socket error:', msg - sys.exit(1) - except KeyboardInterrupt: - print '\n[Goodbye]' - -# Browse a menu -def browse_menu(selector, host, port): - list = get_menu(selector, host, port) - while 1: - print '----- MENU -----' - print 'Selector:', repr(selector) - print 'Host:', host, ' Port:', port - print - for i in range(len(list)): - item = list[i] - typechar, description = item[0], item[1] - print string.rjust(repr(i+1), 3) + ':', description, - if typename.has_key(typechar): - print typename[typechar] - else: - print '' - print - while 1: - try: - str = raw_input('Choice [CR == up a level]: ') - except EOFError: - print - return - if not str: - return - try: - choice = string.atoi(str) - except string.atoi_error: - print 'Choice must be a number; try again:' - continue - if not 0 < choice <= len(list): - print 'Choice out of range; try again:' - continue - break - item = list[choice-1] - typechar = item[0] - [i_selector, i_host, i_port] = item[2:5] - if typebrowser.has_key(typechar): - browserfunc = typebrowser[typechar] - try: - browserfunc(i_selector, i_host, i_port) - except (IOError, socket.error): - print '***', sys.exc_type, ':', sys.exc_value - else: - print 'Unsupported object type' - -# Browse a text file -def browse_textfile(selector, host, port): - x = None - try: - p = os.popen('${PAGER-more}', 'w') - x = SaveLines(p) - get_alt_textfile(selector, host, port, x.writeln) - except IOError, msg: - print 'IOError:', msg - if x: - x.close() - f = open_savefile() - if not f: - return - x = SaveLines(f) - try: - get_alt_textfile(selector, host, port, x.writeln) - print 'Done.' - except IOError, msg: - print 'IOError:', msg - x.close() - -# Browse a search index -def browse_search(selector, host, port): - while 1: - print '----- SEARCH -----' - print 'Selector:', repr(selector) - print 'Host:', host, ' Port:', port - print - try: - query = raw_input('Query [CR == up a level]: ') - except EOFError: - print - break - query = string.strip(query) - if not query: - break - if '\t' in query: - print 'Sorry, queries cannot contain tabs' - continue - browse_menu(selector + TAB + query, host, port) - -# "Browse" telnet-based information, i.e. open a telnet session -def browse_telnet(selector, host, port): - if selector: - print 'Log in as', repr(selector) - if type(port) <> type(''): - port = repr(port) - sts = os.system('set -x; exec telnet ' + host + ' ' + port) - if sts: - print 'Exit status:', sts - -# "Browse" a binary file, i.e. save it to a file -def browse_binary(selector, host, port): - f = open_savefile() - if not f: - return - x = SaveWithProgress(f) - get_alt_binary(selector, host, port, x.write, 8*1024) - x.close() - -# "Browse" a sound file, i.e. play it or save it -def browse_sound(selector, host, port): - browse_binary(selector, host, port) - -# Dictionary mapping types to browser functions -typebrowser = {'0': browse_textfile, '1': browse_menu, \ - '4': browse_binary, '5': browse_binary, '6': browse_textfile, \ - '7': browse_search, \ - '8': browse_telnet, '9': browse_binary, 's': browse_sound} - -# Class used to save lines, appending a newline to each line -class SaveLines: - def __init__(self, f): - self.f = f - def writeln(self, line): - self.f.write(line + '\n') - def close(self): - sts = self.f.close() - if sts: - print 'Exit status:', sts - -# Class used to save data while showing progress -class SaveWithProgress: - def __init__(self, f): - self.f = f - def write(self, data): - sys.stdout.write('#') - sys.stdout.flush() - self.f.write(data) - def close(self): - print - sts = self.f.close() - if sts: - print 'Exit status:', sts - -# Ask for and open a save file, or return None if not to save -def open_savefile(): - try: - savefile = raw_input( \ - 'Save as file [CR == don\'t save; |pipeline or ~user/... OK]: ') - except EOFError: - print - return None - savefile = string.strip(savefile) - if not savefile: - return None - if savefile[0] == '|': - cmd = string.strip(savefile[1:]) - try: - p = os.popen(cmd, 'w') - except IOError, msg: - print repr(cmd), ':', msg - return None - print 'Piping through', repr(cmd), '...' - return p - if savefile[0] == '~': - savefile = os.path.expanduser(savefile) - try: - f = open(savefile, 'w') - except IOError, msg: - print repr(savefile), ':', msg - return None - print 'Saving to', repr(savefile), '...' - return f - -# Test program -def test(): - if sys.argv[4:]: - print 'usage: gopher [ [selector] host [port] ]' - sys.exit(2) - elif sys.argv[3:]: - browser(sys.argv[1], sys.argv[2], sys.argv[3]) - elif sys.argv[2:]: - try: - port = string.atoi(sys.argv[2]) - selector = '' - host = sys.argv[1] - except string.atoi_error: - selector = sys.argv[1] - host = sys.argv[2] - port = '' - browser(selector, host, port) - elif sys.argv[1:]: - browser('', sys.argv[1]) - else: - browser() - -# Call the test program as a main program -test() diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/mcast.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/mcast.py deleted file mode 100644 index 55d405e..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/mcast.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env python -# -# Send/receive UDP multicast packets. -# Requires that your OS kernel supports IP multicast. -# -# Usage: -# mcast -s (sender, IPv4) -# mcast -s -6 (sender, IPv6) -# mcast (receivers, IPv4) -# mcast -6 (receivers, IPv6) - -MYPORT = 8123 -MYGROUP_4 = '225.0.0.250' -MYGROUP_6 = 'ff15:7079:7468:6f6e:6465:6d6f:6d63:6173' -MYTTL = 1 # Increase to reach other networks - -import time -import struct -import socket -import sys - -def main(): - group = MYGROUP_6 if "-6" in sys.argv[1:] else MYGROUP_4 - - if "-s" in sys.argv[1:]: - sender(group) - else: - receiver(group) - - -def sender(group): - addrinfo = socket.getaddrinfo(group, None)[0] - - s = socket.socket(addrinfo[0], socket.SOCK_DGRAM) - - # Set Time-to-live (optional) - ttl_bin = struct.pack('@i', MYTTL) - if addrinfo[0] == socket.AF_INET: # IPv4 - s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl_bin) - else: - s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, ttl_bin) - - while True: - data = repr(time.time()) - s.sendto(data + '\0', (addrinfo[4][0], MYPORT)) - time.sleep(1) - - -def receiver(group): - # Look up multicast group address in name server and find out IP version - addrinfo = socket.getaddrinfo(group, None)[0] - - # Create a socket - s = socket.socket(addrinfo[0], socket.SOCK_DGRAM) - - # Allow multiple copies of this program on one machine - # (not strictly needed) - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - - # Bind it to the port - s.bind(('', MYPORT)) - - group_bin = socket.inet_pton(addrinfo[0], addrinfo[4][0]) - # Join group - if addrinfo[0] == socket.AF_INET: # IPv4 - mreq = group_bin + struct.pack('=I', socket.INADDR_ANY) - s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) - else: - mreq = group_bin + struct.pack('@I', 0) - s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq) - - # Loop, printing any data we receive - while True: - data, sender = s.recvfrom(1500) - while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's - print (str(sender) + ' ' + repr(data)) - - -if __name__ == '__main__': - main() diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/radio.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/radio.py deleted file mode 100644 index 084ef88..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/radio.py +++ /dev/null @@ -1,14 +0,0 @@ -# Receive UDP packets transmitted by a broadcasting service - -MYPORT = 50000 - -import sys -from socket import * - -s = socket(AF_INET, SOCK_DGRAM) -s.bind(('', MYPORT)) - -while 1: - data, wherefrom = s.recvfrom(1500, 0) - sys.stderr.write(repr(wherefrom) + '\n') - sys.stdout.write(data) diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/rpython.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/rpython.py deleted file mode 100644 index a28de1d..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/rpython.py +++ /dev/null @@ -1,35 +0,0 @@ -#! /usr/bin/env python - -# Remote python client. -# Execute Python commands remotely and send output back. - -import sys -import string -from socket import * - -PORT = 4127 -BUFSIZE = 1024 - -def main(): - if len(sys.argv) < 3: - print "usage: rpython host command" - sys.exit(2) - host = sys.argv[1] - port = PORT - i = string.find(host, ':') - if i >= 0: - port = string.atoi(port[i+1:]) - host = host[:i] - command = string.join(sys.argv[2:]) - s = socket(AF_INET, SOCK_STREAM) - s.connect((host, port)) - s.send(command) - s.shutdown(1) - reply = '' - while 1: - data = s.recv(BUFSIZE) - if not data: break - reply = reply + data - print reply, - -main() diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/rpythond.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/rpythond.py deleted file mode 100644 index 50653fb..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/rpythond.py +++ /dev/null @@ -1,52 +0,0 @@ -#! /usr/bin/env python - -# Remote python server. -# Execute Python commands remotely and send output back. -# WARNING: This version has a gaping security hole -- it accepts requests -# from any host on the Internet! - -import sys -from socket import * -import StringIO -import traceback - -PORT = 4127 -BUFSIZE = 1024 - -def main(): - if len(sys.argv) > 1: - port = int(eval(sys.argv[1])) - else: - port = PORT - s = socket(AF_INET, SOCK_STREAM) - s.bind(('', port)) - s.listen(1) - while 1: - conn, (remotehost, remoteport) = s.accept() - print 'connected by', remotehost, remoteport - request = '' - while 1: - data = conn.recv(BUFSIZE) - if not data: - break - request = request + data - reply = execute(request) - conn.send(reply) - conn.close() - -def execute(request): - stdout = sys.stdout - stderr = sys.stderr - sys.stdout = sys.stderr = fakefile = StringIO.StringIO() - try: - try: - exec request in {}, {} - except: - print - traceback.print_exc(100) - finally: - sys.stderr = stderr - sys.stdout = stdout - return fakefile.getvalue() - -main() diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/telnet.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/telnet.py deleted file mode 100644 index 1702392..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/telnet.py +++ /dev/null @@ -1,109 +0,0 @@ -#! /usr/bin/env python - -# Minimal interface to the Internet telnet protocol. -# -# It refuses all telnet options and does not recognize any of the other -# telnet commands, but can still be used to connect in line-by-line mode. -# It's also useful to play with a number of other services, -# like time, finger, smtp and even ftp. -# -# Usage: telnet host [port] -# -# The port may be a service name or a decimal port number; -# it defaults to 'telnet'. - - -import sys, posix, time -from socket import * - -BUFSIZE = 1024 - -# Telnet protocol characters - -IAC = chr(255) # Interpret as command -DONT = chr(254) -DO = chr(253) -WONT = chr(252) -WILL = chr(251) - -def main(): - host = sys.argv[1] - try: - hostaddr = gethostbyname(host) - except error: - sys.stderr.write(sys.argv[1] + ': bad host name\n') - sys.exit(2) - # - if len(sys.argv) > 2: - servname = sys.argv[2] - else: - servname = 'telnet' - # - if '0' <= servname[:1] <= '9': - port = eval(servname) - else: - try: - port = getservbyname(servname, 'tcp') - except error: - sys.stderr.write(servname + ': bad tcp service name\n') - sys.exit(2) - # - s = socket(AF_INET, SOCK_STREAM) - # - try: - s.connect((host, port)) - except error, msg: - sys.stderr.write('connect failed: ' + repr(msg) + '\n') - sys.exit(1) - # - pid = posix.fork() - # - if pid == 0: - # child -- read stdin, write socket - while 1: - line = sys.stdin.readline() - s.send(line) - else: - # parent -- read socket, write stdout - iac = 0 # Interpret next char as command - opt = '' # Interpret next char as option - while 1: - data = s.recv(BUFSIZE) - if not data: - # EOF; kill child and exit - sys.stderr.write( '(Closed by remote host)\n') - posix.kill(pid, 9) - sys.exit(1) - cleandata = '' - for c in data: - if opt: - print ord(c) - s.send(opt + c) - opt = '' - elif iac: - iac = 0 - if c == IAC: - cleandata = cleandata + c - elif c in (DO, DONT): - if c == DO: print '(DO)', - else: print '(DONT)', - opt = IAC + WONT - elif c in (WILL, WONT): - if c == WILL: print '(WILL)', - else: print '(WONT)', - opt = IAC + DONT - else: - print '(command)', ord(c) - elif c == IAC: - iac = 1 - print '(IAC)', - else: - cleandata = cleandata + c - sys.stdout.write(cleandata) - sys.stdout.flush() - - -try: - main() -except KeyboardInterrupt: - pass diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/throughput.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/throughput.py deleted file mode 100644 index 6ac76af..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/throughput.py +++ /dev/null @@ -1,93 +0,0 @@ -#! /usr/bin/env python - -# Test network throughput. -# -# Usage: -# 1) on host_A: throughput -s [port] # start a server -# 2) on host_B: throughput -c count host_A [port] # start a client -# -# The server will service multiple clients until it is killed. -# -# The client performs one transfer of count*BUFSIZE bytes and -# measures the time it takes (roundtrip!). - - -import sys, time -from socket import * - -MY_PORT = 50000 + 42 - -BUFSIZE = 1024 - - -def main(): - if len(sys.argv) < 2: - usage() - if sys.argv[1] == '-s': - server() - elif sys.argv[1] == '-c': - client() - else: - usage() - - -def usage(): - sys.stdout = sys.stderr - print 'Usage: (on host_A) throughput -s [port]' - print 'and then: (on host_B) throughput -c count host_A [port]' - sys.exit(2) - - -def server(): - if len(sys.argv) > 2: - port = eval(sys.argv[2]) - else: - port = MY_PORT - s = socket(AF_INET, SOCK_STREAM) - s.bind(('', port)) - s.listen(1) - print 'Server ready...' - while 1: - conn, (host, remoteport) = s.accept() - while 1: - data = conn.recv(BUFSIZE) - if not data: - break - del data - conn.send('OK\n') - conn.close() - print 'Done with', host, 'port', remoteport - - -def client(): - if len(sys.argv) < 4: - usage() - count = int(eval(sys.argv[2])) - host = sys.argv[3] - if len(sys.argv) > 4: - port = eval(sys.argv[4]) - else: - port = MY_PORT - testdata = 'x' * (BUFSIZE-1) + '\n' - t1 = time.time() - s = socket(AF_INET, SOCK_STREAM) - t2 = time.time() - s.connect((host, port)) - t3 = time.time() - i = 0 - while i < count: - i = i+1 - s.send(testdata) - s.shutdown(1) # Send EOF - t4 = time.time() - data = s.recv(BUFSIZE) - t5 = time.time() - print data - print 'Raw timers:', t1, t2, t3, t4, t5 - print 'Intervals:', t2-t1, t3-t2, t4-t3, t5-t4 - print 'Total:', t5-t1 - print 'Throughput:', round((BUFSIZE*count*0.001) / (t5-t1), 3), - print 'K/sec.' - - -main() diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/udpecho.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/udpecho.py deleted file mode 100644 index ea7d396..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/udpecho.py +++ /dev/null @@ -1,63 +0,0 @@ -#! /usr/bin/env python - -# Client and server for udp (datagram) echo. -# -# Usage: udpecho -s [port] (to start a server) -# or: udpecho -c host [port] 2: - port = eval(sys.argv[2]) - else: - port = ECHO_PORT - s = socket(AF_INET, SOCK_DGRAM) - s.bind(('', port)) - print 'udp echo server ready' - while 1: - data, addr = s.recvfrom(BUFSIZE) - print 'server received %r from %r' % (data, addr) - s.sendto(data, addr) - -def client(): - if len(sys.argv) < 3: - usage() - host = sys.argv[2] - if len(sys.argv) > 3: - port = eval(sys.argv[3]) - else: - port = ECHO_PORT - addr = host, port - s = socket(AF_INET, SOCK_DGRAM) - s.bind(('', 0)) - print 'udp echo client ready, reading stdin' - while 1: - line = sys.stdin.readline() - if not line: - break - s.sendto(line, addr) - data, fromaddr = s.recvfrom(BUFSIZE) - print 'client received %r from %r' % (data, fromaddr) - -main() diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/unicast.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/unicast.py deleted file mode 100644 index 9d36f45..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/unicast.py +++ /dev/null @@ -1,14 +0,0 @@ -# Send UDP broadcast packets - -MYPORT = 50000 - -import sys, time -from socket import * - -s = socket(AF_INET, SOCK_DGRAM) -s.bind(('', 0)) - -while 1: - data = repr(time.time()) + '\n' - s.sendto(data, ('', MYPORT)) - time.sleep(2) diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/unixclient.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/unixclient.py deleted file mode 100644 index 369e225..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/unixclient.py +++ /dev/null @@ -1,12 +0,0 @@ -# Echo client demo using Unix sockets -# Piet van Oostrum - -from socket import * - -FILE = 'unix-socket' -s = socket(AF_UNIX, SOCK_STREAM) -s.connect(FILE) -s.send('Hello, world') -data = s.recv(1024) -s.close() -print 'Received', repr(data) diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/unixserver.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/unixserver.py deleted file mode 100644 index a597b3b..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/unixserver.py +++ /dev/null @@ -1,24 +0,0 @@ -# Echo server demo using Unix sockets (handles one connection only) -# Piet van Oostrum - -import os -from socket import * - -FILE = 'unix-socket' -s = socket(AF_UNIX, SOCK_STREAM) -s.bind(FILE) - -print 'Sock name is: ['+s.getsockname()+']' - -# Wait for a connection -s.listen(1) -conn, addr = s.accept() - -while True: - data = conn.recv(1024) - if not data: - break - conn.send(data) - -conn.close() -os.unlink(FILE) diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/xml/elem_count.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/xml/elem_count.py deleted file mode 100644 index 73ac380..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/xml/elem_count.py +++ /dev/null @@ -1,42 +0,0 @@ -""" -A simple demo that reads in an XML document and displays the number of -elements and attributes as well as a tally of elements and attributes by name. -""" - -import sys -from collections import defaultdict - -from xml.sax import make_parser, handler - -class FancyCounter(handler.ContentHandler): - - def __init__(self): - self._elems = 0 - self._attrs = 0 - self._elem_types = defaultdict(int) - self._attr_types = defaultdict(int) - - def startElement(self, name, attrs): - self._elems += 1 - self._attrs += len(attrs) - self._elem_types[name] += 1 - - for name in attrs.keys(): - self._attr_types[name] += 1 - - def endDocument(self): - print "There were", self._elems, "elements." - print "There were", self._attrs, "attributes." - - print "---ELEMENT TYPES" - for pair in self._elem_types.items(): - print "%20s %d" % pair - - print "---ATTRIBUTE TYPES" - for pair in self._attr_types.items(): - print "%20s %d" % pair - -if __name__ == '__main__': - parser = make_parser() - parser.setContentHandler(FancyCounter()) - parser.parse(sys.argv[1]) diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/xml/roundtrip.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/xml/roundtrip.py deleted file mode 100644 index 921b2b8..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/xml/roundtrip.py +++ /dev/null @@ -1,46 +0,0 @@ -""" -A simple demo that reads in an XML document and spits out an equivalent, -but not necessarily identical, document. -""" - -import sys - -from xml.sax import saxutils, handler, make_parser - -# --- The ContentHandler - -class ContentGenerator(handler.ContentHandler): - - def __init__(self, out=sys.stdout): - handler.ContentHandler.__init__(self) - self._out = out - - # ContentHandler methods - - def startDocument(self): - self._out.write('\n') - - def startElement(self, name, attrs): - self._out.write('<' + name) - for (name, value) in attrs.items(): - self._out.write(' %s="%s"' % (name, saxutils.escape(value))) - self._out.write('>') - - def endElement(self, name): - self._out.write('' % name) - - def characters(self, content): - self._out.write(saxutils.escape(content)) - - def ignorableWhitespace(self, content): - self._out.write(content) - - def processingInstruction(self, target, data): - self._out.write('' % (target, data)) - -# --- The main program - -if __name__ == '__main__': - parser = make_parser() - parser.setContentHandler(ContentGenerator()) - parser.parse(sys.argv[1]) diff --git a/AppPkg/Applications/Python/Python-2.7.2/Demo/xml/rss2html.py b/AppPkg/Applications/Python/Python-2.7.2/Demo/xml/rss2html.py deleted file mode 100644 index e9bb76d..0000000 --- a/AppPkg/Applications/Python/Python-2.7.2/Demo/xml/rss2html.py +++ /dev/null @@ -1,97 +0,0 @@ -""" -A demo that reads in an RSS XML document and emits an HTML file containing -a list of the individual items in the feed. -""" - -import sys -import codecs - -from xml.sax import make_parser, handler - -# --- Templates - -top = """\ - - - - %s - - - - -

      %s

      -""" - -bottom = """ -
    - -
    -
    -Converted to HTML by rss2html.py. -
    - - - -""" - -# --- The ContentHandler - -class RSSHandler(handler.ContentHandler): - - def __init__(self, out=sys.stdout): - handler.ContentHandler.__init__(self) - self._out = codecs.getwriter('utf-8')(out) - - self._text = "" - self._parent = None - self._list_started = False - self._title = None - self._link = None - self._descr = "" - - # ContentHandler methods - - def startElement(self, name, attrs): - if name == "channel" or name == "image" or name == "item": - self._parent = name - - self._text = "" - - def endElement(self, name): - if self._parent == "channel": - if name == "title": - self._out.write(top % (self._text, self._text)) - elif name == "description": - self._out.write("

    %s

    \n" % self._text) - - elif self._parent == "item": - if name == "title": - self._title = self._text - elif name == "link": - self._link = self._text - elif name == "description": - self._descr = self._text - elif name == "item": - if not self._list_started: - self._out.write("